4200ad598cdc6281f4b7dfaad24f9a8de7384268
[yaffs2.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2010 Aleph One Ltd.
5  *   for Toby Churchill Ltd and Brightstar Engineering
6  *
7  * Created by Charles Manning <charles@aleph1.co.uk>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  */
13
14 #include "yportenv.h"
15 #include "yaffs_trace.h"
16
17 #include "yaffsinterface.h"
18 #include "yaffs_guts.h"
19 #include "yaffs_tagsvalidity.h"
20 #include "yaffs_getblockinfo.h"
21
22 #include "yaffs_tagscompat.h"
23
24 #include "yaffs_nand.h"
25
26 #include "yaffs_yaffs1.h"
27 #include "yaffs_yaffs2.h"
28 #include "yaffs_bitmap.h"
29 #include "yaffs_verify.h"
30
31 #include "yaffs_nand.h"
32 #include "yaffs_packedtags2.h"
33
34 #include "yaffs_nameval.h"
35 #include "yaffs_allocator.h"
36
37 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
38 #define YAFFS_GC_GOOD_ENOUGH 2
39 #define YAFFS_GC_PASSIVE_THRESHOLD 4
40
41 #include "yaffs_ecc.h"
42
43
44
45 /* Robustification (if it ever comes about...) */
46 static void yaffs_retire_block(yaffs_dev_t *dev, int flash_block);
47 static void yaffs_handle_chunk_wr_error(yaffs_dev_t *dev, int nand_chunk,
48                 int erasedOk);
49 static void yaffs_handle_chunk_wr_ok(yaffs_dev_t *dev, int nand_chunk,
50                                 const __u8 *data,
51                                 const yaffs_ext_tags *tags);
52 static void yaffs_handle_chunk_update(yaffs_dev_t *dev, int nand_chunk,
53                                 const yaffs_ext_tags *tags);
54
55 /* Other local prototypes */
56 static void yaffs_update_parent(yaffs_obj_t *obj);
57 static int yaffs_unlink_obj(yaffs_obj_t *obj);
58 static int yaffs_obj_cache_dirty(yaffs_obj_t *obj);
59
60 static int yaffs_write_new_chunk(yaffs_dev_t *dev,
61                                         const __u8 *buffer,
62                                         yaffs_ext_tags *tags,
63                                         int useReserve);
64
65
66 static yaffs_obj_t *yaffs_new_obj(yaffs_dev_t *dev, int number,
67                                         yaffs_obj_type type);
68
69
70 static int yaffs_apply_xattrib_mod(yaffs_obj_t *obj, char *buffer, yaffs_xattr_mod *xmod);
71
72 static void yaffs_remove_obj_from_dir(yaffs_obj_t *obj);
73 static int yaffs_check_structures(void);
74 static int yaffs_generic_obj_del(yaffs_obj_t *in);
75
76 static int yaffs_check_chunk_erased(struct yaffs_dev_s *dev,
77                                 int nand_chunk);
78
79 static int yaffs_unlink_worker(yaffs_obj_t *obj);
80
81 static int yaffs_tags_match(const yaffs_ext_tags *tags, int obj_id,
82                         int chunkInObject);
83
84 static int yaffs_alloc_chunk(yaffs_dev_t *dev, int useReserve,
85                                 yaffs_block_info_t **blockUsedPtr);
86
87 static void yaffs_check_obj_details_loaded(yaffs_obj_t *in);
88
89 static void yaffs_invalidate_whole_cache(yaffs_obj_t *in);
90 static void yaffs_invalidate_chunk_cache(yaffs_obj_t *object, int chunk_id);
91
92 static int yaffs_find_chunk_in_file(yaffs_obj_t *in, int inode_chunk,
93                                 yaffs_ext_tags *tags);
94
95 static int yaffs_verify_chunk_written(yaffs_dev_t *dev,
96                                         int nand_chunk,
97                                         const __u8 *data,
98                                         yaffs_ext_tags *tags);
99
100
101 static void yaffs_load_name_from_oh(yaffs_dev_t *dev,YCHAR *name, const YCHAR *ohName, int bufferSize);
102 static void yaffs_load_oh_from_name(yaffs_dev_t *dev,YCHAR *ohName, const YCHAR *name);
103
104
105 /* Function to calculate chunk and offset */
106
107 static void yaffs_addr_to_chunk(yaffs_dev_t *dev, loff_t addr, int *chunkOut,
108                 __u32 *offsetOut)
109 {
110         int chunk;
111         __u32 offset;
112
113         chunk  = (__u32)(addr >> dev->chunk_shift);
114
115         if (dev->chunk_div == 1) {
116                 /* easy power of 2 case */
117                 offset = (__u32)(addr & dev->chunk_mask);
118         } else {
119                 /* Non power-of-2 case */
120
121                 loff_t chunkBase;
122
123                 chunk /= dev->chunk_div;
124
125                 chunkBase = ((loff_t)chunk) * dev->data_bytes_per_chunk;
126                 offset = (__u32)(addr - chunkBase);
127         }
128
129         *chunkOut = chunk;
130         *offsetOut = offset;
131 }
132
133 /* Function to return the number of shifts for a power of 2 greater than or
134  * equal to the given number
135  * Note we don't try to cater for all possible numbers and this does not have to
136  * be hellishly efficient.
137  */
138
139 static __u32 ShiftsGE(__u32 x)
140 {
141         int extraBits;
142         int nShifts;
143
144         nShifts = extraBits = 0;
145
146         while (x > 1) {
147                 if (x & 1)
148                         extraBits++;
149                 x >>= 1;
150                 nShifts++;
151         }
152
153         if (extraBits)
154                 nShifts++;
155
156         return nShifts;
157 }
158
159 /* Function to return the number of shifts to get a 1 in bit 0
160  */
161
162 static __u32 Shifts(__u32 x)
163 {
164         __u32 nShifts;
165
166         nShifts =  0;
167
168         if (!x)
169                 return 0;
170
171         while (!(x&1)) {
172                 x >>= 1;
173                 nShifts++;
174         }
175
176         return nShifts;
177 }
178
179
180
181 /*
182  * Temporary buffer manipulations.
183  */
184
185 static int yaffs_init_tmp_buffers(yaffs_dev_t *dev)
186 {
187         int i;
188         __u8 *buf = (__u8 *)1;
189
190         memset(dev->temp_buffer, 0, sizeof(dev->temp_buffer));
191
192         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
193                 dev->temp_buffer[i].line = 0;   /* not in use */
194                 dev->temp_buffer[i].buffer = buf =
195                     YMALLOC_DMA(dev->param.total_bytes_per_chunk);
196         }
197
198         return buf ? YAFFS_OK : YAFFS_FAIL;
199 }
200
201 __u8 *yaffs_get_temp_buffer(yaffs_dev_t *dev, int line_no)
202 {
203         int i, j;
204
205         dev->temp_in_use++;
206         if (dev->temp_in_use > dev->max_temp)
207                 dev->max_temp = dev->temp_in_use;
208
209         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
210                 if (dev->temp_buffer[i].line == 0) {
211                         dev->temp_buffer[i].line = line_no;
212                         if ((i + 1) > dev->max_temp) {
213                                 dev->max_temp = i + 1;
214                                 for (j = 0; j <= i; j++)
215                                         dev->temp_buffer[j].max_line =
216                                             dev->temp_buffer[j].line;
217                         }
218
219                         return dev->temp_buffer[i].buffer;
220                 }
221         }
222
223         T(YAFFS_TRACE_BUFFERS,
224           (TSTR("Out of temp buffers at line %d, other held by lines:"),
225            line_no));
226         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
227                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->temp_buffer[i].line));
228
229         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
230
231         /*
232          * If we got here then we have to allocate an unmanaged one
233          * This is not good.
234          */
235
236         dev->unmanaged_buffer_allocs++;
237         return YMALLOC(dev->data_bytes_per_chunk);
238
239 }
240
241 void yaffs_release_temp_buffer(yaffs_dev_t *dev, __u8 *buffer,
242                                     int line_no)
243 {
244         int i;
245
246         dev->temp_in_use--;
247
248         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
249                 if (dev->temp_buffer[i].buffer == buffer) {
250                         dev->temp_buffer[i].line = 0;
251                         return;
252                 }
253         }
254
255         if (buffer) {
256                 /* assume it is an unmanaged one. */
257                 T(YAFFS_TRACE_BUFFERS,
258                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
259                    line_no));
260                 YFREE(buffer);
261                 dev->unmanaged_buffer_deallocs++;
262         }
263
264 }
265
266 /*
267  * Determine if we have a managed buffer.
268  */
269 int yaffs_is_managed_tmp_buffer(yaffs_dev_t *dev, const __u8 *buffer)
270 {
271         int i;
272
273         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
274                 if (dev->temp_buffer[i].buffer == buffer)
275                         return 1;
276         }
277
278         for (i = 0; i < dev->param.n_caches; i++) {
279                 if (dev->cache[i].data == buffer)
280                         return 1;
281         }
282
283         if (buffer == dev->checkpt_buffer)
284                 return 1;
285
286         T(YAFFS_TRACE_ALWAYS,
287                 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
288         return 0;
289 }
290
291 /*
292  * Verification code
293  */
294
295
296
297
298 /*
299  *  Simple hash function. Needs to have a reasonable spread
300  */
301
302 static Y_INLINE int yaffs_hash_fn(int n)
303 {
304         n = abs(n);
305         return n % YAFFS_NOBJECT_BUCKETS;
306 }
307
308 /*
309  * Access functions to useful fake objects.
310  * Note that root might have a presence in NAND if permissions are set.
311  */
312
313 yaffs_obj_t *yaffs_root(yaffs_dev_t *dev)
314 {
315         return dev->root_dir;
316 }
317
318 yaffs_obj_t *yaffs_lost_n_found(yaffs_dev_t *dev)
319 {
320         return dev->lost_n_found;
321 }
322
323
324 /*
325  *  Erased NAND checking functions
326  */
327
328 int yaffs_check_ff(__u8 *buffer, int n_bytes)
329 {
330         /* Horrible, slow implementation */
331         while (n_bytes--) {
332                 if (*buffer != 0xFF)
333                         return 0;
334                 buffer++;
335         }
336         return 1;
337 }
338
339 static int yaffs_check_chunk_erased(struct yaffs_dev_s *dev,
340                                 int nand_chunk)
341 {
342         int retval = YAFFS_OK;
343         __u8 *data = yaffs_get_temp_buffer(dev, __LINE__);
344         yaffs_ext_tags tags;
345         int result;
346
347         result = yaffs_rd_chunk_tags_nand(dev, nand_chunk, data, &tags);
348
349         if (tags.ecc_result > YAFFS_ECC_RESULT_NO_ERROR)
350                 retval = YAFFS_FAIL;
351
352         if (!yaffs_check_ff(data, dev->data_bytes_per_chunk) || tags.chunk_used) {
353                 T(YAFFS_TRACE_NANDACCESS,
354                   (TSTR("Chunk %d not erased" TENDSTR), nand_chunk));
355                 retval = YAFFS_FAIL;
356         }
357
358         yaffs_release_temp_buffer(dev, data, __LINE__);
359
360         return retval;
361
362 }
363
364
365 static int yaffs_verify_chunk_written(yaffs_dev_t *dev,
366                                         int nand_chunk,
367                                         const __u8 *data,
368                                         yaffs_ext_tags *tags)
369 {
370         int retval = YAFFS_OK;
371         yaffs_ext_tags tempTags;
372         __u8 *buffer = yaffs_get_temp_buffer(dev,__LINE__);
373         int result;
374         
375         result = yaffs_rd_chunk_tags_nand(dev,nand_chunk,buffer,&tempTags);
376         if(memcmp(buffer,data,dev->data_bytes_per_chunk) ||
377                 tempTags.obj_id != tags->obj_id ||
378                 tempTags.chunk_id  != tags->chunk_id ||
379                 tempTags.n_bytes != tags->n_bytes)
380                 retval = YAFFS_FAIL;
381
382         yaffs_release_temp_buffer(dev, buffer, __LINE__);
383
384         return retval;
385 }
386
387 static int yaffs_write_new_chunk(struct yaffs_dev_s *dev,
388                                         const __u8 *data,
389                                         yaffs_ext_tags *tags,
390                                         int useReserve)
391 {
392         int attempts = 0;
393         int writeOk = 0;
394         int chunk;
395
396         yaffs2_checkpt_invalidate(dev);
397
398         do {
399                 yaffs_block_info_t *bi = 0;
400                 int erasedOk = 0;
401
402                 chunk = yaffs_alloc_chunk(dev, useReserve, &bi);
403                 if (chunk < 0) {
404                         /* no space */
405                         break;
406                 }
407
408                 /* First check this chunk is erased, if it needs
409                  * checking.  The checking policy (unless forced
410                  * always on) is as follows:
411                  *
412                  * Check the first page we try to write in a block.
413                  * If the check passes then we don't need to check any
414                  * more.        If the check fails, we check again...
415                  * If the block has been erased, we don't need to check.
416                  *
417                  * However, if the block has been prioritised for gc,
418                  * then we think there might be something odd about
419                  * this block and stop using it.
420                  *
421                  * Rationale: We should only ever see chunks that have
422                  * not been erased if there was a partially written
423                  * chunk due to power loss.  This checking policy should
424                  * catch that case with very few checks and thus save a
425                  * lot of checks that are most likely not needed.
426                  *
427                  * Mods to the above
428                  * If an erase check fails or the write fails we skip the 
429                  * rest of the block.
430                  */
431
432                 /* let's give it a try */
433                 attempts++;
434
435                 if(dev->param.always_check_erased)
436                         bi->skip_erased_check = 0;
437
438                 if (!bi->skip_erased_check) {
439                         erasedOk = yaffs_check_chunk_erased(dev, chunk);
440                         if (erasedOk != YAFFS_OK) {
441                                 T(YAFFS_TRACE_ERROR,
442                                 (TSTR("**>> yaffs chunk %d was not erased"
443                                 TENDSTR), chunk));
444
445                                 /* If not erased, delete this one,
446                                  * skip rest of block and
447                                  * try another chunk */
448                                  yaffs_chunk_del(dev,chunk,1,__LINE__);
449                                  yaffs_skip_rest_of_block(dev);
450                                 continue;
451                         }
452                 }
453
454                 writeOk = yaffs_wr_chunk_tags_nand(dev, chunk,
455                                 data, tags);
456
457                 if(!bi->skip_erased_check)
458                         writeOk = yaffs_verify_chunk_written(dev, chunk, data, tags);
459
460                 if (writeOk != YAFFS_OK) {
461                         /* Clean up aborted write, skip to next block and
462                          * try another chunk */
463                         yaffs_handle_chunk_wr_error(dev, chunk, erasedOk);
464                         continue;
465                 }
466
467                 bi->skip_erased_check = 1;
468
469                 /* Copy the data into the robustification buffer */
470                 yaffs_handle_chunk_wr_ok(dev, chunk, data, tags);
471
472         } while (writeOk != YAFFS_OK &&
473                 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
474
475         if (!writeOk)
476                 chunk = -1;
477
478         if (attempts > 1) {
479                 T(YAFFS_TRACE_ERROR,
480                         (TSTR("**>> yaffs write required %d attempts" TENDSTR),
481                         attempts));
482
483                 dev->n_retired_writes += (attempts - 1);
484         }
485
486         return chunk;
487 }
488
489
490  
491 /*
492  * Block retiring for handling a broken block.
493  */
494
495 static void yaffs_retire_block(yaffs_dev_t *dev, int flash_block)
496 {
497         yaffs_block_info_t *bi = yaffs_get_block_info(dev, flash_block);
498
499         yaffs2_checkpt_invalidate(dev);
500         
501         yaffs2_clear_oldest_dirty_seq(dev,bi);
502
503         if (yaffs_mark_bad(dev, flash_block) != YAFFS_OK) {
504                 if (yaffs_erase_block(dev, flash_block) != YAFFS_OK) {
505                         T(YAFFS_TRACE_ALWAYS, (TSTR(
506                                 "yaffs: Failed to mark bad and erase block %d"
507                                 TENDSTR), flash_block));
508                 } else {
509                         yaffs_ext_tags tags;
510                         int chunk_id = flash_block * dev->param.chunks_per_block;
511
512                         __u8 *buffer = yaffs_get_temp_buffer(dev, __LINE__);
513
514                         memset(buffer, 0xff, dev->data_bytes_per_chunk);
515                         yaffs_init_tags(&tags);
516                         tags.seq_number = YAFFS_SEQUENCE_BAD_BLOCK;
517                         if (dev->param.write_chunk_tags_fn(dev, chunk_id -
518                                 dev->chunk_offset, buffer, &tags) != YAFFS_OK)
519                                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
520                                         TCONT("write bad block marker to block %d")
521                                         TENDSTR), flash_block));
522
523                         yaffs_release_temp_buffer(dev, buffer, __LINE__);
524                 }
525         }
526
527         bi->block_state = YAFFS_BLOCK_STATE_DEAD;
528         bi->gc_prioritise = 0;
529         bi->needs_retiring = 0;
530
531         dev->n_retired_blocks++;
532 }
533
534 /*
535  * Functions for robustisizing TODO
536  *
537  */
538
539 static void yaffs_handle_chunk_wr_ok(yaffs_dev_t *dev, int nand_chunk,
540                                 const __u8 *data,
541                                 const yaffs_ext_tags *tags)
542 {
543         dev=dev;
544         nand_chunk=nand_chunk;
545         data=data;
546         tags=tags;
547 }
548
549 static void yaffs_handle_chunk_update(yaffs_dev_t *dev, int nand_chunk,
550                                 const yaffs_ext_tags *tags)
551 {
552         dev=dev;
553         nand_chunk=nand_chunk;
554         tags=tags;
555 }
556
557 void yaffs_handle_chunk_error(yaffs_dev_t *dev, yaffs_block_info_t *bi)
558 {
559         if (!bi->gc_prioritise) {
560                 bi->gc_prioritise = 1;
561                 dev->has_pending_prioritised_gc = 1;
562                 bi->chunk_error_strikes++;
563
564                 if (bi->chunk_error_strikes > 3) {
565                         bi->needs_retiring = 1; /* Too many stikes, so retire this */
566                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
567
568                 }
569         }
570 }
571
572 static void yaffs_handle_chunk_wr_error(yaffs_dev_t *dev, int nand_chunk,
573                 int erasedOk)
574 {
575         int flash_block = nand_chunk / dev->param.chunks_per_block;
576         yaffs_block_info_t *bi = yaffs_get_block_info(dev, flash_block);
577
578         yaffs_handle_chunk_error(dev, bi);
579
580         if (erasedOk) {
581                 /* Was an actual write failure, so mark the block for retirement  */
582                 bi->needs_retiring = 1;
583                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
584                   (TSTR("**>> Block %d needs retiring" TENDSTR), flash_block));
585         }
586
587         /* Delete the chunk */
588         yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
589         yaffs_skip_rest_of_block(dev);
590 }
591
592
593 /*---------------- Name handling functions ------------*/
594
595 static __u16 yaffs_calc_name_sum(const YCHAR *name)
596 {
597         __u16 sum = 0;
598         __u16 i = 1;
599
600         const YUCHAR *bname = (const YUCHAR *) name;
601         if (bname) {
602                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
603
604 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
605                         sum += yaffs_toupper(*bname) * i;
606 #else
607                         sum += (*bname) * i;
608 #endif
609                         i++;
610                         bname++;
611                 }
612         }
613         return sum;
614 }
615
616 void yaffs_set_obj_name(yaffs_obj_t *obj, const YCHAR *name)
617 {
618 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
619         memset(obj->short_name, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
620         if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
621                 yaffs_strcpy(obj->short_name, name);
622         else
623                 obj->short_name[0] = _Y('\0');
624 #endif
625         obj->sum = yaffs_calc_name_sum(name);
626 }
627
628 void yaffs_set_obj_name_from_oh(yaffs_obj_t *obj, const yaffs_obj_header *oh)
629 {
630 #ifdef CONFIG_YAFFS_AUTO_UNICODE
631         YCHAR tmpName[YAFFS_MAX_NAME_LENGTH+1];
632         memset(tmpName,0,sizeof(tmpName));
633         yaffs_load_name_from_oh(obj->my_dev,tmpName,oh->name,YAFFS_MAX_NAME_LENGTH+1);
634         yaffs_set_obj_name(obj,tmpName);
635 #else
636         yaffs_set_obj_name(obj,oh->name);
637 #endif
638 }
639
640 /*-------------------- TNODES -------------------
641
642  * List of spare tnodes
643  * The list is hooked together using the first pointer
644  * in the tnode.
645  */
646
647
648 yaffs_tnode_t *yaffs_get_tnode(yaffs_dev_t *dev)
649 {
650         yaffs_tnode_t *tn = yaffs_alloc_raw_tnode(dev);
651         if (tn){
652                 memset(tn, 0, dev->tnode_size);
653                 dev->n_tnodes++;
654         }
655
656         dev->checkpoint_blocks_required = 0; /* force recalculation*/
657
658         return tn;
659 }
660
661 /* FreeTnode frees up a tnode and puts it back on the free list */
662 static void yaffs_free_tnode(yaffs_dev_t *dev, yaffs_tnode_t *tn)
663 {
664         yaffs_free_raw_tnode(dev,tn);
665         dev->n_tnodes--;
666         dev->checkpoint_blocks_required = 0; /* force recalculation*/
667 }
668
669 static void yaffs_deinit_tnodes_and_objs(yaffs_dev_t *dev)
670 {
671         yaffs_deinit_raw_tnodes_and_objs(dev);
672         dev->n_obj = 0;
673         dev->n_tnodes = 0;
674 }
675
676
677 void yaffs_load_tnode_0(yaffs_dev_t *dev, yaffs_tnode_t *tn, unsigned pos,
678                 unsigned val)
679 {
680         __u32 *map = (__u32 *)tn;
681         __u32 bitInMap;
682         __u32 bitInWord;
683         __u32 wordInMap;
684         __u32 mask;
685
686         pos &= YAFFS_TNODES_LEVEL0_MASK;
687         val >>= dev->chunk_grp_bits;
688
689         bitInMap = pos * dev->tnode_width;
690         wordInMap = bitInMap / 32;
691         bitInWord = bitInMap & (32 - 1);
692
693         mask = dev->tnode_mask << bitInWord;
694
695         map[wordInMap] &= ~mask;
696         map[wordInMap] |= (mask & (val << bitInWord));
697
698         if (dev->tnode_width > (32 - bitInWord)) {
699                 bitInWord = (32 - bitInWord);
700                 wordInMap++;;
701                 mask = dev->tnode_mask >> (/*dev->tnode_width -*/ bitInWord);
702                 map[wordInMap] &= ~mask;
703                 map[wordInMap] |= (mask & (val >> bitInWord));
704         }
705 }
706
707 __u32 yaffs_get_group_base(yaffs_dev_t *dev, yaffs_tnode_t *tn,
708                 unsigned pos)
709 {
710         __u32 *map = (__u32 *)tn;
711         __u32 bitInMap;
712         __u32 bitInWord;
713         __u32 wordInMap;
714         __u32 val;
715
716         pos &= YAFFS_TNODES_LEVEL0_MASK;
717
718         bitInMap = pos * dev->tnode_width;
719         wordInMap = bitInMap / 32;
720         bitInWord = bitInMap & (32 - 1);
721
722         val = map[wordInMap] >> bitInWord;
723
724         if      (dev->tnode_width > (32 - bitInWord)) {
725                 bitInWord = (32 - bitInWord);
726                 wordInMap++;;
727                 val |= (map[wordInMap] << bitInWord);
728         }
729
730         val &= dev->tnode_mask;
731         val <<= dev->chunk_grp_bits;
732
733         return val;
734 }
735
736 /* ------------------- End of individual tnode manipulation -----------------*/
737
738 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
739  * The look up tree is represented by the top tnode and the number of top_level
740  * in the tree. 0 means only the level 0 tnode is in the tree.
741  */
742
743 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
744 yaffs_tnode_t *yaffs_find_tnode_0(yaffs_dev_t *dev,
745                                         yaffs_file_s *file_struct,
746                                         __u32 chunk_id)
747 {
748         yaffs_tnode_t *tn = file_struct->top;
749         __u32 i;
750         int requiredTallness;
751         int level = file_struct->top_level;
752
753         dev=dev;
754
755         /* Check sane level and chunk Id */
756         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
757                 return NULL;
758
759         if (chunk_id > YAFFS_MAX_CHUNK_ID)
760                 return NULL;
761
762         /* First check we're tall enough (ie enough top_level) */
763
764         i = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
765         requiredTallness = 0;
766         while (i) {
767                 i >>= YAFFS_TNODES_INTERNAL_BITS;
768                 requiredTallness++;
769         }
770
771         if (requiredTallness > file_struct->top_level)
772                 return NULL; /* Not tall enough, so we can't find it */
773
774         /* Traverse down to level 0 */
775         while (level > 0 && tn) {
776                 tn = tn->internal[(chunk_id >>
777                         (YAFFS_TNODES_LEVEL0_BITS +
778                                 (level - 1) *
779                                 YAFFS_TNODES_INTERNAL_BITS)) &
780                         YAFFS_TNODES_INTERNAL_MASK];
781                 level--;
782         }
783
784         return tn;
785 }
786
787 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
788  * This happens in two steps:
789  *  1. If the tree isn't tall enough, then make it taller.
790  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
791  *
792  * Used when modifying the tree.
793  *
794  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
795  *  be plugged into the ttree.
796  */
797
798 yaffs_tnode_t *yaffs_add_find_tnode_0(yaffs_dev_t *dev,
799                                         yaffs_file_s *file_struct,
800                                         __u32 chunk_id,
801                                         yaffs_tnode_t *passed_tn)
802 {
803         int requiredTallness;
804         int i;
805         int l;
806         yaffs_tnode_t *tn;
807
808         __u32 x;
809
810
811         /* Check sane level and page Id */
812         if (file_struct->top_level < 0 || file_struct->top_level > YAFFS_TNODES_MAX_LEVEL)
813                 return NULL;
814
815         if (chunk_id > YAFFS_MAX_CHUNK_ID)
816                 return NULL;
817
818         /* First check we're tall enough (ie enough top_level) */
819
820         x = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
821         requiredTallness = 0;
822         while (x) {
823                 x >>= YAFFS_TNODES_INTERNAL_BITS;
824                 requiredTallness++;
825         }
826
827
828         if (requiredTallness > file_struct->top_level) {
829                 /* Not tall enough, gotta make the tree taller */
830                 for (i = file_struct->top_level; i < requiredTallness; i++) {
831
832                         tn = yaffs_get_tnode(dev);
833
834                         if (tn) {
835                                 tn->internal[0] = file_struct->top;
836                                 file_struct->top = tn;
837                                 file_struct->top_level++;
838                         } else {
839                                 T(YAFFS_TRACE_ERROR,
840                                         (TSTR("yaffs: no more tnodes" TENDSTR)));
841                                 return NULL;
842                         }
843                 }
844         }
845
846         /* Traverse down to level 0, adding anything we need */
847
848         l = file_struct->top_level;
849         tn = file_struct->top;
850
851         if (l > 0) {
852                 while (l > 0 && tn) {
853                         x = (chunk_id >>
854                              (YAFFS_TNODES_LEVEL0_BITS +
855                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
856                             YAFFS_TNODES_INTERNAL_MASK;
857
858
859                         if ((l > 1) && !tn->internal[x]) {
860                                 /* Add missing non-level-zero tnode */
861                                 tn->internal[x] = yaffs_get_tnode(dev);
862                                 if(!tn->internal[x])
863                                         return NULL;
864                         } else if (l == 1) {
865                                 /* Looking from level 1 at level 0 */
866                                 if (passed_tn) {
867                                         /* If we already have one, then release it.*/
868                                         if (tn->internal[x])
869                                                 yaffs_free_tnode(dev, tn->internal[x]);
870                                         tn->internal[x] = passed_tn;
871
872                                 } else if (!tn->internal[x]) {
873                                         /* Don't have one, none passed in */
874                                         tn->internal[x] = yaffs_get_tnode(dev);
875                                         if(!tn->internal[x])
876                                                 return NULL;
877                                 }
878                         }
879
880                         tn = tn->internal[x];
881                         l--;
882                 }
883         } else {
884                 /* top is level 0 */
885                 if (passed_tn) {
886                         memcpy(tn, passed_tn, (dev->tnode_width * YAFFS_NTNODES_LEVEL0)/8);
887                         yaffs_free_tnode(dev, passed_tn);
888                 }
889         }
890
891         return tn;
892 }
893
894 static int yaffs_find_chunk_in_group(yaffs_dev_t *dev, int theChunk,
895                                 yaffs_ext_tags *tags, int obj_id,
896                                 int inode_chunk)
897 {
898         int j;
899
900         for (j = 0; theChunk && j < dev->chunk_grp_size; j++) {
901                 if (yaffs_check_chunk_bit(dev, theChunk / dev->param.chunks_per_block,
902                                 theChunk % dev->param.chunks_per_block)) {
903                         
904                         if(dev->chunk_grp_size == 1)
905                                 return theChunk;
906                         else {
907                                 yaffs_rd_chunk_tags_nand(dev, theChunk, NULL,
908                                                                 tags);
909                                 if (yaffs_tags_match(tags, obj_id, inode_chunk)) {
910                                         /* found it; */
911                                         return theChunk;
912                                 }
913                         }
914                 }
915                 theChunk++;
916         }
917         return -1;
918 }
919
920 #if 0
921 /* Experimental code not being used yet. Might speed up file deletion */
922 /* DeleteWorker scans backwards through the tnode tree and deletes all the
923  * chunks and tnodes in the file.
924  * Returns 1 if the tree was deleted.
925  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
926  */
927
928 static int yaffs_del_worker(yaffs_obj_t *in, yaffs_tnode_t *tn, __u32 level,
929                               int chunk_offset, int *limit)
930 {
931         int i;
932         int inode_chunk;
933         int theChunk;
934         yaffs_ext_tags tags;
935         int foundChunk;
936         yaffs_dev_t *dev = in->my_dev;
937
938         int allDone = 1;
939
940         if (tn) {
941                 if (level > 0) {
942                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
943                              i--) {
944                                 if (tn->internal[i]) {
945                                         if (limit && (*limit) < 0) {
946                                                 allDone = 0;
947                                         } else {
948                                                 allDone =
949                                                         yaffs_del_worker(in,
950                                                                 tn->
951                                                                 internal
952                                                                 [i],
953                                                                 level -
954                                                                 1,
955                                                                 (chunk_offset
956                                                                         <<
957                                                                         YAFFS_TNODES_INTERNAL_BITS)
958                                                                 + i,
959                                                                 limit);
960                                         }
961                                         if (allDone) {
962                                                 yaffs_free_tnode(dev,
963                                                                 tn->
964                                                                 internal[i]);
965                                                 tn->internal[i] = NULL;
966                                         }
967                                 }
968                         }
969                         return (allDone) ? 1 : 0;
970                 } else if (level == 0) {
971                         int hitLimit = 0;
972
973                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
974                                         i--) {
975                                 theChunk = yaffs_get_group_base(dev, tn, i);
976                                 if (theChunk) {
977
978                                         inode_chunk = (chunk_offset <<
979                                                 YAFFS_TNODES_LEVEL0_BITS) + i;
980
981                                         foundChunk =
982                                                 yaffs_find_chunk_in_group(dev,
983                                                                 theChunk,
984                                                                 &tags,
985                                                                 in->obj_id,
986                                                                 inode_chunk);
987
988                                         if (foundChunk > 0) {
989                                                 yaffs_chunk_del(dev,
990                                                                   foundChunk, 1,
991                                                                   __LINE__);
992                                                 in->n_data_chunks--;
993                                                 if (limit) {
994                                                         *limit = *limit - 1;
995                                                         if (*limit <= 0)
996                                                                 hitLimit = 1;
997                                                 }
998
999                                         }
1000
1001                                         yaffs_load_tnode_0(dev, tn, i, 0);
1002                                 }
1003
1004                         }
1005                         return (i < 0) ? 1 : 0;
1006
1007                 }
1008
1009         }
1010
1011         return 1;
1012
1013 }
1014
1015 #endif
1016
1017 static void yaffs_soft_del_chunk(yaffs_dev_t *dev, int chunk)
1018 {
1019         yaffs_block_info_t *theBlock;
1020         unsigned block_no;
1021
1022         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1023
1024         block_no =  chunk / dev->param.chunks_per_block;
1025         theBlock = yaffs_get_block_info(dev, block_no);
1026         if (theBlock) {
1027                 theBlock->soft_del_pages++;
1028                 dev->n_free_chunks++;
1029                 yaffs2_update_oldest_dirty_seq(dev, block_no, theBlock);
1030         }
1031 }
1032
1033 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1034  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1035  * of the tnode.
1036  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1037  */
1038
1039 static int yaffs_soft_del_worker(yaffs_obj_t *in, yaffs_tnode_t *tn,
1040                                   __u32 level, int chunk_offset)
1041 {
1042         int i;
1043         int theChunk;
1044         int allDone = 1;
1045         yaffs_dev_t *dev = in->my_dev;
1046
1047         if (tn) {
1048                 if (level > 0) {
1049
1050                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1051                              i--) {
1052                                 if (tn->internal[i]) {
1053                                         allDone =
1054                                             yaffs_soft_del_worker(in,
1055                                                                    tn->
1056                                                                    internal[i],
1057                                                                    level - 1,
1058                                                                    (chunk_offset
1059                                                                     <<
1060                                                                     YAFFS_TNODES_INTERNAL_BITS)
1061                                                                    + i);
1062                                         if (allDone) {
1063                                                 yaffs_free_tnode(dev,
1064                                                                 tn->
1065                                                                 internal[i]);
1066                                                 tn->internal[i] = NULL;
1067                                         } else {
1068                                                 /* Hoosterman... how could this happen? */
1069                                         }
1070                                 }
1071                         }
1072                         return (allDone) ? 1 : 0;
1073                 } else if (level == 0) {
1074
1075                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1076                                 theChunk = yaffs_get_group_base(dev, tn, i);
1077                                 if (theChunk) {
1078                                         /* Note this does not find the real chunk, only the chunk group.
1079                                          * We make an assumption that a chunk group is not larger than
1080                                          * a block.
1081                                          */
1082                                         yaffs_soft_del_chunk(dev, theChunk);
1083                                         yaffs_load_tnode_0(dev, tn, i, 0);
1084                                 }
1085
1086                         }
1087                         return 1;
1088
1089                 }
1090
1091         }
1092
1093         return 1;
1094
1095 }
1096
1097 static void yaffs_soft_del_file(yaffs_obj_t *obj)
1098 {
1099         if (obj->deleted &&
1100             obj->variant_type == YAFFS_OBJECT_TYPE_FILE && !obj->soft_del) {
1101                 if (obj->n_data_chunks <= 0) {
1102                         /* Empty file with no duplicate object headers, just delete it immediately */
1103                         yaffs_free_tnode(obj->my_dev,
1104                                         obj->variant.file_variant.top);
1105                         obj->variant.file_variant.top = NULL;
1106                         T(YAFFS_TRACE_TRACING,
1107                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1108                            obj->obj_id));
1109                         yaffs_generic_obj_del(obj);
1110                 } else {
1111                         yaffs_soft_del_worker(obj,
1112                                                obj->variant.file_variant.top,
1113                                                obj->variant.file_variant.
1114                                                top_level, 0);
1115                         obj->soft_del = 1;
1116                 }
1117         }
1118 }
1119
1120 /* Pruning removes any part of the file structure tree that is beyond the
1121  * bounds of the file (ie that does not point to chunks).
1122  *
1123  * A file should only get pruned when its size is reduced.
1124  *
1125  * Before pruning, the chunks must be pulled from the tree and the
1126  * level 0 tnode entries must be zeroed out.
1127  * Could also use this for file deletion, but that's probably better handled
1128  * by a special case.
1129  *
1130  * This function is recursive. For levels > 0 the function is called again on
1131  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1132  * If there is no data in a subtree then it is pruned.
1133  */
1134
1135 static yaffs_tnode_t *yaffs_prune_worker(yaffs_dev_t *dev, yaffs_tnode_t *tn,
1136                                 __u32 level, int del0)
1137 {
1138         int i;
1139         int hasData;
1140
1141         if (tn) {
1142                 hasData = 0;
1143
1144                 if(level > 0){
1145                         for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1146                                 if (tn->internal[i]) {
1147                                         tn->internal[i] =
1148                                                 yaffs_prune_worker(dev, tn->internal[i],
1149                                                         level - 1,
1150                                                         (i == 0) ? del0 : 1);
1151                                 }
1152
1153                                 if (tn->internal[i])
1154                                         hasData++;
1155                         }
1156                 } else {
1157                         int tnode_size_u32 = dev->tnode_size/sizeof(__u32);
1158                         __u32 *map = (__u32 *)tn;
1159
1160                         for(i = 0; !hasData && i < tnode_size_u32; i++){
1161                                 if(map[i])
1162                                         hasData++;
1163                         }
1164                 }
1165
1166                 if (hasData == 0 && del0) {
1167                         /* Free and return NULL */
1168
1169                         yaffs_free_tnode(dev, tn);
1170                         tn = NULL;
1171                 }
1172
1173         }
1174
1175         return tn;
1176
1177 }
1178
1179 static int yaffs_prune_tree(yaffs_dev_t *dev,
1180                                 yaffs_file_s *file_struct)
1181 {
1182         int i;
1183         int hasData;
1184         int done = 0;
1185         yaffs_tnode_t *tn;
1186
1187         if (file_struct->top_level > 0) {
1188                 file_struct->top =
1189                     yaffs_prune_worker(dev, file_struct->top, file_struct->top_level, 0);
1190
1191                 /* Now we have a tree with all the non-zero branches NULL but the height
1192                  * is the same as it was.
1193                  * Let's see if we can trim internal tnodes to shorten the tree.
1194                  * We can do this if only the 0th element in the tnode is in use
1195                  * (ie all the non-zero are NULL)
1196                  */
1197
1198                 while (file_struct->top_level && !done) {
1199                         tn = file_struct->top;
1200
1201                         hasData = 0;
1202                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1203                                 if (tn->internal[i])
1204                                         hasData++;
1205                         }
1206
1207                         if (!hasData) {
1208                                 file_struct->top = tn->internal[0];
1209                                 file_struct->top_level--;
1210                                 yaffs_free_tnode(dev, tn);
1211                         } else {
1212                                 done = 1;
1213                         }
1214                 }
1215         }
1216
1217         return YAFFS_OK;
1218 }
1219
1220 /*-------------------- End of File Structure functions.-------------------*/
1221
1222
1223 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1224 static yaffs_obj_t *yaffs_alloc_empty_obj(yaffs_dev_t *dev)
1225 {
1226         yaffs_obj_t *obj = yaffs_alloc_raw_obj(dev);
1227
1228         if (obj) {
1229                 dev->n_obj++;
1230
1231                 /* Now sweeten it up... */
1232
1233                 memset(obj, 0, sizeof(yaffs_obj_t));
1234                 obj->being_created = 1;
1235
1236                 obj->my_dev = dev;
1237                 obj->hdr_chunk = 0;
1238                 obj->variant_type = YAFFS_OBJECT_TYPE_UNKNOWN;
1239                 YINIT_LIST_HEAD(&(obj->hard_links));
1240                 YINIT_LIST_HEAD(&(obj->hash_link));
1241                 YINIT_LIST_HEAD(&obj->siblings);
1242
1243
1244                 /* Now make the directory sane */
1245                 if (dev->root_dir) {
1246                         obj->parent = dev->root_dir;
1247                         ylist_add(&(obj->siblings), &dev->root_dir->variant.dir_variant.children);
1248                 }
1249
1250                 /* Add it to the lost and found directory.
1251                  * NB Can't put root or lostNFound in lostNFound so
1252                  * check if lostNFound exists first
1253                  */
1254                 if (dev->lost_n_found)
1255                         yaffs_add_obj_to_dir(dev->lost_n_found, obj);
1256
1257                 obj->being_created = 0;
1258         }
1259
1260         dev->checkpoint_blocks_required = 0; /* force recalculation*/
1261
1262         return obj;
1263 }
1264
1265 static yaffs_obj_t *yaffs_create_fake_dir(yaffs_dev_t *dev, int number,
1266                                                __u32 mode)
1267 {
1268
1269         yaffs_obj_t *obj =
1270             yaffs_new_obj(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1271         if (obj) {
1272                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
1273                 obj->rename_allowed = 0;        /* ... and we're not allowed to rename it... */
1274                 obj->unlink_allowed = 0;        /* ... or unlink it */
1275                 obj->deleted = 0;
1276                 obj->unlinked = 0;
1277                 obj->yst_mode = mode;
1278                 obj->my_dev = dev;
1279                 obj->hdr_chunk = 0;     /* Not a valid chunk. */
1280         }
1281
1282         return obj;
1283
1284 }
1285
1286 static void yaffs_unhash_obj(yaffs_obj_t *obj)
1287 {
1288         int bucket;
1289         yaffs_dev_t *dev = obj->my_dev;
1290
1291         /* If it is still linked into the bucket list, free from the list */
1292         if (!ylist_empty(&obj->hash_link)) {
1293                 ylist_del_init(&obj->hash_link);
1294                 bucket = yaffs_hash_fn(obj->obj_id);
1295                 dev->obj_bucket[bucket].count--;
1296         }
1297 }
1298
1299 /*  FreeObject frees up a Object and puts it back on the free list */
1300 static void yaffs_free_obj(yaffs_obj_t *obj)
1301 {
1302         yaffs_dev_t *dev = obj->my_dev;
1303
1304         T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), obj, obj->my_inode));
1305
1306         if (!obj)
1307                 YBUG();
1308         if (obj->parent)
1309                 YBUG();
1310         if (!ylist_empty(&obj->siblings))
1311                 YBUG();
1312
1313
1314         if (obj->my_inode) {
1315                 /* We're still hooked up to a cached inode.
1316                  * Don't delete now, but mark for later deletion
1317                  */
1318                 obj->defered_free = 1;
1319                 return;
1320         }
1321
1322         yaffs_unhash_obj(obj);
1323
1324         yaffs_free_raw_obj(dev,obj);
1325         dev->n_obj--;
1326         dev->checkpoint_blocks_required = 0; /* force recalculation*/
1327 }
1328
1329
1330 void yaffs_handle_defered_free(yaffs_obj_t *obj)
1331 {
1332         if (obj->defered_free)
1333                 yaffs_free_obj(obj);
1334 }
1335
1336 static void yaffs_init_tnodes_and_objs(yaffs_dev_t *dev)
1337 {
1338         int i;
1339
1340         dev->n_obj = 0;
1341         dev->n_tnodes = 0;
1342
1343         yaffs_init_raw_tnodes_and_objs(dev);
1344
1345         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1346                 YINIT_LIST_HEAD(&dev->obj_bucket[i].list);
1347                 dev->obj_bucket[i].count = 0;
1348         }
1349 }
1350
1351 static int yaffs_find_nice_bucket(yaffs_dev_t *dev)
1352 {
1353         int i;
1354         int l = 999;
1355         int lowest = 999999;
1356
1357
1358         /* Search for the shortest list or one that
1359          * isn't too long.
1360          */
1361
1362         for (i = 0; i < 10 && lowest > 4; i++) {
1363                 dev->bucket_finder++;
1364                 dev->bucket_finder %= YAFFS_NOBJECT_BUCKETS;
1365                 if (dev->obj_bucket[dev->bucket_finder].count < lowest) {
1366                         lowest = dev->obj_bucket[dev->bucket_finder].count;
1367                         l = dev->bucket_finder;
1368                 }
1369
1370         }
1371
1372         return l;
1373 }
1374
1375 static int yaffs_new_obj_id(yaffs_dev_t *dev)
1376 {
1377         int bucket = yaffs_find_nice_bucket(dev);
1378
1379         /* Now find an object value that has not already been taken
1380          * by scanning the list.
1381          */
1382
1383         int found = 0;
1384         struct ylist_head *i;
1385
1386         __u32 n = (__u32) bucket;
1387
1388         /* yaffs_check_obj_hash_sane();  */
1389
1390         while (!found) {
1391                 found = 1;
1392                 n += YAFFS_NOBJECT_BUCKETS;
1393                 if (1 || dev->obj_bucket[bucket].count > 0) {
1394                         ylist_for_each(i, &dev->obj_bucket[bucket].list) {
1395                                 /* If there is already one in the list */
1396                                 if (i && ylist_entry(i, yaffs_obj_t,
1397                                                 hash_link)->obj_id == n) {
1398                                         found = 0;
1399                                 }
1400                         }
1401                 }
1402         }
1403
1404         return n;
1405 }
1406
1407 static void yaffs_hash_obj(yaffs_obj_t *in)
1408 {
1409         int bucket = yaffs_hash_fn(in->obj_id);
1410         yaffs_dev_t *dev = in->my_dev;
1411
1412         ylist_add(&in->hash_link, &dev->obj_bucket[bucket].list);
1413         dev->obj_bucket[bucket].count++;
1414 }
1415
1416 yaffs_obj_t *yaffs_find_by_number(yaffs_dev_t *dev, __u32 number)
1417 {
1418         int bucket = yaffs_hash_fn(number);
1419         struct ylist_head *i;
1420         yaffs_obj_t *in;
1421
1422         ylist_for_each(i, &dev->obj_bucket[bucket].list) {
1423                 /* Look if it is in the list */
1424                 if (i) {
1425                         in = ylist_entry(i, yaffs_obj_t, hash_link);
1426                         if (in->obj_id == number) {
1427
1428                                 /* Don't tell the VFS about this one if it is defered free */
1429                                 if (in->defered_free)
1430                                         return NULL;
1431
1432                                 return in;
1433                         }
1434                 }
1435         }
1436
1437         return NULL;
1438 }
1439
1440 yaffs_obj_t *yaffs_new_obj(yaffs_dev_t *dev, int number,
1441                                     yaffs_obj_type type)
1442 {
1443         yaffs_obj_t *theObject=NULL;
1444         yaffs_tnode_t *tn = NULL;
1445
1446         if (number < 0)
1447                 number = yaffs_new_obj_id(dev);
1448
1449         if (type == YAFFS_OBJECT_TYPE_FILE) {
1450                 tn = yaffs_get_tnode(dev);
1451                 if (!tn)
1452                         return NULL;
1453         }
1454
1455         theObject = yaffs_alloc_empty_obj(dev);
1456         if (!theObject){
1457                 if(tn)
1458                         yaffs_free_tnode(dev,tn);
1459                 return NULL;
1460         }
1461
1462
1463         if (theObject) {
1464                 theObject->fake = 0;
1465                 theObject->rename_allowed = 1;
1466                 theObject->unlink_allowed = 1;
1467                 theObject->obj_id = number;
1468                 yaffs_hash_obj(theObject);
1469                 theObject->variant_type = type;
1470 #ifdef CONFIG_YAFFS_WINCE
1471                 yfsd_win_file_time_now(theObject->win_atime);
1472                 theObject->win_ctime[0] = theObject->win_mtime[0] =
1473                     theObject->win_atime[0];
1474                 theObject->win_ctime[1] = theObject->win_mtime[1] =
1475                     theObject->win_atime[1];
1476
1477 #else
1478
1479                 theObject->yst_atime = theObject->yst_mtime =
1480                     theObject->yst_ctime = Y_CURRENT_TIME;
1481 #endif
1482                 switch (type) {
1483                 case YAFFS_OBJECT_TYPE_FILE:
1484                         theObject->variant.file_variant.file_size = 0;
1485                         theObject->variant.file_variant.scanned_size = 0;
1486                         theObject->variant.file_variant.shrink_size = 0xFFFFFFFF;       /* max __u32 */
1487                         theObject->variant.file_variant.top_level = 0;
1488                         theObject->variant.file_variant.top = tn;
1489                         break;
1490                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1491                         YINIT_LIST_HEAD(&theObject->variant.dir_variant.
1492                                         children);
1493                         YINIT_LIST_HEAD(&theObject->variant.dir_variant.
1494                                         dirty);
1495                         break;
1496                 case YAFFS_OBJECT_TYPE_SYMLINK:
1497                 case YAFFS_OBJECT_TYPE_HARDLINK:
1498                 case YAFFS_OBJECT_TYPE_SPECIAL:
1499                         /* No action required */
1500                         break;
1501                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1502                         /* todo this should not happen */
1503                         break;
1504                 }
1505         }
1506
1507         return theObject;
1508 }
1509
1510 yaffs_obj_t *yaffs_find_or_create_by_number(yaffs_dev_t *dev,
1511                                                 int number,
1512                                                 yaffs_obj_type type)
1513 {
1514         yaffs_obj_t *theObject = NULL;
1515
1516         if (number > 0)
1517                 theObject = yaffs_find_by_number(dev, number);
1518
1519         if (!theObject)
1520                 theObject = yaffs_new_obj(dev, number, type);
1521
1522         return theObject;
1523
1524 }
1525
1526
1527 YCHAR *yaffs_clone_str(const YCHAR *str)
1528 {
1529         YCHAR *newStr = NULL;
1530         int len;
1531
1532         if (!str)
1533                 str = _Y("");
1534
1535         len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
1536         newStr = YMALLOC((len + 1) * sizeof(YCHAR));
1537         if (newStr){
1538                 yaffs_strncpy(newStr, str,len);
1539                 newStr[len] = 0;
1540         }
1541         return newStr;
1542
1543 }
1544
1545 /*
1546  * Mknod (create) a new object.
1547  * equiv_obj only has meaning for a hard link;
1548  * aliasString only has meaning for a symlink.
1549  * rdev only has meaning for devices (a subset of special objects)
1550  */
1551
1552 static yaffs_obj_t *yaffs_create_obj(yaffs_obj_type type,
1553                                        yaffs_obj_t *parent,
1554                                        const YCHAR *name,
1555                                        __u32 mode,
1556                                        __u32 uid,
1557                                        __u32 gid,
1558                                        yaffs_obj_t *equiv_obj,
1559                                        const YCHAR *aliasString, __u32 rdev)
1560 {
1561         yaffs_obj_t *in;
1562         YCHAR *str = NULL;
1563
1564         yaffs_dev_t *dev = parent->my_dev;
1565
1566         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1567         if (yaffs_find_by_name(parent, name))
1568                 return NULL;
1569
1570         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
1571                 str = yaffs_clone_str(aliasString);
1572                 if (!str)
1573                         return NULL;
1574         }
1575
1576         in = yaffs_new_obj(dev, -1, type);
1577
1578         if (!in){
1579                 if(str)
1580                         YFREE(str);
1581                 return NULL;
1582         }
1583
1584
1585
1586
1587
1588         if (in) {
1589                 in->hdr_chunk = 0;
1590                 in->valid = 1;
1591                 in->variant_type = type;
1592
1593                 in->yst_mode = mode;
1594
1595 #ifdef CONFIG_YAFFS_WINCE
1596                 yfsd_win_file_time_now(in->win_atime);
1597                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1598                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1599
1600 #else
1601                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1602
1603                 in->yst_rdev = rdev;
1604                 in->yst_uid = uid;
1605                 in->yst_gid = gid;
1606 #endif
1607                 in->n_data_chunks = 0;
1608
1609                 yaffs_set_obj_name(in, name);
1610                 in->dirty = 1;
1611
1612                 yaffs_add_obj_to_dir(parent, in);
1613
1614                 in->my_dev = parent->my_dev;
1615
1616                 switch (type) {
1617                 case YAFFS_OBJECT_TYPE_SYMLINK:
1618                         in->variant.symlink_variant.alias = str;
1619                         break;
1620                 case YAFFS_OBJECT_TYPE_HARDLINK:
1621                         in->variant.hardlink_variant.equiv_obj =
1622                                 equiv_obj;
1623                         in->variant.hardlink_variant.equiv_id =
1624                                 equiv_obj->obj_id;
1625                         ylist_add(&in->hard_links, &equiv_obj->hard_links);
1626                         break;
1627                 case YAFFS_OBJECT_TYPE_FILE:
1628                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1629                 case YAFFS_OBJECT_TYPE_SPECIAL:
1630                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1631                         /* do nothing */
1632                         break;
1633                 }
1634
1635                 if (yaffs_update_oh(in, name, 0, 0, 0, NULL) < 0) {
1636                         /* Could not create the object header, fail the creation */
1637                         yaffs_del_obj(in);
1638                         in = NULL;
1639                 }
1640
1641                 yaffs_update_parent(parent);
1642         }
1643
1644         return in;
1645 }
1646
1647 yaffs_obj_t *yaffs_create_file(yaffs_obj_t *parent, const YCHAR *name,
1648                         __u32 mode, __u32 uid, __u32 gid)
1649 {
1650         return yaffs_create_obj(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1651                                 uid, gid, NULL, NULL, 0);
1652 }
1653
1654 yaffs_obj_t *yaffs_create_dir(yaffs_obj_t *parent, const YCHAR *name,
1655                                 __u32 mode, __u32 uid, __u32 gid)
1656 {
1657         return yaffs_create_obj(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1658                                  mode, uid, gid, NULL, NULL, 0);
1659 }
1660
1661 yaffs_obj_t *yaffs_create_special(yaffs_obj_t *parent, const YCHAR *name,
1662                                 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1663 {
1664         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1665                                  uid, gid, NULL, NULL, rdev);
1666 }
1667
1668 yaffs_obj_t *yaffs_create_symlink(yaffs_obj_t *parent, const YCHAR *name,
1669                                 __u32 mode, __u32 uid, __u32 gid,
1670                                 const YCHAR *alias)
1671 {
1672         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1673                                 uid, gid, NULL, alias, 0);
1674 }
1675
1676 /* yaffs_link_obj returns the object id of the equivalent object.*/
1677 yaffs_obj_t *yaffs_link_obj(yaffs_obj_t *parent, const YCHAR *name,
1678                         yaffs_obj_t *equiv_obj)
1679 {
1680         /* Get the real object in case we were fed a hard link as an equivalent object */
1681         equiv_obj = yaffs_get_equivalent_obj(equiv_obj);
1682
1683         if (yaffs_create_obj
1684             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1685              equiv_obj, NULL, 0)) {
1686                 return equiv_obj;
1687         } else {
1688                 return NULL;
1689         }
1690
1691 }
1692
1693 static int yaffs_change_obj_name(yaffs_obj_t *obj, yaffs_obj_t *new_dir,
1694                                 const YCHAR *new_name, int force, int shadows)
1695 {
1696         int unlinkOp;
1697         int deleteOp;
1698
1699         yaffs_obj_t *existingTarget;
1700
1701         if (new_dir == NULL)
1702                 new_dir = obj->parent;  /* use the old directory */
1703
1704         if (new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
1705                 T(YAFFS_TRACE_ALWAYS,
1706                   (TSTR
1707                    ("tragedy: yaffs_change_obj_name: new_dir is not a directory"
1708                     TENDSTR)));
1709                 YBUG();
1710         }
1711
1712         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1713         if (obj->my_dev->param.is_yaffs2)
1714                 unlinkOp = (new_dir == obj->my_dev->unlinked_dir);
1715         else
1716                 unlinkOp = (new_dir == obj->my_dev->unlinked_dir
1717                             && obj->variant_type == YAFFS_OBJECT_TYPE_FILE);
1718
1719         deleteOp = (new_dir == obj->my_dev->del_dir);
1720
1721         existingTarget = yaffs_find_by_name(new_dir, new_name);
1722
1723         /* If the object is a file going into the unlinked directory,
1724          *   then it is OK to just stuff it in since duplicate names are allowed.
1725          *   else only proceed if the new name does not exist and if we're putting
1726          *   it into a directory.
1727          */
1728         if ((unlinkOp ||
1729              deleteOp ||
1730              force ||
1731              (shadows > 0) ||
1732              !existingTarget) &&
1733             new_dir->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY) {
1734                 yaffs_set_obj_name(obj, new_name);
1735                 obj->dirty = 1;
1736
1737                 yaffs_add_obj_to_dir(new_dir, obj);
1738
1739                 if (unlinkOp)
1740                         obj->unlinked = 1;
1741
1742                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1743                 if (yaffs_update_oh(obj, new_name, 0, deleteOp, shadows, NULL) >= 0)
1744                         return YAFFS_OK;
1745         }
1746
1747         return YAFFS_FAIL;
1748 }
1749
1750 int yaffs_rename_obj(yaffs_obj_t *old_dir, const YCHAR *old_name,
1751                 yaffs_obj_t *new_dir, const YCHAR *new_name)
1752 {
1753         yaffs_obj_t *obj = NULL;
1754         yaffs_obj_t *existingTarget = NULL;
1755         int force = 0;
1756         int result;
1757         yaffs_dev_t *dev;
1758
1759
1760         if (!old_dir || old_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1761                 YBUG();
1762         if (!new_dir || new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1763                 YBUG();
1764
1765         dev = old_dir->my_dev;
1766
1767 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1768         /* Special case for case insemsitive systems (eg. WinCE).
1769          * While look-up is case insensitive, the name isn't.
1770          * Therefore we might want to change x.txt to X.txt
1771         */
1772         if (old_dir == new_dir && yaffs_strcmp(old_name, new_name) == 0)
1773                 force = 1;
1774 #endif
1775
1776         if(yaffs_strnlen(new_name,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
1777                 /* ENAMETOOLONG */
1778                 return YAFFS_FAIL;
1779
1780         obj = yaffs_find_by_name(old_dir, old_name);
1781
1782         if (obj && obj->rename_allowed) {
1783
1784                 /* Now do the handling for an existing target, if there is one */
1785
1786                 existingTarget = yaffs_find_by_name(new_dir, new_name);
1787                 if (existingTarget &&
1788                         existingTarget->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY &&
1789                         !ylist_empty(&existingTarget->variant.dir_variant.children)) {
1790                         /* There is a target that is a non-empty directory, so we fail */
1791                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
1792                 } else if (existingTarget && existingTarget != obj) {
1793                         /* Nuke the target first, using shadowing,
1794                          * but only if it isn't the same object.
1795                          *
1796                          * Note we must disable gc otherwise it can mess up the shadowing.
1797                          *
1798                          */
1799                         dev->gc_disable=1;
1800                         yaffs_change_obj_name(obj, new_dir, new_name, force,
1801                                                 existingTarget->obj_id);
1802                         existingTarget->is_shadowed = 1;
1803                         yaffs_unlink_obj(existingTarget);
1804                         dev->gc_disable=0;
1805                 }
1806
1807                 result = yaffs_change_obj_name(obj, new_dir, new_name, 1, 0);
1808
1809                 yaffs_update_parent(old_dir);
1810                 if(new_dir != old_dir)
1811                         yaffs_update_parent(new_dir);
1812                 
1813                 return result;
1814         }
1815         return YAFFS_FAIL;
1816 }
1817
1818 /*------------------------- Block Management and Page Allocation ----------------*/
1819
1820 static int yaffs_init_blocks(yaffs_dev_t *dev)
1821 {
1822         int nBlocks = dev->internal_end_block - dev->internal_start_block + 1;
1823
1824         dev->block_info = NULL;
1825         dev->chunk_bits = NULL;
1826
1827         dev->alloc_block = -1;  /* force it to get a new one */
1828
1829         /* If the first allocation strategy fails, thry the alternate one */
1830         dev->block_info = YMALLOC(nBlocks * sizeof(yaffs_block_info_t));
1831         if (!dev->block_info) {
1832                 dev->block_info = YMALLOC_ALT(nBlocks * sizeof(yaffs_block_info_t));
1833                 dev->block_info_alt = 1;
1834         } else
1835                 dev->block_info_alt = 0;
1836
1837         if (dev->block_info) {
1838                 /* Set up dynamic blockinfo stuff. */
1839                 dev->chunk_bit_stride = (dev->param.chunks_per_block + 7) / 8; /* round up bytes */
1840                 dev->chunk_bits = YMALLOC(dev->chunk_bit_stride * nBlocks);
1841                 if (!dev->chunk_bits) {
1842                         dev->chunk_bits = YMALLOC_ALT(dev->chunk_bit_stride * nBlocks);
1843                         dev->chunk_bits_alt = 1;
1844                 } else
1845                         dev->chunk_bits_alt = 0;
1846         }
1847
1848         if (dev->block_info && dev->chunk_bits) {
1849                 memset(dev->block_info, 0, nBlocks * sizeof(yaffs_block_info_t));
1850                 memset(dev->chunk_bits, 0, dev->chunk_bit_stride * nBlocks);
1851                 return YAFFS_OK;
1852         }
1853
1854         return YAFFS_FAIL;
1855 }
1856
1857 static void yaffs_deinit_blocks(yaffs_dev_t *dev)
1858 {
1859         if (dev->block_info_alt && dev->block_info)
1860                 YFREE_ALT(dev->block_info);
1861         else if (dev->block_info)
1862                 YFREE(dev->block_info);
1863
1864         dev->block_info_alt = 0;
1865
1866         dev->block_info = NULL;
1867
1868         if (dev->chunk_bits_alt && dev->chunk_bits)
1869                 YFREE_ALT(dev->chunk_bits);
1870         else if (dev->chunk_bits)
1871                 YFREE(dev->chunk_bits);
1872         dev->chunk_bits_alt = 0;
1873         dev->chunk_bits = NULL;
1874 }
1875
1876 void yaffs_block_became_dirty(yaffs_dev_t *dev, int block_no)
1877 {
1878         yaffs_block_info_t *bi = yaffs_get_block_info(dev, block_no);
1879
1880         int erasedOk = 0;
1881
1882         /* If the block is still healthy erase it and mark as clean.
1883          * If the block has had a data failure, then retire it.
1884          */
1885
1886         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
1887                 (TSTR("yaffs_block_became_dirty block %d state %d %s"TENDSTR),
1888                 block_no, bi->block_state, (bi->needs_retiring) ? "needs retiring" : ""));
1889
1890         yaffs2_clear_oldest_dirty_seq(dev,bi);
1891
1892         bi->block_state = YAFFS_BLOCK_STATE_DIRTY;
1893
1894         /* If this is the block being garbage collected then stop gc'ing this block */
1895         if(block_no == dev->gc_block)
1896                 dev->gc_block = 0;
1897
1898         /* If this block is currently the best candidate for gc then drop as a candidate */
1899         if(block_no == dev->gc_dirtiest){
1900                 dev->gc_dirtiest = 0;
1901                 dev->gc_pages_in_use = 0;
1902         }
1903
1904         if (!bi->needs_retiring) {
1905                 yaffs2_checkpt_invalidate(dev);
1906                 erasedOk = yaffs_erase_block(dev, block_no);
1907                 if (!erasedOk) {
1908                         dev->n_erase_failures++;
1909                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1910                           (TSTR("**>> Erasure failed %d" TENDSTR), block_no));
1911                 }
1912         }
1913
1914         if (erasedOk &&
1915             ((yaffs_trace_mask & YAFFS_TRACE_ERASE) || !yaffs_skip_verification(dev))) {
1916                 int i;
1917                 for (i = 0; i < dev->param.chunks_per_block; i++) {
1918                         if (!yaffs_check_chunk_erased
1919                             (dev, block_no * dev->param.chunks_per_block + i)) {
1920                                 T(YAFFS_TRACE_ERROR,
1921                                   (TSTR
1922                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
1923                                     TENDSTR), block_no, i));
1924                         }
1925                 }
1926         }
1927
1928         if (erasedOk) {
1929                 /* Clean it up... */
1930                 bi->block_state = YAFFS_BLOCK_STATE_EMPTY;
1931                 bi->seq_number = 0;
1932                 dev->n_erased_blocks++;
1933                 bi->pages_in_use = 0;
1934                 bi->soft_del_pages = 0;
1935                 bi->has_shrink_hdr = 0;
1936                 bi->skip_erased_check = 1;  /* This is clean, so no need to check */
1937                 bi->gc_prioritise = 0;
1938                 yaffs_clear_chunk_bits(dev, block_no);
1939
1940                 T(YAFFS_TRACE_ERASE,
1941                   (TSTR("Erased block %d" TENDSTR), block_no));
1942         } else {
1943                 dev->n_free_chunks -= dev->param.chunks_per_block;      /* We lost a block of free space */
1944
1945                 yaffs_retire_block(dev, block_no);
1946                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1947                   (TSTR("**>> Block %d retired" TENDSTR), block_no));
1948         }
1949 }
1950
1951 static int yaffs_find_alloc_block(yaffs_dev_t *dev)
1952 {
1953         int i;
1954
1955         yaffs_block_info_t *bi;
1956
1957         if (dev->n_erased_blocks < 1) {
1958                 /* Hoosterman we've got a problem.
1959                  * Can't get space to gc
1960                  */
1961                 T(YAFFS_TRACE_ERROR,
1962                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
1963
1964                 return -1;
1965         }
1966
1967         /* Find an empty block. */
1968
1969         for (i = dev->internal_start_block; i <= dev->internal_end_block; i++) {
1970                 dev->alloc_block_finder++;
1971                 if (dev->alloc_block_finder < dev->internal_start_block
1972                     || dev->alloc_block_finder > dev->internal_end_block) {
1973                         dev->alloc_block_finder = dev->internal_start_block;
1974                 }
1975
1976                 bi = yaffs_get_block_info(dev, dev->alloc_block_finder);
1977
1978                 if (bi->block_state == YAFFS_BLOCK_STATE_EMPTY) {
1979                         bi->block_state = YAFFS_BLOCK_STATE_ALLOCATING;
1980                         dev->seq_number++;
1981                         bi->seq_number = dev->seq_number;
1982                         dev->n_erased_blocks--;
1983                         T(YAFFS_TRACE_ALLOCATE,
1984                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
1985                            dev->alloc_block_finder, dev->seq_number,
1986                            dev->n_erased_blocks));
1987                         return dev->alloc_block_finder;
1988                 }
1989         }
1990
1991         T(YAFFS_TRACE_ALWAYS,
1992           (TSTR
1993            ("yaffs tragedy: no more erased blocks, but there should have been %d"
1994             TENDSTR), dev->n_erased_blocks));
1995
1996         return -1;
1997 }
1998
1999
2000 /*
2001  * Check if there's space to allocate...
2002  * Thinks.... do we need top make this ths same as yaffs_get_free_chunks()?
2003  */
2004 int yaffs_check_alloc_available(yaffs_dev_t *dev, int n_chunks)
2005 {
2006         int reservedChunks;
2007         int reservedBlocks = dev->param.n_reserved_blocks;
2008         int checkpointBlocks;
2009
2010         checkpointBlocks = yaffs_calc_checkpt_blocks_required(dev);
2011
2012         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.chunks_per_block);
2013
2014         return (dev->n_free_chunks > (reservedChunks + n_chunks));
2015 }
2016
2017 static int yaffs_alloc_chunk(yaffs_dev_t *dev, int useReserve,
2018                 yaffs_block_info_t **blockUsedPtr)
2019 {
2020         int retVal;
2021         yaffs_block_info_t *bi;
2022
2023         if (dev->alloc_block < 0) {
2024                 /* Get next block to allocate off */
2025                 dev->alloc_block = yaffs_find_alloc_block(dev);
2026                 dev->alloc_page = 0;
2027         }
2028
2029         if (!useReserve && !yaffs_check_alloc_available(dev, 1)) {
2030                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2031                 return -1;
2032         }
2033
2034         if (dev->n_erased_blocks < dev->param.n_reserved_blocks
2035                         && dev->alloc_page == 0) {
2036                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2037         }
2038
2039         /* Next page please.... */
2040         if (dev->alloc_block >= 0) {
2041                 bi = yaffs_get_block_info(dev, dev->alloc_block);
2042
2043                 retVal = (dev->alloc_block * dev->param.chunks_per_block) +
2044                         dev->alloc_page;
2045                 bi->pages_in_use++;
2046                 yaffs_set_chunk_bit(dev, dev->alloc_block,
2047                                 dev->alloc_page);
2048
2049                 dev->alloc_page++;
2050
2051                 dev->n_free_chunks--;
2052
2053                 /* If the block is full set the state to full */
2054                 if (dev->alloc_page >= dev->param.chunks_per_block) {
2055                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
2056                         dev->alloc_block = -1;
2057                 }
2058
2059                 if (blockUsedPtr)
2060                         *blockUsedPtr = bi;
2061
2062                 return retVal;
2063         }
2064
2065         T(YAFFS_TRACE_ERROR,
2066                         (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2067
2068         return -1;
2069 }
2070
2071 static int yaffs_get_erased_chunks(yaffs_dev_t *dev)
2072 {
2073         int n;
2074
2075         n = dev->n_erased_blocks * dev->param.chunks_per_block;
2076
2077         if (dev->alloc_block > 0)
2078                 n += (dev->param.chunks_per_block - dev->alloc_page);
2079
2080         return n;
2081
2082 }
2083
2084 /*
2085  * yaffs_skip_rest_of_block() skips over the rest of the allocation block
2086  * if we don't want to write to it.
2087  */
2088 void yaffs_skip_rest_of_block(yaffs_dev_t *dev)
2089 {
2090         if(dev->alloc_block > 0){
2091                 yaffs_block_info_t *bi = yaffs_get_block_info(dev, dev->alloc_block);
2092                 if(bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING){
2093                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
2094                         dev->alloc_block = -1;
2095                 }
2096         }
2097 }
2098
2099
2100 static int yaffs_gc_block(yaffs_dev_t *dev, int block,
2101                 int wholeBlock)
2102 {
2103         int oldChunk;
2104         int newChunk;
2105         int mark_flash;
2106         int retVal = YAFFS_OK;
2107         int i;
2108         int isCheckpointBlock;
2109         int matchingChunk;
2110         int maxCopies;
2111
2112         int chunksBefore = yaffs_get_erased_chunks(dev);
2113         int chunksAfter;
2114
2115         yaffs_ext_tags tags;
2116
2117         yaffs_block_info_t *bi = yaffs_get_block_info(dev, block);
2118
2119         yaffs_obj_t *object;
2120
2121         isCheckpointBlock = (bi->block_state == YAFFS_BLOCK_STATE_CHECKPOINT);
2122
2123
2124         T(YAFFS_TRACE_TRACING,
2125                         (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
2126                          block,
2127                          bi->pages_in_use,
2128                          bi->has_shrink_hdr,
2129                          wholeBlock));
2130
2131         /*yaffs_verify_free_chunks(dev); */
2132
2133         if(bi->block_state == YAFFS_BLOCK_STATE_FULL)
2134                 bi->block_state = YAFFS_BLOCK_STATE_COLLECTING;
2135         
2136         bi->has_shrink_hdr = 0; /* clear the flag so that the block can erase */
2137
2138         dev->gc_disable = 1;
2139
2140         if (isCheckpointBlock ||
2141                         !yaffs_still_some_chunks(dev, block)) {
2142                 T(YAFFS_TRACE_TRACING,
2143                                 (TSTR
2144                                  ("Collecting block %d that has no chunks in use" TENDSTR),
2145                                  block));
2146                 yaffs_block_became_dirty(dev, block);
2147         } else {
2148
2149                 __u8 *buffer = yaffs_get_temp_buffer(dev, __LINE__);
2150
2151                 yaffs_verify_blk(dev, bi, block);
2152
2153                 maxCopies = (wholeBlock) ? dev->param.chunks_per_block : 5;
2154                 oldChunk = block * dev->param.chunks_per_block + dev->gc_chunk;
2155
2156                 for (/* init already done */;
2157                      retVal == YAFFS_OK &&
2158                      dev->gc_chunk < dev->param.chunks_per_block &&
2159                      (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) &&
2160                      maxCopies > 0;
2161                      dev->gc_chunk++, oldChunk++) {
2162                         if (yaffs_check_chunk_bit(dev, block, dev->gc_chunk)) {
2163
2164                                 /* This page is in use and might need to be copied off */
2165
2166                                 maxCopies--;
2167
2168                                 mark_flash = 1;
2169
2170                                 yaffs_init_tags(&tags);
2171
2172                                 yaffs_rd_chunk_tags_nand(dev, oldChunk,
2173                                                                 buffer, &tags);
2174
2175                                 object =
2176                                     yaffs_find_by_number(dev,
2177                                                              tags.obj_id);
2178
2179                                 T(YAFFS_TRACE_GC_DETAIL,
2180                                   (TSTR
2181                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
2182                                    dev->gc_chunk, tags.obj_id, tags.chunk_id,
2183                                    tags.n_bytes));
2184
2185                                 if (object && !yaffs_skip_verification(dev)) {
2186                                         if (tags.chunk_id == 0)
2187                                                 matchingChunk = object->hdr_chunk;
2188                                         else if (object->soft_del)
2189                                                 matchingChunk = oldChunk; /* Defeat the test */
2190                                         else
2191                                                 matchingChunk = yaffs_find_chunk_in_file(object, tags.chunk_id, NULL);
2192
2193                                         if (oldChunk != matchingChunk)
2194                                                 T(YAFFS_TRACE_ERROR,
2195                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2196                                                   oldChunk, matchingChunk, tags.obj_id, tags.chunk_id));
2197
2198                                 }
2199
2200                                 if (!object) {
2201                                         T(YAFFS_TRACE_ERROR,
2202                                           (TSTR
2203                                            ("page %d in gc has no object: %d %d %d "
2204                                             TENDSTR), oldChunk,
2205                                             tags.obj_id, tags.chunk_id, tags.n_bytes));
2206                                 }
2207
2208                                 if (object &&
2209                                     object->deleted &&
2210                                     object->soft_del &&
2211                                     tags.chunk_id != 0) {
2212                                         /* Data chunk in a soft deleted file, throw it away
2213                                          * It's a soft deleted data chunk,
2214                                          * No need to copy this, just forget about it and
2215                                          * fix up the object.
2216                                          */
2217                                          
2218                                         /* Free chunks already includes softdeleted chunks.
2219                                          * How ever this chunk is going to soon be really deleted
2220                                          * which will increment free chunks.
2221                                          * We have to decrement free chunks so this works out properly.
2222                                          */
2223                                         dev->n_free_chunks--;
2224                                         bi->soft_del_pages--;
2225
2226                                         object->n_data_chunks--;
2227
2228                                         if (object->n_data_chunks <= 0) {
2229                                                 /* remeber to clean up the object */
2230                                                 dev->gc_cleanup_list[dev->n_clean_ups] =
2231                                                     tags.obj_id;
2232                                                 dev->n_clean_ups++;
2233                                         }
2234                                         mark_flash = 0;
2235                                 } else if (0) {
2236                                         /* Todo object && object->deleted && object->n_data_chunks == 0 */
2237                                         /* Deleted object header with no data chunks.
2238                                          * Can be discarded and the file deleted.
2239                                          */
2240                                         object->hdr_chunk = 0;
2241                                         yaffs_free_tnode(object->my_dev,
2242                                                         object->variant.
2243                                                         file_variant.top);
2244                                         object->variant.file_variant.top = NULL;
2245                                         yaffs_generic_obj_del(object);
2246
2247                                 } else if (object) {
2248                                         /* It's either a data chunk in a live file or
2249                                          * an ObjectHeader, so we're interested in it.
2250                                          * NB Need to keep the ObjectHeaders of deleted files
2251                                          * until the whole file has been deleted off
2252                                          */
2253                                         tags.serial_number++;
2254
2255                                         dev->n_gc_copies++;
2256
2257                                         if (tags.chunk_id == 0) {
2258                                                 /* It is an object Id,
2259                                                  * We need to nuke the shrinkheader flags first
2260                                                  * Also need to clean up shadowing.
2261                                                  * We no longer want the shrinkHeader flag since its work is done
2262                                                  * and if it is left in place it will mess up scanning.
2263                                                  */
2264
2265                                                 yaffs_obj_header *oh;
2266                                                 oh = (yaffs_obj_header *)buffer;
2267
2268                                                 oh->is_shrink = 0;
2269                                                 tags.extra_is_shrink = 0;
2270
2271                                                 oh->shadows_obj = 0;
2272                                                 oh->inband_shadowed_obj_id = 0;
2273                                                 tags.extra_shadows = 0;
2274
2275                                                 /* Update file size */
2276                                                 if(object->variant_type == YAFFS_OBJECT_TYPE_FILE){
2277                                                         oh->file_size = object->variant.file_variant.file_size;
2278                                                         tags.extra_length = oh->file_size;
2279                                                 }
2280
2281                                                 yaffs_verify_oh(object, oh, &tags, 1);
2282                                                 newChunk =
2283                                                     yaffs_write_new_chunk(dev,(__u8 *) oh, &tags, 1);
2284                                         } else
2285                                                 newChunk =
2286                                                     yaffs_write_new_chunk(dev, buffer, &tags, 1);
2287
2288                                         if (newChunk < 0) {
2289                                                 retVal = YAFFS_FAIL;
2290                                         } else {
2291
2292                                                 /* Ok, now fix up the Tnodes etc. */
2293
2294                                                 if (tags.chunk_id == 0) {
2295                                                         /* It's a header */
2296                                                         object->hdr_chunk =  newChunk;
2297                                                         object->serial =   tags.serial_number;
2298                                                 } else {
2299                                                         /* It's a data chunk */
2300                                                         int ok;
2301                                                         ok = yaffs_put_chunk_in_file
2302                                                             (object,
2303                                                              tags.chunk_id,
2304                                                              newChunk, 0);
2305                                                 }
2306                                         }
2307                                 }
2308
2309                                 if (retVal == YAFFS_OK)
2310                                         yaffs_chunk_del(dev, oldChunk, mark_flash, __LINE__);
2311
2312                         }
2313                 }
2314
2315                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
2316
2317
2318
2319         }
2320
2321         yaffs_verify_collected_blk(dev, bi, block);
2322
2323
2324
2325         if (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2326                 /*
2327                  * The gc did not complete. Set block state back to FULL
2328                  * because checkpointing does not restore gc.
2329                  */
2330                 bi->block_state = YAFFS_BLOCK_STATE_FULL;
2331         } else {
2332                 /* The gc completed. */
2333                 /* Do any required cleanups */
2334                 for (i = 0; i < dev->n_clean_ups; i++) {
2335                         /* Time to delete the file too */
2336                         object =
2337                             yaffs_find_by_number(dev,
2338                                                      dev->gc_cleanup_list[i]);
2339                         if (object) {
2340                                 yaffs_free_tnode(dev,
2341                                                 object->variant.file_variant.
2342                                                 top);
2343                                 object->variant.file_variant.top = NULL;
2344                                 T(YAFFS_TRACE_GC,
2345                                   (TSTR
2346                                    ("yaffs: About to finally delete object %d"
2347                                     TENDSTR), object->obj_id));
2348                                 yaffs_generic_obj_del(object);
2349                                 object->my_dev->n_deleted_files--;
2350                         }
2351
2352                 }
2353
2354
2355                 chunksAfter = yaffs_get_erased_chunks(dev);
2356                 if (chunksBefore >= chunksAfter) {
2357                         T(YAFFS_TRACE_GC,
2358                           (TSTR
2359                            ("gc did not increase free chunks before %d after %d"
2360                             TENDSTR), chunksBefore, chunksAfter));
2361                 }
2362                 dev->gc_block = 0;
2363                 dev->gc_chunk = 0;
2364                 dev->n_clean_ups = 0;
2365         }
2366
2367         dev->gc_disable = 0;
2368
2369         return retVal;
2370 }
2371
2372 /*
2373  * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
2374  * for garbage collection.
2375  */
2376
2377 static unsigned yaffs_find_gc_block(yaffs_dev_t *dev,
2378                                         int aggressive,
2379                                         int background)
2380 {
2381         int i;
2382         int iterations;
2383         unsigned selected = 0;
2384         int prioritised = 0;
2385         int prioritisedExists = 0;
2386         yaffs_block_info_t *bi;
2387         int threshold;
2388
2389         /* First let's see if we need to grab a prioritised block */
2390         if (dev->has_pending_prioritised_gc && !aggressive) {
2391                 dev->gc_dirtiest = 0;
2392                 bi = dev->block_info;
2393                 for (i = dev->internal_start_block;
2394                         i <= dev->internal_end_block && !selected;
2395                         i++) {
2396
2397                         if (bi->gc_prioritise) {
2398                                 prioritisedExists = 1;
2399                                 if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2400                                    yaffs_block_ok_for_gc(dev, bi)) {
2401                                         selected = i;
2402                                         prioritised = 1;
2403                                 }
2404                         }
2405                         bi++;
2406                 }
2407
2408                 /*
2409                  * If there is a prioritised block and none was selected then
2410                  * this happened because there is at least one old dirty block gumming
2411                  * up the works. Let's gc the oldest dirty block.
2412                  */
2413
2414                 if(prioritisedExists &&
2415                         !selected &&
2416                         dev->oldest_dirty_block > 0)
2417                         selected = dev->oldest_dirty_block;
2418
2419                 if (!prioritisedExists) /* None found, so we can clear this */
2420                         dev->has_pending_prioritised_gc = 0;
2421         }
2422
2423         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2424          * search harder.
2425          * else (we're doing a leasurely gc), then we only bother to do this if the
2426          * block has only a few pages in use.
2427          */
2428
2429         if (!selected){
2430                 int pagesUsed;
2431                 int nBlocks = dev->internal_end_block - dev->internal_start_block + 1;
2432                 if (aggressive){
2433                         threshold = dev->param.chunks_per_block;
2434                         iterations = nBlocks;
2435                 } else {
2436                         int maxThreshold;
2437
2438                         if(background)
2439                                 maxThreshold = dev->param.chunks_per_block/2;
2440                         else
2441                                 maxThreshold = dev->param.chunks_per_block/8;
2442
2443                         if(maxThreshold <  YAFFS_GC_PASSIVE_THRESHOLD)
2444                                 maxThreshold = YAFFS_GC_PASSIVE_THRESHOLD;
2445
2446                         threshold = background ?
2447                                 (dev->gc_not_done + 2) * 2 : 0;
2448                         if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
2449                                 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2450                         if(threshold > maxThreshold)
2451                                 threshold = maxThreshold;
2452
2453                         iterations = nBlocks / 16 + 1;
2454                         if (iterations > 100)
2455                                 iterations = 100;
2456                 }
2457
2458                 for (i = 0;
2459                         i < iterations &&
2460                         (dev->gc_dirtiest < 1 ||
2461                                 dev->gc_pages_in_use > YAFFS_GC_GOOD_ENOUGH);
2462                         i++) {
2463                         dev->gc_block_finder++;
2464                         if (dev->gc_block_finder < dev->internal_start_block ||
2465                                 dev->gc_block_finder > dev->internal_end_block)
2466                                 dev->gc_block_finder = dev->internal_start_block;
2467
2468                         bi = yaffs_get_block_info(dev, dev->gc_block_finder);
2469
2470                         pagesUsed = bi->pages_in_use - bi->soft_del_pages;
2471
2472                         if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2473                                 pagesUsed < dev->param.chunks_per_block &&
2474                                 (dev->gc_dirtiest < 1 || pagesUsed < dev->gc_pages_in_use) &&
2475                                 yaffs_block_ok_for_gc(dev, bi)) {
2476                                 dev->gc_dirtiest = dev->gc_block_finder;
2477                                 dev->gc_pages_in_use = pagesUsed;
2478                         }
2479                 }
2480
2481                 if(dev->gc_dirtiest > 0 && dev->gc_pages_in_use <= threshold)
2482                         selected = dev->gc_dirtiest;
2483         }
2484
2485         /*
2486          * If nothing has been selected for a while, try selecting the oldest dirty
2487          * because that's gumming up the works.
2488          */
2489
2490         if(!selected && dev->param.is_yaffs2 &&
2491                 dev->gc_not_done >= ( background ? 10 : 20)){
2492                 yaffs2_find_oldest_dirty_seq(dev);
2493                 if(dev->oldest_dirty_block > 0) {
2494                         selected = dev->oldest_dirty_block;
2495                         dev->gc_dirtiest = selected;
2496                         dev->oldest_dirty_gc_count++;
2497                         bi = yaffs_get_block_info(dev, selected);
2498                         dev->gc_pages_in_use =  bi->pages_in_use - bi->soft_del_pages;
2499                 } else
2500                         dev->gc_not_done = 0;
2501         }
2502
2503         if(selected){
2504                 T(YAFFS_TRACE_GC,
2505                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
2506                   selected,
2507                   dev->param.chunks_per_block - dev->gc_pages_in_use,
2508                   prioritised));
2509
2510                 dev->n_gc_blocks++;
2511                 if(background)
2512                         dev->bg_gcs++;
2513
2514                 dev->gc_dirtiest = 0;
2515                 dev->gc_pages_in_use = 0;
2516                 dev->gc_not_done = 0;
2517                 if(dev->refresh_skip > 0)
2518                         dev->refresh_skip--;
2519         } else{
2520                 dev->gc_not_done++;
2521                 T(YAFFS_TRACE_GC,
2522                   (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
2523                   dev->gc_block_finder, dev->gc_not_done,
2524                   threshold,
2525                   dev->gc_dirtiest, dev->gc_pages_in_use,
2526                   dev->oldest_dirty_block,
2527                   background ? " bg" : ""));
2528         }
2529
2530         return selected;
2531 }
2532
2533 /* New garbage collector
2534  * If we're very low on erased blocks then we do aggressive garbage collection
2535  * otherwise we do "leasurely" garbage collection.
2536  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2537  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2538  *
2539  * The idea is to help clear out space in a more spread-out manner.
2540  * Dunno if it really does anything useful.
2541  */
2542 static int yaffs_check_gc(yaffs_dev_t *dev, int background)
2543 {
2544         int aggressive = 0;
2545         int gcOk = YAFFS_OK;
2546         int maxTries = 0;
2547         int minErased;
2548         int erasedChunks;
2549         int checkpointBlockAdjust;
2550
2551         if(dev->param.gc_control &&
2552                 (dev->param.gc_control(dev) & 1) == 0)
2553                 return YAFFS_OK;
2554
2555         if (dev->gc_disable) {
2556                 /* Bail out so we don't get recursive gc */
2557                 return YAFFS_OK;
2558         }
2559
2560         /* This loop should pass the first time.
2561          * We'll only see looping here if the collection does not increase space.
2562          */
2563
2564         do {
2565                 maxTries++;
2566
2567                 checkpointBlockAdjust = yaffs_calc_checkpt_blocks_required(dev);
2568
2569                 minErased  = dev->param.n_reserved_blocks + checkpointBlockAdjust + 1;
2570                 erasedChunks = dev->n_erased_blocks * dev->param.chunks_per_block;
2571
2572                 /* If we need a block soon then do aggressive gc.*/
2573                 if (dev->n_erased_blocks < minErased)
2574                         aggressive = 1;
2575                 else {
2576                         if(!background && erasedChunks > (dev->n_free_chunks / 4))
2577                                 break;
2578
2579                         if(dev->gc_skip > 20)
2580                                 dev->gc_skip = 20;
2581                         if(erasedChunks < dev->n_free_chunks/2 ||
2582                                 dev->gc_skip < 1 ||
2583                                 background)
2584                                 aggressive = 0;
2585                         else {
2586                                 dev->gc_skip--;
2587                                 break;
2588                         }
2589                 }
2590
2591                 dev->gc_skip = 5;
2592
2593                 /* If we don't already have a block being gc'd then see if we should start another */
2594
2595                 if (dev->gc_block < 1 && !aggressive) {
2596                         dev->gc_block = yaffs2_find_refresh_block(dev);
2597                         dev->gc_chunk = 0;
2598                         dev->n_clean_ups=0;
2599                 }
2600                 if (dev->gc_block < 1) {
2601                         dev->gc_block = yaffs_find_gc_block(dev, aggressive, background);
2602                         dev->gc_chunk = 0;
2603                         dev->n_clean_ups=0;
2604                 }
2605
2606                 if (dev->gc_block > 0) {
2607                         dev->all_gcs++;
2608                         if (!aggressive)
2609                                 dev->passive_gc_count++;
2610
2611                         T(YAFFS_TRACE_GC,
2612                           (TSTR
2613                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2614                            dev->n_erased_blocks, aggressive));
2615
2616                         gcOk = yaffs_gc_block(dev, dev->gc_block, aggressive);
2617                 }
2618
2619                 if (dev->n_erased_blocks < (dev->param.n_reserved_blocks) && dev->gc_block > 0) {
2620                         T(YAFFS_TRACE_GC,
2621                           (TSTR
2622                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2623                             TENDSTR), dev->n_erased_blocks, maxTries, dev->gc_block));
2624                 }
2625         } while ((dev->n_erased_blocks < dev->param.n_reserved_blocks) &&
2626                  (dev->gc_block > 0) &&
2627                  (maxTries < 2));
2628
2629         return aggressive ? gcOk : YAFFS_OK;
2630 }
2631
2632 /*
2633  * yaffs_bg_gc()
2634  * Garbage collects. Intended to be called from a background thread.
2635  * Returns non-zero if at least half the free chunks are erased.
2636  */
2637 int yaffs_bg_gc(yaffs_dev_t *dev, unsigned urgency)
2638 {
2639         int erasedChunks = dev->n_erased_blocks * dev->param.chunks_per_block;
2640
2641         T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
2642
2643         yaffs_check_gc(dev, 1);
2644         return erasedChunks > dev->n_free_chunks/2;
2645 }
2646
2647 /*-------------------------  TAGS --------------------------------*/
2648
2649 static int yaffs_tags_match(const yaffs_ext_tags *tags, int obj_id,
2650                            int chunkInObject)
2651 {
2652         return (tags->chunk_id == chunkInObject &&
2653                 tags->obj_id == obj_id && !tags->is_deleted) ? 1 : 0;
2654
2655 }
2656
2657
2658 /*-------------------- Data file manipulation -----------------*/
2659
2660 static int yaffs_find_chunk_in_file(yaffs_obj_t *in, int inode_chunk,
2661                                  yaffs_ext_tags *tags)
2662 {
2663         /*Get the Tnode, then get the level 0 offset chunk offset */
2664         yaffs_tnode_t *tn;
2665         int theChunk = -1;
2666         yaffs_ext_tags localTags;
2667         int retVal = -1;
2668
2669         yaffs_dev_t *dev = in->my_dev;
2670
2671         if (!tags) {
2672                 /* Passed a NULL, so use our own tags space */
2673                 tags = &localTags;
2674         }
2675
2676         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
2677
2678         if (tn) {
2679                 theChunk = yaffs_get_group_base(dev, tn, inode_chunk);
2680
2681                 retVal =
2682                     yaffs_find_chunk_in_group(dev, theChunk, tags, in->obj_id,
2683                                            inode_chunk);
2684         }
2685         return retVal;
2686 }
2687
2688 static int yaffs_find_del_file_chunk(yaffs_obj_t *in, int inode_chunk,
2689                                           yaffs_ext_tags *tags)
2690 {
2691         /* Get the Tnode, then get the level 0 offset chunk offset */
2692         yaffs_tnode_t *tn;
2693         int theChunk = -1;
2694         yaffs_ext_tags localTags;
2695
2696         yaffs_dev_t *dev = in->my_dev;
2697         int retVal = -1;
2698
2699         if (!tags) {
2700                 /* Passed a NULL, so use our own tags space */
2701                 tags = &localTags;
2702         }
2703
2704         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
2705
2706         if (tn) {
2707
2708                 theChunk = yaffs_get_group_base(dev, tn, inode_chunk);
2709
2710                 retVal =
2711                     yaffs_find_chunk_in_group(dev, theChunk, tags, in->obj_id,
2712                                            inode_chunk);
2713
2714                 /* Delete the entry in the filestructure (if found) */
2715                 if (retVal != -1)
2716                         yaffs_load_tnode_0(dev, tn, inode_chunk, 0);
2717         }
2718
2719         return retVal;
2720 }
2721
2722
2723 int yaffs_put_chunk_in_file(yaffs_obj_t *in, int inode_chunk,
2724                                 int nand_chunk, int in_scan)
2725 {
2726         /* NB in_scan is zero unless scanning.
2727          * For forward scanning, in_scan is > 0;
2728          * for backward scanning in_scan is < 0
2729          *
2730          * nand_chunk = 0 is a dummy insert to make sure the tnodes are there.
2731          */
2732
2733         yaffs_tnode_t *tn;
2734         yaffs_dev_t *dev = in->my_dev;
2735         int existingChunk;
2736         yaffs_ext_tags existingTags;
2737         yaffs_ext_tags newTags;
2738         unsigned existingSerial, newSerial;
2739
2740         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE) {
2741                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2742                  * If it is not during Scanning then something went wrong!
2743                  */
2744                 if (!in_scan) {
2745                         T(YAFFS_TRACE_ERROR,
2746                           (TSTR
2747                            ("yaffs tragedy:attempt to put data chunk into a non-file"
2748                             TENDSTR)));
2749                         YBUG();
2750                 }
2751
2752                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
2753                 return YAFFS_OK;
2754         }
2755
2756         tn = yaffs_add_find_tnode_0(dev,
2757                                         &in->variant.file_variant,
2758                                         inode_chunk,
2759                                         NULL);
2760         if (!tn)
2761                 return YAFFS_FAIL;
2762         
2763         if(!nand_chunk)
2764                 /* Dummy insert, bail now */
2765                 return YAFFS_OK;
2766
2767         existingChunk = yaffs_get_group_base(dev, tn, inode_chunk);
2768
2769         if (in_scan != 0) {
2770                 /* If we're scanning then we need to test for duplicates
2771                  * NB This does not need to be efficient since it should only ever
2772                  * happen when the power fails during a write, then only one
2773                  * chunk should ever be affected.
2774                  *
2775                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2776                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2777                  */
2778
2779                 if (existingChunk > 0) {
2780                         /* NB Right now existing chunk will not be real chunk_id if the chunk group size > 1
2781                          *    thus we have to do a FindChunkInFile to get the real chunk id.
2782                          *
2783                          * We have a duplicate now we need to decide which one to use:
2784                          *
2785                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2786                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2787                          * YAFFS1: Get both sets of tags and compare serial numbers.
2788                          */
2789
2790                         if (in_scan > 0) {
2791                                 /* Only do this for forward scanning */
2792                                 yaffs_rd_chunk_tags_nand(dev,
2793                                                                 nand_chunk,
2794                                                                 NULL, &newTags);
2795
2796                                 /* Do a proper find */
2797                                 existingChunk =
2798                                     yaffs_find_chunk_in_file(in, inode_chunk,
2799                                                           &existingTags);
2800                         }
2801
2802                         if (existingChunk <= 0) {
2803                                 /*Hoosterman - how did this happen? */
2804
2805                                 T(YAFFS_TRACE_ERROR,
2806                                   (TSTR
2807                                    ("yaffs tragedy: existing chunk < 0 in scan"
2808                                     TENDSTR)));
2809
2810                         }
2811
2812                         /* NB The deleted flags should be false, otherwise the chunks will
2813                          * not be loaded during a scan
2814                          */
2815
2816                         if (in_scan > 0) {
2817                                 newSerial = newTags.serial_number;
2818                                 existingSerial = existingTags.serial_number;
2819                         }
2820
2821                         if ((in_scan > 0) &&
2822                             (existingChunk <= 0 ||
2823                              ((existingSerial + 1) & 3) == newSerial)) {
2824                                 /* Forward scanning.
2825                                  * Use new
2826                                  * Delete the old one and drop through to update the tnode
2827                                  */
2828                                 yaffs_chunk_del(dev, existingChunk, 1,
2829                                                   __LINE__);
2830                         } else {
2831                                 /* Backward scanning or we want to use the existing one
2832                                  * Use existing.
2833                                  * Delete the new one and return early so that the tnode isn't changed
2834                                  */
2835                                 yaffs_chunk_del(dev, nand_chunk, 1,
2836                                                   __LINE__);
2837                                 return YAFFS_OK;
2838                         }
2839                 }
2840
2841         }
2842
2843         if (existingChunk == 0)
2844                 in->n_data_chunks++;
2845
2846         yaffs_load_tnode_0(dev, tn, inode_chunk, nand_chunk);
2847
2848         return YAFFS_OK;
2849 }
2850
2851 static int yaffs_rd_data_obj(yaffs_obj_t *in, int inode_chunk,
2852                                         __u8 *buffer)
2853 {
2854         int nand_chunk = yaffs_find_chunk_in_file(in, inode_chunk, NULL);
2855
2856         if (nand_chunk >= 0)
2857                 return yaffs_rd_chunk_tags_nand(in->my_dev, nand_chunk,
2858                                                 buffer, NULL);
2859         else {
2860                 T(YAFFS_TRACE_NANDACCESS,
2861                   (TSTR("Chunk %d not found zero instead" TENDSTR),
2862                    nand_chunk));
2863                 /* get sane (zero) data if you read a hole */
2864                 memset(buffer, 0, in->my_dev->data_bytes_per_chunk);
2865                 return 0;
2866         }
2867
2868 }
2869
2870 void yaffs_chunk_del(yaffs_dev_t *dev, int chunk_id, int mark_flash, int lyn)
2871 {
2872         int block;
2873         int page;
2874         yaffs_ext_tags tags;
2875         yaffs_block_info_t *bi;
2876
2877         if (chunk_id <= 0)
2878                 return;
2879
2880         dev->n_deletions++;
2881         block = chunk_id / dev->param.chunks_per_block;
2882         page = chunk_id % dev->param.chunks_per_block;
2883
2884
2885         if (!yaffs_check_chunk_bit(dev, block, page))
2886                 T(YAFFS_TRACE_VERIFY,
2887                         (TSTR("Deleting invalid chunk %d"TENDSTR),
2888                          chunk_id));
2889
2890         bi = yaffs_get_block_info(dev, block);
2891         
2892         yaffs2_update_oldest_dirty_seq(dev, block, bi);
2893
2894         T(YAFFS_TRACE_DELETION,
2895           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunk_id));
2896
2897         if (!dev->param.is_yaffs2 && mark_flash &&
2898             bi->block_state != YAFFS_BLOCK_STATE_COLLECTING) {
2899
2900                 yaffs_init_tags(&tags);
2901
2902                 tags.is_deleted = 1;
2903
2904                 yaffs_wr_chunk_tags_nand(dev, chunk_id, NULL, &tags);
2905                 yaffs_handle_chunk_update(dev, chunk_id, &tags);
2906         } else {
2907                 dev->n_unmarked_deletions++;
2908         }
2909
2910         /* Pull out of the management area.
2911          * If the whole block became dirty, this will kick off an erasure.
2912          */
2913         if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING ||
2914             bi->block_state == YAFFS_BLOCK_STATE_FULL ||
2915             bi->block_state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2916             bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2917                 dev->n_free_chunks++;
2918
2919                 yaffs_clear_chunk_bit(dev, block, page);
2920
2921                 bi->pages_in_use--;
2922
2923                 if (bi->pages_in_use == 0 &&
2924                     !bi->has_shrink_hdr &&
2925                     bi->block_state != YAFFS_BLOCK_STATE_ALLOCATING &&
2926                     bi->block_state != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2927                         yaffs_block_became_dirty(dev, block);
2928                 }
2929
2930         }
2931
2932 }
2933
2934 static int yaffs_wr_data_obj(yaffs_obj_t *in, int inode_chunk,
2935                                         const __u8 *buffer, int n_bytes,
2936                                         int useReserve)
2937 {
2938         /* Find old chunk Need to do this to get serial number
2939          * Write new one and patch into tree.
2940          * Invalidate old tags.
2941          */
2942
2943         int prevChunkId;
2944         yaffs_ext_tags prevTags;
2945
2946         int newChunkId;
2947         yaffs_ext_tags newTags;
2948
2949         yaffs_dev_t *dev = in->my_dev;
2950
2951         yaffs_check_gc(dev,0);
2952
2953         /* Get the previous chunk at this location in the file if it exists.
2954          * If it does not exist then put a zero into the tree. This creates
2955          * the tnode now, rather than later when it is harder to clean up.
2956          */
2957         prevChunkId = yaffs_find_chunk_in_file(in, inode_chunk, &prevTags);
2958         if(prevChunkId < 1 &&
2959                 !yaffs_put_chunk_in_file(in, inode_chunk, 0, 0))
2960                 return 0;
2961
2962         /* Set up new tags */
2963         yaffs_init_tags(&newTags);
2964
2965         newTags.chunk_id = inode_chunk;
2966         newTags.obj_id = in->obj_id;
2967         newTags.serial_number =
2968             (prevChunkId > 0) ? prevTags.serial_number + 1 : 1;
2969         newTags.n_bytes = n_bytes;
2970
2971         if (n_bytes < 1 || n_bytes > dev->param.total_bytes_per_chunk) {
2972                 T(YAFFS_TRACE_ERROR,
2973                 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), n_bytes));
2974                 YBUG();
2975         }
2976         
2977                 
2978         newChunkId =
2979             yaffs_write_new_chunk(dev, buffer, &newTags,
2980                                               useReserve);
2981
2982         if (newChunkId > 0) {
2983                 yaffs_put_chunk_in_file(in, inode_chunk, newChunkId, 0);
2984
2985                 if (prevChunkId > 0)
2986                         yaffs_chunk_del(dev, prevChunkId, 1, __LINE__);
2987
2988                 yaffs_verify_file_sane(in);
2989         }
2990         return newChunkId;
2991
2992 }
2993
2994 /* UpdateObjectHeader updates the header on NAND for an object.
2995  * If name is not NULL, then that new name is used.
2996  */
2997 int yaffs_update_oh(yaffs_obj_t *in, const YCHAR *name, int force,
2998                              int is_shrink, int shadows, yaffs_xattr_mod *xmod)
2999 {
3000
3001         yaffs_block_info_t *bi;
3002
3003         yaffs_dev_t *dev = in->my_dev;
3004
3005         int prevChunkId;
3006         int retVal = 0;
3007         int result = 0;
3008
3009         int newChunkId;
3010         yaffs_ext_tags newTags;
3011         yaffs_ext_tags oldTags;
3012         const YCHAR *alias = NULL;
3013
3014         __u8 *buffer = NULL;
3015         YCHAR old_name[YAFFS_MAX_NAME_LENGTH + 1];
3016
3017         yaffs_obj_header *oh = NULL;
3018
3019         yaffs_strcpy(old_name, _Y("silly old name"));
3020
3021
3022         if (!in->fake ||
3023                 in == dev->root_dir || /* The root_dir should also be saved */
3024                 force  || xmod) {
3025
3026                 yaffs_check_gc(dev,0);
3027                 yaffs_check_obj_details_loaded(in);
3028
3029                 buffer = yaffs_get_temp_buffer(in->my_dev, __LINE__);
3030                 oh = (yaffs_obj_header *) buffer;
3031
3032                 prevChunkId = in->hdr_chunk;
3033
3034                 if (prevChunkId > 0) {
3035                         result = yaffs_rd_chunk_tags_nand(dev, prevChunkId,
3036                                                         buffer, &oldTags);
3037
3038                         yaffs_verify_oh(in, oh, &oldTags, 0);
3039
3040                         memcpy(old_name, oh->name, sizeof(oh->name));
3041                         memset(buffer, 0xFF, sizeof(yaffs_obj_header));
3042                 } else
3043                         memset(buffer, 0xFF, dev->data_bytes_per_chunk);
3044
3045                 oh->type = in->variant_type;
3046                 oh->yst_mode = in->yst_mode;
3047                 oh->shadows_obj = oh->inband_shadowed_obj_id = shadows;
3048
3049 #ifdef CONFIG_YAFFS_WINCE
3050                 oh->win_atime[0] = in->win_atime[0];
3051                 oh->win_ctime[0] = in->win_ctime[0];
3052                 oh->win_mtime[0] = in->win_mtime[0];
3053                 oh->win_atime[1] = in->win_atime[1];
3054                 oh->win_ctime[1] = in->win_ctime[1];
3055                 oh->win_mtime[1] = in->win_mtime[1];
3056 #else
3057                 oh->yst_uid = in->yst_uid;
3058                 oh->yst_gid = in->yst_gid;
3059                 oh->yst_atime = in->yst_atime;
3060                 oh->yst_mtime = in->yst_mtime;
3061                 oh->yst_ctime = in->yst_ctime;
3062                 oh->yst_rdev = in->yst_rdev;
3063 #endif
3064                 if (in->parent)
3065                         oh->parent_obj_id = in->parent->obj_id;
3066                 else
3067                         oh->parent_obj_id = 0;
3068
3069                 if (name && *name) {
3070                         memset(oh->name, 0, sizeof(oh->name));
3071                         yaffs_load_oh_from_name(dev,oh->name,name);
3072                 } else if (prevChunkId > 0)
3073                         memcpy(oh->name, old_name, sizeof(oh->name));
3074                 else
3075                         memset(oh->name, 0, sizeof(oh->name));
3076
3077                 oh->is_shrink = is_shrink;
3078
3079                 switch (in->variant_type) {
3080                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3081                         /* Should not happen */
3082                         break;
3083                 case YAFFS_OBJECT_TYPE_FILE:
3084                         oh->file_size =
3085                             (oh->parent_obj_id == YAFFS_OBJECTID_DELETED
3086                              || oh->parent_obj_id ==
3087                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3088                             file_variant.file_size;
3089                         break;
3090                 case YAFFS_OBJECT_TYPE_HARDLINK:
3091                         oh->equiv_id =
3092                             in->variant.hardlink_variant.equiv_id;
3093                         break;
3094                 case YAFFS_OBJECT_TYPE_SPECIAL:
3095                         /* Do nothing */
3096                         break;
3097                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3098                         /* Do nothing */
3099                         break;
3100                 case YAFFS_OBJECT_TYPE_SYMLINK:
3101                         alias = in->variant.symlink_variant.alias;
3102                         if(!alias)
3103                                 alias = _Y("no alias");
3104                         yaffs_strncpy(oh->alias,
3105                                         alias,
3106                                       YAFFS_MAX_ALIAS_LENGTH);
3107                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3108                         break;
3109                 }
3110
3111                 /* process any xattrib modifications */
3112                 if(xmod)
3113                         yaffs_apply_xattrib_mod(in, (char *)buffer, xmod);
3114
3115
3116                 /* Tags */
3117                 yaffs_init_tags(&newTags);
3118                 in->serial++;
3119                 newTags.chunk_id = 0;
3120                 newTags.obj_id = in->obj_id;
3121                 newTags.serial_number = in->serial;
3122
3123                 /* Add extra info for file header */
3124
3125                 newTags.extra_available = 1;
3126                 newTags.extra_parent_id = oh->parent_obj_id;
3127                 newTags.extra_length = oh->file_size;
3128                 newTags.extra_is_shrink = oh->is_shrink;
3129                 newTags.extra_equiv_id = oh->equiv_id;
3130                 newTags.extra_shadows = (oh->shadows_obj > 0) ? 1 : 0;
3131                 newTags.extra_obj_type = in->variant_type;
3132
3133                 yaffs_verify_oh(in, oh, &newTags, 1);
3134
3135                 /* Create new chunk in NAND */
3136                 newChunkId =
3137                     yaffs_write_new_chunk(dev, buffer, &newTags,
3138                                                       (prevChunkId > 0) ? 1 : 0);
3139
3140                 if (newChunkId >= 0) {
3141
3142                         in->hdr_chunk = newChunkId;
3143
3144                         if (prevChunkId > 0) {
3145                                 yaffs_chunk_del(dev, prevChunkId, 1,
3146                                                   __LINE__);
3147                         }
3148
3149                         if (!yaffs_obj_cache_dirty(in))
3150                                 in->dirty = 0;
3151
3152                         /* If this was a shrink, then mark the block that the chunk lives on */
3153                         if (is_shrink) {
3154                                 bi = yaffs_get_block_info(in->my_dev,
3155                                         newChunkId / in->my_dev->param.chunks_per_block);
3156                                 bi->has_shrink_hdr = 1;
3157                         }
3158
3159                 }
3160
3161                 retVal = newChunkId;
3162
3163         }
3164
3165         if (buffer)
3166                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
3167
3168         return retVal;
3169 }
3170
3171 /*------------------------ Short Operations Cache ----------------------------------------
3172  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3173  *   reads might be short sequential reads, and a lot of writes may be short
3174  *   sequential writes. eg. scanning/writing a jpeg file.
3175  *   In these cases, a short read/write cache can provide a huge perfomance benefit
3176  *   with dumb-as-a-rock code.
3177  *   In Linux, the page cache provides read buffering aand the short op cache provides write
3178  *   buffering.
3179  *
3180  *   There are a limited number (~10) of cache chunks per device so that we don't
3181  *   need a very intelligent search.
3182  */
3183
3184 static int yaffs_obj_cache_dirty(yaffs_obj_t *obj)
3185 {
3186         yaffs_dev_t *dev = obj->my_dev;
3187         int i;
3188         yaffs_cache_t *cache;
3189         int nCaches = obj->my_dev->param.n_caches;
3190
3191         for (i = 0; i < nCaches; i++) {
3192                 cache = &dev->cache[i];
3193                 if (cache->object == obj &&
3194                     cache->dirty)
3195                         return 1;
3196         }
3197
3198         return 0;
3199 }
3200
3201
3202 static void yaffs_flush_file_cache(yaffs_obj_t *obj)
3203 {
3204         yaffs_dev_t *dev = obj->my_dev;
3205         int lowest = -99;       /* Stop compiler whining. */
3206         int i;
3207         yaffs_cache_t *cache;
3208         int chunkWritten = 0;
3209         int nCaches = obj->my_dev->param.n_caches;
3210
3211         if (nCaches > 0) {
3212                 do {
3213                         cache = NULL;
3214
3215                         /* Find the dirty cache for this object with the lowest chunk id. */
3216                         for (i = 0; i < nCaches; i++) {
3217                                 if (dev->cache[i].object == obj &&
3218                                     dev->cache[i].dirty) {
3219                                         if (!cache
3220                                             || dev->cache[i].chunk_id <
3221                                             lowest) {
3222                                                 cache = &dev->cache[i];
3223                                                 lowest = cache->chunk_id;
3224                                         }
3225                                 }
3226                         }
3227
3228                         if (cache && !cache->locked) {
3229                                 /* Write it out and free it up */
3230
3231                                 chunkWritten =
3232                                     yaffs_wr_data_obj(cache->object,
3233                                                                  cache->chunk_id,
3234                                                                  cache->data,
3235                                                                  cache->n_bytes,
3236                                                                  1);
3237                                 cache->dirty = 0;
3238                                 cache->object = NULL;
3239                         }
3240
3241                 } while (cache && chunkWritten > 0);
3242
3243                 if (cache) {
3244                         /* Hoosterman, disk full while writing cache out. */
3245                         T(YAFFS_TRACE_ERROR,
3246                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3247
3248                 }
3249         }
3250
3251 }
3252
3253 /*yaffs_flush_whole_cache(dev)
3254  *
3255  *
3256  */
3257
3258 void yaffs_flush_whole_cache(yaffs_dev_t *dev)
3259 {
3260         yaffs_obj_t *obj;
3261         int nCaches = dev->param.n_caches;
3262         int i;
3263
3264         /* Find a dirty object in the cache and flush it...
3265          * until there are no further dirty objects.
3266          */
3267         do {
3268                 obj = NULL;
3269                 for (i = 0; i < nCaches && !obj; i++) {
3270                         if (dev->cache[i].object &&
3271                             dev->cache[i].dirty)
3272                                 obj = dev->cache[i].object;
3273
3274                 }
3275                 if (obj)
3276                         yaffs_flush_file_cache(obj);
3277
3278         } while (obj);
3279
3280 }
3281
3282
3283 /* Grab us a cache chunk for use.