yaffs: More clean up.
[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 "yaffs_guts.h"
18 #include "yaffs_tagsvalidity.h"
19 #include "yaffs_getblockinfo.h"
20
21 #include "yaffs_tagscompat.h"
22
23 #include "yaffs_nand.h"
24
25 #include "yaffs_yaffs1.h"
26 #include "yaffs_yaffs2.h"
27 #include "yaffs_bitmap.h"
28 #include "yaffs_verify.h"
29
30 #include "yaffs_nand.h"
31 #include "yaffs_packedtags2.h"
32
33 #include "yaffs_nameval.h"
34 #include "yaffs_allocator.h"
35
36 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
37 #define YAFFS_GC_GOOD_ENOUGH 2
38 #define YAFFS_GC_PASSIVE_THRESHOLD 4
39
40 #include "yaffs_ecc.h"
41
42
43
44 /* Robustification (if it ever comes about...) */
45 static void yaffs_retire_block(struct yaffs_dev *dev, int flash_block);
46 static void yaffs_handle_chunk_wr_error(struct yaffs_dev *dev, int nand_chunk,
47                 int erased_ok);
48 static void yaffs_handle_chunk_wr_ok(struct yaffs_dev *dev, int nand_chunk,
49                                 const u8 *data,
50                                 const struct yaffs_ext_tags *tags);
51 static void yaffs_handle_chunk_update(struct yaffs_dev *dev, int nand_chunk,
52                                 const struct yaffs_ext_tags *tags);
53
54 /* Other local prototypes */
55 static void yaffs_update_parent(struct yaffs_obj *obj);
56 static int yaffs_unlink_obj(struct yaffs_obj *obj);
57 static int yaffs_obj_cache_dirty(struct yaffs_obj *obj);
58
59 static int yaffs_write_new_chunk(struct yaffs_dev *dev,
60                                         const u8 *buffer,
61                                         struct yaffs_ext_tags *tags,
62                                         int use_reserver);
63
64
65 static struct yaffs_obj *yaffs_new_obj(struct yaffs_dev *dev, int number,
66                                         enum yaffs_obj_type type);
67
68
69 static int yaffs_apply_xattrib_mod(struct yaffs_obj *obj, char *buffer, struct yaffs_xattr_mod *xmod);
70
71 static void yaffs_remove_obj_from_dir(struct yaffs_obj *obj);
72 static int yaffs_generic_obj_del(struct yaffs_obj *in);
73
74 static int yaffs_check_chunk_erased(struct yaffs_dev *dev,
75                                 int nand_chunk);
76
77 static int yaffs_unlink_worker(struct yaffs_obj *obj);
78
79 static int yaffs_tags_match(const struct yaffs_ext_tags *tags, int obj_id,
80                         int chunk_obj);
81
82 static int yaffs_alloc_chunk(struct yaffs_dev *dev, int use_reserver,
83                                 struct yaffs_block_info **block_ptr);
84
85 static void yaffs_check_obj_details_loaded(struct yaffs_obj *in);
86
87 static void yaffs_invalidate_whole_cache(struct yaffs_obj *in);
88 static void yaffs_invalidate_chunk_cache(struct yaffs_obj *object, int chunk_id);
89
90 static int yaffs_find_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
91                                 struct yaffs_ext_tags *tags);
92
93 static int yaffs_verify_chunk_written(struct yaffs_dev *dev,
94                                         int nand_chunk,
95                                         const u8 *data,
96                                         struct yaffs_ext_tags *tags);
97
98
99 static void yaffs_load_name_from_oh(struct yaffs_dev *dev,YCHAR *name, const YCHAR *oh_name, int buff_size);
100 static void yaffs_load_oh_from_name(struct yaffs_dev *dev,YCHAR *oh_name, const YCHAR *name);
101
102
103 /* Function to calculate chunk and offset */
104
105 static void yaffs_addr_to_chunk(struct yaffs_dev *dev, loff_t addr, int *chunk_out,
106                 u32 *offset_out)
107 {
108         int chunk;
109         u32 offset;
110
111         chunk  = (u32)(addr >> dev->chunk_shift);
112
113         if (dev->chunk_div == 1) {
114                 /* easy power of 2 case */
115                 offset = (u32)(addr & dev->chunk_mask);
116         } else {
117                 /* Non power-of-2 case */
118
119                 loff_t chunk_base;
120
121                 chunk /= dev->chunk_div;
122
123                 chunk_base = ((loff_t)chunk) * dev->data_bytes_per_chunk;
124                 offset = (u32)(addr - chunk_base);
125         }
126
127         *chunk_out = chunk;
128         *offset_out = offset;
129 }
130
131 /* Function to return the number of shifts for a power of 2 greater than or
132  * equal to the given number
133  * Note we don't try to cater for all possible numbers and this does not have to
134  * be hellishly efficient.
135  */
136
137 static u32 calc_shifts_ceiling(u32 x)
138 {
139         int extra_bits;
140         int shifts;
141
142         shifts = extra_bits = 0;
143
144         while (x > 1) {
145                 if (x & 1)
146                         extra_bits++;
147                 x >>= 1;
148                 shifts++;
149         }
150
151         if (extra_bits)
152                 shifts++;
153
154         return shifts;
155 }
156
157 /* Function to return the number of shifts to get a 1 in bit 0
158  */
159
160 static u32 calc_shifts(u32 x)
161 {
162         u32 shifts;
163
164         shifts =  0;
165
166         if (!x)
167                 return 0;
168
169         while (!(x&1)) {
170                 x >>= 1;
171                 shifts++;
172         }
173
174         return shifts;
175 }
176
177
178
179 /*
180  * Temporary buffer manipulations.
181  */
182
183 static int yaffs_init_tmp_buffers(struct yaffs_dev *dev)
184 {
185         int i;
186         u8 *buf = (u8 *)1;
187
188         memset(dev->temp_buffer, 0, sizeof(dev->temp_buffer));
189
190         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
191                 dev->temp_buffer[i].line = 0;   /* not in use */
192                 dev->temp_buffer[i].buffer = buf =
193                     YMALLOC_DMA(dev->param.total_bytes_per_chunk);
194         }
195
196         return buf ? YAFFS_OK : YAFFS_FAIL;
197 }
198
199 u8 *yaffs_get_temp_buffer(struct yaffs_dev *dev, int line_no)
200 {
201         int i, j;
202
203         dev->temp_in_use++;
204         if (dev->temp_in_use > dev->max_temp)
205                 dev->max_temp = dev->temp_in_use;
206
207         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
208                 if (dev->temp_buffer[i].line == 0) {
209                         dev->temp_buffer[i].line = line_no;
210                         if ((i + 1) > dev->max_temp) {
211                                 dev->max_temp = i + 1;
212                                 for (j = 0; j <= i; j++)
213                                         dev->temp_buffer[j].max_line =
214                                             dev->temp_buffer[j].line;
215                         }
216
217                         return dev->temp_buffer[i].buffer;
218                 }
219         }
220
221         T(YAFFS_TRACE_BUFFERS,
222           (TSTR("Out of temp buffers at line %d, other held by lines:"),
223            line_no));
224         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
225                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->temp_buffer[i].line));
226
227         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
228
229         /*
230          * If we got here then we have to allocate an unmanaged one
231          * This is not good.
232          */
233
234         dev->unmanaged_buffer_allocs++;
235         return YMALLOC(dev->data_bytes_per_chunk);
236
237 }
238
239 void yaffs_release_temp_buffer(struct yaffs_dev *dev, u8 *buffer,
240                                     int line_no)
241 {
242         int i;
243
244         dev->temp_in_use--;
245
246         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
247                 if (dev->temp_buffer[i].buffer == buffer) {
248                         dev->temp_buffer[i].line = 0;
249                         return;
250                 }
251         }
252
253         if (buffer) {
254                 /* assume it is an unmanaged one. */
255                 T(YAFFS_TRACE_BUFFERS,
256                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
257                    line_no));
258                 YFREE(buffer);
259                 dev->unmanaged_buffer_deallocs++;
260         }
261
262 }
263
264 /*
265  * Determine if we have a managed buffer.
266  */
267 int yaffs_is_managed_tmp_buffer(struct yaffs_dev *dev, const u8 *buffer)
268 {
269         int i;
270
271         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
272                 if (dev->temp_buffer[i].buffer == buffer)
273                         return 1;
274         }
275
276         for (i = 0; i < dev->param.n_caches; i++) {
277                 if (dev->cache[i].data == buffer)
278                         return 1;
279         }
280
281         if (buffer == dev->checkpt_buffer)
282                 return 1;
283
284         T(YAFFS_TRACE_ALWAYS,
285                 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
286         return 0;
287 }
288
289 /*
290  * Verification code
291  */
292
293
294
295
296 /*
297  *  Simple hash function. Needs to have a reasonable spread
298  */
299
300 static Y_INLINE int yaffs_hash_fn(int n)
301 {
302         n = abs(n);
303         return n % YAFFS_NOBJECT_BUCKETS;
304 }
305
306 /*
307  * Access functions to useful fake objects.
308  * Note that root might have a presence in NAND if permissions are set.
309  */
310
311 struct yaffs_obj *yaffs_root(struct yaffs_dev *dev)
312 {
313         return dev->root_dir;
314 }
315
316 struct yaffs_obj *yaffs_lost_n_found(struct yaffs_dev *dev)
317 {
318         return dev->lost_n_found;
319 }
320
321
322 /*
323  *  Erased NAND checking functions
324  */
325
326 int yaffs_check_ff(u8 *buffer, int n_bytes)
327 {
328         /* Horrible, slow implementation */
329         while (n_bytes--) {
330                 if (*buffer != 0xFF)
331                         return 0;
332                 buffer++;
333         }
334         return 1;
335 }
336
337 static int yaffs_check_chunk_erased(struct yaffs_dev *dev,
338                                 int nand_chunk)
339 {
340         int retval = YAFFS_OK;
341         u8 *data = yaffs_get_temp_buffer(dev, __LINE__);
342         struct yaffs_ext_tags tags;
343         int result;
344
345         result = yaffs_rd_chunk_tags_nand(dev, nand_chunk, data, &tags);
346
347         if (tags.ecc_result > YAFFS_ECC_RESULT_NO_ERROR)
348                 retval = YAFFS_FAIL;
349
350         if (!yaffs_check_ff(data, dev->data_bytes_per_chunk) || tags.chunk_used) {
351                 T(YAFFS_TRACE_NANDACCESS,
352                   (TSTR("Chunk %d not erased" TENDSTR), nand_chunk));
353                 retval = YAFFS_FAIL;
354         }
355
356         yaffs_release_temp_buffer(dev, data, __LINE__);
357
358         return retval;
359
360 }
361
362
363 static int yaffs_verify_chunk_written(struct yaffs_dev *dev,
364                                         int nand_chunk,
365                                         const u8 *data,
366                                         struct yaffs_ext_tags *tags)
367 {
368         int retval = YAFFS_OK;
369         struct yaffs_ext_tags temp_tags;
370         u8 *buffer = yaffs_get_temp_buffer(dev,__LINE__);
371         int result;
372         
373         result = yaffs_rd_chunk_tags_nand(dev,nand_chunk,buffer,&temp_tags);
374         if(memcmp(buffer,data,dev->data_bytes_per_chunk) ||
375                 temp_tags.obj_id != tags->obj_id ||
376                 temp_tags.chunk_id  != tags->chunk_id ||
377                 temp_tags.n_bytes != tags->n_bytes)
378                 retval = YAFFS_FAIL;
379
380         yaffs_release_temp_buffer(dev, buffer, __LINE__);
381
382         return retval;
383 }
384
385 static int yaffs_write_new_chunk(struct yaffs_dev *dev,
386                                         const u8 *data,
387                                         struct yaffs_ext_tags *tags,
388                                         int use_reserver)
389 {
390         int attempts = 0;
391         int write_ok = 0;
392         int chunk;
393
394         yaffs2_checkpt_invalidate(dev);
395
396         do {
397                 struct yaffs_block_info *bi = 0;
398                 int erased_ok = 0;
399
400                 chunk = yaffs_alloc_chunk(dev, use_reserver, &bi);
401                 if (chunk < 0) {
402                         /* no space */
403                         break;
404                 }
405
406                 /* First check this chunk is erased, if it needs
407                  * checking.  The checking policy (unless forced
408                  * always on) is as follows:
409                  *
410                  * Check the first page we try to write in a block.
411                  * If the check passes then we don't need to check any
412                  * more.        If the check fails, we check again...
413                  * If the block has been erased, we don't need to check.
414                  *
415                  * However, if the block has been prioritised for gc,
416                  * then we think there might be something odd about
417                  * this block and stop using it.
418                  *
419                  * Rationale: We should only ever see chunks that have
420                  * not been erased if there was a partially written
421                  * chunk due to power loss.  This checking policy should
422                  * catch that case with very few checks and thus save a
423                  * lot of checks that are most likely not needed.
424                  *
425                  * Mods to the above
426                  * If an erase check fails or the write fails we skip the 
427                  * rest of the block.
428                  */
429
430                 /* let's give it a try */
431                 attempts++;
432
433                 if(dev->param.always_check_erased)
434                         bi->skip_erased_check = 0;
435
436                 if (!bi->skip_erased_check) {
437                         erased_ok = yaffs_check_chunk_erased(dev, chunk);
438                         if (erased_ok != YAFFS_OK) {
439                                 T(YAFFS_TRACE_ERROR,
440                                 (TSTR("**>> yaffs chunk %d was not erased"
441                                 TENDSTR), chunk));
442
443                                 /* If not erased, delete this one,
444                                  * skip rest of block and
445                                  * try another chunk */
446                                  yaffs_chunk_del(dev,chunk,1,__LINE__);
447                                  yaffs_skip_rest_of_block(dev);
448                                 continue;
449                         }
450                 }
451
452                 write_ok = yaffs_wr_chunk_tags_nand(dev, chunk,
453                                 data, tags);
454
455                 if(!bi->skip_erased_check)
456                         write_ok = yaffs_verify_chunk_written(dev, chunk, data, tags);
457
458                 if (write_ok != YAFFS_OK) {
459                         /* Clean up aborted write, skip to next block and
460                          * try another chunk */
461                         yaffs_handle_chunk_wr_error(dev, chunk, erased_ok);
462                         continue;
463                 }
464
465                 bi->skip_erased_check = 1;
466
467                 /* Copy the data into the robustification buffer */
468                 yaffs_handle_chunk_wr_ok(dev, chunk, data, tags);
469
470         } while (write_ok != YAFFS_OK &&
471                 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
472
473         if (!write_ok)
474                 chunk = -1;
475
476         if (attempts > 1) {
477                 T(YAFFS_TRACE_ERROR,
478                         (TSTR("**>> yaffs write required %d attempts" TENDSTR),
479                         attempts));
480
481                 dev->n_retired_writes += (attempts - 1);
482         }
483
484         return chunk;
485 }
486
487
488  
489 /*
490  * Block retiring for handling a broken block.
491  */
492
493 static void yaffs_retire_block(struct yaffs_dev *dev, int flash_block)
494 {
495         struct yaffs_block_info *bi = yaffs_get_block_info(dev, flash_block);
496
497         yaffs2_checkpt_invalidate(dev);
498         
499         yaffs2_clear_oldest_dirty_seq(dev,bi);
500
501         if (yaffs_mark_bad(dev, flash_block) != YAFFS_OK) {
502                 if (yaffs_erase_block(dev, flash_block) != YAFFS_OK) {
503                         T(YAFFS_TRACE_ALWAYS, (TSTR(
504                                 "yaffs: Failed to mark bad and erase block %d"
505                                 TENDSTR), flash_block));
506                 } else {
507                         struct yaffs_ext_tags tags;
508                         int chunk_id = flash_block * dev->param.chunks_per_block;
509
510                         u8 *buffer = yaffs_get_temp_buffer(dev, __LINE__);
511
512                         memset(buffer, 0xff, dev->data_bytes_per_chunk);
513                         yaffs_init_tags(&tags);
514                         tags.seq_number = YAFFS_SEQUENCE_BAD_BLOCK;
515                         if (dev->param.write_chunk_tags_fn(dev, chunk_id -
516                                 dev->chunk_offset, buffer, &tags) != YAFFS_OK)
517                                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
518                                         TCONT("write bad block marker to block %d")
519                                         TENDSTR), flash_block));
520
521                         yaffs_release_temp_buffer(dev, buffer, __LINE__);
522                 }
523         }
524
525         bi->block_state = YAFFS_BLOCK_STATE_DEAD;
526         bi->gc_prioritise = 0;
527         bi->needs_retiring = 0;
528
529         dev->n_retired_blocks++;
530 }
531
532 /*
533  * Functions for robustisizing TODO
534  *
535  */
536
537 static void yaffs_handle_chunk_wr_ok(struct yaffs_dev *dev, int nand_chunk,
538                                 const u8 *data,
539                                 const struct yaffs_ext_tags *tags)
540 {
541         dev=dev;
542         nand_chunk=nand_chunk;
543         data=data;
544         tags=tags;
545 }
546
547 static void yaffs_handle_chunk_update(struct yaffs_dev *dev, int nand_chunk,
548                                 const struct yaffs_ext_tags *tags)
549 {
550         dev=dev;
551         nand_chunk=nand_chunk;
552         tags=tags;
553 }
554
555 void yaffs_handle_chunk_error(struct yaffs_dev *dev, struct yaffs_block_info *bi)
556 {
557         if (!bi->gc_prioritise) {
558                 bi->gc_prioritise = 1;
559                 dev->has_pending_prioritised_gc = 1;
560                 bi->chunk_error_strikes++;
561
562                 if (bi->chunk_error_strikes > 3) {
563                         bi->needs_retiring = 1; /* Too many stikes, so retire this */
564                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
565
566                 }
567         }
568 }
569
570 static void yaffs_handle_chunk_wr_error(struct yaffs_dev *dev, int nand_chunk,
571                 int erased_ok)
572 {
573         int flash_block = nand_chunk / dev->param.chunks_per_block;
574         struct yaffs_block_info *bi = yaffs_get_block_info(dev, flash_block);
575
576         yaffs_handle_chunk_error(dev, bi);
577
578         if (erased_ok) {
579                 /* Was an actual write failure, so mark the block for retirement  */
580                 bi->needs_retiring = 1;
581                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
582                   (TSTR("**>> Block %d needs retiring" TENDSTR), flash_block));
583         }
584
585         /* Delete the chunk */
586         yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
587         yaffs_skip_rest_of_block(dev);
588 }
589
590
591 /*---------------- Name handling functions ------------*/
592
593 static u16 yaffs_calc_name_sum(const YCHAR *name)
594 {
595         u16 sum = 0;
596         u16 i = 1;
597
598         const YUCHAR *bname = (const YUCHAR *) name;
599         if (bname) {
600                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
601
602                         /* 0x1f mask is case insensitive */
603                         sum += ((*bname) & 0x1f) * i;
604                         i++;
605                         bname++;
606                 }
607         }
608         return sum;
609 }
610
611 void yaffs_set_obj_name(struct yaffs_obj *obj, const YCHAR *name)
612 {
613 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
614         memset(obj->short_name, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
615         if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
616                 yaffs_strcpy(obj->short_name, name);
617         else
618                 obj->short_name[0] = _Y('\0');
619 #endif
620         obj->sum = yaffs_calc_name_sum(name);
621 }
622
623 void yaffs_set_obj_name_from_oh(struct yaffs_obj *obj, const struct yaffs_obj_hdr *oh)
624 {
625 #ifdef CONFIG_YAFFS_AUTO_UNICODE
626         YCHAR tmp_name[YAFFS_MAX_NAME_LENGTH+1];
627         memset(tmp_name,0,sizeof(tmp_name));
628         yaffs_load_name_from_oh(obj->my_dev,tmp_name,oh->name,YAFFS_MAX_NAME_LENGTH+1);
629         yaffs_set_obj_name(obj,tmp_name);
630 #else
631         yaffs_set_obj_name(obj,oh->name);
632 #endif
633 }
634
635 /*-------------------- TNODES -------------------
636
637  * List of spare tnodes
638  * The list is hooked together using the first pointer
639  * in the tnode.
640  */
641
642
643 struct yaffs_tnode *yaffs_get_tnode(struct yaffs_dev *dev)
644 {
645         struct yaffs_tnode *tn = yaffs_alloc_raw_tnode(dev);
646         if (tn){
647                 memset(tn, 0, dev->tnode_size);
648                 dev->n_tnodes++;
649         }
650
651         dev->checkpoint_blocks_required = 0; /* force recalculation*/
652
653         return tn;
654 }
655
656 /* FreeTnode frees up a tnode and puts it back on the free list */
657 static void yaffs_free_tnode(struct yaffs_dev *dev, struct yaffs_tnode *tn)
658 {
659         yaffs_free_raw_tnode(dev,tn);
660         dev->n_tnodes--;
661         dev->checkpoint_blocks_required = 0; /* force recalculation*/
662 }
663
664 static void yaffs_deinit_tnodes_and_objs(struct yaffs_dev *dev)
665 {
666         yaffs_deinit_raw_tnodes_and_objs(dev);
667         dev->n_obj = 0;
668         dev->n_tnodes = 0;
669 }
670
671
672 void yaffs_load_tnode_0(struct yaffs_dev *dev, struct yaffs_tnode *tn, unsigned pos,
673                 unsigned val)
674 {
675         u32 *map = (u32 *)tn;
676         u32 bit_in_map;
677         u32 bit_in_word;
678         u32 word_in_map;
679         u32 mask;
680
681         pos &= YAFFS_TNODES_LEVEL0_MASK;
682         val >>= dev->chunk_grp_bits;
683
684         bit_in_map = pos * dev->tnode_width;
685         word_in_map = bit_in_map / 32;
686         bit_in_word = bit_in_map & (32 - 1);
687
688         mask = dev->tnode_mask << bit_in_word;
689
690         map[word_in_map] &= ~mask;
691         map[word_in_map] |= (mask & (val << bit_in_word));
692
693         if (dev->tnode_width > (32 - bit_in_word)) {
694                 bit_in_word = (32 - bit_in_word);
695                 word_in_map++;;
696                 mask = dev->tnode_mask >> (/*dev->tnode_width -*/ bit_in_word);
697                 map[word_in_map] &= ~mask;
698                 map[word_in_map] |= (mask & (val >> bit_in_word));
699         }
700 }
701
702 u32 yaffs_get_group_base(struct yaffs_dev *dev, struct yaffs_tnode *tn,
703                 unsigned pos)
704 {
705         u32 *map = (u32 *)tn;
706         u32 bit_in_map;
707         u32 bit_in_word;
708         u32 word_in_map;
709         u32 val;
710
711         pos &= YAFFS_TNODES_LEVEL0_MASK;
712
713         bit_in_map = pos * dev->tnode_width;
714         word_in_map = bit_in_map / 32;
715         bit_in_word = bit_in_map & (32 - 1);
716
717         val = map[word_in_map] >> bit_in_word;
718
719         if      (dev->tnode_width > (32 - bit_in_word)) {
720                 bit_in_word = (32 - bit_in_word);
721                 word_in_map++;;
722                 val |= (map[word_in_map] << bit_in_word);
723         }
724
725         val &= dev->tnode_mask;
726         val <<= dev->chunk_grp_bits;
727
728         return val;
729 }
730
731 /* ------------------- End of individual tnode manipulation -----------------*/
732
733 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
734  * The look up tree is represented by the top tnode and the number of top_level
735  * in the tree. 0 means only the level 0 tnode is in the tree.
736  */
737
738 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
739 struct yaffs_tnode *yaffs_find_tnode_0(struct yaffs_dev *dev,
740                                         struct yaffs_file_var *file_struct,
741                                         u32 chunk_id)
742 {
743         struct yaffs_tnode *tn = file_struct->top;
744         u32 i;
745         int required_depth;
746         int level = file_struct->top_level;
747
748         dev=dev;
749
750         /* Check sane level and chunk Id */
751         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
752                 return NULL;
753
754         if (chunk_id > YAFFS_MAX_CHUNK_ID)
755                 return NULL;
756
757         /* First check we're tall enough (ie enough top_level) */
758
759         i = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
760         required_depth = 0;
761         while (i) {
762                 i >>= YAFFS_TNODES_INTERNAL_BITS;
763                 required_depth++;
764         }
765
766         if (required_depth > file_struct->top_level)
767                 return NULL; /* Not tall enough, so we can't find it */
768
769         /* Traverse down to level 0 */
770         while (level > 0 && tn) {
771                 tn = tn->internal[(chunk_id >>
772                         (YAFFS_TNODES_LEVEL0_BITS +
773                                 (level - 1) *
774                                 YAFFS_TNODES_INTERNAL_BITS)) &
775                         YAFFS_TNODES_INTERNAL_MASK];
776                 level--;
777         }
778
779         return tn;
780 }
781
782 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
783  * This happens in two steps:
784  *  1. If the tree isn't tall enough, then make it taller.
785  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
786  *
787  * Used when modifying the tree.
788  *
789  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
790  *  be plugged into the ttree.
791  */
792
793 struct yaffs_tnode *yaffs_add_find_tnode_0(struct yaffs_dev *dev,
794                                         struct yaffs_file_var *file_struct,
795                                         u32 chunk_id,
796                                         struct yaffs_tnode *passed_tn)
797 {
798         int required_depth;
799         int i;
800         int l;
801         struct yaffs_tnode *tn;
802
803         u32 x;
804
805
806         /* Check sane level and page Id */
807         if (file_struct->top_level < 0 || file_struct->top_level > YAFFS_TNODES_MAX_LEVEL)
808                 return NULL;
809
810         if (chunk_id > YAFFS_MAX_CHUNK_ID)
811                 return NULL;
812
813         /* First check we're tall enough (ie enough top_level) */
814
815         x = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
816         required_depth = 0;
817         while (x) {
818                 x >>= YAFFS_TNODES_INTERNAL_BITS;
819                 required_depth++;
820         }
821
822
823         if (required_depth > file_struct->top_level) {
824                 /* Not tall enough, gotta make the tree taller */
825                 for (i = file_struct->top_level; i < required_depth; i++) {
826
827                         tn = yaffs_get_tnode(dev);
828
829                         if (tn) {
830                                 tn->internal[0] = file_struct->top;
831                                 file_struct->top = tn;
832                                 file_struct->top_level++;
833                         } else {
834                                 T(YAFFS_TRACE_ERROR,
835                                         (TSTR("yaffs: no more tnodes" TENDSTR)));
836                                 return NULL;
837                         }
838                 }
839         }
840
841         /* Traverse down to level 0, adding anything we need */
842
843         l = file_struct->top_level;
844         tn = file_struct->top;
845
846         if (l > 0) {
847                 while (l > 0 && tn) {
848                         x = (chunk_id >>
849                              (YAFFS_TNODES_LEVEL0_BITS +
850                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
851                             YAFFS_TNODES_INTERNAL_MASK;
852
853
854                         if ((l > 1) && !tn->internal[x]) {
855                                 /* Add missing non-level-zero tnode */
856                                 tn->internal[x] = yaffs_get_tnode(dev);
857                                 if(!tn->internal[x])
858                                         return NULL;
859                         } else if (l == 1) {
860                                 /* Looking from level 1 at level 0 */
861                                 if (passed_tn) {
862                                         /* If we already have one, then release it.*/
863                                         if (tn->internal[x])
864                                                 yaffs_free_tnode(dev, tn->internal[x]);
865                                         tn->internal[x] = passed_tn;
866
867                                 } else if (!tn->internal[x]) {
868                                         /* Don't have one, none passed in */
869                                         tn->internal[x] = yaffs_get_tnode(dev);
870                                         if(!tn->internal[x])
871                                                 return NULL;
872                                 }
873                         }
874
875                         tn = tn->internal[x];
876                         l--;
877                 }
878         } else {
879                 /* top is level 0 */
880                 if (passed_tn) {
881                         memcpy(tn, passed_tn, (dev->tnode_width * YAFFS_NTNODES_LEVEL0)/8);
882                         yaffs_free_tnode(dev, passed_tn);
883                 }
884         }
885
886         return tn;
887 }
888
889 static int yaffs_find_chunk_in_group(struct yaffs_dev *dev, int the_chunk,
890                                 struct yaffs_ext_tags *tags, int obj_id,
891                                 int inode_chunk)
892 {
893         int j;
894
895         for (j = 0; the_chunk && j < dev->chunk_grp_size; j++) {
896                 if (yaffs_check_chunk_bit(dev, the_chunk / dev->param.chunks_per_block,
897                                 the_chunk % dev->param.chunks_per_block)) {
898                         
899                         if(dev->chunk_grp_size == 1)
900                                 return the_chunk;
901                         else {
902                                 yaffs_rd_chunk_tags_nand(dev, the_chunk, NULL,
903                                                                 tags);
904                                 if (yaffs_tags_match(tags, obj_id, inode_chunk)) {
905                                         /* found it; */
906                                         return the_chunk;
907                                 }
908                         }
909                 }
910                 the_chunk++;
911         }
912         return -1;
913 }
914
915
916 static void yaffs_soft_del_chunk(struct yaffs_dev *dev, int chunk)
917 {
918         struct yaffs_block_info *the_block;
919         unsigned block_no;
920
921         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
922
923         block_no =  chunk / dev->param.chunks_per_block;
924         the_block = yaffs_get_block_info(dev, block_no);
925         if (the_block) {
926                 the_block->soft_del_pages++;
927                 dev->n_free_chunks++;
928                 yaffs2_update_oldest_dirty_seq(dev, block_no, the_block);
929         }
930 }
931
932 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
933  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
934  * of the tnode.
935  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
936  */
937
938 static int yaffs_soft_del_worker(struct yaffs_obj *in, struct yaffs_tnode *tn,
939                                   u32 level, int chunk_offset)
940 {
941         int i;
942         int the_chunk;
943         int all_done = 1;
944         struct yaffs_dev *dev = in->my_dev;
945
946         if (tn) {
947                 if (level > 0) {
948
949                         for (i = YAFFS_NTNODES_INTERNAL - 1; all_done && i >= 0;
950                              i--) {
951                                 if (tn->internal[i]) {
952                                         all_done =
953                                             yaffs_soft_del_worker(in,
954                                                                    tn->
955                                                                    internal[i],
956                                                                    level - 1,
957                                                                    (chunk_offset
958                                                                     <<
959                                                                     YAFFS_TNODES_INTERNAL_BITS)
960                                                                    + i);
961                                         if (all_done) {
962                                                 yaffs_free_tnode(dev,
963                                                                 tn->
964                                                                 internal[i]);
965                                                 tn->internal[i] = NULL;
966                                         } else {
967                                                 /* Hoosterman... how could this happen? */
968                                         }
969                                 }
970                         }
971                         return (all_done) ? 1 : 0;
972                 } else if (level == 0) {
973
974                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
975                                 the_chunk = yaffs_get_group_base(dev, tn, i);
976                                 if (the_chunk) {
977                                         /* Note this does not find the real chunk, only the chunk group.
978                                          * We make an assumption that a chunk group is not larger than
979                                          * a block.
980                                          */
981                                         yaffs_soft_del_chunk(dev, the_chunk);
982                                         yaffs_load_tnode_0(dev, tn, i, 0);
983                                 }
984
985                         }
986                         return 1;
987
988                 }
989
990         }
991
992         return 1;
993
994 }
995
996 static void yaffs_soft_del_file(struct yaffs_obj *obj)
997 {
998         if (obj->deleted &&
999             obj->variant_type == YAFFS_OBJECT_TYPE_FILE && !obj->soft_del) {
1000                 if (obj->n_data_chunks <= 0) {
1001                         /* Empty file with no duplicate object headers, just delete it immediately */
1002                         yaffs_free_tnode(obj->my_dev,
1003                                         obj->variant.file_variant.top);
1004                         obj->variant.file_variant.top = NULL;
1005                         T(YAFFS_TRACE_TRACING,
1006                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1007                            obj->obj_id));
1008                         yaffs_generic_obj_del(obj);
1009                 } else {
1010                         yaffs_soft_del_worker(obj,
1011                                                obj->variant.file_variant.top,
1012                                                obj->variant.file_variant.
1013                                                top_level, 0);
1014                         obj->soft_del = 1;
1015                 }
1016         }
1017 }
1018
1019 /* Pruning removes any part of the file structure tree that is beyond the
1020  * bounds of the file (ie that does not point to chunks).
1021  *
1022  * A file should only get pruned when its size is reduced.
1023  *
1024  * Before pruning, the chunks must be pulled from the tree and the
1025  * level 0 tnode entries must be zeroed out.
1026  * Could also use this for file deletion, but that's probably better handled
1027  * by a special case.
1028  *
1029  * This function is recursive. For levels > 0 the function is called again on
1030  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1031  * If there is no data in a subtree then it is pruned.
1032  */
1033
1034 static struct yaffs_tnode *yaffs_prune_worker(struct yaffs_dev *dev, struct yaffs_tnode *tn,
1035                                 u32 level, int del0)
1036 {
1037         int i;
1038         int has_data;
1039
1040         if (tn) {
1041                 has_data = 0;
1042
1043                 if(level > 0){
1044                         for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1045                                 if (tn->internal[i]) {
1046                                         tn->internal[i] =
1047                                                 yaffs_prune_worker(dev, tn->internal[i],
1048                                                         level - 1,
1049                                                         (i == 0) ? del0 : 1);
1050                                 }
1051
1052                                 if (tn->internal[i])
1053                                         has_data++;
1054                         }
1055                 } else {
1056                         int tnode_size_u32 = dev->tnode_size/sizeof(u32);
1057                         u32 *map = (u32 *)tn;
1058
1059                         for(i = 0; !has_data && i < tnode_size_u32; i++){
1060                                 if(map[i])
1061                                         has_data++;
1062                         }
1063                 }
1064
1065                 if (has_data == 0 && del0) {
1066                         /* Free and return NULL */
1067
1068                         yaffs_free_tnode(dev, tn);
1069                         tn = NULL;
1070                 }
1071
1072         }
1073
1074         return tn;
1075
1076 }
1077
1078 static int yaffs_prune_tree(struct yaffs_dev *dev,
1079                                 struct yaffs_file_var *file_struct)
1080 {
1081         int i;
1082         int has_data;
1083         int done = 0;
1084         struct yaffs_tnode *tn;
1085
1086         if (file_struct->top_level > 0) {
1087                 file_struct->top =
1088                     yaffs_prune_worker(dev, file_struct->top, file_struct->top_level, 0);
1089
1090                 /* Now we have a tree with all the non-zero branches NULL but the height
1091                  * is the same as it was.
1092                  * Let's see if we can trim internal tnodes to shorten the tree.
1093                  * We can do this if only the 0th element in the tnode is in use
1094                  * (ie all the non-zero are NULL)
1095                  */
1096
1097                 while (file_struct->top_level && !done) {
1098                         tn = file_struct->top;
1099
1100                         has_data = 0;
1101                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1102                                 if (tn->internal[i])
1103                                         has_data++;
1104                         }
1105
1106                         if (!has_data) {
1107                                 file_struct->top = tn->internal[0];
1108                                 file_struct->top_level--;
1109                                 yaffs_free_tnode(dev, tn);
1110                         } else {
1111                                 done = 1;
1112                         }
1113                 }
1114         }
1115
1116         return YAFFS_OK;
1117 }
1118
1119 /*-------------------- End of File Structure functions.-------------------*/
1120
1121
1122 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1123 static struct yaffs_obj *yaffs_alloc_empty_obj(struct yaffs_dev *dev)
1124 {
1125         struct yaffs_obj *obj = yaffs_alloc_raw_obj(dev);
1126
1127         if (obj) {
1128                 dev->n_obj++;
1129
1130                 /* Now sweeten it up... */
1131
1132                 memset(obj, 0, sizeof(struct yaffs_obj));
1133                 obj->being_created = 1;
1134
1135                 obj->my_dev = dev;
1136                 obj->hdr_chunk = 0;
1137                 obj->variant_type = YAFFS_OBJECT_TYPE_UNKNOWN;
1138                 INIT_LIST_HEAD(&(obj->hard_links));
1139                 INIT_LIST_HEAD(&(obj->hash_link));
1140                 INIT_LIST_HEAD(&obj->siblings);
1141
1142
1143                 /* Now make the directory sane */
1144                 if (dev->root_dir) {
1145                         obj->parent = dev->root_dir;
1146                         list_add(&(obj->siblings), &dev->root_dir->variant.dir_variant.children);
1147                 }
1148
1149                 /* Add it to the lost and found directory.
1150                  * NB Can't put root or lost-n-found in lost-n-found so
1151                  * check if lost-n-found exists first
1152                  */
1153                 if (dev->lost_n_found)
1154                         yaffs_add_obj_to_dir(dev->lost_n_found, obj);
1155
1156                 obj->being_created = 0;
1157         }
1158
1159         dev->checkpoint_blocks_required = 0; /* force recalculation*/
1160
1161         return obj;
1162 }
1163
1164 static struct yaffs_obj *yaffs_create_fake_dir(struct yaffs_dev *dev, int number,
1165                                                u32 mode)
1166 {
1167
1168         struct yaffs_obj *obj =
1169             yaffs_new_obj(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1170         if (obj) {
1171                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
1172                 obj->rename_allowed = 0;        /* ... and we're not allowed to rename it... */
1173                 obj->unlink_allowed = 0;        /* ... or unlink it */
1174                 obj->deleted = 0;
1175                 obj->unlinked = 0;
1176                 obj->yst_mode = mode;
1177                 obj->my_dev = dev;
1178                 obj->hdr_chunk = 0;     /* Not a valid chunk. */
1179         }
1180
1181         return obj;
1182
1183 }
1184
1185 static void yaffs_unhash_obj(struct yaffs_obj *obj)
1186 {
1187         int bucket;
1188         struct yaffs_dev *dev = obj->my_dev;
1189
1190         /* If it is still linked into the bucket list, free from the list */
1191         if (!list_empty(&obj->hash_link)) {
1192                 list_del_init(&obj->hash_link);
1193                 bucket = yaffs_hash_fn(obj->obj_id);
1194                 dev->obj_bucket[bucket].count--;
1195         }
1196 }
1197
1198 /*  FreeObject frees up a Object and puts it back on the free list */
1199 static void yaffs_free_obj(struct yaffs_obj *obj)
1200 {
1201         struct yaffs_dev *dev = obj->my_dev;
1202
1203         T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), obj, obj->my_inode));
1204
1205         if (!obj)
1206                 YBUG();
1207         if (obj->parent)
1208                 YBUG();
1209         if (!list_empty(&obj->siblings))
1210                 YBUG();
1211
1212
1213         if (obj->my_inode) {
1214                 /* We're still hooked up to a cached inode.
1215                  * Don't delete now, but mark for later deletion
1216                  */
1217                 obj->defered_free = 1;
1218                 return;
1219         }
1220
1221         yaffs_unhash_obj(obj);
1222
1223         yaffs_free_raw_obj(dev,obj);
1224         dev->n_obj--;
1225         dev->checkpoint_blocks_required = 0; /* force recalculation*/
1226 }
1227
1228
1229 void yaffs_handle_defered_free(struct yaffs_obj *obj)
1230 {
1231         if (obj->defered_free)
1232                 yaffs_free_obj(obj);
1233 }
1234
1235 static void yaffs_init_tnodes_and_objs(struct yaffs_dev *dev)
1236 {
1237         int i;
1238
1239         dev->n_obj = 0;
1240         dev->n_tnodes = 0;
1241
1242         yaffs_init_raw_tnodes_and_objs(dev);
1243
1244         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1245                 INIT_LIST_HEAD(&dev->obj_bucket[i].list);
1246                 dev->obj_bucket[i].count = 0;
1247         }
1248 }
1249
1250 static int yaffs_find_nice_bucket(struct yaffs_dev *dev)
1251 {
1252         int i;
1253         int l = 999;
1254         int lowest = 999999;
1255
1256
1257         /* Search for the shortest list or one that
1258          * isn't too long.
1259          */
1260
1261         for (i = 0; i < 10 && lowest > 4; i++) {
1262                 dev->bucket_finder++;
1263                 dev->bucket_finder %= YAFFS_NOBJECT_BUCKETS;
1264                 if (dev->obj_bucket[dev->bucket_finder].count < lowest) {
1265                         lowest = dev->obj_bucket[dev->bucket_finder].count;
1266                         l = dev->bucket_finder;
1267                 }
1268
1269         }
1270
1271         return l;
1272 }
1273
1274 static int yaffs_new_obj_id(struct yaffs_dev *dev)
1275 {
1276         int bucket = yaffs_find_nice_bucket(dev);
1277
1278         /* Now find an object value that has not already been taken
1279          * by scanning the list.
1280          */
1281
1282         int found = 0;
1283         struct list_head *i;
1284
1285         u32 n = (u32) bucket;
1286
1287         /* yaffs_check_obj_hash_sane();  */
1288
1289         while (!found) {
1290                 found = 1;
1291                 n += YAFFS_NOBJECT_BUCKETS;
1292                 if (1 || dev->obj_bucket[bucket].count > 0) {
1293                         list_for_each(i, &dev->obj_bucket[bucket].list) {
1294                                 /* If there is already one in the list */
1295                                 if (i && list_entry(i, struct yaffs_obj,
1296                                                 hash_link)->obj_id == n) {
1297                                         found = 0;
1298                                 }
1299                         }
1300                 }
1301         }
1302
1303         return n;
1304 }
1305
1306 static void yaffs_hash_obj(struct yaffs_obj *in)
1307 {
1308         int bucket = yaffs_hash_fn(in->obj_id);
1309         struct yaffs_dev *dev = in->my_dev;
1310
1311         list_add(&in->hash_link, &dev->obj_bucket[bucket].list);
1312         dev->obj_bucket[bucket].count++;
1313 }
1314
1315 struct yaffs_obj *yaffs_find_by_number(struct yaffs_dev *dev, u32 number)
1316 {
1317         int bucket = yaffs_hash_fn(number);
1318         struct list_head *i;
1319         struct yaffs_obj *in;
1320
1321         list_for_each(i, &dev->obj_bucket[bucket].list) {
1322                 /* Look if it is in the list */
1323                 if (i) {
1324                         in = list_entry(i, struct yaffs_obj, hash_link);
1325                         if (in->obj_id == number) {
1326
1327                                 /* Don't tell the VFS about this one if it is defered free */
1328                                 if (in->defered_free)
1329                                         return NULL;
1330
1331                                 return in;
1332                         }
1333                 }
1334         }
1335
1336         return NULL;
1337 }
1338
1339 struct yaffs_obj *yaffs_new_obj(struct yaffs_dev *dev, int number,
1340                                     enum yaffs_obj_type type)
1341 {
1342         struct yaffs_obj *the_obj=NULL;
1343         struct yaffs_tnode *tn = NULL;
1344
1345         if (number < 0)
1346                 number = yaffs_new_obj_id(dev);
1347
1348         if (type == YAFFS_OBJECT_TYPE_FILE) {
1349                 tn = yaffs_get_tnode(dev);
1350                 if (!tn)
1351                         return NULL;
1352         }
1353
1354         the_obj = yaffs_alloc_empty_obj(dev);
1355         if (!the_obj){
1356                 if(tn)
1357                         yaffs_free_tnode(dev,tn);
1358                 return NULL;
1359         }
1360
1361
1362         if (the_obj) {
1363                 the_obj->fake = 0;
1364                 the_obj->rename_allowed = 1;
1365                 the_obj->unlink_allowed = 1;
1366                 the_obj->obj_id = number;
1367                 yaffs_hash_obj(the_obj);
1368                 the_obj->variant_type = type;
1369 #ifdef CONFIG_YAFFS_WINCE
1370                 yfsd_win_file_time_now(the_obj->win_atime);
1371                 the_obj->win_ctime[0] = the_obj->win_mtime[0] =
1372                     the_obj->win_atime[0];
1373                 the_obj->win_ctime[1] = the_obj->win_mtime[1] =
1374                     the_obj->win_atime[1];
1375
1376 #else
1377
1378                 the_obj->yst_atime = the_obj->yst_mtime =
1379                     the_obj->yst_ctime = Y_CURRENT_TIME;
1380 #endif
1381                 switch (type) {
1382                 case YAFFS_OBJECT_TYPE_FILE:
1383                         the_obj->variant.file_variant.file_size = 0;
1384                         the_obj->variant.file_variant.scanned_size = 0;
1385                         the_obj->variant.file_variant.shrink_size = 0xFFFFFFFF; /* max u32 */
1386                         the_obj->variant.file_variant.top_level = 0;
1387                         the_obj->variant.file_variant.top = tn;
1388                         break;
1389                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1390                         INIT_LIST_HEAD(&the_obj->variant.dir_variant.
1391                                         children);
1392                         INIT_LIST_HEAD(&the_obj->variant.dir_variant.
1393                                         dirty);
1394                         break;
1395                 case YAFFS_OBJECT_TYPE_SYMLINK:
1396                 case YAFFS_OBJECT_TYPE_HARDLINK:
1397                 case YAFFS_OBJECT_TYPE_SPECIAL:
1398                         /* No action required */
1399                         break;
1400                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1401                         /* todo this should not happen */
1402                         break;
1403                 }
1404         }
1405
1406         return the_obj;
1407 }
1408
1409 struct yaffs_obj *yaffs_find_or_create_by_number(struct yaffs_dev *dev,
1410                                                 int number,
1411                                                 enum yaffs_obj_type type)
1412 {
1413         struct yaffs_obj *the_obj = NULL;
1414
1415         if (number > 0)
1416                 the_obj = yaffs_find_by_number(dev, number);
1417
1418         if (!the_obj)
1419                 the_obj = yaffs_new_obj(dev, number, type);
1420
1421         return the_obj;
1422
1423 }
1424
1425
1426 YCHAR *yaffs_clone_str(const YCHAR *str)
1427 {
1428         YCHAR *new_str = NULL;
1429         int len;
1430
1431         if (!str)
1432                 str = _Y("");
1433
1434         len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
1435         new_str = YMALLOC((len + 1) * sizeof(YCHAR));
1436         if (new_str){
1437                 yaffs_strncpy(new_str, str,len);
1438                 new_str[len] = 0;
1439         }
1440         return new_str;
1441
1442 }
1443
1444 /*
1445  * Mknod (create) a new object.
1446  * equiv_obj only has meaning for a hard link;
1447  * alias_str only has meaning for a symlink.
1448  * rdev only has meaning for devices (a subset of special objects)
1449  */
1450
1451 static struct yaffs_obj *yaffs_create_obj(enum yaffs_obj_type type,
1452                                        struct yaffs_obj *parent,
1453                                        const YCHAR *name,
1454                                        u32 mode,
1455                                        u32 uid,
1456                                        u32 gid,
1457                                        struct yaffs_obj *equiv_obj,
1458                                        const YCHAR *alias_str, u32 rdev)
1459 {
1460         struct yaffs_obj *in;
1461         YCHAR *str = NULL;
1462
1463         struct yaffs_dev *dev = parent->my_dev;
1464
1465         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1466         if (yaffs_find_by_name(parent, name))
1467                 return NULL;
1468
1469         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
1470                 str = yaffs_clone_str(alias_str);
1471                 if (!str)
1472                         return NULL;
1473         }
1474
1475         in = yaffs_new_obj(dev, -1, type);
1476
1477         if (!in){
1478                 if(str)
1479                         YFREE(str);
1480                 return NULL;
1481         }
1482
1483
1484
1485
1486
1487         if (in) {
1488                 in->hdr_chunk = 0;
1489                 in->valid = 1;
1490                 in->variant_type = type;
1491
1492                 in->yst_mode = mode;
1493
1494 #ifdef CONFIG_YAFFS_WINCE
1495                 yfsd_win_file_time_now(in->win_atime);
1496                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1497                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1498
1499 #else
1500                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1501
1502                 in->yst_rdev = rdev;
1503                 in->yst_uid = uid;
1504                 in->yst_gid = gid;
1505 #endif
1506                 in->n_data_chunks = 0;
1507
1508                 yaffs_set_obj_name(in, name);
1509                 in->dirty = 1;
1510
1511                 yaffs_add_obj_to_dir(parent, in);
1512
1513                 in->my_dev = parent->my_dev;
1514
1515                 switch (type) {
1516                 case YAFFS_OBJECT_TYPE_SYMLINK:
1517                         in->variant.symlink_variant.alias = str;
1518                         break;
1519                 case YAFFS_OBJECT_TYPE_HARDLINK:
1520                         in->variant.hardlink_variant.equiv_obj =
1521                                 equiv_obj;
1522                         in->variant.hardlink_variant.equiv_id =
1523                                 equiv_obj->obj_id;
1524                         list_add(&in->hard_links, &equiv_obj->hard_links);
1525                         break;
1526                 case YAFFS_OBJECT_TYPE_FILE:
1527                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1528                 case YAFFS_OBJECT_TYPE_SPECIAL:
1529                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1530                         /* do nothing */
1531                         break;
1532                 }
1533
1534                 if (yaffs_update_oh(in, name, 0, 0, 0, NULL) < 0) {
1535                         /* Could not create the object header, fail the creation */
1536                         yaffs_del_obj(in);
1537                         in = NULL;
1538                 }
1539
1540                 yaffs_update_parent(parent);
1541         }
1542
1543         return in;
1544 }
1545
1546 struct yaffs_obj *yaffs_create_file(struct yaffs_obj *parent, const YCHAR *name,
1547                         u32 mode, u32 uid, u32 gid)
1548 {
1549         return yaffs_create_obj(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1550                                 uid, gid, NULL, NULL, 0);
1551 }
1552
1553 struct yaffs_obj *yaffs_create_dir(struct yaffs_obj *parent, const YCHAR *name,
1554                                 u32 mode, u32 uid, u32 gid)
1555 {
1556         return yaffs_create_obj(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1557                                  mode, uid, gid, NULL, NULL, 0);
1558 }
1559
1560 struct yaffs_obj *yaffs_create_special(struct yaffs_obj *parent, const YCHAR *name,
1561                                 u32 mode, u32 uid, u32 gid, u32 rdev)
1562 {
1563         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1564                                  uid, gid, NULL, NULL, rdev);
1565 }
1566
1567 struct yaffs_obj *yaffs_create_symlink(struct yaffs_obj *parent, const YCHAR *name,
1568                                 u32 mode, u32 uid, u32 gid,
1569                                 const YCHAR *alias)
1570 {
1571         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1572                                 uid, gid, NULL, alias, 0);
1573 }
1574
1575 /* yaffs_link_obj returns the object id of the equivalent object.*/
1576 struct yaffs_obj *yaffs_link_obj(struct yaffs_obj *parent, const YCHAR *name,
1577                         struct yaffs_obj *equiv_obj)
1578 {
1579         /* Get the real object in case we were fed a hard link as an equivalent object */
1580         equiv_obj = yaffs_get_equivalent_obj(equiv_obj);
1581
1582         if (yaffs_create_obj
1583             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1584              equiv_obj, NULL, 0)) {
1585                 return equiv_obj;
1586         } else {
1587                 return NULL;
1588         }
1589
1590 }
1591
1592 static int yaffs_change_obj_name(struct yaffs_obj *obj, struct yaffs_obj *new_dir,
1593                                 const YCHAR *new_name, int force, int shadows)
1594 {
1595         int unlink_op;
1596         int del_op;
1597
1598         struct yaffs_obj *existing_target;
1599
1600         if (new_dir == NULL)
1601                 new_dir = obj->parent;  /* use the old directory */
1602
1603         if (new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
1604                 T(YAFFS_TRACE_ALWAYS,
1605                   (TSTR
1606                    ("tragedy: yaffs_change_obj_name: new_dir is not a directory"
1607                     TENDSTR)));
1608                 YBUG();
1609         }
1610
1611         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1612         if (obj->my_dev->param.is_yaffs2)
1613                 unlink_op = (new_dir == obj->my_dev->unlinked_dir);
1614         else
1615                 unlink_op = (new_dir == obj->my_dev->unlinked_dir
1616                             && obj->variant_type == YAFFS_OBJECT_TYPE_FILE);
1617
1618         del_op = (new_dir == obj->my_dev->del_dir);
1619
1620         existing_target = yaffs_find_by_name(new_dir, new_name);
1621
1622         /* If the object is a file going into the unlinked directory,
1623          *   then it is OK to just stuff it in since duplicate names are allowed.
1624          *   else only proceed if the new name does not exist and if we're putting
1625          *   it into a directory.
1626          */
1627         if ((unlink_op ||
1628              del_op ||
1629              force ||
1630              (shadows > 0) ||
1631              !existing_target) &&
1632             new_dir->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY) {
1633                 yaffs_set_obj_name(obj, new_name);
1634                 obj->dirty = 1;
1635
1636                 yaffs_add_obj_to_dir(new_dir, obj);
1637
1638                 if (unlink_op)
1639                         obj->unlinked = 1;
1640
1641                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1642                 if (yaffs_update_oh(obj, new_name, 0, del_op, shadows, NULL) >= 0)
1643                         return YAFFS_OK;
1644         }
1645
1646         return YAFFS_FAIL;
1647 }
1648
1649 int yaffs_rename_obj(struct yaffs_obj *old_dir, const YCHAR *old_name,
1650                 struct yaffs_obj *new_dir, const YCHAR *new_name)
1651 {
1652         struct yaffs_obj *obj = NULL;
1653         struct yaffs_obj *existing_target = NULL;
1654         int force = 0;
1655         int result;
1656         struct yaffs_dev *dev;
1657
1658
1659         if (!old_dir || old_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1660                 YBUG();
1661         if (!new_dir || new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1662                 YBUG();
1663
1664         dev = old_dir->my_dev;
1665
1666 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1667         /* Special case for case insemsitive systems (eg. WinCE).
1668          * While look-up is case insensitive, the name isn't.
1669          * Therefore we might want to change x.txt to X.txt
1670         */
1671         if (old_dir == new_dir && yaffs_strcmp(old_name, new_name) == 0)
1672                 force = 1;
1673 #endif
1674
1675         if(yaffs_strnlen(new_name,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
1676                 /* ENAMETOOLONG */
1677                 return YAFFS_FAIL;
1678
1679         obj = yaffs_find_by_name(old_dir, old_name);
1680
1681         if (obj && obj->rename_allowed) {
1682
1683                 /* Now do the handling for an existing target, if there is one */
1684
1685                 existing_target = yaffs_find_by_name(new_dir, new_name);
1686                 if (existing_target &&
1687                         existing_target->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY &&
1688                         !list_empty(&existing_target->variant.dir_variant.children)) {
1689                         /* There is a target that is a non-empty directory, so we fail */
1690                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
1691                 } else if (existing_target && existing_target != obj) {
1692                         /* Nuke the target first, using shadowing,
1693                          * but only if it isn't the same object.
1694                          *
1695                          * Note we must disable gc otherwise it can mess up the shadowing.
1696                          *
1697                          */
1698                         dev->gc_disable=1;
1699                         yaffs_change_obj_name(obj, new_dir, new_name, force,
1700                                                 existing_target->obj_id);
1701                         existing_target->is_shadowed = 1;
1702                         yaffs_unlink_obj(existing_target);
1703                         dev->gc_disable=0;
1704                 }
1705
1706                 result = yaffs_change_obj_name(obj, new_dir, new_name, 1, 0);
1707
1708                 yaffs_update_parent(old_dir);
1709                 if(new_dir != old_dir)
1710                         yaffs_update_parent(new_dir);
1711                 
1712                 return result;
1713         }
1714         return YAFFS_FAIL;
1715 }
1716
1717 /*------------------------- Block Management and Page Allocation ----------------*/
1718
1719 static int yaffs_init_blocks(struct yaffs_dev *dev)
1720 {
1721         int n_blocks = dev->internal_end_block - dev->internal_start_block + 1;
1722
1723         dev->block_info = NULL;
1724         dev->chunk_bits = NULL;
1725
1726         dev->alloc_block = -1;  /* force it to get a new one */
1727
1728         /* If the first allocation strategy fails, thry the alternate one */
1729         dev->block_info = YMALLOC(n_blocks * sizeof(struct yaffs_block_info));
1730         if (!dev->block_info) {
1731                 dev->block_info = YMALLOC_ALT(n_blocks * sizeof(struct yaffs_block_info));
1732                 dev->block_info_alt = 1;
1733         } else
1734                 dev->block_info_alt = 0;
1735
1736         if (dev->block_info) {
1737                 /* Set up dynamic blockinfo stuff. */
1738                 dev->chunk_bit_stride = (dev->param.chunks_per_block + 7) / 8; /* round up bytes */
1739                 dev->chunk_bits = YMALLOC(dev->chunk_bit_stride * n_blocks);
1740                 if (!dev->chunk_bits) {
1741                         dev->chunk_bits = YMALLOC_ALT(dev->chunk_bit_stride * n_blocks);
1742                         dev->chunk_bits_alt = 1;
1743                 } else
1744                         dev->chunk_bits_alt = 0;
1745         }
1746
1747         if (dev->block_info && dev->chunk_bits) {
1748                 memset(dev->block_info, 0, n_blocks * sizeof(struct yaffs_block_info));
1749                 memset(dev->chunk_bits, 0, dev->chunk_bit_stride * n_blocks);
1750                 return YAFFS_OK;
1751         }
1752
1753         return YAFFS_FAIL;
1754 }
1755
1756 static void yaffs_deinit_blocks(struct yaffs_dev *dev)
1757 {
1758         if (dev->block_info_alt && dev->block_info)
1759                 YFREE_ALT(dev->block_info);
1760         else if (dev->block_info)
1761                 YFREE(dev->block_info);
1762
1763         dev->block_info_alt = 0;
1764
1765         dev->block_info = NULL;
1766
1767         if (dev->chunk_bits_alt && dev->chunk_bits)
1768                 YFREE_ALT(dev->chunk_bits);
1769         else if (dev->chunk_bits)
1770                 YFREE(dev->chunk_bits);
1771         dev->chunk_bits_alt = 0;
1772         dev->chunk_bits = NULL;
1773 }
1774
1775 void yaffs_block_became_dirty(struct yaffs_dev *dev, int block_no)
1776 {
1777         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block_no);
1778
1779         int erased_ok = 0;
1780
1781         /* If the block is still healthy erase it and mark as clean.
1782          * If the block has had a data failure, then retire it.
1783          */
1784
1785         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
1786                 (TSTR("yaffs_block_became_dirty block %d state %d %s"TENDSTR),
1787                 block_no, bi->block_state, (bi->needs_retiring) ? "needs retiring" : ""));
1788
1789         yaffs2_clear_oldest_dirty_seq(dev,bi);
1790
1791         bi->block_state = YAFFS_BLOCK_STATE_DIRTY;
1792
1793         /* If this is the block being garbage collected then stop gc'ing this block */
1794         if(block_no == dev->gc_block)
1795                 dev->gc_block = 0;
1796
1797         /* If this block is currently the best candidate for gc then drop as a candidate */
1798         if(block_no == dev->gc_dirtiest){
1799                 dev->gc_dirtiest = 0;
1800                 dev->gc_pages_in_use = 0;
1801         }
1802
1803         if (!bi->needs_retiring) {
1804                 yaffs2_checkpt_invalidate(dev);
1805                 erased_ok = yaffs_erase_block(dev, block_no);
1806                 if (!erased_ok) {
1807                         dev->n_erase_failures++;
1808                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1809                           (TSTR("**>> Erasure failed %d" TENDSTR), block_no));
1810                 }
1811         }
1812
1813         if (erased_ok &&
1814             ((yaffs_trace_mask & YAFFS_TRACE_ERASE) || !yaffs_skip_verification(dev))) {
1815                 int i;
1816                 for (i = 0; i < dev->param.chunks_per_block; i++) {
1817                         if (!yaffs_check_chunk_erased
1818                             (dev, block_no * dev->param.chunks_per_block + i)) {
1819                                 T(YAFFS_TRACE_ERROR,
1820                                   (TSTR
1821                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
1822                                     TENDSTR), block_no, i));
1823                         }
1824                 }
1825         }
1826
1827         if (erased_ok) {
1828                 /* Clean it up... */
1829                 bi->block_state = YAFFS_BLOCK_STATE_EMPTY;
1830                 bi->seq_number = 0;
1831                 dev->n_erased_blocks++;
1832                 bi->pages_in_use = 0;
1833                 bi->soft_del_pages = 0;
1834                 bi->has_shrink_hdr = 0;
1835                 bi->skip_erased_check = 1;  /* This is clean, so no need to check */
1836                 bi->gc_prioritise = 0;
1837                 yaffs_clear_chunk_bits(dev, block_no);
1838
1839                 T(YAFFS_TRACE_ERASE,
1840                   (TSTR("Erased block %d" TENDSTR), block_no));
1841         } else {
1842                 dev->n_free_chunks -= dev->param.chunks_per_block;      /* We lost a block of free space */
1843
1844                 yaffs_retire_block(dev, block_no);
1845                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1846                   (TSTR("**>> Block %d retired" TENDSTR), block_no));
1847         }
1848 }
1849
1850 static int yaffs_find_alloc_block(struct yaffs_dev *dev)
1851 {
1852         int i;
1853
1854         struct yaffs_block_info *bi;
1855
1856         if (dev->n_erased_blocks < 1) {
1857                 /* Hoosterman we've got a problem.
1858                  * Can't get space to gc
1859                  */
1860                 T(YAFFS_TRACE_ERROR,
1861                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
1862
1863                 return -1;
1864         }
1865
1866         /* Find an empty block. */
1867
1868         for (i = dev->internal_start_block; i <= dev->internal_end_block; i++) {
1869                 dev->alloc_block_finder++;
1870                 if (dev->alloc_block_finder < dev->internal_start_block
1871                     || dev->alloc_block_finder > dev->internal_end_block) {
1872                         dev->alloc_block_finder = dev->internal_start_block;
1873                 }
1874
1875                 bi = yaffs_get_block_info(dev, dev->alloc_block_finder);
1876
1877                 if (bi->block_state == YAFFS_BLOCK_STATE_EMPTY) {
1878                         bi->block_state = YAFFS_BLOCK_STATE_ALLOCATING;
1879                         dev->seq_number++;
1880                         bi->seq_number = dev->seq_number;
1881                         dev->n_erased_blocks--;
1882                         T(YAFFS_TRACE_ALLOCATE,
1883                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
1884                            dev->alloc_block_finder, dev->seq_number,
1885                            dev->n_erased_blocks));
1886                         return dev->alloc_block_finder;
1887                 }
1888         }
1889
1890         T(YAFFS_TRACE_ALWAYS,
1891           (TSTR
1892            ("yaffs tragedy: no more erased blocks, but there should have been %d"
1893             TENDSTR), dev->n_erased_blocks));
1894
1895         return -1;
1896 }
1897
1898
1899 /*
1900  * Check if there's space to allocate...
1901  * Thinks.... do we need top make this ths same as yaffs_get_free_chunks()?
1902  */
1903 int yaffs_check_alloc_available(struct yaffs_dev *dev, int n_chunks)
1904 {
1905         int reserved_chunks;
1906         int reserved_blocks = dev->param.n_reserved_blocks;
1907         int checkpt_blocks;
1908
1909         checkpt_blocks = yaffs_calc_checkpt_blocks_required(dev);
1910
1911         reserved_chunks = ((reserved_blocks + checkpt_blocks) * dev->param.chunks_per_block);
1912
1913         return (dev->n_free_chunks > (reserved_chunks + n_chunks));
1914 }
1915
1916 static int yaffs_alloc_chunk(struct yaffs_dev *dev, int use_reserver,
1917                 struct yaffs_block_info **block_ptr)
1918 {
1919         int ret_val;
1920         struct yaffs_block_info *bi;
1921
1922         if (dev->alloc_block < 0) {
1923                 /* Get next block to allocate off */
1924                 dev->alloc_block = yaffs_find_alloc_block(dev);
1925                 dev->alloc_page = 0;
1926         }
1927
1928         if (!use_reserver && !yaffs_check_alloc_available(dev, 1)) {
1929                 /* Not enough space to allocate unless we're allowed to use the reserve. */
1930                 return -1;
1931         }
1932
1933         if (dev->n_erased_blocks < dev->param.n_reserved_blocks
1934                         && dev->alloc_page == 0) {
1935                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
1936         }
1937
1938         /* Next page please.... */
1939         if (dev->alloc_block >= 0) {
1940                 bi = yaffs_get_block_info(dev, dev->alloc_block);
1941
1942                 ret_val = (dev->alloc_block * dev->param.chunks_per_block) +
1943                         dev->alloc_page;
1944                 bi->pages_in_use++;
1945                 yaffs_set_chunk_bit(dev, dev->alloc_block,
1946                                 dev->alloc_page);
1947
1948                 dev->alloc_page++;
1949
1950                 dev->n_free_chunks--;
1951
1952                 /* If the block is full set the state to full */
1953                 if (dev->alloc_page >= dev->param.chunks_per_block) {
1954                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
1955                         dev->alloc_block = -1;
1956                 }
1957
1958                 if (block_ptr)
1959                         *block_ptr = bi;
1960
1961                 return ret_val;
1962         }
1963
1964         T(YAFFS_TRACE_ERROR,
1965                         (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
1966
1967         return -1;
1968 }
1969
1970 static int yaffs_get_erased_chunks(struct yaffs_dev *dev)
1971 {
1972         int n;
1973
1974         n = dev->n_erased_blocks * dev->param.chunks_per_block;
1975
1976         if (dev->alloc_block > 0)
1977                 n += (dev->param.chunks_per_block - dev->alloc_page);
1978
1979         return n;
1980
1981 }
1982
1983 /*
1984  * yaffs_skip_rest_of_block() skips over the rest of the allocation block
1985  * if we don't want to write to it.
1986  */
1987 void yaffs_skip_rest_of_block(struct yaffs_dev *dev)
1988 {
1989         if(dev->alloc_block > 0){
1990                 struct yaffs_block_info *bi = yaffs_get_block_info(dev, dev->alloc_block);
1991                 if(bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING){
1992                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
1993                         dev->alloc_block = -1;
1994                 }
1995         }
1996 }
1997
1998
1999 static int yaffs_gc_block(struct yaffs_dev *dev, int block,
2000                 int whole_block)
2001 {
2002         int old_chunk;
2003         int new_chunk;
2004         int mark_flash;
2005         int ret_val = YAFFS_OK;
2006         int i;
2007         int is_checkpt_block;
2008         int matching_chunk;
2009         int max_copies;
2010
2011         int chunks_before = yaffs_get_erased_chunks(dev);
2012         int chunks_after;
2013
2014         struct yaffs_ext_tags tags;
2015
2016         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block);
2017
2018         struct yaffs_obj *object;
2019
2020         is_checkpt_block = (bi->block_state == YAFFS_BLOCK_STATE_CHECKPOINT);
2021
2022
2023         T(YAFFS_TRACE_TRACING,
2024                         (TSTR("Collecting block %d, in use %d, shrink %d, whole_block %d" TENDSTR),
2025                          block,
2026                          bi->pages_in_use,
2027                          bi->has_shrink_hdr,
2028                          whole_block));
2029
2030         /*yaffs_verify_free_chunks(dev); */
2031
2032         if(bi->block_state == YAFFS_BLOCK_STATE_FULL)
2033                 bi->block_state = YAFFS_BLOCK_STATE_COLLECTING;
2034         
2035         bi->has_shrink_hdr = 0; /* clear the flag so that the block can erase */
2036
2037         dev->gc_disable = 1;
2038
2039         if (is_checkpt_block ||
2040                         !yaffs_still_some_chunks(dev, block)) {
2041                 T(YAFFS_TRACE_TRACING,
2042                                 (TSTR
2043                                  ("Collecting block %d that has no chunks in use" TENDSTR),
2044                                  block));
2045                 yaffs_block_became_dirty(dev, block);
2046         } else {
2047
2048                 u8 *buffer = yaffs_get_temp_buffer(dev, __LINE__);
2049
2050                 yaffs_verify_blk(dev, bi, block);
2051
2052                 max_copies = (whole_block) ? dev->param.chunks_per_block : 5;
2053                 old_chunk = block * dev->param.chunks_per_block + dev->gc_chunk;
2054
2055                 for (/* init already done */;
2056                      ret_val == YAFFS_OK &&
2057                      dev->gc_chunk < dev->param.chunks_per_block &&
2058                      (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) &&
2059                      max_copies > 0;
2060                      dev->gc_chunk++, old_chunk++) {
2061                         if (yaffs_check_chunk_bit(dev, block, dev->gc_chunk)) {
2062
2063                                 /* This page is in use and might need to be copied off */
2064
2065                                 max_copies--;
2066
2067                                 mark_flash = 1;
2068
2069                                 yaffs_init_tags(&tags);
2070
2071                                 yaffs_rd_chunk_tags_nand(dev, old_chunk,
2072                                                                 buffer, &tags);
2073
2074                                 object =
2075                                     yaffs_find_by_number(dev,
2076                                                              tags.obj_id);
2077
2078                                 T(YAFFS_TRACE_GC_DETAIL,
2079                                   (TSTR
2080                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
2081                                    dev->gc_chunk, tags.obj_id, tags.chunk_id,
2082                                    tags.n_bytes));
2083
2084                                 if (object && !yaffs_skip_verification(dev)) {
2085                                         if (tags.chunk_id == 0)
2086                                                 matching_chunk = object->hdr_chunk;
2087                                         else if (object->soft_del)
2088                                                 matching_chunk = old_chunk; /* Defeat the test */
2089                                         else
2090                                                 matching_chunk = yaffs_find_chunk_in_file(object, tags.chunk_id, NULL);
2091
2092                                         if (old_chunk != matching_chunk)
2093                                                 T(YAFFS_TRACE_ERROR,
2094                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2095                                                   old_chunk, matching_chunk, tags.obj_id, tags.chunk_id));
2096
2097                                 }
2098
2099                                 if (!object) {
2100                                         T(YAFFS_TRACE_ERROR,
2101                                           (TSTR
2102                                            ("page %d in gc has no object: %d %d %d "
2103                                             TENDSTR), old_chunk,
2104                                             tags.obj_id, tags.chunk_id, tags.n_bytes));
2105                                 }
2106
2107                                 if (object &&
2108                                     object->deleted &&
2109                                     object->soft_del &&
2110                                     tags.chunk_id != 0) {
2111                                         /* Data chunk in a soft deleted file, throw it away
2112                                          * It's a soft deleted data chunk,
2113                                          * No need to copy this, just forget about it and
2114                                          * fix up the object.
2115                                          */
2116                                          
2117                                         /* Free chunks already includes softdeleted chunks.
2118                                          * How ever this chunk is going to soon be really deleted
2119                                          * which will increment free chunks.
2120                                          * We have to decrement free chunks so this works out properly.
2121                                          */
2122                                         dev->n_free_chunks--;
2123                                         bi->soft_del_pages--;
2124
2125                                         object->n_data_chunks--;
2126
2127                                         if (object->n_data_chunks <= 0) {
2128                                                 /* remeber to clean up the object */
2129                                                 dev->gc_cleanup_list[dev->n_clean_ups] =
2130                                                     tags.obj_id;
2131                                                 dev->n_clean_ups++;
2132                                         }
2133                                         mark_flash = 0;
2134                                 } else if (0) {
2135                                         /* Todo object && object->deleted && object->n_data_chunks == 0 */
2136                                         /* Deleted object header with no data chunks.
2137                                          * Can be discarded and the file deleted.
2138                                          */
2139                                         object->hdr_chunk = 0;
2140                                         yaffs_free_tnode(object->my_dev,
2141                                                         object->variant.
2142                                                         file_variant.top);
2143                                         object->variant.file_variant.top = NULL;
2144                                         yaffs_generic_obj_del(object);
2145
2146                                 } else if (object) {
2147                                         /* It's either a data chunk in a live file or
2148                                          * an ObjectHeader, so we're interested in it.
2149                                          * NB Need to keep the ObjectHeaders of deleted files
2150                                          * until the whole file has been deleted off
2151                                          */
2152                                         tags.serial_number++;
2153
2154                                         dev->n_gc_copies++;
2155
2156                                         if (tags.chunk_id == 0) {
2157                                                 /* It is an object Id,
2158                                                  * We need to nuke the shrinkheader flags first
2159                                                  * Also need to clean up shadowing.
2160                                                  * We no longer want the shrink_header flag since its work is done
2161                                                  * and if it is left in place it will mess up scanning.
2162                                                  */
2163
2164                                                 struct yaffs_obj_hdr *oh;
2165                                                 oh = (struct yaffs_obj_hdr *)buffer;
2166
2167                                                 oh->is_shrink = 0;
2168                                                 tags.extra_is_shrink = 0;
2169
2170                                                 oh->shadows_obj = 0;
2171                                                 oh->inband_shadowed_obj_id = 0;
2172                                                 tags.extra_shadows = 0;
2173
2174                                                 /* Update file size */
2175                                                 if(object->variant_type == YAFFS_OBJECT_TYPE_FILE){
2176                                                         oh->file_size = object->variant.file_variant.file_size;
2177                                                         tags.extra_length = oh->file_size;
2178                                                 }
2179
2180                                                 yaffs_verify_oh(object, oh, &tags, 1);
2181                                                 new_chunk =
2182                                                     yaffs_write_new_chunk(dev,(u8 *) oh, &tags, 1);
2183                                         } else
2184                                                 new_chunk =
2185                                                     yaffs_write_new_chunk(dev, buffer, &tags, 1);
2186
2187                                         if (new_chunk < 0) {
2188                                                 ret_val = YAFFS_FAIL;
2189                                         } else {
2190
2191                                                 /* Ok, now fix up the Tnodes etc. */
2192
2193                                                 if (tags.chunk_id == 0) {
2194                                                         /* It's a header */
2195                                                         object->hdr_chunk =  new_chunk;
2196                                                         object->serial =   tags.serial_number;
2197                                                 } else {
2198                                                         /* It's a data chunk */
2199                                                         int ok;
2200                                                         ok = yaffs_put_chunk_in_file
2201                                                             (object,
2202                                                              tags.chunk_id,
2203                                                              new_chunk, 0);
2204                                                 }
2205                                         }
2206                                 }
2207
2208                                 if (ret_val == YAFFS_OK)
2209                                         yaffs_chunk_del(dev, old_chunk, mark_flash, __LINE__);
2210
2211                         }
2212                 }
2213
2214                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
2215
2216
2217
2218         }
2219
2220         yaffs_verify_collected_blk(dev, bi, block);
2221
2222
2223
2224         if (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2225                 /*
2226                  * The gc did not complete. Set block state back to FULL
2227                  * because checkpointing does not restore gc.
2228                  */
2229                 bi->block_state = YAFFS_BLOCK_STATE_FULL;
2230         } else {
2231                 /* The gc completed. */
2232                 /* Do any required cleanups */
2233                 for (i = 0; i < dev->n_clean_ups; i++) {
2234                         /* Time to delete the file too */
2235                         object =
2236                             yaffs_find_by_number(dev,
2237                                                      dev->gc_cleanup_list[i]);
2238                         if (object) {
2239                                 yaffs_free_tnode(dev,
2240                                                 object->variant.file_variant.
2241                                                 top);
2242                                 object->variant.file_variant.top = NULL;
2243                                 T(YAFFS_TRACE_GC,
2244                                   (TSTR
2245                                    ("yaffs: About to finally delete object %d"
2246                                     TENDSTR), object->obj_id));
2247                                 yaffs_generic_obj_del(object);
2248                                 object->my_dev->n_deleted_files--;
2249                         }
2250
2251                 }
2252
2253
2254                 chunks_after = yaffs_get_erased_chunks(dev);
2255                 if (chunks_before >= chunks_after) {
2256                         T(YAFFS_TRACE_GC,
2257                           (TSTR
2258                            ("gc did not increase free chunks before %d after %d"
2259                             TENDSTR), chunks_before, chunks_after));
2260                 }
2261                 dev->gc_block = 0;
2262                 dev->gc_chunk = 0;
2263                 dev->n_clean_ups = 0;
2264         }
2265
2266         dev->gc_disable = 0;
2267
2268         return ret_val;
2269 }
2270
2271 /*
2272  * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
2273  * for garbage collection.
2274  */
2275
2276 static unsigned yaffs_find_gc_block(struct yaffs_dev *dev,
2277                                         int aggressive,
2278                                         int background)
2279 {
2280         int i;
2281         int iterations;
2282         unsigned selected = 0;
2283         int prioritised = 0;
2284         int prioritised_exist = 0;
2285         struct yaffs_block_info *bi;
2286         int threshold;
2287
2288         /* First let's see if we need to grab a prioritised block */
2289         if (dev->has_pending_prioritised_gc && !aggressive) {
2290                 dev->gc_dirtiest = 0;
2291                 bi = dev->block_info;
2292                 for (i = dev->internal_start_block;
2293                         i <= dev->internal_end_block && !selected;
2294                         i++) {
2295
2296                         if (bi->gc_prioritise) {
2297                                 prioritised_exist = 1;
2298                                 if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2299                                    yaffs_block_ok_for_gc(dev, bi)) {
2300                                         selected = i;
2301                                         prioritised = 1;
2302                                 }
2303                         }
2304                         bi++;
2305                 }
2306
2307                 /*
2308                  * If there is a prioritised block and none was selected then
2309                  * this happened because there is at least one old dirty block gumming
2310                  * up the works. Let's gc the oldest dirty block.
2311                  */
2312
2313                 if(prioritised_exist &&
2314                         !selected &&
2315                         dev->oldest_dirty_block > 0)
2316                         selected = dev->oldest_dirty_block;
2317
2318                 if (!prioritised_exist) /* None found, so we can clear this */
2319                         dev->has_pending_prioritised_gc = 0;
2320         }
2321
2322         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2323          * search harder.
2324          * else (we're doing a leasurely gc), then we only bother to do this if the
2325          * block has only a few pages in use.
2326          */
2327
2328         if (!selected){
2329                 int pages_used;
2330                 int n_blocks = dev->internal_end_block - dev->internal_start_block + 1;
2331                 if (aggressive){
2332                         threshold = dev->param.chunks_per_block;
2333                         iterations = n_blocks;
2334                 } else {
2335                         int max_threshold;
2336
2337                         if(background)
2338                                 max_threshold = dev->param.chunks_per_block/2;
2339                         else
2340                                 max_threshold = dev->param.chunks_per_block/8;
2341
2342                         if(max_threshold <  YAFFS_GC_PASSIVE_THRESHOLD)
2343                                 max_threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2344
2345                         threshold = background ?
2346                                 (dev->gc_not_done + 2) * 2 : 0;
2347                         if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
2348                                 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2349                         if(threshold > max_threshold)
2350                                 threshold = max_threshold;
2351
2352                         iterations = n_blocks / 16 + 1;
2353                         if (iterations > 100)
2354                                 iterations = 100;
2355                 }
2356
2357                 for (i = 0;
2358                         i < iterations &&
2359                         (dev->gc_dirtiest < 1 ||
2360                                 dev->gc_pages_in_use > YAFFS_GC_GOOD_ENOUGH);
2361                         i++) {
2362                         dev->gc_block_finder++;
2363                         if (dev->gc_block_finder < dev->internal_start_block ||
2364                                 dev->gc_block_finder > dev->internal_end_block)
2365                                 dev->gc_block_finder = dev->internal_start_block;
2366
2367                         bi = yaffs_get_block_info(dev, dev->gc_block_finder);
2368
2369                         pages_used = bi->pages_in_use - bi->soft_del_pages;
2370
2371                         if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2372                                 pages_used < dev->param.chunks_per_block &&
2373                                 (dev->gc_dirtiest < 1 || pages_used < dev->gc_pages_in_use) &&
2374                                 yaffs_block_ok_for_gc(dev, bi)) {
2375                                 dev->gc_dirtiest = dev->gc_block_finder;
2376                                 dev->gc_pages_in_use = pages_used;
2377                         }
2378                 }
2379
2380                 if(dev->gc_dirtiest > 0 && dev->gc_pages_in_use <= threshold)
2381                         selected = dev->gc_dirtiest;
2382         }
2383
2384         /*
2385          * If nothing has been selected for a while, try selecting the oldest dirty
2386          * because that's gumming up the works.
2387          */
2388
2389         if(!selected && dev->param.is_yaffs2 &&
2390                 dev->gc_not_done >= ( background ? 10 : 20)){
2391                 yaffs2_find_oldest_dirty_seq(dev);
2392                 if(dev->oldest_dirty_block > 0) {
2393                         selected = dev->oldest_dirty_block;
2394                         dev->gc_dirtiest = selected;
2395                         dev->oldest_dirty_gc_count++;
2396                         bi = yaffs_get_block_info(dev, selected);
2397                         dev->gc_pages_in_use =  bi->pages_in_use - bi->soft_del_pages;
2398                 } else
2399                         dev->gc_not_done = 0;
2400         }
2401
2402         if(selected){
2403                 T(YAFFS_TRACE_GC,
2404                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
2405                   selected,
2406                   dev->param.chunks_per_block - dev->gc_pages_in_use,
2407                   prioritised));
2408
2409                 dev->n_gc_blocks++;
2410                 if(background)
2411                         dev->bg_gcs++;
2412
2413                 dev->gc_dirtiest = 0;
2414                 dev->gc_pages_in_use = 0;
2415                 dev->gc_not_done = 0;
2416                 if(dev->refresh_skip > 0)
2417                         dev->refresh_skip--;
2418         } else{
2419                 dev->gc_not_done++;
2420                 T(YAFFS_TRACE_GC,
2421                   (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
2422                   dev->gc_block_finder, dev->gc_not_done,
2423                   threshold,
2424                   dev->gc_dirtiest, dev->gc_pages_in_use,
2425                   dev->oldest_dirty_block,
2426                   background ? " bg" : ""));
2427         }
2428
2429         return selected;
2430 }
2431
2432 /* New garbage collector
2433  * If we're very low on erased blocks then we do aggressive garbage collection
2434  * otherwise we do "leasurely" garbage collection.
2435  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2436  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2437  *
2438  * The idea is to help clear out space in a more spread-out manner.
2439  * Dunno if it really does anything useful.
2440  */
2441 static int yaffs_check_gc(struct yaffs_dev *dev, int background)
2442 {
2443         int aggressive = 0;
2444         int gc_ok = YAFFS_OK;
2445         int max_tries = 0;
2446         int min_erased;
2447         int erased_chunks;
2448         int checkpt_block_adjust;
2449
2450         if(dev->param.gc_control &&
2451                 (dev->param.gc_control(dev) & 1) == 0)
2452                 return YAFFS_OK;
2453
2454         if (dev->gc_disable) {
2455                 /* Bail out so we don't get recursive gc */
2456                 return YAFFS_OK;
2457         }
2458
2459         /* This loop should pass the first time.
2460          * We'll only see looping here if the collection does not increase space.
2461          */
2462
2463         do {
2464                 max_tries++;
2465
2466                 checkpt_block_adjust = yaffs_calc_checkpt_blocks_required(dev);
2467
2468                 min_erased  = dev->param.n_reserved_blocks + checkpt_block_adjust + 1;
2469                 erased_chunks = dev->n_erased_blocks * dev->param.chunks_per_block;
2470
2471                 /* If we need a block soon then do aggressive gc.*/
2472                 if (dev->n_erased_blocks < min_erased)
2473                         aggressive = 1;
2474                 else {
2475                         if(!background && erased_chunks > (dev->n_free_chunks / 4))
2476                                 break;
2477
2478                         if(dev->gc_skip > 20)
2479                                 dev->gc_skip = 20;
2480                         if(erased_chunks < dev->n_free_chunks/2 ||
2481                                 dev->gc_skip < 1 ||
2482                                 background)
2483                                 aggressive = 0;
2484                         else {
2485                                 dev->gc_skip--;
2486                                 break;
2487                         }
2488                 }
2489
2490                 dev->gc_skip = 5;
2491
2492                 /* If we don't already have a block being gc'd then see if we should start another */
2493
2494                 if (dev->gc_block < 1 && !aggressive) {
2495                         dev->gc_block = yaffs2_find_refresh_block(dev);
2496                         dev->gc_chunk = 0;
2497                         dev->n_clean_ups=0;
2498                 }
2499                 if (dev->gc_block < 1) {
2500                         dev->gc_block = yaffs_find_gc_block(dev, aggressive, background);
2501                         dev->gc_chunk = 0;
2502                         dev->n_clean_ups=0;
2503                 }
2504
2505                 if (dev->gc_block > 0) {
2506                         dev->all_gcs++;
2507                         if (!aggressive)
2508                                 dev->passive_gc_count++;
2509
2510                         T(YAFFS_TRACE_GC,
2511                           (TSTR
2512                            ("yaffs: GC n_erased_blocks %d aggressive %d" TENDSTR),
2513                            dev->n_erased_blocks, aggressive));
2514
2515                         gc_ok = yaffs_gc_block(dev, dev->gc_block, aggressive);
2516                 }
2517
2518                 if (dev->n_erased_blocks < (dev->param.n_reserved_blocks) && dev->gc_block > 0) {
2519                         T(YAFFS_TRACE_GC,
2520                           (TSTR
2521                            ("yaffs: GC !!!no reclaim!!! n_erased_blocks %d after try %d block %d"
2522                             TENDSTR), dev->n_erased_blocks, max_tries, dev->gc_block));
2523                 }
2524         } while ((dev->n_erased_blocks < dev->param.n_reserved_blocks) &&
2525                  (dev->gc_block > 0) &&
2526                  (max_tries < 2));
2527
2528         return aggressive ? gc_ok : YAFFS_OK;
2529 }
2530
2531 /*
2532  * yaffs_bg_gc()
2533  * Garbage collects. Intended to be called from a background thread.
2534  * Returns non-zero if at least half the free chunks are erased.
2535  */
2536 int yaffs_bg_gc(struct yaffs_dev *dev, unsigned urgency)
2537 {
2538         int erased_chunks = dev->n_erased_blocks * dev->param.chunks_per_block;
2539
2540         T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
2541
2542         yaffs_check_gc(dev, 1);
2543         return erased_chunks > dev->n_free_chunks/2;
2544 }
2545
2546 /*-------------------------  TAGS --------------------------------*/
2547
2548 static int yaffs_tags_match(const struct yaffs_ext_tags *tags, int obj_id,
2549                            int chunk_obj)
2550 {
2551         return (tags->chunk_id == chunk_obj &&
2552                 tags->obj_id == obj_id && !tags->is_deleted) ? 1 : 0;
2553
2554 }
2555
2556
2557 /*-------------------- Data file manipulation -----------------*/
2558
2559 static int yaffs_find_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
2560                                  struct yaffs_ext_tags *tags)
2561 {
2562         /*Get the Tnode, then get the level 0 offset chunk offset */
2563         struct yaffs_tnode *tn;
2564         int the_chunk = -1;
2565         struct yaffs_ext_tags local_tags;
2566         int ret_val = -1;
2567
2568         struct yaffs_dev *dev = in->my_dev;
2569
2570         if (!tags) {
2571                 /* Passed a NULL, so use our own tags space */
2572                 tags = &local_tags;
2573         }
2574
2575         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
2576
2577         if (tn) {
2578                 the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
2579
2580                 ret_val =
2581                     yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
2582                                            inode_chunk);
2583         }
2584         return ret_val;
2585 }
2586
2587 static int yaffs_find_del_file_chunk(struct yaffs_obj *in, int inode_chunk,
2588                                           struct yaffs_ext_tags *tags)
2589 {
2590         /* Get the Tnode, then get the level 0 offset chunk offset */
2591         struct yaffs_tnode *tn;
2592         int the_chunk = -1;
2593         struct yaffs_ext_tags local_tags;
2594
2595         struct yaffs_dev *dev = in->my_dev;
2596         int ret_val = -1;
2597
2598         if (!tags) {
2599                 /* Passed a NULL, so use our own tags space */
2600                 tags = &local_tags;
2601         }
2602
2603         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
2604
2605         if (tn) {
2606
2607                 the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
2608
2609                 ret_val =
2610                     yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
2611                                            inode_chunk);
2612
2613                 /* Delete the entry in the filestructure (if found) */
2614                 if (ret_val != -1)
2615                         yaffs_load_tnode_0(dev, tn, inode_chunk, 0);
2616         }
2617
2618         return ret_val;
2619 }
2620
2621
2622 int yaffs_put_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
2623                                 int nand_chunk, int in_scan)
2624 {
2625         /* NB in_scan is zero unless scanning.
2626          * For forward scanning, in_scan is > 0;
2627          * for backward scanning in_scan is < 0
2628          *
2629          * nand_chunk = 0 is a dummy insert to make sure the tnodes are there.
2630          */
2631
2632         struct yaffs_tnode *tn;
2633         struct yaffs_dev *dev = in->my_dev;
2634         int existing_cunk;
2635         struct yaffs_ext_tags existing_tags;
2636         struct yaffs_ext_tags new_tags;
2637         unsigned existing_serial, new_serial;
2638
2639         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE) {
2640                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2641                  * If it is not during Scanning then something went wrong!
2642                  */
2643                 if (!in_scan) {
2644                         T(YAFFS_TRACE_ERROR,
2645                           (TSTR
2646                            ("yaffs tragedy:attempt to put data chunk into a non-file"
2647                             TENDSTR)));
2648                         YBUG();
2649                 }
2650
2651                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
2652                 return YAFFS_OK;
2653         }
2654
2655         tn = yaffs_add_find_tnode_0(dev,
2656                                         &in->variant.file_variant,
2657                                         inode_chunk,
2658                                         NULL);
2659         if (!tn)
2660                 return YAFFS_FAIL;
2661         
2662         if(!nand_chunk)
2663                 /* Dummy insert, bail now */
2664                 return YAFFS_OK;
2665
2666         existing_cunk = yaffs_get_group_base(dev, tn, inode_chunk);
2667
2668         if (in_scan != 0) {
2669                 /* If we're scanning then we need to test for duplicates
2670                  * NB This does not need to be efficient since it should only ever
2671                  * happen when the power fails during a write, then only one
2672                  * chunk should ever be affected.
2673                  *
2674                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2675                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2676                  */
2677
2678                 if (existing_cunk > 0) {
2679                         /* NB Right now existing chunk will not be real chunk_id if the chunk group size > 1
2680                          *    thus we have to do a FindChunkInFile to get the real chunk id.
2681                          *
2682                          * We have a duplicate now we need to decide which one to use:
2683                          *
2684                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2685                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2686                          * YAFFS1: Get both sets of tags and compare serial numbers.
2687                          */
2688
2689                         if (in_scan > 0) {
2690                                 /* Only do this for forward scanning */
2691                                 yaffs_rd_chunk_tags_nand(dev,
2692                                                                 nand_chunk,
2693                                                                 NULL, &new_tags);
2694
2695                                 /* Do a proper find */
2696                                 existing_cunk =
2697                                     yaffs_find_chunk_in_file(in, inode_chunk,
2698                                                           &existing_tags);
2699                         }
2700
2701                         if (existing_cunk <= 0) {
2702                                 /*Hoosterman - how did this happen? */
2703
2704                                 T(YAFFS_TRACE_ERROR,
2705                                   (TSTR
2706                                    ("yaffs tragedy: existing chunk < 0 in scan"
2707                                     TENDSTR)));
2708
2709                         }
2710
2711                         /* NB The deleted flags should be false, otherwise the chunks will
2712                          * not be loaded during a scan
2713                          */
2714
2715                         if (in_scan > 0) {
2716                                 new_serial = new_tags.serial_number;
2717                                 existing_serial = existing_tags.serial_number;
2718                         }
2719
2720                         if ((in_scan > 0) &&
2721                             (existing_cunk <= 0 ||
2722                              ((existing_serial + 1) & 3) == new_serial)) {
2723                                 /* Forward scanning.
2724                                  * Use new
2725                                  * Delete the old one and drop through to update the tnode
2726                                  */
2727                                 yaffs_chunk_del(dev, existing_cunk, 1,
2728                                                   __LINE__);
2729                         } else {
2730                                 /* Backward scanning or we want to use the existing one
2731                                  * Use existing.
2732                                  * Delete the new one and return early so that the tnode isn't changed
2733                                  */
2734                                 yaffs_chunk_del(dev, nand_chunk, 1,
2735                                                   __LINE__);
2736                                 return YAFFS_OK;
2737                         }
2738                 }
2739
2740         }
2741
2742         if (existing_cunk == 0)
2743                 in->n_data_chunks++;
2744
2745         yaffs_load_tnode_0(dev, tn, inode_chunk, nand_chunk);
2746
2747         return YAFFS_OK;
2748 }
2749
2750 static int yaffs_rd_data_obj(struct yaffs_obj *in, int inode_chunk,
2751                                         u8 *buffer)
2752 {
2753         int nand_chunk = yaffs_find_chunk_in_file(in, inode_chunk, NULL);
2754
2755         if (nand_chunk >= 0)
2756                 return yaffs_rd_chunk_tags_nand(in->my_dev, nand_chunk,
2757                                                 buffer, NULL);
2758         else {
2759                 T(YAFFS_TRACE_NANDACCESS,
2760                   (TSTR("Chunk %d not found zero instead" TENDSTR),
2761                    nand_chunk));
2762                 /* get sane (zero) data if you read a hole */
2763                 memset(buffer, 0, in->my_dev->data_bytes_per_chunk);
2764                 return 0;
2765         }
2766
2767 }
2768
2769 void yaffs_chunk_del(struct yaffs_dev *dev, int chunk_id, int mark_flash, int lyn)
2770 {
2771         int block;
2772         int page;
2773         struct yaffs_ext_tags tags;
2774         struct yaffs_block_info *bi;
2775
2776         if (chunk_id <= 0)
2777                 return;
2778
2779         dev->n_deletions++;
2780         block = chunk_id / dev->param.chunks_per_block;
2781         page = chunk_id % dev->param.chunks_per_block;
2782
2783
2784         if (!yaffs_check_chunk_bit(dev, block, page))
2785                 T(YAFFS_TRACE_VERIFY,
2786                         (TSTR("Deleting invalid chunk %d"TENDSTR),
2787                          chunk_id));
2788
2789         bi = yaffs_get_block_info(dev, block);
2790         
2791         yaffs2_update_oldest_dirty_seq(dev, block, bi);
2792
2793         T(YAFFS_TRACE_DELETION,
2794           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunk_id));
2795
2796         if (!dev->param.is_yaffs2 && mark_flash &&
2797             bi->block_state != YAFFS_BLOCK_STATE_COLLECTING) {
2798
2799                 yaffs_init_tags(&tags);
2800
2801                 tags.is_deleted = 1;
2802
2803                 yaffs_wr_chunk_tags_nand(dev, chunk_id, NULL, &tags);
2804                 yaffs_handle_chunk_update(dev, chunk_id, &tags);
2805         } else {
2806                 dev->n_unmarked_deletions++;
2807         }
2808
2809         /* Pull out of the management area.
2810          * If the whole block became dirty, this will kick off an erasure.
2811          */
2812         if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING ||
2813             bi->block_state == YAFFS_BLOCK_STATE_FULL ||
2814             bi->block_state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2815             bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2816                 dev->n_free_chunks++;
2817
2818                 yaffs_clear_chunk_bit(dev, block, page);
2819
2820                 bi->pages_in_use--;
2821
2822                 if (bi->pages_in_use == 0 &&
2823                     !bi->has_shrink_hdr &&
2824                     bi->block_state != YAFFS_BLOCK_STATE_ALLOCATING &&
2825                     bi->block_state != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2826                         yaffs_block_became_dirty(dev, block);
2827                 }
2828
2829         }
2830
2831 }
2832
2833 static int yaffs_wr_data_obj(struct yaffs_obj *in, int inode_chunk,
2834                                         const u8 *buffer, int n_bytes,
2835                                         int use_reserve)
2836 {
2837         /* Find old chunk Need to do this to get serial number
2838          * Write new one and patch into tree.
2839          * Invalidate old tags.
2840          */
2841
2842         int prev_chunk_id;
2843         struct yaffs_ext_tags prev_tags;
2844
2845         int new_chunk_id;
2846         struct yaffs_ext_tags new_tags;
2847
2848         struct yaffs_dev *dev = in->my_dev;
2849
2850         yaffs_check_gc(dev,0);
2851
2852         /* Get the previous chunk at this location in the file if it exists.
2853          * If it does not exist then put a zero into the tree. This creates
2854          * the tnode now, rather than later when it is harder to clean up.
2855          */
2856         prev_chunk_id = yaffs_find_chunk_in_file(in, inode_chunk, &prev_tags);
2857         if(prev_chunk_id < 1 &&
2858                 !yaffs_put_chunk_in_file(in, inode_chunk, 0, 0))
2859                 return 0;
2860
2861         /* Set up new tags */
2862         yaffs_init_tags(&new_tags);
2863
2864         new_tags.chunk_id = inode_chunk;
2865         new_tags.obj_id = in->obj_id;
2866         new_tags.serial_number =
2867             (prev_chunk_id > 0) ? prev_tags.serial_number + 1 : 1;
2868         new_tags.n_bytes = n_bytes;
2869
2870         if (n_bytes < 1 || n_bytes > dev->param.total_bytes_per_chunk) {
2871                 T(YAFFS_TRACE_ERROR,
2872                 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), n_bytes));
2873                 YBUG();
2874         }
2875         
2876                 
2877         new_chunk_id =
2878             yaffs_write_new_chunk(dev, buffer, &new_tags,
2879                                               use_reserve);
2880
2881         if (new_chunk_id > 0) {
2882                 yaffs_put_chunk_in_file(in, inode_chunk, new_chunk_id, 0);
2883
2884                 if (prev_chunk_id > 0)
2885                         yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
2886
2887                 yaffs_verify_file_sane(in);
2888         }
2889         return new_chunk_id;
2890
2891 }
2892
2893 /* UpdateObjectHeader updates the header on NAND for an object.
2894  * If name is not NULL, then that new name is used.
2895  */
2896 int yaffs_update_oh(struct yaffs_obj *in, const YCHAR *name, int force,
2897                              int is_shrink, int shadows, struct yaffs_xattr_mod *xmod)
2898 {
2899
2900         struct yaffs_block_info *bi;
2901
2902         struct yaffs_dev *dev = in->my_dev;
2903
2904         int prev_chunk_id;
2905         int ret_val = 0;
2906         int result = 0;
2907
2908         int new_chunk_id;
2909         struct yaffs_ext_tags new_tags;
2910         struct yaffs_ext_tags old_tags;
2911         const YCHAR *alias = NULL;
2912
2913         u8 *buffer = NULL;
2914         YCHAR old_name[YAFFS_MAX_NAME_LENGTH + 1];
2915
2916         struct yaffs_obj_hdr *oh = NULL;
2917
2918         yaffs_strcpy(old_name, _Y("silly old name"));
2919
2920
2921         if (!in->fake ||
2922                 in == dev->root_dir || /* The root_dir should also be saved */
2923                 force  || xmod) {
2924
2925                 yaffs_check_gc(dev,0);
2926                 yaffs_check_obj_details_loaded(in);
2927
2928                 buffer = yaffs_get_temp_buffer(in->my_dev, __LINE__);
2929                 oh = (struct yaffs_obj_hdr *) buffer;
2930
2931                 prev_chunk_id = in->hdr_chunk;
2932
2933                 if (prev_chunk_id > 0) {
2934                         result = yaffs_rd_chunk_tags_nand(dev, prev_chunk_id,
2935                                                         buffer, &old_tags);
2936
2937                         yaffs_verify_oh(in, oh, &old_tags, 0);
2938
2939                         memcpy(old_name, oh->name, sizeof(oh->name));
2940                         memset(buffer, 0xFF, sizeof(struct yaffs_obj_hdr));
2941                 } else
2942                         memset(buffer, 0xFF, dev->data_bytes_per_chunk);
2943
2944                 oh->type = in->variant_type;
2945                 oh->yst_mode = in->yst_mode;
2946                 oh->shadows_obj = oh->inband_shadowed_obj_id = shadows;
2947
2948 #ifdef CONFIG_YAFFS_WINCE
2949                 oh->win_atime[0] = in->win_atime[0];
2950                 oh->win_ctime[0] = in->win_ctime[0];
2951                 oh->win_mtime[0] = in->win_mtime[0];
2952                 oh->win_atime[1] = in->win_atime[1];
2953                 oh->win_ctime[1] = in->win_ctime[1];
2954                 oh->win_mtime[1] = in->win_mtime[1];
2955 #else
2956                 oh->yst_uid = in->yst_uid;
2957                 oh->yst_gid = in->yst_gid;
2958                 oh->yst_atime = in->yst_atime;
2959                 oh->yst_mtime = in->yst_mtime;
2960                 oh->yst_ctime = in->yst_ctime;
2961                 oh->yst_rdev = in->yst_rdev;
2962 #endif
2963                 if (in->parent)
2964                         oh->parent_obj_id = in->parent->obj_id;
2965                 else
2966                         oh->parent_obj_id = 0;
2967
2968                 if (name && *name) {
2969                         memset(oh->name, 0, sizeof(oh->name));
2970                         yaffs_load_oh_from_name(dev,oh->name,name);
2971                 } else if (prev_chunk_id > 0)
2972                         memcpy(oh->name, old_name, sizeof(oh->name));
2973                 else
2974                         memset(oh->name, 0, sizeof(oh->name));
2975
2976                 oh->is_shrink = is_shrink;
2977
2978                 switch (in->variant_type) {
2979                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2980                         /* Should not happen */
2981                         break;
2982                 case YAFFS_OBJECT_TYPE_FILE:
2983                         oh->file_size =
2984                             (oh->parent_obj_id == YAFFS_OBJECTID_DELETED
2985                              || oh->parent_obj_id ==
2986                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2987                             file_variant.file_size;
2988                         break;
2989                 case YAFFS_OBJECT_TYPE_HARDLINK:
2990                         oh->equiv_id =
2991                             in->variant.hardlink_variant.equiv_id;
2992                         break;
2993                 case YAFFS_OBJECT_TYPE_SPECIAL:
2994                         /* Do nothing */
2995                         break;
2996                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2997                         /* Do nothing */
2998                         break;
2999                 case YAFFS_OBJECT_TYPE_SYMLINK:
3000                         alias = in->variant.symlink_variant.alias;
3001                         if(!alias)
3002                                 alias = _Y("no alias");
3003                         yaffs_strncpy(oh->alias,
3004                                         alias,
3005                                       YAFFS_MAX_ALIAS_LENGTH);
3006                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3007                         break;
3008                 }
3009
3010                 /* process any xattrib modifications */
3011                 if(xmod)
3012                         yaffs_apply_xattrib_mod(in, (char *)buffer, xmod);
3013
3014
3015                 /* Tags */
3016                 yaffs_init_tags(&new_tags);
3017                 in->serial++;
3018                 new_tags.chunk_id = 0;
3019                 new_tags.obj_id = in->obj_id;
3020                 new_tags.serial_number = in->serial;
3021
3022                 /* Add extra info for file header */
3023
3024                 new_tags.extra_available = 1;
3025                 new_tags.extra_parent_id = oh->parent_obj_id;
3026                 new_tags.extra_length = oh->file_size;
3027                 new_tags.extra_is_shrink = oh->is_shrink;
3028                 new_tags.extra_equiv_id = oh->equiv_id;
3029                 new_tags.extra_shadows = (oh->shadows_obj > 0) ? 1 : 0;
3030                 new_tags.extra_obj_type = in->variant_type;
3031
3032                 yaffs_verify_oh(in, oh, &new_tags, 1);
3033
3034                 /* Create new chunk in NAND */
3035                 new_chunk_id =
3036                     yaffs_write_new_chunk(dev, buffer, &new_tags,
3037                                                       (prev_chunk_id > 0) ? 1 : 0);
3038
3039                 if (new_chunk_id >= 0) {
3040
3041                         in->hdr_chunk = new_chunk_id;
3042
3043                         if (prev_chunk_id > 0) {
3044                                 yaffs_chunk_del(dev, prev_chunk_id, 1,
3045                                                   __LINE__);
3046                         }
3047
3048                         if (!yaffs_obj_cache_dirty(in))
3049                                 in->dirty = 0;
3050
3051                         /* If this was a shrink, then mark the block that the chunk lives on */
3052                         if (is_shrink) {
3053                                 bi = yaffs_get_block_info(in->my_dev,
3054                                         new_chunk_id / in->my_dev->param.chunks_per_block);
3055                                 bi->has_shrink_hdr = 1;
3056                         }
3057
3058                 }
3059
3060                 ret_val = new_chunk_id;
3061
3062         }
3063
3064         if (buffer)
3065                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
3066
3067         return ret_val;
3068 }
3069
3070 /*------------------------ Short Operations Cache ----------------------------------------
3071  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3072  *   reads might be short sequential reads, and a lot of writes may be short
3073  *   sequential writes. eg. scanning/writing a jpeg file.
3074  *   In these cases, a short read/write cache can provide a huge perfomance benefit
3075  *   with dumb-as-a-rock code.
3076  *   In Linux, the page cache provides read buffering aand the short op cache provides write
3077  *   buffering.
3078  *
3079  *   There are a limited number (~10) of cache chunks per device so that we don't
3080  *   need a very intelligent search.
3081  */
3082
3083 static int yaffs_obj_cache_dirty(struct yaffs_obj *obj)
3084 {
3085         struct yaffs_dev *dev = obj->my_dev;
3086         int i;
3087         struct yaffs_cache *cache;
3088         int n_caches = obj->my_dev->param.n_caches;
3089
3090         for (i = 0; i < n_caches; i++) {
3091                 cache = &dev->cache[i];
3092                 if (cache->object == obj &&
3093                     cache->dirty)
3094                         return 1;
3095         }
3096
3097         return 0;
3098 }
3099
3100
3101 static void yaffs_flush_file_cache(struct yaffs_obj *obj)
3102 {
3103         struct yaffs_dev *dev = obj->my_dev;
3104         int lowest = -99;       /* Stop compiler whining. */
3105         int i;
3106         struct yaffs_cache *cache;
3107         int chunk_written = 0;
3108         int n_caches = obj->my_dev->param.n_caches;
3109
3110         if (n_caches > 0) {
3111                 do {
3112                         cache = NULL;
3113
3114                         /* Find the dirty cache for this object with the lowest chunk id. */
3115                         for (i = 0; i < n_caches; i++) {
3116                                 if (dev->cache[i].object == obj &&
3117                                     dev->cache[i].dirty) {
3118                                         if (!cache
3119                                             || dev->cache[i].chunk_id <
3120                                             lowest) {
3121                                                 cache = &dev->cache[i];
3122                                                 lowest = cache->chunk_id;
3123                                         }
3124                                 }
3125                         }
3126
3127                         if (cache && !cache->locked) {
3128                                 /* Write it out and free it up */
3129
3130                                 chunk_written =
3131                                     yaffs_wr_data_obj(cache->object,
3132                                                                  cache->chunk_id,
3133                                                                  cache->data,
3134                                                                  cache->n_bytes,
3135                                                                  1);
3136                                 cache->dirty = 0;
3137                                 cache->object = NULL;
3138                         }
3139
3140                 } while (cache && chunk_written > 0);
3141
3142                 if (cache) {
3143                         /* Hoosterman, disk full while writing cache out. */
3144                         T(YAFFS_TRACE_ERROR,
3145                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3146
3147                 }
3148         }
3149
3150 }
3151
3152 /*yaffs_flush_whole_cache(dev)
3153  *
3154  *
3155  */
3156
3157 void yaffs_flush_whole_cache(struct yaffs_dev *dev)
3158 {
3159         struct yaffs_obj *obj;
3160         int n_caches = dev->param.n_caches;
3161         int i;
3162
3163         /* Find a dirty object in the cache and flush it...
3164          * until there are no further dirty objects.
3165          */
3166         do {
3167                 obj = NULL;
3168                 for (i = 0; i < n_caches && !obj; i++) {
3169                         if (dev->cache[i].object &&
3170                             dev->cache[i].dirty)
3171                                 obj = dev->cache[i].object;
3172
3173                 }
3174                 if (obj)
3175                         yaffs_flush_file_cache(obj);
3176
3177         } while (obj);
3178
3179 }
3180
3181
3182 /* Grab us a cache chunk for use.
3183  * First look for an empty one.
3184  * Then look for the least recently used non-dirty one.
3185  * Then look for the least recently used dirty one...., flush and look again.
3186  */
3187 static struct yaffs_cache *yaffs_grab_chunk_worker(struct yaffs_dev *dev)
3188 {
3189         int i;
3190
3191         if (dev->param.n_caches > 0) {
3192                 for (i = 0; i < dev->param.n_caches; i++) {
3193                         if (!dev->cache[i].object)
3194                                 return &dev->cache[i];
3195                 }
3196         }
3197
3198         return NULL;
3199 }
3200
3201 static struct yaffs_cache *yaffs_grab_chunk_cache(struct yaffs_dev *dev)
3202 {
3203         struct yaffs_cache *cache;
3204         struct yaffs_obj *the_obj;
3205         int usage;
3206         int i;
3207         int pushout;
3208
3209         if (dev->param.n_caches > 0) {
3210                 /* Try find a non-dirty one... */
3211
3212                 cache = yaffs_grab_chunk_worker(dev);
3213
3214                 if (!cache) {
3215                         /* They were all dirty, find the last recently used object and flush
3216                          * its cache, then  find again.
3217                          * NB what's here is not very accurate, we actually flush the object
3218                          * the last recently used page.
3219                          */
3220
3221                         /* With locking we can't assume we can use entry zero */
3222
3223                         the_obj = NULL;
3224                         usage = -1;
3225                         cache = NULL;
3226                         pushout = -1;
3227
3228                         for (i = 0; i < dev->param.n_caches; i++) {
3229                                 if (dev->cache[i].object &&
3230                                     !dev->cache[i].locked &&
3231                                     (dev->cache[i].last_use < usage || !cache)) {
3232                                         usage = dev->cache[i].last_use;
3233                                         the_obj = dev->cache[i].object;
3234                                         cache = &dev->cache[i];
3235                                         pushout = i;
3236                                 }
3237                         }
3238
3239                         if (!cache || cache->dirty) {
3240                                 /* Flush and try again */
3241                                 yaffs_flush_file_cache(the_obj);
3242                                 cache = yaffs_grab_chunk_worker(dev);
3243                         }
3244
3245                 }
3246                 return cache;
3247         } else
3248                 return NULL;
3249
3250 }
3251
3252 /* Find a cached chunk */
3253 static struct yaffs_cache *yaffs_find_chunk_cache(const struct yaffs_obj *obj,
3254                                               int chunk_id)
3255 {
3256         struct yaffs_dev *dev = obj->my_dev;
3257         int i;
3258         if (dev->param.n_caches > 0) {
3259                 for (i = 0; i < dev->param.n_caches; i++) {
3260                         if (dev->cache[i].object == obj &&
3261                             dev->cache[i].chunk_id == chunk_id) {
3262                                 dev->cache_hits++;
3263
3264                                 return &dev->cache[i];
3265                         }
3266                 }
3267         }
3268         return NULL;
3269 }
3270
3271 /* Mark the chunk for the least recently used algorithym */
3272 static void yaffs_use_cache(struct yaffs_dev *dev, struct yaffs_cache *cache,
3273                                 int is_write)
3274 {
3275
3276         if (dev->param.n_caches > 0) {
3277                 if (dev->cache_last_use < 0 || dev->cache_last_use > 100000000) {
3278                         /* Reset the cache usages */
3279                         int i;
3280                         for (i = 1; i < dev->param.n_caches; i++)
3281                                 dev->cache[i].last_use = 0;
3282
3283                         dev->cache_last_use = 0;
3284                 }
3285
3286                 dev->cache_last_use++;
3287
3288                 cache->last_use = dev->cache_last_use;
3289
3290                 if (is_write)
3291                         cache->dirty = 1;
3292         }
3293 }
3294
3295 /* Invalidate a single cache page.
3296  * Do this when a whole page gets written,
3297  * ie the short cache for this page is no longer valid.
3298  */
3299 static void yaffs_invalidate_chunk_cache(struct yaffs_obj *object, int chunk_id)
3300 {
3301         if (object->my_dev->param.n_caches > 0) {
3302                 struct yaffs_cache *cache = yaffs_find_chunk_cache(object, chunk_id);
3303
3304                 if (cache)
3305                         cache->object = NULL;
3306         }
3307 }
3308
3309 /* Invalidate all the cache pages associated with this object
3310  * Do this whenever ther file is deleted or resized.
3311  */
3312 static void yaffs_invalidate_whole_cache(struct yaffs_obj *in)
3313 {
3314         int i;
3315         struct yaffs_dev *dev = in->my_dev;
3316
3317         if (dev->param.n_caches > 0) {
3318                 /* Invalidate it. */
3319                 for (i = 0; i < dev->param.n_caches; i++) {
3320                         if (dev->cache[i].object == in)
3321                                 dev->cache[i].object = NULL;
3322                 }
3323         }
3324 }
3325
3326
3327 /*--------------------- File read/write ------------------------
3328  * Read and write have very similar structures.
3329  * In general the read/write has three parts to it
3330  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3331  * Some complete chunks
3332  * An incomplete chunk to end off with
3333  *
3334  * Curve-balls: the first chunk might also be the last chunk.
3335  */
3336
3337 int yaffs_file_rd(struct yaffs_obj *in, u8 *buffer, loff_t offset,
3338                         int n_bytes)
3339 {
3340
3341         int chunk;
3342         u32 start;
3343         int n_copy;
3344         int n = n_bytes;
3345         int n_done = 0;
3346         struct yaffs_cache *cache;
3347
3348         struct yaffs_dev *dev;
3349
3350         dev = in->my_dev;
3351
3352         while (n > 0) {
3353                 /* chunk = offset / dev->data_bytes_per_chunk + 1; */
3354                 /* start = offset % dev->data_bytes_per_chunk; */
3355                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3356                 chunk++;
3357
3358                 /* OK now check for the curveball where the start and end are in
3359                  * the same chunk.
3360                  */
3361                 if ((start + n) < dev->data_bytes_per_chunk)
3362                         n_copy = n;
3363                 else
3364                         n_copy = dev->data_bytes_per_chunk - start;
3365
3366                 cache = yaffs_find_chunk_cache(in, chunk);
3367
3368                 /* If the chunk is already in the cache or it is less than a whole chunk
3369                  * or we're using inband tags then use the cache (if there is caching)
3370                  * else bypass the cache.
3371                  */
3372                 if (cache || n_copy != dev->data_bytes_per_chunk || dev->param.inband_tags) {
3373                         if (dev->param.n_caches > 0) {
3374
3375                                 /* If we can't find the data in the cache, then load it up. */
3376
3377                                 if (!cache) {
3378                                         cache = yaffs_grab_chunk_cache(in->my_dev);
3379                                         cache->object = in;
3380                                         cache->chunk_id = chunk;
3381                                         cache->dirty = 0;
3382                                         cache->locked = 0;
3383                                         yaffs_rd_data_obj(in, chunk,
3384                                                                       cache->
3385                                                                       data);
3386                                         cache->n_bytes = 0;
3387                                 }
3388
3389                                 yaffs_use_cache(dev, cache, 0);
3390
3391                                 cache->locked = 1;
3392
3393
3394                                 memcpy(buffer, &cache->data[start], n_copy);
3395
3396                                 cache->locked = 0;
3397                         } else {
3398                                 /* Read into the local buffer then copy..*/
3399
3400                                 u8 *local_buffer =
3401                                     yaffs_get_temp_buffer(dev, __LINE__);
3402                                 yaffs_rd_data_obj(in, chunk,
3403                                                               local_buffer);
3404
3405                                 memcpy(buffer, &local_buffer[start], n_copy);
3406
3407
3408                                 yaffs_release_temp_buffer(dev, local_buffer,
3409                                                         __LINE__);
3410                         }
3411
3412                 } else {
3413
3414                         /* A full chunk. Read directly into the supplied buffer. */
3415                         yaffs_rd_data_obj(in, chunk, buffer);
3416
3417                 }
3418
3419                 n -= n_copy;
3420                 offset += n_copy;
3421                 buffer += n_copy;
3422                 n_done += n_copy;
3423
3424         }
3425
3426         return n_done;
3427 }
3428
3429 int yaffs_do_file_wr(struct yaffs_obj *in, const u8 *buffer, loff_t offset,
3430                         int n_bytes, int write_trhrough)
3431 {
3432
3433         int chunk;
3434         u32 start;
3435         int n_copy;
3436         int n = n_bytes;
3437         int n_done = 0;
3438         int n_writeback;
3439         int start_write = offset;
3440         int chunk_written = 0;
3441         u32 n_bytes_read;
3442         u32 chunk_start;
3443
3444         struct yaffs_dev *dev;
3445
3446         dev = in->my_dev;
3447
3448         while (n > 0 && chunk_written >= 0) {
3449                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3450
3451                 if (chunk * dev->data_bytes_per_chunk + start != offset ||
3452                                 start >= dev->data_bytes_per_chunk) {
3453                         T(YAFFS_TRACE_ERROR, (
3454                            TSTR("AddrToChunk of offset %d gives chunk %d start %d"
3455                            TENDSTR),
3456                            (int)offset, chunk, start));
3457                 }
3458                 chunk++; /* File pos to chunk in file offset */
3459
3460                 /* OK now check for the curveball where the start and end are in
3461                  * the same chunk.
3462                  */
3463
3464                 if ((start + n) < dev->data_bytes_per_chunk) {
3465                         n_copy = n;
3466
3467                         /* Now folks, to calculate how many bytes to write back....
3468                          * If we're overwriting and not writing to then end of file then
3469                          * we need to write back as much as was there before.
3470                          */
3471
3472                         chunk_start = ((chunk - 1) * dev->data_bytes_per_chunk);
3473
3474                         if (chunk_start > in->variant.file_variant.file_size)
3475                                 n_bytes_read = 0; /* Past end of file */
3476                         else
3477                                 n_bytes_read = in->variant.file_variant.file_size - chunk_start;
3478
3479                         if (n_bytes_read > dev->data_bytes_per_chunk)
3480                                 n_bytes_read = dev->data_bytes_per_chunk;
3481
3482                         n_writeback =
3483                             (n_bytes_read >
3484                              (start + n)) ? n_bytes_read : (start + n);
3485
3486                         if (n_writeback < 0 || n_writeback > dev->data_bytes_per_chunk)
3487                                 YBUG();
3488
3489                 } else {
3490                         n_copy = dev->data_bytes_per_chunk - start;
3491                         n_writeback = dev->data_bytes_per_chunk;
3492                 }
3493
3494                 if (n_copy != dev->data_bytes_per_chunk || dev->param.inband_tags) {
3495                         /* An incomplete start or end chunk (or maybe both start and end chunk),
3496                          * or we're using inband tags, so we want to use the cache buffers.
3497                          */
3498                         if (dev->param.n_caches > 0) {
3499                                 struct yaffs_cache *cache;
3500                                 /* If we can't find the data in the cache, then load the cache */
3501                                 cache = yaffs_find_chunk_cache(in, chunk);
3502
3503                                 if (!cache
3504                                     && yaffs_check_alloc_available(dev, 1)) {
3505                                         cache = yaffs_grab_chunk_cache(dev);
3506                                         cache->object = in;
3507                                         cache->chunk_id = chunk;
3508                                         cache->dirty = 0;
3509                                         cache->locked = 0;
3510                                         yaffs_rd_data_obj(in, chunk,
3511                                                                       cache->data);
3512                                 } else if (cache &&
3513                                         !cache->dirty &&
3514                                         !yaffs_check_alloc_available(dev, 1)) {
3515                                         /* Drop the cache if it was a read cache item and
3516                                          * no space check has been made for it.
3517                                          */
3518                                          cache = NULL;
3519                                 }
3520
3521                                 if (cache) {
3522                                         yaffs_use_cache(dev, cache, 1);
3523                                         cache->locked = 1;
3524
3525
3526                                         memcpy(&cache->data[start], buffer,
3527                                                n_copy);
3528
3529
3530                                         cache->locked = 0;
3531                                         cache->n_bytes = n_writeback;
3532
3533                                         if (write_trhrough) {
3534                                                 chunk_written =
3535                                                     yaffs_wr_data_obj
3536                                                     (cache->object,
3537                                                      cache->chunk_id,
3538                                                      cache->data, cache->n_bytes,
3539                                                      1);
3540                                                 cache->dirty = 0;
3541                                         }
3542
3543                                 } else {
3544                                         chunk_written = -1;     /* fail the write */
3545                                 }
3546                         } else {
3547                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
3548                                  * Read into the local buffer then copy, then copy over and write back.
3549                                  */
3550
3551                                 u8 *local_buffer =
3552                                     yaffs_get_temp_buffer(dev, __LINE__);
3553
3554                                 yaffs_rd_data_obj(in, chunk,
3555                                                               local_buffer);
3556
3557
3558
3559                                 memcpy(&local_buffer[start], buffer, n_copy);
3560
3561                                 chunk_written =
3562                                     yaffs_wr_data_obj(in, chunk,
3563                                                                  local_buffer,
3564                                                                  n_writeback,
3565                                                                  0);
3566
3567                                 yaffs_release_temp_buffer(dev, local_buffer,
3568                                                         __LINE__);
3569
3570                         }
3571
3572                 } else {
3573                         /* A full chunk. Write directly from the supplied buffer. */
3574
3575
3576
3577                         chunk_written =
3578                             yaffs_wr_data_obj(in, chunk, buffer,
3579                                                          dev->data_bytes_per_chunk,
3580                                                          0);
3581
3582                         /* Since we've overwritten the cached data, we better invalidate it. */
3583                         yaffs_invalidate_chunk_cache(in, chunk);
3584                 }
3585
3586                 if (chunk_written >= 0) {
3587                         n -= n_copy;
3588                         offset += n_copy;
3589                         buffer += n_copy;
3590                         n_done += n_copy;
3591                 }
3592
3593         }
3594
3595         /* Update file object */
3596
3597         if ((start_write + n_done) > in->variant.file_variant.file_size)
3598                 in->variant.file_variant.file_size = (start_write + n_done);
3599
3600         in->dirty = 1;
3601
3602         return n_done;
3603 }
3604
3605 int yaffs_wr_file(struct yaffs_obj *in, const u8 *buffer, loff_t offset,
3606                         int n_bytes, int write_trhrough)
3607 {
3608         yaffs2_handle_hole(in,offset);
3609         return yaffs_do_file_wr(in,buffer,offset,n_bytes,write_trhrough);
3610 }
3611
3612
3613
3614 /* ---------------------- File resizing stuff ------------------ */
3615
3616 static void yaffs_prune_chunks(struct yaffs_obj *in, int new_size)
3617 {
3618
3619         struct yaffs_dev *dev = in->my_dev;
3620         int old_size = in->variant.file_variant.file_size;
3621
3622         int last_del = 1 + (old_size - 1) / dev->data_bytes_per_chunk;
3623
3624         int start_del = 1 + (new_size + dev->data_bytes_per_chunk - 1) /
3625             dev->data_bytes_per_chunk;
3626         int i;
3627         int chunk_id;
3628
3629         /* Delete backwards so that we don't end up with holes if
3630          * power is lost part-way through the operation.
3631          */
3632         for (i = last_del; i >= start_del; i--) {
3633                 /* NB this could be optimised somewhat,
3634                  * eg. could retrieve the tags and write them without
3635                  * using yaffs_chunk_del
3636                  */
3637
3638                 chunk_id = yaffs_find_del_file_chunk(in, i, NULL);
3639                 if (chunk_id > 0) {
3640                         if (chunk_id <
3641                             (dev->internal_start_block * dev->param.chunks_per_block)
3642                             || chunk_id >=
3643                             ((dev->internal_end_block +
3644                               1) * dev->param.chunks_per_block)) {
3645                                 T(YAFFS_TRACE_ALWAYS,
3646                                   (TSTR("Found daft chunk_id %d for %d" TENDSTR),
3647                                    chunk_id, i));
3648                         } else {
3649                                 in->n_data_chunks--;
3650                                 yaffs_chunk_del(dev, chunk_id, 1, __LINE__);
3651                         }
3652                 }
3653         }
3654
3655 }
3656
3657
3658 void yaffs_resize_file_down( struct yaffs_obj *obj, loff_t new_size)
3659 {
3660         int new_full;
3661         u32 new_partial;
3662         struct yaffs_dev *dev = obj->my_dev;
3663
3664         yaffs_addr_to_chunk(dev, new_size, &new_full, &new_partial);
3665
3666         yaffs_prune_chunks(obj, new_size);
3667
3668         if (new_partial != 0) {
3669                 int last_chunk = 1 + new_full;
3670                 u8 *local_buffer = yaffs_get_temp_buffer(dev, __LINE__);
3671
3672                 /* Got to read and rewrite the last chunk with its new size and zero pad */
3673                 yaffs_rd_data_obj(obj, last_chunk, local_buffer);
3674                 memset(local_buffer + new_partial, 0,
3675                         dev->data_bytes_per_chunk - new_partial);
3676
3677                 yaffs_wr_data_obj(obj, last_chunk, local_buffer,
3678                                              new_partial, 1);
3679
3680                 yaffs_release_temp_buffer(dev, local_buffer, __LINE__);
3681         }
3682
3683         obj->variant.file_variant.file_size = new_size;
3684
3685         yaffs_prune_tree(dev, &obj->variant.file_variant);
3686 }
3687
3688
3689 int yaffs_resize_file(struct yaffs_obj *in, loff_t new_size)
3690 {
3691         struct yaffs_dev *dev = in->my_dev;
3692         int old_size = in->variant.file_variant.file_size;
3693
3694         yaffs_flush_file_cache(in);
3695         yaffs_invalidate_whole_cache(in);
3696
3697         yaffs_check_gc(dev,0);
3698
3699         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE)
3700                 return YAFFS_FAIL;
3701
3702         if (new_size == old_size)
3703                 return YAFFS_OK;
3704                 
3705         if(new_size > old_size){
3706                 yaffs2_handle_hole(in,new_size);
3707                 in->variant.file_variant.file_size = new_size;
3708         } else {
3709                 /* new_size < old_size */ 
3710                 yaffs_resize_file_down(in, new_size);
3711         } 
3712
3713         /* Write a new object header to reflect the resize.
3714          * show we've shrunk the file, if need be
3715          * Do this only if the file is not in the deleted directories
3716          * and is not shadowed.
3717          */
3718         if (in->parent &&
3719             !in->is_shadowed &&
3720             in->parent->obj_id != YAFFS_OBJECTID_UNLINKED &&
3721             in->parent->obj_id != YAFFS_OBJECTID_DELETED)
3722                 yaffs_update_oh(in, NULL, 0, 0, 0, NULL);
3723
3724
3725         return YAFFS_OK;
3726 }
3727
3728 loff_t yaffs_get_file_size(struct yaffs_obj *obj)
3729 {
3730         YCHAR *alias = NULL;
3731         obj = yaffs_get_equivalent_obj(obj);
3732
3733         switch (obj->variant_type) {
3734         case YAFFS_OBJECT_TYPE_FILE:
3735                 return obj->variant.file_variant.file_size;
3736         case YAFFS_OBJECT_TYPE_SYMLINK:
3737                 alias = obj->variant.symlink_variant.alias;
3738                 if(!alias)
3739                         return 0;
3740                 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
3741         default:
3742                 return 0;
3743         }
3744 }
3745
3746
3747
3748 int yaffs_flush_file(struct yaffs_obj *in, int update_time, int data_sync)
3749 {
3750         int ret_val;
3751         if (in->dirty) {
3752                 yaffs_flush_file_cache(in);
3753                 if(data_sync) /* Only sync data */
3754                         ret_val=YAFFS_OK;
3755                 else {
3756                         if (update_time) {
3757 #ifdef CONFIG_YAFFS_WINCE
3758                                 yfsd_win_file_time_now(in->win_mtime);
3759 #else
3760
3761                                 in->yst_mtime = Y_CURRENT_TIME;
3762
3763 #endif
3764                         }
3765
3766                         ret_val = (yaffs_update_oh(in, NULL, 0, 0, 0, NULL) >=
3767                                 0) ? YAFFS_OK : YAFFS_FAIL;
3768                 }
3769         } else {
3770                 ret_val = YAFFS_OK;
3771         }
3772
3773         return ret_val;
3774
3775 }
3776
3777 static int yaffs_generic_obj_del(struct yaffs_obj *in)
3778 {
3779
3780         /* First off, invalidate the file's data in the cache, without flushing. */
3781         yaffs_invalidate_whole_cache(in);
3782
3783         if (in->my_dev->param.is_yaffs2 && (in->parent != in->my_dev->del_dir)) {
3784                 /* Move to the unlinked directory so we have a record that it was deleted. */
3785                 yaffs_change_obj_name(in, in->my_dev->del_dir, _Y("deleted"), 0, 0);
3786
3787         }
3788
3789         yaffs_remove_obj_from_dir(in);
3790         yaffs_chunk_del(in->my_dev, in->hdr_chunk, 1, __LINE__);
3791         in->hdr_chunk = 0;
3792
3793         yaffs_free_obj(in);
3794         return YAFFS_OK;
3795
3796 }
3797
3798 /* yaffs_del_file deletes the whole file data
3799  * and the inode associated with the file.
3800  * It does not delete the links associated with the file.
3801  */
3802 static int yaffs_unlink_file_if_needed(struct yaffs_obj *in)
3803 {
3804
3805         int ret_val;
3806         int del_now = 0;
3807         struct yaffs_dev *dev = in->my_dev;
3808
3809         if (!in->my_inode)
3810                 del_now = 1;
3811
3812         if (del_now) {
3813                 ret_val =
3814                     yaffs_change_obj_name(in, in->my_dev->del_dir,
3815                                            _Y("deleted"), 0, 0);
3816                 T(YAFFS_TRACE_TRACING,
3817                   (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3818                    in->obj_id));
3819                 in->deleted = 1;
3820                 in->my_dev->n_deleted_files++;
3821                 if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3822                         yaffs_resize_file(in, 0);
3823                 yaffs_soft_del_file(in);
3824         } else {
3825                 ret_val =
3826                     yaffs_change_obj_name(in, in->my_dev->unlinked_dir,
3827                                            _Y("unlinked"), 0, 0);
3828         }
3829
3830
3831         return ret_val;
3832 }
3833
3834 int yaffs_del_file(struct yaffs_obj *in)
3835 {
3836         int ret_val = YAFFS_OK;
3837         int deleted; /* Need to cache value on stack if in is freed */
3838         struct yaffs_dev *dev = in->my_dev;
3839
3840         if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3841                 yaffs_resize_file(in, 0);
3842
3843         if (in->n_data_chunks > 0) {
3844                 /* Use soft deletion if there is data in the file.
3845                  * That won't be the case if it has been resized to zero.
3846                  */
3847                 if (!in->unlinked)
3848                         ret_val = yaffs_unlink_file_if_needed(in);
3849
3850                 deleted = in->deleted;
3851
3852                 if (ret_val == YAFFS_OK && in->unlinked && !in->deleted) {
3853                         in->deleted = 1;
3854                         deleted = 1;
3855                         in->my_dev->n_deleted_files++;
3856                         yaffs_soft_del_file(in);
3857                 }
3858                 return deleted ? YAFFS_OK : YAFFS_FAIL;
3859         } else {
3860                 /* The file has no data chunks so we toss it immediately */
3861                 yaffs_free_tnode(in->my_dev, in->variant.file_variant.top);
3862                 in->variant.file_variant.top = NULL;
3863                 yaffs_generic_obj_del(in);
3864
3865                 return YAFFS_OK;
3866         }
3867 }
3868
3869 static int yaffs_is_non_empty_dir(struct yaffs_obj *obj)
3870 {
3871         return (obj->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY) &&
3872                 !(list_empty(&obj->variant.dir_variant.children));
3873 }
3874
3875 static int yaffs_del_dir(struct yaffs_obj *obj)
3876 {
3877         /* First check that the directory is empty. */
3878         if (yaffs_is_non_empty_dir(obj))
3879                 return YAFFS_FAIL;
3880
3881         return yaffs_generic_obj_del(obj);
3882 }
3883
3884 static int yaffs_del_symlink(struct yaffs_obj *in)
3885 {
3886         if(in->variant.symlink_variant.alias)
3887                 YFREE(in->variant.symlink_variant.alias);
3888         in->variant.symlink_variant.alias=NULL;
3889
3890         return yaffs_generic_obj_del(in);
3891 }
3892
3893 static int yaffs_del_link(struct yaffs_obj *in)
3894 {
3895         /* remove this hardlink from the list assocaited with the equivalent
3896          * object
3897          */
3898         list_del_init(&in->hard_links);
3899         return yaffs_generic_obj_del(in);
3900 }
3901
3902 int yaffs_del_obj(struct yaffs_obj *obj)
3903 {
3904 int ret_val = -1;
3905         switch (obj->variant_type) {
3906         case YAFFS_OBJECT_TYPE_FILE:
3907                 ret_val = yaffs_del_file(obj);
3908                 break;
3909         case YAFFS_OBJECT_TYPE_DIRECTORY:
3910                 if(!list_empty(&obj->variant.dir_variant.dirty)){
3911                         T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->obj_id));
3912                         list_del_init(&obj->variant.dir_variant.dirty);
3913                 }
3914                 return yaffs_del_dir(obj);
3915                 break;
3916         case YAFFS_OBJECT_TYPE_SYMLINK:
3917                 ret_val = yaffs_del_symlink(obj);
3918                 break;
3919         case YAFFS_OBJECT_TYPE_HARDLINK:
3920                 ret_val = yaffs_del_link(obj);
3921                 break;
3922         case YAFFS_OBJECT_TYPE_SPECIAL:
3923                 ret_val = yaffs_generic_obj_del(obj);
3924                 break;
3925         case YAFFS_OBJECT_TYPE_UNKNOWN:
3926                 ret_val = 0;
3927                 break;          /* should not happen. */
3928         }
3929
3930         return ret_val;
3931 }
3932
3933 static int yaffs_unlink_worker(struct yaffs_obj *obj)
3934 {
3935
3936         int del_now = 0;
3937
3938         if (!obj->my_inode)
3939                 del_now = 1;
3940
3941         if(obj)
3942                 yaffs_update_parent(obj->parent);
3943
3944         if (obj->variant_type == YAFFS_OBJECT_TYPE_HARDLINK) {
3945                 return yaffs_del_link(obj);
3946         } else if (!list_empty(&obj->hard_links)) {
3947                 /* Curve ball: We're unlinking an object that has a hardlink.
3948                  *
3949                  * This problem arises because we are not strictly following
3950                  * The Linux link/inode model.
3951                  *
3952                  * We can't really delete the object.
3953                  * Instead, we do the following:
3954                  * - Select a hardlink.
3955                  * - Unhook it from the hard links
3956                  * - Move it from its parent directory (so that the rename can work)
3957                  * - Rename the object to the hardlink's name.
3958                  * - Delete the hardlink
3959                  */
3960
3961                 struct yaffs_obj *hl;
3962                 struct yaffs_obj *parent;
3963                 int ret_val;
3964                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
3965
3966                 hl = list_entry(obj->hard_links.next, struct yaffs_obj, hard_links);
3967
3968                 yaffs_get_obj_name(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
3969                 parent = hl->parent;
3970
3971                 list_del_init(&hl->hard_links);
3972
3973                 yaffs_add_obj_to_dir(obj->my_dev->unlinked_dir, hl);
3974
3975                 ret_val = yaffs_change_obj_name(obj,parent, name, 0, 0);
3976
3977                 if (ret_val == YAFFS_OK)
3978                         ret_val = yaffs_generic_obj_del(hl);
3979
3980                 return ret_val;
3981
3982         } else if (del_now) {
3983                 switch (obj->variant_type) {
3984                 case YAFFS_OBJECT_TYPE_FILE:
3985                         return yaffs_del_file(obj);
3986                         break;
3987                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3988                         list_del_init(&obj->variant.dir_variant.dirty);
3989                         return yaffs_del_dir(obj);
3990                         break;
3991                 case YAFFS_OBJECT_TYPE_SYMLINK:
3992                         return yaffs_del_symlink(obj);
3993                         break;
3994                 case YAFFS_OBJECT_TYPE_SPECIAL:
3995                         return yaffs_generic_obj_del(obj);
3996                         break;
3997                 case YAFFS_OBJECT_TYPE_HARDLINK:
3998                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3999                 default:
4000                         return YAFFS_FAIL;
4001                 }
4002         } else if(yaffs_is_non_empty_dir(obj))
4003                 return YAFFS_FAIL;
4004         else
4005                 return yaffs_change_obj_name(obj, obj->my_dev->unlinked_dir,
4006                                            _Y("unlinked"), 0, 0);
4007 }
4008
4009
4010 static int yaffs_unlink_obj(struct yaffs_obj *obj)
4011 {
4012
4013         if (obj && obj->unlink_allowed)
4014                 return yaffs_unlink_worker(obj);
4015
4016         return YAFFS_FAIL;
4017
4018 }
4019 int yaffs_unlinker(struct yaffs_obj *dir, const YCHAR *name)
4020 {
4021         struct yaffs_obj *obj;
4022
4023         obj = yaffs_find_by_name(dir, name);
4024         return yaffs_unlink_obj(obj);
4025 }
4026
4027 /*----------------------- Initialisation Scanning ---------------------- */
4028
4029 void yaffs_handle_shadowed_obj(struct yaffs_dev *dev, int obj_id,
4030                                 int backward_scanning)
4031 {
4032         struct yaffs_obj *obj;
4033
4034         if (!backward_scanning) {
4035                 /* Handle YAFFS1 forward scanning case
4036                  * For YAFFS1 we always do the deletion
4037                  */
4038
4039         } else {
4040                 /* Handle YAFFS2 case (backward scanning)
4041                  * If the shadowed object exists then ignore.
4042                  */
4043                 obj = yaffs_find_by_number(dev, obj_id);
4044                 if(obj)
4045                         return;
4046         }
4047
4048         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4049          * We put it in unlinked dir to be cleaned up after the scanning
4050          */
4051         obj =
4052             yaffs_find_or_create_by_number(dev, obj_id,
4053                                              YAFFS_OBJECT_TYPE_FILE);
4054         if (!obj)
4055                 return;
4056         obj->is_shadowed = 1;
4057         yaffs_add_obj_to_dir(dev->unlinked_dir, obj);
4058         obj->variant.file_variant.shrink_size = 0;
4059         obj->valid = 1;         /* So that we don't read any other info for this file */
4060
4061 }
4062
4063
4064 void yaffs_link_fixup(struct yaffs_dev *dev, struct yaffs_obj *hard_list)
4065 {
4066         struct yaffs_obj *hl;
4067         struct yaffs_obj *in;
4068
4069         while (hard_list) {
4070                 hl = hard_list;
4071                 hard_list = (struct yaffs_obj *) (hard_list->hard_links.next);
4072
4073                 in = yaffs_find_by_number(dev,
4074                                               hl->variant.hardlink_variant.
4075                                               equiv_id);
4076
4077                 if (in) {
4078                         /* Add the hardlink pointers */
4079                         hl->variant.hardlink_variant.equiv_obj = in;
4080                         list_add(&hl->hard_links, &in->hard_links);
4081                 } else {
4082                         /* Todo Need to report/handle this better.
4083                          * Got a problem... hardlink to a non-existant object
4084                          */
4085                         hl->variant.hardlink_variant.equiv_obj = NULL;
4086                         INIT_LIST_HEAD(&hl->hard_links);
4087
4088                 }
4089         }
4090 }
4091
4092
4093 static void yaffs_strip_deleted_objs(struct yaffs_dev *dev)
4094 {
4095         /*
4096         *  Sort out state of unlinked and deleted objects after scanning.
4097         */
4098         struct list_head *i;
4099         struct list_head *n;
4100         struct yaffs_obj *l;
4101
4102         if (dev->read_only)
4103                 return;
4104
4105         /* Soft delete all the unlinked files */
4106         list_for_each_safe(i, n,
4107                 &dev->unlinked_dir->variant.dir_variant.children) {
4108                 if (i) {
4109                         l = list_entry(i, struct yaffs_obj, siblings);
4110                         yaffs_del_obj(l);
4111                 }
4112         }
4113
4114         list_for_each_safe(i, n,
4115                 &dev->del_dir->variant.dir_variant.children) {
4116                 if (i) {
4117                         l = list_entry(i, struct yaffs_obj, siblings);
4118                         yaffs_del_obj(l);
4119                 }
4120         }
4121
4122 }
4123
4124 /*
4125  * This code iterates through all the objects making sure that they are rooted.
4126  * Any unrooted objects are re-rooted in lost+found.
4127  * An object needs to be in one of:
4128  * - Directly under deleted, unlinked
4129  * - Directly or indirectly under root.
4130  *
4131  * Note:
4132  *  This code assumes that we don't ever change the current relationships between
4133  *  directories:
4134  *   root_dir->parent == unlinked_dir->parent == del_dir->parent == NULL
4135  *   lost-n-found->parent == root_dir
4136  *
4137  * This fixes the problem where directories might have inadvertently been deleted
4138  * leaving the object "hanging" without being rooted in the directory tree.
4139  */
4140  
4141 static int yaffs_has_null_parent(struct yaffs_dev *dev, struct yaffs_obj *obj)
4142 {
4143         return (obj == dev->del_dir ||
4144                 obj == dev->unlinked_dir||
4145                 obj == dev->root_dir);
4146 }
4147
4148 static void yaffs_fix_hanging_objs(struct yaffs_dev *dev)
4149 {
4150         struct yaffs_obj *obj;
4151         struct yaffs_obj *parent;
4152         int i;
4153         struct list_head *lh;
4154         struct list_head *n;
4155         int depth_limit;
4156         int hanging;
4157
4158         if (dev->read_only)
4159                 return;
4160
4161         /* Iterate through the objects in each hash entry,
4162          * looking at each object.
4163          * Make sure it is rooted.
4164          */
4165
4166         for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
4167                 list_for_each_safe(lh, n, &dev->obj_bucket[i].list) {
4168                         if (lh) {
4169                                 obj = list_entry(lh, struct yaffs_obj, hash_link);
4170                                 parent= obj->parent;
4171                                 
4172                                 if(yaffs_has_null_parent(dev,obj)){
4173                                         /* These directories are not hanging */
4174                                         hanging = 0;
4175                                 }
4176                                 else if(!parent || parent->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
4177                                         hanging = 1;
4178                                 else if(yaffs_has_null_parent(dev,parent))
4179                                         hanging = 0;
4180                                 else {
4181                                         /*
4182                                          * Need to follow the parent chain to see if it is hanging.
4183                                          */
4184                                         hanging = 0;
4185                                         depth_limit=100;
4186
4187                                         while(parent != dev->root_dir &&
4188                                                 parent->parent &&
4189                                                 parent->parent->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY &&
4190                                                 depth_limit > 0){
4191                                                 parent = parent->parent;
4192                                                 depth_limit--;
4193                                         }
4194                                         if(parent != dev->root_dir)
4195                                                 hanging = 1;
4196                                 }
4197                                 if(hanging){
4198                                         T(YAFFS_TRACE_SCAN,
4199                                           (TSTR("Hanging object %d moved to lost and found" TENDSTR),
4200                                                 obj->obj_id));
4201                                         yaffs_add_obj_to_dir(dev->lost_n_found,obj);
4202                                 }
4203                         }
4204                 }
4205         }
4206 }
4207
4208
4209 /*
4210  * Delete directory contents for cleaning up lost and found.
4211  */
4212 static void yaffs_del_dir_contents(struct yaffs_obj *dir)
4213 {
4214         struct yaffs_obj *obj;
4215         struct list_head *lh;
4216         struct list_head *n;
4217
4218         if(dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
4219                 YBUG();
4220         
4221         list_for_each_safe(lh, n, &dir->variant.dir_variant.children) {
4222                 if (lh) {
4223                         obj = list_entry(lh, struct yaffs_obj, siblings);
4224                         if(obj->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY)
4225                                 yaffs_del_dir_contents(obj);
4226
4227                         T(YAFFS_TRACE_SCAN,
4228                                 (TSTR("Deleting lost_found object %d" TENDSTR),
4229                                 obj->obj_id));
4230
4231                         /* Need to use UnlinkObject since Delete would not handle
4232                          * hardlinked objects correctly.
4233                          */
4234                         yaffs_unlink_obj(obj); 
4235                 }
4236         }
4237                         
4238 }
4239
4240 static void yaffs_empty_l_n_f(struct yaffs_dev *dev)
4241 {
4242         yaffs_del_dir_contents(dev->lost_n_found);
4243 }
4244
4245 static void yaffs_check_obj_details_loaded(struct yaffs_obj *in)
4246 {
4247         u8 *chunk_data;
4248         struct yaffs_obj_hdr *oh;
4249         struct yaffs_dev *dev;
4250         struct yaffs_ext_tags tags;
4251         int result;
4252         int alloc_failed = 0;
4253
4254         if (!in)
4255                 return;
4256
4257         dev = in->my_dev;
4258
4259         if (in->lazy_loaded && in->hdr_chunk > 0) {
4260                 in->lazy_loaded = 0;
4261                 chunk_data = yaffs_get_temp_buffer(dev, __LINE__);
4262
4263                 result = yaffs_rd_chunk_tags_nand(dev, in->hdr_chunk, chunk_data, &tags);
4264                 oh = (struct yaffs_obj_hdr *) chunk_data;
4265
4266                 in->yst_mode = oh->yst_mode;
4267 #ifdef CONFIG_YAFFS_WINCE
4268                 in->win_atime[0] = oh->win_atime[0];
4269                 in->win_ctime[0] = oh->win_ctime[0];
4270                 in->win_mtime[0] = oh->win_mtime[0];
4271                 in->win_atime[1] = oh->win_atime[1];
4272                 in->win_ctime[1] = oh->win_ctime[1];
4273                 in->win_mtime[1] = oh->win_mtime[1];
4274 #else
4275                 in->yst_uid = oh->yst_uid;
4276                 in->yst_gid = oh->yst_gid;
4277                 in->yst_atime = oh->yst_atime;
4278                 in->yst_mtime = oh->yst_mtime;
4279                 in->yst_ctime = oh->yst_ctime;
4280                 in->yst_rdev = oh->yst_rdev;
4281
4282 #endif
4283                 yaffs_set_obj_name_from_oh(in, oh);
4284
4285                 if (in->variant_type == YAFFS_OBJECT_TYPE_SYMLINK) {
4286                         in->variant.symlink_variant.alias =
4287                                                     yaffs_clone_str(oh->alias);
4288                         if (!in->variant.symlink_variant.alias)
4289                                 alloc_failed = 1; /* Not returned to caller */
4290                 }
4291
4292                 yaffs_release_temp_buffer(dev, chunk_data, __LINE__);
4293         }
4294 }
4295
4296 /*------------------------------  Directory Functions ----------------------------- */
4297
4298 /*
4299  *yaffs_update_parent() handles fixing a directories mtime and ctime when a new
4300  * link (ie. name) is created or deleted in the directory.
4301  *
4302  * ie.
4303  *   create dir/a : update dir's mtime/ctime
4304  *   rm dir/a:   update dir's mtime/ctime
4305  *   modify dir/a: don't update dir's mtimme/ctime
4306  *
4307  * This can be handled immediately or defered. Defering helps reduce the number
4308  * of updates when many files in a directory are changed within a brief period.
4309  *
4310  * If the directory updating is defered then yaffs_update_dirty_dirs must be
4311  * called periodically.
4312  */
4313  
4314 static void yaffs_update_parent(struct yaffs_obj *obj)
4315 {
4316         struct yaffs_dev *dev;
4317         if(!obj)
4318                 return;
4319 #ifndef CONFIG_YAFFS_WINCE
4320
4321         dev = obj->my_dev;
4322         obj->dirty = 1;
4323         obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
4324         if(dev->param.defered_dir_update){
4325                 struct list_head *link = &obj->variant.dir_variant.dirty; 
4326         
4327                 if(list_empty(link)){
4328                         list_add(link,&dev->dirty_dirs);
4329                         T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->obj_id));
4330                 }
4331
4332         } else
4333                 yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
4334 #endif
4335 }
4336
4337 void yaffs_update_dirty_dirs(struct yaffs_dev *dev)
4338 {
4339         struct list_head *link;
4340         struct yaffs_obj *obj;
4341         struct yaffs_dir_var *d_s;
4342         union yaffs_obj_var *o_v;
4343
4344         T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
4345
4346         while(!list_empty(&dev->dirty_dirs)){
4347                 link = dev->dirty_dirs.next;
4348                 list_del_init(link);
4349                 
4350                 d_s=list_entry(link,struct yaffs_dir_var,dirty);
4351                 o_v = list_entry(d_s,union yaffs_obj_var,dir_variant);
4352                 obj = list_entry(o_v,struct yaffs_obj,variant);
4353
4354                 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->obj_id));
4355
4356                 if(obj->dirty)
4357                         yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
4358         }
4359 }
4360
4361 static void yaffs_remove_obj_from_dir(struct yaffs_obj *obj)
4362 {
4363         struct yaffs_dev *dev = obj->my_dev;
4364         struct yaffs_obj *parent;
4365
4366         yaffs_verify_obj_in_dir(obj);
4367         parent = obj->parent;
4368
4369         yaffs_verify_dir(parent);
4370
4371         if (dev && dev->param.remove_obj_fn)
4372                 dev->param.remove_obj_fn(obj);
4373
4374
4375         list_del_init(&obj->siblings);
4376         obj->parent = NULL;
4377         
4378         yaffs_verify_dir(parent);
4379 }
4380
4381 void yaffs_add_obj_to_dir(struct yaffs_obj *directory,
4382                                         struct yaffs_obj *obj)
4383 {
4384         if (!directory) {
4385                 T(YAFFS_TRACE_ALWAYS,
4386                   (TSTR
4387                    ("tragedy: Trying to add an object to a null pointer directory"
4388                     TENDSTR)));
4389                 YBUG();
4390                 return;
4391         }
4392         if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
4393                 T(YAFFS_TRACE_ALWAYS,
4394                   (TSTR
4395                    ("tragedy: Trying to add an object to a non-directory"
4396                     TENDSTR)));
4397                 YBUG();
4398         }
4399
4400         if (obj->siblings.prev == NULL) {
4401                 /* Not initialised */
4402                 YBUG();
4403         }
4404
4405
4406         yaffs_verify_dir(directory);
4407
4408         yaffs_remove_obj_from_dir(obj);
4409
4410
4411         /* Now add it */
4412         list_add(&obj->siblings, &directory->variant.dir_variant.children);
4413         obj->parent = directory;
4414
4415         if (directory == obj->my_dev->unlinked_dir
4416                         || directory == obj->my_dev->del_dir) {
4417                 obj->unlinked = 1;
4418                 obj->my_dev->n_unlinked_files++;
4419                 obj->rename_allowed = 0;
4420         }
4421
4422         yaffs_verify_dir(directory);
4423         yaffs_verify_obj_in_dir(obj);
4424 }
4425
4426 struct yaffs_obj *yaffs_find_by_name(struct yaffs_obj *directory,
4427                                      const YCHAR *name)
4428 {
4429         int sum;
4430
4431         struct list_head *i;
4432         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4433
4434         struct yaffs_obj *l;
4435
4436         if (!name)
4437                 return NULL;
4438
4439         if (!directory) {
4440                 T(YAFFS_TRACE_ALWAYS,
4441                   (TSTR
4442                    ("tragedy: yaffs_find_by_name: null pointer directory"
4443                     TENDSTR)));
4444                 YBUG();
4445                 return NULL;
4446         }
4447         if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
4448                 T(YAFFS_TRACE_ALWAYS,
4449                   (TSTR
4450                    ("tragedy: yaffs_find_by_name: non-directory" TENDSTR)));
4451                 YBUG();
4452         }
4453
4454         sum = yaffs_calc_name_sum(name);
4455
4456         list_for_each(i, &directory->variant.dir_variant.children) {
4457                 if (i) {
4458                         l = list_entry(i, struct yaffs_obj, siblings);
4459
4460                         if (l->parent != directory)
4461                                 YBUG();
4462
4463                         yaffs_check_obj_details_loaded(l);
4464
4465                         /* Special case for lost-n-found */
4466                         if (l->obj_id == YAFFS_OBJECTID_LOSTNFOUND) {
4467                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
4468                                         return l;
4469                         } else if (yaffs_sum_cmp(l->sum, sum) || l->hdr_chunk <= 0) {
4470                                 /* LostnFound chunk called Objxxx
4471                                  * Do a real check
4472                                  */
4473                                 yaffs_get_obj_name(l, buffer,
4474                                                     YAFFS_MAX_NAME_LENGTH + 1);
4475                                 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
4476                                         return l;
4477                         }
4478                 }
4479         }
4480
4481         return NULL;
4482 }
4483
4484
4485 /* GetEquivalentObject dereferences any hard links to get to the
4486  * actual object.
4487  */
4488
4489 struct yaffs_obj *yaffs_get_equivalent_obj(struct yaffs_obj *obj)
4490 {
4491         if (obj && obj->variant_type == YAFFS_OBJECT_TYPE_HARDLINK) {
4492                 /* We want the object id of the equivalent object, not this one */
4493                 obj = obj->variant.hardlink_variant.equiv_obj;
4494                 yaffs_check_obj_details_loaded(obj);
4495         }
4496         return obj;
4497 }
4498
4499 /*
4500  *  A note or two on object names.
4501  *  * If the object name is missing, we then make one up in the form objnnn
4502  *
4503  *  * ASCII names are stored in the object header's name field from byte zero
4504  *  * Unicode names are historically stored starting from byte zero.
4505  *
4506  * Then there are automatic Unicode names...
4507  * The purpose of these is to save names in a way that can be read as
4508  * ASCII or Unicode names as appropriate, thus allowing a Unicode and ASCII
4509  * system to share files.
4510  *
4511  * These automatic unicode are stored slightly differently...
4512  *  - If the name can fit in the ASCII character space then they are saved as 
4513  *    ascii names as per above.
4514  *  - If the name needs Unicode then the name is saved in Unicode
4515  *    starting at oh->name[1].
4516
4517  */
4518 static void yaffs_fix_null_name(struct yaffs_obj * obj,YCHAR * name, int buffer_size)
4519 {
4520         /* Create an object name if we could not find one. */
4521         if(yaffs_strnlen(name,YAFFS_MAX_NAME_LENGTH) == 0){
4522                 YCHAR local_name[20];
4523                 YCHAR num_string[20];
4524                 YCHAR *x = &num_string[19];
4525                 unsigned v = obj->obj_id;
4526                 num_string[19] = 0;
4527                 while(v>0){
4528                         x--;
4529                         *x = '0' + (v % 10);
4530                         v /= 10;
4531                 }
4532                 /* make up a name */
4533                 yaffs_strcpy(local_name, YAFFS_LOSTNFOUND_PREFIX);
4534                 yaffs_strcat(local_name,x);
4535                 yaffs_strncpy(name, local_name, buffer_size - 1);
4536         }
4537 }
4538
4539 static void yaffs_load_name_from_oh(struct yaffs_dev *dev,YCHAR *name, const YCHAR *oh_name, int buff_size)
4540 {
4541 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4542         if(dev->param.auto_unicode){
4543                 if(*oh_name){
4544                         /* It is an ASCII name, so do an ASCII to unicode conversion */
4545                         const char *ascii_oh_name = (const char *)oh_name;
4546                         int n = buff_size - 1;
4547                         while(n > 0 && *ascii_oh_name){
4548                                 *name = *ascii_oh_name;
4549                                 name++;
4550                                 ascii_oh_name++;
4551                                 n--;
4552                         }
4553                 } else 
4554                         yaffs_strncpy(name,oh_name+1, buff_size -1);
4555         } else
4556 #endif
4557                 yaffs_strncpy(name, oh_name, buff_size - 1);
4558 }
4559
4560
4561 static void yaffs_load_oh_from_name(struct yaffs_dev *dev, YCHAR *oh_name, const YCHAR *name)
4562 {
4563 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4564
4565         int is_ascii;
4566         YCHAR *w;
4567
4568         if(dev->param.auto_unicode){
4569
4570                 is_ascii = 1;
4571                 w = name;
4572         
4573                 /* Figure out if the name will fit in ascii character set */
4574                 while(is_ascii && *w){
4575                         if((*w) & 0xff00)
4576                                 is_ascii = 0;
4577                         w++;
4578                 }
4579
4580                 if(is_ascii){
4581                         /* It is an ASCII name, so do a unicode to ascii conversion */
4582                         char *ascii_oh_name = (char *)oh_name;
4583                         int n = YAFFS_MAX_NAME_LENGTH  - 1;
4584                         while(n > 0 && *name){
4585                                 *ascii_oh_name= *name;
4586                                 name++;
4587                                 ascii_oh_name++;
4588                                 n--;
4589                         }
4590                 } else{
4591                         /* It is a unicode name, so save starting at the second YCHAR */
4592                         *oh_name = 0;
4593                         yaffs_strncpy(oh_name+1,name, YAFFS_MAX_NAME_LENGTH -2);
4594                 }
4595         }
4596         else 
4597 #endif
4598                 yaffs_strncpy(oh_name,name, YAFFS_MAX_NAME_LENGTH - 1);
4599
4600 }
4601
4602 int yaffs_get_obj_name(struct yaffs_obj * obj, YCHAR * name, int buffer_size)
4603 {
4604         memset(name, 0, buffer_size * sizeof(YCHAR));
4605         
4606         yaffs_check_obj_details_loaded(obj);
4607
4608         if (obj->obj_id == YAFFS_OBJECTID_LOSTNFOUND) {
4609                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffer_size - 1);
4610         } 
4611 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4612         else if (obj->short_name[0]) {
4613                 yaffs_strcpy(name, obj->short_name);
4614         }
4615 #endif
4616         else if(obj->hdr_chunk > 0) {
4617                 int result;
4618                 u8 *buffer = yaffs_get_temp_buffer(obj->my_dev, __LINE__);
4619
4620                 struct yaffs_obj_hdr *oh = (struct yaffs_obj_hdr *) buffer;
4621
4622                 memset(buffer, 0, obj->my_dev->data_bytes_per_chunk);
4623
4624                 if (obj->hdr_chunk > 0) {
4625                         result = yaffs_rd_chunk_tags_nand(obj->my_dev,
4626                                                         obj->hdr_chunk, buffer,
4627                                                         NULL);
4628                 }
4629                 yaffs_load_name_from_oh(obj->my_dev,name,oh->name,buffer_size);
4630
4631                 yaffs_release_temp_buffer(obj->my_dev, buffer, __LINE__);
4632         }
4633
4634         yaffs_fix_null_name(obj,name,buffer_size);
4635
4636         return yaffs_strnlen(name,YAFFS_MAX_NAME_LENGTH);
4637 }
4638
4639
4640 int yaffs_get_obj_length(struct yaffs_obj *obj)
4641 {
4642         /* Dereference any hard linking */
4643         obj = yaffs_get_equivalent_obj(obj);
4644
4645         if (obj->variant_type == YAFFS_OBJECT_TYPE_FILE)
4646                 return obj->variant.file_variant.file_size;
4647         if (obj->variant_type == YAFFS_OBJECT_TYPE_SYMLINK){
4648                 if(!obj->variant.symlink_variant.alias)
4649                         return 0;
4650                 return yaffs_strnlen(obj->variant.symlink_variant.alias,YAFFS_MAX_ALIAS_LENGTH);
4651         } else {
4652                 /* Only a directory should drop through to here */
4653                 return obj->my_dev->data_bytes_per_chunk;
4654         }
4655 }
4656
4657 int yaffs_get_obj_link_count(struct yaffs_obj *obj)
4658 {
4659         int count = 0;
4660         struct list_head *i;
4661
4662         if (!obj->unlinked)
4663                 count++;                /* the object itself */
4664
4665         list_for_each(i, &obj->hard_links)
4666                 count++;                /* add the hard links; */
4667
4668         return count;
4669 }
4670
4671 int yaffs_get_obj_inode(struct yaffs_obj *obj)
4672 {
4673         obj = yaffs_get_equivalent_obj(obj);
4674
4675         return obj->obj_id;
4676 }
4677
4678 unsigned yaffs_get_obj_type(struct yaffs_obj *obj)
4679 {
4680         obj = yaffs_get_equivalent_obj(obj);
4681
4682         switch (obj->variant_type) {
4683         case YAFFS_OBJECT_TYPE_FILE:
4684                 return DT_REG;
4685                 break;
4686         case YAFFS_OBJECT_TYPE_DIRECTORY:
4687                 return DT_DIR;
4688                 break;
4689         case YAFFS_OBJECT_TYPE_SYMLINK:
4690                 return DT_LNK;
4691                 break;
4692         case YAFFS_OBJECT_TYPE_HARDLINK:
4693                 return DT_REG;
4694                 break;
4695         case YAFFS_OBJECT_TYPE_SPECIAL:
4696                 if (S_ISFIFO(obj->yst_mode))
4697                         return DT_FIFO;
4698                 if (S_ISCHR(obj->yst_mode))
4699                         return DT_CHR;
4700                 if (S_ISBLK(obj->yst_mode))
4701                         return DT_BLK;
4702                 if (S_ISSOCK(obj->yst_mode))
4703                         return DT_SOCK;
4704         default:
4705                 return DT_REG;
4706                 break;
4707         }
4708 }
4709
4710 YCHAR *yaffs_get_symlink_alias(struct yaffs_obj *obj)
4711 {
4712         obj = yaffs_get_equivalent_obj(obj);
4713         if (obj->variant_type == YAFFS_OBJECT_TYPE_SYMLINK)
4714                 return yaffs_clone_str(obj->variant.symlink_variant.alias);
4715         else
4716                 return yaffs_clone_str(_Y(""));
4717 }
4718
4719 #ifndef CONFIG_YAFFS_WINCE
4720
4721 int yaffs_set_attribs(struct yaffs_obj *obj, struct iattr *attr)
4722 {
4723         unsigned int valid = attr->ia_valid;
4724
4725         if (valid & ATTR_MODE)
4726                 obj->yst_mode = attr->ia_mode;
4727         if (valid & ATTR_UID)
4728                 obj->yst_uid = attr->ia_uid;
4729         if (valid & ATTR_GID)
4730                 obj->yst_gid = attr->ia_gid;
4731
4732         if (valid & ATTR_ATIME)
4733                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
4734         if (valid & ATTR_CTIME)
4735                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
4736         if (valid & ATTR_MTIME)
4737                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
4738
4739         if (valid & ATTR_SIZE)
4740                 yaffs_resize_file(obj, attr->ia_size);
4741
4742         yaffs_update_oh(obj, NULL, 1, 0, 0, NULL);
4743
4744         return YAFFS_OK;
4745
4746 }
4747 int yaffs_get_attribs(struct yaffs_obj *obj, struct iattr *attr)
4748 {
4749         unsigned int valid = 0;
4750
4751         attr->ia_mode = obj->yst_mode;
4752         valid |= ATTR_MODE;
4753         attr->ia_uid = obj->yst_uid;
4754         valid |= ATTR_UID;
4755         attr->ia_gid = obj->yst_gid;
4756         valid |= ATTR_GID;
4757
4758         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
4759         valid |= ATTR_ATIME;
4760         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
4761         valid |= ATTR_CTIME;
4762         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
4763         valid |= ATTR_MTIME;
4764
4765         attr->ia_size = yaffs_get_file_size(obj);
4766         valid |= ATTR_SIZE;
4767
4768         attr->ia_valid = valid;
4769
4770         return YAFFS_OK;
4771 }
4772
4773 #endif
4774
4775
4776 static int yaffs_do_xattrib_mod(struct yaffs_obj *obj, int set, const YCHAR *name, const void *value, int size, int flags)
4777 {
4778         struct yaffs_xattr_mod xmod;
4779
4780         int result;
4781
4782         xmod.set = set;
4783         xmod.name = name;
4784         xmod.data = value;
4785         xmod.size =  size;
4786         xmod.flags = flags;
4787         xmod.result = -ENOSPC;
4788
4789         result = yaffs_update_oh(obj, NULL, 0, 0, 0, &xmod);
4790
4791         if(result > 0)
4792                 return xmod.result;
4793         else
4794                 return -ENOSPC;
4795 }
4796
4797 static int yaffs_apply_xattrib_mod(struct yaffs_obj *obj, char *buffer, struct yaffs_xattr_mod *xmod)
4798 {
4799         int retval = 0;
4800         int x_offs = sizeof(struct yaffs_obj_hdr);
4801         struct yaffs_dev *dev = obj->my_dev;
4802         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
4803
4804         char * x_buffer = buffer + x_offs;
4805
4806         if(xmod->set)
4807                 retval = nval_set(x_buffer, x_size, xmod->name, xmod->data, xmod->size, xmod->flags);
4808         else
4809                 retval = nval_del(x_buffer, x_size, xmod->name);
4810
4811         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
4812         obj->xattr_known = 1;
4813
4814         xmod->result = retval;
4815
4816         return retval;
4817 }
4818
4819 static int yaffs_do_xattrib_fetch(struct yaffs_obj *obj, const YCHAR *name, void *value, int size)
4820 {
4821         char *buffer = NULL;
4822         int result;
4823         struct yaffs_ext_tags tags;
4824         struct yaffs_dev *dev = obj->my_dev;
4825         int x_offs = sizeof(struct yaffs_obj_hdr);
4826         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
4827
4828         char * x_buffer;
4829
4830         int retval = 0;
4831
4832         if(obj->hdr_chunk < 1)
4833                 return -ENODATA;
4834
4835         /* If we know that the object has no xattribs then don't do all the
4836          * reading and parsing.
4837          */
4838         if(obj->xattr_known && !obj->has_xattr){
4839                 if(name)
4840                         return -ENODATA;
4841                 else
4842                         return 0;
4843         }
4844
4845         buffer = (char *) yaffs_get_temp_buffer(dev, __LINE__);
4846         if(!buffer)
4847                 return -ENOMEM;
4848
4849         result = yaffs_rd_chunk_tags_nand(dev,obj->hdr_chunk, (u8 *)buffer, &tags);
4850
4851         if(result != YAFFS_OK)
4852                 retval = -ENOENT;
4853         else{
4854                 x_buffer =  buffer + x_offs;
4855
4856                 if (!obj->xattr_known){
4857                         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
4858                         obj->xattr_known = 1;
4859                 }
4860
4861                 if(name)
4862                         retval = nval_get(x_buffer, x_size, name, value, size);
4863                 else
4864                         retval = nval_list(x_buffer, x_size, value,size);
4865         }
4866         yaffs_release_temp_buffer(dev,(u8 *)buffer,__LINE__);
4867         return retval;
4868 }
4869
4870 int yaffs_set_xattrib(struct yaffs_obj *obj, const YCHAR *name, const void * value, int size, int flags)
4871 {
4872         return yaffs_do_xattrib_mod(obj, 1, name, value, size, flags);
4873 }
4874
4875 int yaffs_remove_xattrib(struct yaffs_obj *obj, const YCHAR *name)
4876 {
4877         return yaffs_do_xattrib_mod(obj, 0, name, NULL, 0, 0);
4878 }
4879
4880 int yaffs_get_xattrib(struct yaffs_obj *obj, const YCHAR *name, void *value, int size)
4881 {
4882         return yaffs_do_xattrib_fetch(obj, name, value, size);
4883 }
4884
4885 int yaffs_list_xattrib(struct yaffs_obj *obj, char *buffer, int size)
4886 {
4887         return yaffs_do_xattrib_fetch(obj, NULL, buffer,size);
4888 }
4889
4890 /*---------------------------- Initialisation code -------------------------------------- */
4891
4892 static int yaffs_check_dev_fns(const struct yaffs_dev *dev)
4893 {
4894
4895         /* Common functions, gotta have */
4896         if (!dev->param.erase_fn || !dev->param.initialise_flash_fn)
4897                 return 0;
4898
4899 #ifdef CONFIG_YAFFS_YAFFS2
4900
4901         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
4902         if (dev->param.write_chunk_tags_fn &&
4903             dev->param.read_chunk_tags_fn &&
4904             !dev->param.write_chunk_fn &&
4905             !dev->param.read_chunk_fn &&
4906             dev->param.bad_block_fn &&
4907             dev->param.query_block_fn)
4908                 return 1;
4909 #endif
4910
4911         /* Can use the "spare" style interface for yaffs1 */
4912         if (!dev->param.is_yaffs2 &&
4913             !dev->param.write_chunk_tags_fn &&
4914             !dev->param.read_chunk_tags_fn &&
4915             dev->param.write_chunk_fn &&
4916             dev->param.read_chunk_fn &&
4917             !dev->param.bad_block_fn &&
4918             !dev->param.query_block_fn)
4919                 return 1;
4920
4921         return 0;       /* bad */
4922 }
4923
4924
4925 static int yaffs_create_initial_dir(struct yaffs_dev *dev)
4926 {
4927         /* Initialise the unlinked, deleted, root and lost and found directories */
4928
4929         dev->lost_n_found = dev->root_dir =  NULL;
4930         dev->unlinked_dir = dev->del_dir = NULL;
4931
4932         dev->unlinked_dir =
4933             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4934
4935         dev->del_dir =
4936             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
4937
4938         dev->root_dir =
4939             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_ROOT,
4940                                       YAFFS_ROOT_MODE | S_IFDIR);
4941         dev->lost_n_found =
4942             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_LOSTNFOUND,
4943                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4944
4945         if (dev->lost_n_found && dev->root_dir && dev->unlinked_dir && dev->del_dir) {
4946                 yaffs_add_obj_to_dir(dev->root_dir, dev->lost_n_found);
4947                 return YAFFS_OK;
4948         }
4949
4950         return YAFFS_FAIL;
4951 }
4952
4953 int yaffs_guts_initialise(struct yaffs_dev *dev)
4954 {
4955         int init_failed = 0;
4956         unsigned x;
4957         int bits;
4958
4959         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_guts_initialise()" TENDSTR)));
4960
4961         /* Check stuff that must be set */
4962
4963         if (!dev) {
4964                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
4965                 return YAFFS_FAIL;
4966         }
4967
4968         dev->internal_start_block = dev->param.start_block;
4969         dev->internal_end_block = dev->param.end_block;
4970         dev->block_offset = 0;
4971         dev->chunk_offset = 0;
4972         dev->n_free_chunks = 0;
4973
4974         dev->gc_block = 0;
4975
4976         if (dev->param.start_block == 0) {
4977                 dev->internal_start_block = dev->param.start_block + 1;
4978                 dev->internal_end_block = dev->param.end_block + 1;
4979                 dev->block_offset = 1;
4980                 dev->chunk_offset = dev->param.chunks_per_block;
4981         }
4982
4983         /* Check geometry parameters. */
4984
4985         if ((!dev->param.inband_tags && dev->param.is_yaffs2 && dev->param.total_bytes_per_chunk < 1024) ||
4986             (!dev->param.is_yaffs2 && dev->param.total_bytes_per_chunk < 512) ||
4987             (dev->param.inband_tags && !dev->param.is_yaffs2) ||
4988              dev->param.chunks_per_block < 2 ||
4989              dev->param.n_reserved_blocks < 2 ||
4990              dev->internal_start_block <= 0 ||
4991              dev->internal_end_block <= 0 ||
4992              dev->internal_end_block <= (dev->internal_start_block + dev->param.n_reserved_blocks + 2)) {       /* otherwise it is too small */
4993                 T(YAFFS_TRACE_ALWAYS,
4994                   (TSTR
4995                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inband_tags %d "
4996                     TENDSTR), dev->param.total_bytes_per_chunk, dev->param.is_yaffs2 ? "2" : "", dev->param.inband_tags));
4997                 return YAFFS_FAIL;
4998         }
4999
5000         if (yaffs_init_nand(dev) != YAFFS_OK) {
5001                 T(YAFFS_TRACE_ALWAYS,
5002                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5003                 return YAFFS_FAIL;
5004         }
5005
5006         /* Sort out space for inband tags, if required */
5007         if (dev->param.inband_tags)
5008                 dev->data_bytes_per_chunk = dev->param.total_bytes_per_chunk - sizeof(struct yaffs_packed_tags2_tags_only);
5009         else
5010                 dev->data_bytes_per_chunk = dev->param.total_bytes_per_chunk;
5011
5012         /* Got the right mix of functions? */
5013         if (!yaffs_check_dev_fns(dev)) {
5014                 /* Function missing */
5015                 T(YAFFS_TRACE_ALWAYS,
5016                   (TSTR
5017                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5018
5019                 return YAFFS_FAIL;
5020         }
5021
5022         if (dev->is_mounted) {
5023                 T(YAFFS_TRACE_ALWAYS,
5024                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
5025                 return YAFFS_FAIL;
5026         }
5027
5028         /* Finished with most checks. One or two more checks happen later on too. */
5029
5030         dev->is_mounted = 1;
5031
5032         /* OK now calculate a few things for the device */
5033
5034         /*
5035          *  Calculate all the chunk size manipulation numbers:
5036          */
5037         x = dev->data_bytes_per_chunk;
5038         /* We always use dev->chunk_shift and dev->chunk_div */
5039         dev->chunk_shift = calc_shifts(x);
5040         x >>= dev->chunk_shift;
5041         dev->chunk_div = x;
5042         /* We only use chunk mask if chunk_div is 1 */
5043         dev->chunk_mask = (1<<dev->chunk_shift) - 1;
5044
5045         /*
5046          * Calculate chunk_grp_bits.
5047          * We need to find the next power of 2 > than internal_end_block
5048          */
5049
5050         x = dev->param.chunks_per_block * (dev->internal_end_block + 1);
5051
5052         bits = calc_shifts_ceiling(x);
5053
5054         /* Set up tnode width if wide tnodes are enabled. */
5055         if (!dev->param.wide_tnodes_disabled) {
5056                 /* bits must be even so that we end up with 32-bit words */
5057                 if (bits & 1)
5058                         bits++;
5059                 if (bits < 16)
5060                         dev->tnode_width = 16;
5061                 else
5062                         dev->tnode_width = bits;
5063         } else
5064                 dev->tnode_width = 16;
5065
5066         dev->tnode_mask = (1<<dev->tnode_width)-1;
5067
5068         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
5069          * so if the bitwidth of the
5070          * chunk range we're using is greater than 16 we need
5071          * to figure out chunk shift and chunk_grp_size
5072          */
5073
5074         if (bits <= dev->tnode_width)
5075                 dev->chunk_grp_bits = 0;
5076         else
5077                 dev->chunk_grp_bits = bits - dev->tnode_width;
5078
5079         dev->tnode_size = (dev->tnode_width * YAFFS_NTNODES_LEVEL0)/8;
5080         if(dev->tnode_size < sizeof(struct yaffs_tnode))
5081                 dev->tnode_size = sizeof(struct yaffs_tnode);
5082
5083         dev->chunk_grp_size = 1 << dev->chunk_grp_bits;
5084
5085         if (dev->param.chunks_per_block < dev->chunk_grp_size) {
5086                 /* We have a problem because the soft delete won't work if
5087                  * the chunk group size > chunks per block.
5088                  * This can be remedied by using larger "virtual blocks".
5089                  */
5090                 T(YAFFS_TRACE_ALWAYS,
5091                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5092
5093                 return YAFFS_FAIL;
5094         }
5095
5096         /* OK, we've finished verifying the device, lets continue with initialisation */
5097
5098         /* More device initialisation */
5099         dev->all_gcs = 0;
5100         dev->passive_gc_count = 0;
5101         dev->oldest_dirty_gc_count = 0;
5102         dev->bg_gcs = 0;
5103         dev->gc_block_finder = 0;
5104         dev->buffered_block = -1;
5105         dev->doing_buffered_block_rewrite = 0;
5106         dev->n_deleted_files = 0;
5107         dev->n_bg_deletions = 0;
5108         dev->n_unlinked_files = 0;
5109         dev->n_ecc_fixed = 0;
5110         dev->n_ecc_unfixed = 0;
5111         dev->n_tags_ecc_fixed = 0;
5112         dev->n_tags_ecc_unfixed = 0;
5113         dev->n_erase_failures = 0;
5114         dev->n_erased_blocks = 0;
5115         dev->gc_disable= 0;
5116         dev->has_pending_prioritised_gc = 1; /* Assume the worst for now, will get fixed on first GC */
5117         INIT_LIST_HEAD(&dev->dirty_dirs);
5118         dev->oldest_dirty_seq = 0;
5119         dev->oldest_dirty_block = 0;
5120
5121         /* Initialise temporary buffers and caches. */
5122         if (!yaffs_init_tmp_buffers(dev))
5123                 init_failed = 1;
5124
5125         dev->cache = NULL;
5126         dev->gc_cleanup_list = NULL;
5127
5128
5129         if (!init_failed &&
5130             dev->param.n_caches > 0) {
5131                 int i;
5132                 void *buf;
5133                 int cache_bytes = dev->param.n_caches * sizeof(struct yaffs_cache);
5134
5135                 if (dev->param.n_caches > YAFFS_MAX_SHORT_OP_CACHES)
5136                         dev->param.n_caches = YAFFS_MAX_SHORT_OP_CACHES;
5137
5138                 dev->cache =  YMALLOC(cache_bytes);
5139
5140                 buf = (u8 *) dev->cache;
5141
5142                 if (dev->cache)
5143                         memset(dev->cache, 0, cache_bytes);
5144
5145                 for (i = 0; i < dev->param.n_caches && buf; i++) {
5146                         dev->cache[i].object = NULL;
5147                         dev->cache[i].last_use = 0;
5148                         dev->cache[i].dirty = 0;
5149                         dev->cache[i].data = buf = YMALLOC_DMA(dev->param.total_bytes_per_chunk);
5150                 }
5151                 if (!buf)
5152                         init_failed = 1;
5153
5154                 dev->cache_last_use = 0;
5155         }
5156
5157         dev->cache_hits = 0;
5158
5159         if (!init_failed) {
5160                 dev->gc_cleanup_list = YMALLOC(dev->param.chunks_per_block * sizeof(u32));
5161                 if (!dev->gc_cleanup_list)
5162                         init_failed = 1;
5163         }
5164
5165         if (dev->param.is_yaffs2)
5166                 dev->param.use_header_file_size = 1;
5167
5168         if (!init_failed && !yaffs_init_blocks(dev))
5169                 init_failed = 1;
5170
5171         yaffs_init_tnodes_and_objs(dev);
5172
5173         if (!init_failed && !yaffs_create_initial_dir(dev))
5174                 init_failed = 1;
5175
5176
5177         if (!init_failed) {
5178                 /* Now scan the flash. */
5179                 if (dev->param.is_yaffs2) {
5180                         if (yaffs2_checkpt_restore(dev)) {
5181                                 yaffs_check_obj_details_loaded(dev->root_dir);
5182                                 T(YAFFS_TRACE_ALWAYS,
5183                                   (TSTR("yaffs: restored from checkpoint" TENDSTR)));
5184                         } else {
5185
5186                                 /* Clean up the mess caused by an aborted checkpoint load
5187                                  * and scan backwards.
5188                                  */
5189                                 yaffs_deinit_blocks(dev);
5190
5191                                 yaffs_deinit_tnodes_and_objs(dev);
5192
5193                                 dev->n_erased_blocks = 0;
5194                                 dev->n_free_chunks = 0;
5195                                 dev->alloc_block = -1;
5196                                 dev->alloc_page = -1;
5197                                 dev->n_deleted_files = 0;
5198                                 dev->n_unlinked_files = 0;
5199                                 dev->n_bg_deletions = 0;
5200
5201                                 if (!init_failed && !yaffs_init_blocks(dev))
5202                                         init_failed = 1;
5203
5204                                 yaffs_init_tnodes_and_objs(dev);
5205
5206                                 if (!init_failed && !yaffs_create_initial_dir(dev))
5207                                         init_failed = 1;
5208
5209                                 if (!init_failed && !yaffs2_scan_backwards(dev))
5210                                         init_failed = 1;
5211                         }
5212                 } else if (!yaffs1_scan(dev))
5213                                 init_failed = 1;
5214
5215                 yaffs_strip_deleted_objs(dev);
5216                 yaffs_fix_hanging_objs(dev);
5217                 if(dev->param.empty_lost_n_found)
5218                         yaffs_empty_l_n_f(dev);
5219         }
5220
5221         if (init_failed) {
5222                 /* Clean up the mess */
5223                 T(YAFFS_TRACE_TRACING,
5224                   (TSTR("yaffs: yaffs_guts_initialise() aborted.\n" TENDSTR)));
5225
5226                 yaffs_deinitialise(dev);
5227                 return YAFFS_FAIL;
5228         }
5229
5230         /* Zero out stats */
5231         dev->n_page_reads = 0;
5232         dev->n_page_writes = 0;
5233         dev->n_erasures = 0;
5234         dev->n_gc_copies = 0;
5235         dev->n_retired_writes = 0;
5236
5237         dev->n_retired_blocks = 0;
5238
5239         yaffs_verify_free_chunks(dev);
5240         yaffs_verify_blocks(dev);
5241
5242         /* Clean up any aborted checkpoint data */
5243         if(!dev->is_checkpointed && dev->blocks_in_checkpt > 0)
5244                 yaffs2_checkpt_invalidate(dev);
5245
5246         T(YAFFS_TRACE_TRACING,
5247           (TSTR("yaffs: yaffs_guts_initialise() done.\n" TENDSTR)));
5248         return YAFFS_OK;
5249
5250 }
5251
5252 void yaffs_deinitialise(struct yaffs_dev *dev)
5253 {
5254         if (dev->is_mounted) {
5255                 int i;
5256
5257                 yaffs_deinit_blocks(dev);
5258                 yaffs_deinit_tnodes_and_objs(dev);
5259                 if (dev->param.n_caches > 0 &&
5260                     dev->cache) {
5261
5262                         for (i = 0; i < dev->param.n_caches; i++) {
5263                                 if (dev->cache[i].data)
5264                                         YFREE(dev->cache[i].data);
5265                                 dev->cache[i].data = NULL;
5266                         }
5267
5268                         YFREE(dev->cache);
5269                         dev->cache = NULL;
5270                 }
5271
5272                 YFREE(dev->gc_cleanup_list);
5273
5274                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
5275                         YFREE(dev->temp_buffer[i].buffer);
5276
5277                 dev->is_mounted = 0;
5278
5279                 if (dev->param.deinitialise_flash_fn)
5280                         dev->param.deinitialise_flash_fn(dev);
5281         }
5282 }
5283
5284 int yaffs_count_free_chunks(struct yaffs_dev *dev)
5285 {
5286         int n_free=0;
5287         int b;
5288
5289         struct yaffs_block_info *blk;
5290
5291         blk = dev->block_info;
5292         for (b = dev->internal_start_block; b <= dev->internal_end_block; b++) {
5293                 switch (blk->block_state) {
5294                 case YAFFS_BLOCK_STATE_EMPTY:
5295                 case YAFFS_BLOCK_STATE_ALLOCATING:
5296                 case YAFFS_BLOCK_STATE_COLLECTING:
5297                 case YAFFS_BLOCK_STATE_FULL:
5298                         n_free +=
5299                             (dev->param.chunks_per_block - blk->pages_in_use +
5300                              blk->soft_del_pages);
5301                         break;
5302                 default:
5303                         break;
5304                 }
5305                 blk++;
5306         }
5307
5308         return n_free;
5309 }
5310
5311 int yaffs_get_n_free_chunks(struct yaffs_dev *dev)
5312 {
5313         /* This is what we report to the outside world */
5314
5315         int n_free;
5316         int n_dirty_caches;
5317         int blocks_for_checkpt;
5318         int i;
5319
5320         n_free = dev->n_free_chunks;
5321         n_free += dev->n_deleted_files;
5322
5323         /* Now count the number of dirty chunks in the cache and subtract those */
5324
5325         for (n_dirty_caches = 0, i = 0; i < dev->param.n_caches; i++) {
5326                 if (dev->cache[i].dirty)
5327                         n_dirty_caches++;
5328         }
5329
5330         n_free -= n_dirty_caches;
5331
5332         n_free -= ((dev->param.n_reserved_blocks + 1) * dev->param.chunks_per_block);
5333
5334         /* Now we figure out how much to reserve for the checkpoint and report that... */
5335         blocks_for_checkpt = yaffs_calc_checkpt_blocks_required(dev);
5336
5337         n_free -= (blocks_for_checkpt * dev->param.chunks_per_block);
5338
5339         if (n_free < 0)
5340                 n_free = 0;
5341
5342         return n_free;
5343
5344 }