c334b17d0872a877f52cd9c0e4234ad118df7d09
[openwrt.git] / target / linux / generic / patches-3.3 / 501-yaffs_cvs_2009_04_24.patch
1 --- a/fs/yaffs2/devextras.h
2 +++ b/fs/yaffs2/devextras.h
3 @@ -14,194 +14,135 @@
4   */
5  
6  /*
7 - * This file is just holds extra declarations used during development.
8 - * Most of these are from kernel includes placed here so we can use them in
9 - * applications.
10 + * This file is just holds extra declarations of macros that would normally
11 + * be providesd in the Linux kernel. These macros have been written from
12 + * scratch but are functionally equivalent to the Linux ones.
13   *
14   */
15  
16  #ifndef __EXTRAS_H__
17  #define __EXTRAS_H__
18  
19 -#if defined WIN32
20 -#define __inline__ __inline
21 -#define new newHack
22 -#endif
23 -
24 -#if !(defined __KERNEL__) || (defined WIN32)
25  
26 -/* User space defines */
27 +#if !(defined __KERNEL__)
28  
29 +/* Definition of types */
30  typedef unsigned char __u8;
31  typedef unsigned short __u16;
32  typedef unsigned __u32;
33  
34 +#endif
35 +
36  /*
37 - * Simple doubly linked list implementation.
38 - *
39 - * Some of the internal functions ("__xxx") are useful when
40 - * manipulating whole lists rather than single entries, as
41 - * sometimes we already know the next/prev entries and we can
42 - * generate better code by using them directly rather than
43 - * using the generic single-entry routines.
44 + * This is a simple doubly linked list implementation that matches the
45 + * way the Linux kernel doubly linked list implementation works.
46   */
47  
48 -#define prefetch(x) 1
49 -
50 -struct list_head {
51 -       struct list_head *next, *prev;
52 +struct ylist_head {
53 +       struct ylist_head *next; /* next in chain */
54 +       struct ylist_head *prev; /* previous in chain */
55  };
56  
57 -#define LIST_HEAD_INIT(name) { &(name), &(name) }
58  
59 -#define LIST_HEAD(name) \
60 -       struct list_head name = LIST_HEAD_INIT(name)
61 +/* Initialise a static list */
62 +#define YLIST_HEAD(name) \
63 +struct ylist_head name = { &(name), &(name)}
64 +
65  
66 -#define INIT_LIST_HEAD(ptr) do { \
67 -       (ptr)->next = (ptr); (ptr)->prev = (ptr); \
68 +
69 +/* Initialise a list head to an empty list */
70 +#define YINIT_LIST_HEAD(p) \
71 +do { \
72 +       (p)->next = (p);\
73 +       (p)->prev = (p); \
74  } while (0)
75  
76 -/*
77 - * Insert a new entry between two known consecutive entries.
78 - *
79 - * This is only for internal list manipulation where we know
80 - * the prev/next entries already!
81 - */
82 -static __inline__ void __list_add(struct list_head *new,
83 -                                 struct list_head *prev,
84 -                                 struct list_head *next)
85 -{
86 -       next->prev = new;
87 -       new->next = next;
88 -       new->prev = prev;
89 -       prev->next = new;
90 -}
91  
92 -/**
93 - * list_add - add a new entry
94 - * @new: new entry to be added
95 - * @head: list head to add it after
96 - *
97 - * Insert a new entry after the specified head.
98 - * This is good for implementing stacks.
99 - */
100 -static __inline__ void list_add(struct list_head *new, struct list_head *head)
101 +/* Add an element to a list */
102 +static __inline__ void ylist_add(struct ylist_head *newEntry,
103 +                               struct ylist_head *list)
104  {
105 -       __list_add(new, head, head->next);
106 -}
107 +       struct ylist_head *listNext = list->next;
108 +
109 +       list->next = newEntry;
110 +       newEntry->prev = list;
111 +       newEntry->next = listNext;
112 +       listNext->prev = newEntry;
113  
114 -/**
115 - * list_add_tail - add a new entry
116 - * @new: new entry to be added
117 - * @head: list head to add it before
118 - *
119 - * Insert a new entry before the specified head.
120 - * This is useful for implementing queues.
121 - */
122 -static __inline__ void list_add_tail(struct list_head *new,
123 -                                    struct list_head *head)
124 -{
125 -       __list_add(new, head->prev, head);
126  }
127  
128 -/*
129 - * Delete a list entry by making the prev/next entries
130 - * point to each other.
131 - *
132 - * This is only for internal list manipulation where we know
133 - * the prev/next entries already!
134 - */
135 -static __inline__ void __list_del(struct list_head *prev,
136 -                                 struct list_head *next)
137 +static __inline__ void ylist_add_tail(struct ylist_head *newEntry,
138 +                                struct ylist_head *list)
139  {
140 -       next->prev = prev;
141 -       prev->next = next;
142 +       struct ylist_head *listPrev = list->prev;
143 +
144 +       list->prev = newEntry;
145 +       newEntry->next = list;
146 +       newEntry->prev = listPrev;
147 +       listPrev->next = newEntry;
148 +
149  }
150  
151 -/**
152 - * list_del - deletes entry from list.
153 - * @entry: the element to delete from the list.
154 - * Note: list_empty on entry does not return true after this, the entry is
155 - * in an undefined state.
156 - */
157 -static __inline__ void list_del(struct list_head *entry)
158 +
159 +/* Take an element out of its current list, with or without
160 + * reinitialising the links.of the entry*/
161 +static __inline__ void ylist_del(struct ylist_head *entry)
162  {
163 -       __list_del(entry->prev, entry->next);
164 +       struct ylist_head *listNext = entry->next;
165 +       struct ylist_head *listPrev = entry->prev;
166 +
167 +       listNext->prev = listPrev;
168 +       listPrev->next = listNext;
169 +
170  }
171  
172 -/**
173 - * list_del_init - deletes entry from list and reinitialize it.
174 - * @entry: the element to delete from the list.
175 - */
176 -static __inline__ void list_del_init(struct list_head *entry)
177 +static __inline__ void ylist_del_init(struct ylist_head *entry)
178  {
179 -       __list_del(entry->prev, entry->next);
180 -       INIT_LIST_HEAD(entry);
181 +       ylist_del(entry);
182 +       entry->next = entry->prev = entry;
183  }
184  
185 -/**
186 - * list_empty - tests whether a list is empty
187 - * @head: the list to test.
188 - */
189 -static __inline__ int list_empty(struct list_head *head)
190 +
191 +/* Test if the list is empty */
192 +static __inline__ int ylist_empty(struct ylist_head *entry)
193  {
194 -       return head->next == head;
195 +       return (entry->next == entry);
196  }
197  
198 -/**
199 - * list_splice - join two lists
200 - * @list: the new list to add.
201 - * @head: the place to add it in the first list.
202 +
203 +/* ylist_entry takes a pointer to a list entry and offsets it to that
204 + * we can find a pointer to the object it is embedded in.
205   */
206 -static __inline__ void list_splice(struct list_head *list,
207 -                                  struct list_head *head)
208 -{
209 -       struct list_head *first = list->next;
210  
211 -       if (first != list) {
212 -               struct list_head *last = list->prev;
213 -               struct list_head *at = head->next;
214 -
215 -               first->prev = head;
216 -               head->next = first;
217 -
218 -               last->next = at;
219 -               at->prev = last;
220 -       }
221 -}
222  
223 -/**
224 - * list_entry - get the struct for this entry
225 - * @ptr:       the &struct list_head pointer.
226 - * @type:      the type of the struct this is embedded in.
227 - * @member:    the name of the list_struct within the struct.
228 - */
229 -#define list_entry(ptr, type, member) \
230 -       ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
231 -
232 -/**
233 - * list_for_each       -       iterate over a list
234 - * @pos:       the &struct list_head to use as a loop counter.
235 - * @head:      the head for your list.
236 - */
237 -#define list_for_each(pos, head) \
238 -       for (pos = (head)->next, prefetch(pos->next); pos != (head); \
239 -               pos = pos->next, prefetch(pos->next))
240 -
241 -/**
242 - * list_for_each_safe  -       iterate over a list safe against removal
243 - *                              of list entry
244 - * @pos:       the &struct list_head to use as a loop counter.
245 - * @n:         another &struct list_head to use as temporary storage
246 - * @head:      the head for your list.
247 - */
248 -#define list_for_each_safe(pos, n, head) \
249 -       for (pos = (head)->next, n = pos->next; pos != (head); \
250 -               pos = n, n = pos->next)
251 +#define ylist_entry(entry, type, member) \
252 +       ((type *)((char *)(entry)-(unsigned long)(&((type *)NULL)->member)))
253  
254 -/*
255 - * File types
256 +
257 +/* ylist_for_each and list_for_each_safe  iterate over lists.
258 + * ylist_for_each_safe uses temporary storage to make the list delete safe
259   */
260 +
261 +#define ylist_for_each(itervar, list) \
262 +       for (itervar = (list)->next; itervar != (list); itervar = itervar->next)
263 +
264 +#define ylist_for_each_safe(itervar, saveVar, list) \
265 +       for (itervar = (list)->next, saveVar = (list)->next->next; \
266 +               itervar != (list); itervar = saveVar, saveVar = saveVar->next)
267 +
268 +
269 +#if !(defined __KERNEL__)
270 +
271 +
272 +#ifndef WIN32
273 +#include <sys/stat.h>
274 +#endif
275 +
276 +
277 +#ifdef CONFIG_YAFFS_PROVIDE_DEFS
278 +/* File types */
279 +
280 +
281  #define DT_UNKNOWN     0
282  #define DT_FIFO                1
283  #define DT_CHR         2
284 @@ -212,6 +153,7 @@ static __inline__ void list_splice(struc
285  #define DT_SOCK                12
286  #define DT_WHT         14
287  
288 +
289  #ifndef WIN32
290  #include <sys/stat.h>
291  #endif
292 @@ -227,10 +169,6 @@ static __inline__ void list_splice(struc
293  #define ATTR_ATIME     16
294  #define ATTR_MTIME     32
295  #define ATTR_CTIME     64
296 -#define ATTR_ATIME_SET 128
297 -#define ATTR_MTIME_SET 256
298 -#define ATTR_FORCE     512     /* Not a change, but a change it */
299 -#define ATTR_ATTR_FLAG 1024
300  
301  struct iattr {
302         unsigned int ia_valid;
303 @@ -244,21 +182,15 @@ struct iattr {
304         unsigned int ia_attr_flags;
305  };
306  
307 -#define KERN_DEBUG
308 +#endif
309  
310  #else
311  
312 -#ifndef WIN32
313  #include <linux/types.h>
314 -#include <linux/list.h>
315  #include <linux/fs.h>
316  #include <linux/stat.h>
317 -#endif
318  
319  #endif
320  
321 -#if defined WIN32
322 -#undef new
323 -#endif
324  
325  #endif
326 --- a/fs/yaffs2/Kconfig
327 +++ b/fs/yaffs2/Kconfig
328 @@ -5,7 +5,7 @@
329  config YAFFS_FS
330         tristate "YAFFS2 file system support"
331         default n
332 -       depends on MTD
333 +       depends on MTD_BLOCK
334         select YAFFS_YAFFS1
335         select YAFFS_YAFFS2
336         help
337 @@ -43,7 +43,8 @@ config YAFFS_9BYTE_TAGS
338           format that you need to continue to support.  New data written
339           also uses the older-style format.  Note: Use of this option
340           generally requires that MTD's oob layout be adjusted to use the
341 -         older-style format.  See notes on tags formats and MTD versions.
342 +         older-style format.  See notes on tags formats and MTD versions
343 +         in yaffs_mtdif1.c.
344  
345           If unsure, say N.
346  
347 @@ -109,26 +110,6 @@ config YAFFS_DISABLE_LAZY_LOAD
348  
349           If unsure, say N.
350  
351 -config YAFFS_CHECKPOINT_RESERVED_BLOCKS
352 -       int "Reserved blocks for checkpointing"
353 -       depends on YAFFS_YAFFS2
354 -       default 10
355 -       help
356 -          Give the number of Blocks to reserve for checkpointing.
357 -         Checkpointing saves the state at unmount so that mounting is
358 -         much faster as a scan of all the flash to regenerate this state
359 -         is not needed.  These Blocks are reserved per partition, so if
360 -         you have very small partitions the default (10) may be a mess
361 -         for you.  You can set this value to 0, but that does not mean
362 -         checkpointing is disabled at all. There only won't be any
363 -         specially reserved blocks for checkpointing, so if there is
364 -         enough free space on the filesystem, it will be used for
365 -         checkpointing.
366 -
367 -         If unsure, leave at default (10), but don't wonder if there are
368 -         always 2MB used on your large page device partition (10 x 2k
369 -         pagesize). When using small partitions or when being very small
370 -         on space, you probably want to set this to zero.
371  
372  config YAFFS_DISABLE_WIDE_TNODES
373         bool "Turn off wide tnodes"
374 --- a/fs/yaffs2/Makefile
375 +++ b/fs/yaffs2/Makefile
376 @@ -5,7 +5,6 @@
377  obj-$(CONFIG_YAFFS_FS) += yaffs.o
378  
379  yaffs-y := yaffs_ecc.o yaffs_fs.o yaffs_guts.o yaffs_checkptrw.o
380 -yaffs-y += yaffs_packedtags2.o yaffs_nand.o yaffs_qsort.o
381 +yaffs-y += yaffs_packedtags1.o yaffs_packedtags2.o yaffs_nand.o yaffs_qsort.o
382  yaffs-y += yaffs_tagscompat.o yaffs_tagsvalidity.o
383 -yaffs-y += yaffs_mtdif1.o yaffs_packedtags1.o
384 -yaffs-y += yaffs_mtdif.o yaffs_mtdif2.o
385 +yaffs-y += yaffs_mtdif.o yaffs_mtdif1.o yaffs_mtdif2.o
386 --- a/fs/yaffs2/moduleconfig.h
387 +++ b/fs/yaffs2/moduleconfig.h
388 @@ -27,12 +27,12 @@
389  
390  /* Default: Not selected */
391  /* Meaning: Yaffs does its own ECC, rather than using MTD ECC */
392 -//#define CONFIG_YAFFS_DOES_ECC
393 +/* #define CONFIG_YAFFS_DOES_ECC */
394  
395  /* Default: Not selected */
396  /* Meaning: ECC byte order is 'wrong'.  Only meaningful if */
397  /*          CONFIG_YAFFS_DOES_ECC is set */
398 -//#define CONFIG_YAFFS_ECC_WRONG_ORDER
399 +/* #define CONFIG_YAFFS_ECC_WRONG_ORDER */
400  
401  /* Default: Selected */
402  /* Meaning: Disables testing whether chunks are erased before writing to them*/
403 @@ -54,11 +54,11 @@ that you need to continue to support.  N
404  older-style format.
405  Note: Use of this option generally requires that MTD's oob layout be
406  adjusted to use the older-style format.  See notes on tags formats and
407 -MTD versions.
408 +MTD versions in yaffs_mtdif1.c.
409  */
410  /* Default: Not selected */
411  /* Meaning: Use older-style on-NAND data format with pageStatus byte */
412 -#define CONFIG_YAFFS_9BYTE_TAGS
413 +/* #define CONFIG_YAFFS_9BYTE_TAGS */
414  
415  #endif /* YAFFS_OUT_OF_TREE */
416  
417 --- a/fs/yaffs2/yaffs_checkptrw.c
418 +++ b/fs/yaffs2/yaffs_checkptrw.c
419 @@ -12,48 +12,43 @@
420   */
421  
422  const char *yaffs_checkptrw_c_version =
423 -    "$Id: yaffs_checkptrw.c,v 1.14 2007-05-15 20:07:40 charles Exp $";
424 +       "$Id: yaffs_checkptrw.c,v 1.18 2009-03-06 17:20:49 wookey Exp $";
425  
426  
427  #include "yaffs_checkptrw.h"
428 -
429 +#include "yaffs_getblockinfo.h"
430  
431  static int yaffs_CheckpointSpaceOk(yaffs_Device *dev)
432  {
433 -
434         int blocksAvailable = dev->nErasedBlocks - dev->nReservedBlocks;
435  
436         T(YAFFS_TRACE_CHECKPOINT,
437                 (TSTR("checkpt blocks available = %d" TENDSTR),
438                 blocksAvailable));
439  
440 -
441         return (blocksAvailable <= 0) ? 0 : 1;
442  }
443  
444  
445  static int yaffs_CheckpointErase(yaffs_Device *dev)
446  {
447 -
448         int i;
449  
450 -
451 -       if(!dev->eraseBlockInNAND)
452 +       if (!dev->eraseBlockInNAND)
453                 return 0;
454 -       T(YAFFS_TRACE_CHECKPOINT,(TSTR("checking blocks %d to %d"TENDSTR),
455 -               dev->internalStartBlock,dev->internalEndBlock));
456 +       T(YAFFS_TRACE_CHECKPOINT, (TSTR("checking blocks %d to %d"TENDSTR),
457 +               dev->internalStartBlock, dev->internalEndBlock));
458  
459 -       for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
460 -               yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
461 -               if(bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT){
462 -                       T(YAFFS_TRACE_CHECKPOINT,(TSTR("erasing checkpt block %d"TENDSTR),i));
463 -                       if(dev->eraseBlockInNAND(dev,i- dev->blockOffset /* realign */)){
464 +       for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
465 +               yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
466 +               if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
467 +                       T(YAFFS_TRACE_CHECKPOINT, (TSTR("erasing checkpt block %d"TENDSTR), i));
468 +                       if (dev->eraseBlockInNAND(dev, i - dev->blockOffset /* realign */)) {
469                                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
470                                 dev->nErasedBlocks++;
471                                 dev->nFreeChunks += dev->nChunksPerBlock;
472 -                       }
473 -                       else {
474 -                               dev->markNANDBlockBad(dev,i);
475 +                       } else {
476 +                               dev->markNANDBlockBad(dev, i);
477                                 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
478                         }
479                 }
480 @@ -71,23 +66,23 @@ static void yaffs_CheckpointFindNextEras
481         int blocksAvailable = dev->nErasedBlocks - dev->nReservedBlocks;
482         T(YAFFS_TRACE_CHECKPOINT,
483                 (TSTR("allocating checkpt block: erased %d reserved %d avail %d next %d "TENDSTR),
484 -               dev->nErasedBlocks,dev->nReservedBlocks,blocksAvailable,dev->checkpointNextBlock));
485 +               dev->nErasedBlocks, dev->nReservedBlocks, blocksAvailable, dev->checkpointNextBlock));
486  
487 -       if(dev->checkpointNextBlock >= 0 &&
488 -          dev->checkpointNextBlock <= dev->internalEndBlock &&
489 -          blocksAvailable > 0){
490 -
491 -               for(i = dev->checkpointNextBlock; i <= dev->internalEndBlock; i++){
492 -                       yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
493 -                       if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY){
494 +       if (dev->checkpointNextBlock >= 0 &&
495 +                       dev->checkpointNextBlock <= dev->internalEndBlock &&
496 +                       blocksAvailable > 0) {
497 +
498 +               for (i = dev->checkpointNextBlock; i <= dev->internalEndBlock; i++) {
499 +                       yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
500 +                       if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
501                                 dev->checkpointNextBlock = i + 1;
502                                 dev->checkpointCurrentBlock = i;
503 -                               T(YAFFS_TRACE_CHECKPOINT,(TSTR("allocating checkpt block %d"TENDSTR),i));
504 +                               T(YAFFS_TRACE_CHECKPOINT, (TSTR("allocating checkpt block %d"TENDSTR), i));
505                                 return;
506                         }
507                 }
508         }
509 -       T(YAFFS_TRACE_CHECKPOINT,(TSTR("out of checkpt blocks"TENDSTR)));
510 +       T(YAFFS_TRACE_CHECKPOINT, (TSTR("out of checkpt blocks"TENDSTR)));
511  
512         dev->checkpointNextBlock = -1;
513         dev->checkpointCurrentBlock = -1;
514 @@ -98,30 +93,31 @@ static void yaffs_CheckpointFindNextChec
515         int  i;
516         yaffs_ExtendedTags tags;
517  
518 -       T(YAFFS_TRACE_CHECKPOINT,(TSTR("find next checkpt block: start:  blocks %d next %d" TENDSTR),
519 +       T(YAFFS_TRACE_CHECKPOINT, (TSTR("find next checkpt block: start:  blocks %d next %d" TENDSTR),
520                 dev->blocksInCheckpoint, dev->checkpointNextBlock));
521  
522 -       if(dev->blocksInCheckpoint < dev->checkpointMaxBlocks)
523 -               for(i = dev->checkpointNextBlock; i <= dev->internalEndBlock; i++){
524 +       if (dev->blocksInCheckpoint < dev->checkpointMaxBlocks)
525 +               for (i = dev->checkpointNextBlock; i <= dev->internalEndBlock; i++) {
526                         int chunk = i * dev->nChunksPerBlock;
527                         int realignedChunk = chunk - dev->chunkOffset;
528  
529 -                       dev->readChunkWithTagsFromNAND(dev,realignedChunk,NULL,&tags);
530 -                       T(YAFFS_TRACE_CHECKPOINT,(TSTR("find next checkpt block: search: block %d oid %d seq %d eccr %d" TENDSTR),
531 -                               i, tags.objectId,tags.sequenceNumber,tags.eccResult));
532 +                       dev->readChunkWithTagsFromNAND(dev, realignedChunk,
533 +                                       NULL, &tags);
534 +                       T(YAFFS_TRACE_CHECKPOINT, (TSTR("find next checkpt block: search: block %d oid %d seq %d eccr %d" TENDSTR),
535 +                               i, tags.objectId, tags.sequenceNumber, tags.eccResult));
536  
537 -                       if(tags.sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA){
538 +                       if (tags.sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA) {
539                                 /* Right kind of block */
540                                 dev->checkpointNextBlock = tags.objectId;
541                                 dev->checkpointCurrentBlock = i;
542                                 dev->checkpointBlockList[dev->blocksInCheckpoint] = i;
543                                 dev->blocksInCheckpoint++;
544 -                               T(YAFFS_TRACE_CHECKPOINT,(TSTR("found checkpt block %d"TENDSTR),i));
545 +                               T(YAFFS_TRACE_CHECKPOINT, (TSTR("found checkpt block %d"TENDSTR), i));
546                                 return;
547                         }
548                 }
549  
550 -       T(YAFFS_TRACE_CHECKPOINT,(TSTR("found no more checkpt blocks"TENDSTR)));
551 +       T(YAFFS_TRACE_CHECKPOINT, (TSTR("found no more checkpt blocks"TENDSTR)));
552  
553         dev->checkpointNextBlock = -1;
554         dev->checkpointCurrentBlock = -1;
555 @@ -133,17 +129,17 @@ int yaffs_CheckpointOpen(yaffs_Device *d
556  
557         /* Got the functions we need? */
558         if (!dev->writeChunkWithTagsToNAND ||
559 -           !dev->readChunkWithTagsFromNAND ||
560 -           !dev->eraseBlockInNAND ||
561 -           !dev->markNANDBlockBad)
562 +                       !dev->readChunkWithTagsFromNAND ||
563 +                       !dev->eraseBlockInNAND ||
564 +                       !dev->markNANDBlockBad)
565                 return 0;
566  
567 -       if(forWriting && !yaffs_CheckpointSpaceOk(dev))
568 +       if (forWriting && !yaffs_CheckpointSpaceOk(dev))
569                 return 0;
570  
571 -       if(!dev->checkpointBuffer)
572 -               dev->checkpointBuffer = YMALLOC_DMA(dev->nDataBytesPerChunk);
573 -       if(!dev->checkpointBuffer)
574 +       if (!dev->checkpointBuffer)
575 +               dev->checkpointBuffer = YMALLOC_DMA(dev->totalBytesPerChunk);
576 +       if (!dev->checkpointBuffer)
577                 return 0;
578  
579  
580 @@ -159,12 +155,10 @@ int yaffs_CheckpointOpen(yaffs_Device *d
581         dev->checkpointNextBlock = dev->internalStartBlock;
582  
583         /* Erase all the blocks in the checkpoint area */
584 -       if(forWriting){
585 -               memset(dev->checkpointBuffer,0,dev->nDataBytesPerChunk);
586 +       if (forWriting) {
587 +               memset(dev->checkpointBuffer, 0, dev->nDataBytesPerChunk);
588                 dev->checkpointByteOffset = 0;
589                 return yaffs_CheckpointErase(dev);
590 -
591 -
592         } else {
593                 int i;
594                 /* Set to a value that will kick off a read */
595 @@ -174,7 +168,7 @@ int yaffs_CheckpointOpen(yaffs_Device *d
596                 dev->blocksInCheckpoint = 0;
597                 dev->checkpointMaxBlocks = (dev->internalEndBlock - dev->internalStartBlock)/16 + 2;
598                 dev->checkpointBlockList = YMALLOC(sizeof(int) * dev->checkpointMaxBlocks);
599 -               for(i = 0; i < dev->checkpointMaxBlocks; i++)
600 +               for (i = 0; i < dev->checkpointMaxBlocks; i++)
601                         dev->checkpointBlockList[i] = -1;
602         }
603  
604 @@ -191,18 +185,17 @@ int yaffs_GetCheckpointSum(yaffs_Device
605  
606  static int yaffs_CheckpointFlushBuffer(yaffs_Device *dev)
607  {
608 -
609         int chunk;
610         int realignedChunk;
611  
612         yaffs_ExtendedTags tags;
613  
614 -       if(dev->checkpointCurrentBlock < 0){
615 +       if (dev->checkpointCurrentBlock < 0) {
616                 yaffs_CheckpointFindNextErasedBlock(dev);
617                 dev->checkpointCurrentChunk = 0;
618         }
619  
620 -       if(dev->checkpointCurrentBlock < 0)
621 +       if (dev->checkpointCurrentBlock < 0)
622                 return 0;
623  
624         tags.chunkDeleted = 0;
625 @@ -210,10 +203,10 @@ static int yaffs_CheckpointFlushBuffer(y
626         tags.chunkId = dev->checkpointPageSequence + 1;
627         tags.sequenceNumber =  YAFFS_SEQUENCE_CHECKPOINT_DATA;
628         tags.byteCount = dev->nDataBytesPerChunk;
629 -       if(dev->checkpointCurrentChunk == 0){
630 +       if (dev->checkpointCurrentChunk == 0) {
631                 /* First chunk we write for the block? Set block state to
632                    checkpoint */
633 -               yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,dev->checkpointCurrentBlock);
634 +               yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->checkpointCurrentBlock);
635                 bi->blockState = YAFFS_BLOCK_STATE_CHECKPOINT;
636                 dev->blocksInCheckpoint++;
637         }
638 @@ -221,28 +214,29 @@ static int yaffs_CheckpointFlushBuffer(y
639         chunk = dev->checkpointCurrentBlock * dev->nChunksPerBlock + dev->checkpointCurrentChunk;
640  
641  
642 -       T(YAFFS_TRACE_CHECKPOINT,(TSTR("checkpoint wite buffer nand %d(%d:%d) objid %d chId %d" TENDSTR),
643 -               chunk, dev->checkpointCurrentBlock, dev->checkpointCurrentChunk,tags.objectId,tags.chunkId));
644 +       T(YAFFS_TRACE_CHECKPOINT, (TSTR("checkpoint wite buffer nand %d(%d:%d) objid %d chId %d" TENDSTR),
645 +               chunk, dev->checkpointCurrentBlock, dev->checkpointCurrentChunk, tags.objectId, tags.chunkId));
646  
647         realignedChunk = chunk - dev->chunkOffset;
648  
649 -       dev->writeChunkWithTagsToNAND(dev,realignedChunk,dev->checkpointBuffer,&tags);
650 +       dev->writeChunkWithTagsToNAND(dev, realignedChunk,
651 +                       dev->checkpointBuffer, &tags);
652         dev->checkpointByteOffset = 0;
653         dev->checkpointPageSequence++;
654         dev->checkpointCurrentChunk++;
655 -       if(dev->checkpointCurrentChunk >= dev->nChunksPerBlock){
656 +       if (dev->checkpointCurrentChunk >= dev->nChunksPerBlock) {
657                 dev->checkpointCurrentChunk = 0;
658                 dev->checkpointCurrentBlock = -1;
659         }
660 -       memset(dev->checkpointBuffer,0,dev->nDataBytesPerChunk);
661 +       memset(dev->checkpointBuffer, 0, dev->nDataBytesPerChunk);
662  
663         return 1;
664  }
665  
666  
667 -int yaffs_CheckpointWrite(yaffs_Device *dev,const void *data, int nBytes)
668 +int yaffs_CheckpointWrite(yaffs_Device *dev, const void *data, int nBytes)
669  {
670 -       int i=0;
671 +       int i = 0;
672         int ok = 1;
673  
674  
675 @@ -250,17 +244,14 @@ int yaffs_CheckpointWrite(yaffs_Device *
676  
677  
678  
679 -       if(!dev->checkpointBuffer)
680 +       if (!dev->checkpointBuffer)
681                 return 0;
682  
683 -       if(!dev->checkpointOpenForWrite)
684 +       if (!dev->checkpointOpenForWrite)
685                 return -1;
686  
687 -       while(i < nBytes && ok) {
688 -
689 -
690 -
691 -               dev->checkpointBuffer[dev->checkpointByteOffset] = *dataBytes ;
692 +       while (i < nBytes && ok) {
693 +               dev->checkpointBuffer[dev->checkpointByteOffset] = *dataBytes;
694                 dev->checkpointSum += *dataBytes;
695                 dev->checkpointXor ^= *dataBytes;
696  
697 @@ -270,18 +261,17 @@ int yaffs_CheckpointWrite(yaffs_Device *
698                 dev->checkpointByteCount++;
699  
700  
701 -               if(dev->checkpointByteOffset < 0 ||
702 +               if (dev->checkpointByteOffset < 0 ||
703                    dev->checkpointByteOffset >= dev->nDataBytesPerChunk)
704                         ok = yaffs_CheckpointFlushBuffer(dev);
705 -
706         }
707  
708 -       return  i;
709 +       return i;
710  }
711  
712  int yaffs_CheckpointRead(yaffs_Device *dev, void *data, int nBytes)
713  {
714 -       int i=0;
715 +       int i = 0;
716         int ok = 1;
717         yaffs_ExtendedTags tags;
718  
719 @@ -291,52 +281,54 @@ int yaffs_CheckpointRead(yaffs_Device *d
720  
721         __u8 *dataBytes = (__u8 *)data;
722  
723 -       if(!dev->checkpointBuffer)
724 +       if (!dev->checkpointBuffer)
725                 return 0;
726  
727 -       if(dev->checkpointOpenForWrite)
728 +       if (dev->checkpointOpenForWrite)
729                 return -1;
730  
731 -       while(i < nBytes && ok) {
732 +       while (i < nBytes && ok) {
733  
734  
735 -               if(dev->checkpointByteOffset < 0 ||
736 -                  dev->checkpointByteOffset >= dev->nDataBytesPerChunk) {
737 +               if (dev->checkpointByteOffset < 0 ||
738 +                       dev->checkpointByteOffset >= dev->nDataBytesPerChunk) {
739  
740 -                       if(dev->checkpointCurrentBlock < 0){
741 +                       if (dev->checkpointCurrentBlock < 0) {
742                                 yaffs_CheckpointFindNextCheckpointBlock(dev);
743                                 dev->checkpointCurrentChunk = 0;
744                         }
745  
746 -                       if(dev->checkpointCurrentBlock < 0)
747 +                       if (dev->checkpointCurrentBlock < 0)
748                                 ok = 0;
749                         else {
750 -
751 -                               chunk = dev->checkpointCurrentBlock * dev->nChunksPerBlock +
752 -                                         dev->checkpointCurrentChunk;
753 +                               chunk = dev->checkpointCurrentBlock *
754 +                                       dev->nChunksPerBlock +
755 +                                       dev->checkpointCurrentChunk;
756  
757                                 realignedChunk = chunk - dev->chunkOffset;
758  
759 -                               /* read in the next chunk */
760 -                               /* printf("read checkpoint page %d\n",dev->checkpointPage); */
761 -                               dev->readChunkWithTagsFromNAND(dev, realignedChunk,
762 -                                                              dev->checkpointBuffer,
763 -                                                             &tags);
764 -
765 -                               if(tags.chunkId != (dev->checkpointPageSequence + 1) ||
766 -                                  tags.sequenceNumber != YAFFS_SEQUENCE_CHECKPOINT_DATA)
767 -                                  ok = 0;
768 +                               /* read in the next chunk */
769 +                               /* printf("read checkpoint page %d\n",dev->checkpointPage); */
770 +                               dev->readChunkWithTagsFromNAND(dev,
771 +                                               realignedChunk,
772 +                                               dev->checkpointBuffer,
773 +                                               &tags);
774 +
775 +                               if (tags.chunkId != (dev->checkpointPageSequence + 1) ||
776 +                                       tags.eccResult > YAFFS_ECC_RESULT_FIXED ||
777 +                                       tags.sequenceNumber != YAFFS_SEQUENCE_CHECKPOINT_DATA)
778 +                                       ok = 0;
779  
780                                 dev->checkpointByteOffset = 0;
781                                 dev->checkpointPageSequence++;
782                                 dev->checkpointCurrentChunk++;
783  
784 -                               if(dev->checkpointCurrentChunk >= dev->nChunksPerBlock)
785 +                               if (dev->checkpointCurrentChunk >= dev->nChunksPerBlock)
786                                         dev->checkpointCurrentBlock = -1;
787                         }
788                 }
789  
790 -               if(ok){
791 +               if (ok) {
792                         *dataBytes = dev->checkpointBuffer[dev->checkpointByteOffset];
793                         dev->checkpointSum += *dataBytes;
794                         dev->checkpointXor ^= *dataBytes;
795 @@ -353,17 +345,17 @@ int yaffs_CheckpointRead(yaffs_Device *d
796  int yaffs_CheckpointClose(yaffs_Device *dev)
797  {
798  
799 -       if(dev->checkpointOpenForWrite){
800 -               if(dev->checkpointByteOffset != 0)
801 +       if (dev->checkpointOpenForWrite) {
802 +               if (dev->checkpointByteOffset != 0)
803                         yaffs_CheckpointFlushBuffer(dev);
804         } else {
805                 int i;
806 -               for(i = 0; i < dev->blocksInCheckpoint && dev->checkpointBlockList[i] >= 0; i++){
807 -                       yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,dev->checkpointBlockList[i]);
808 -                       if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
809 +               for (i = 0; i < dev->blocksInCheckpoint && dev->checkpointBlockList[i] >= 0; i++) {
810 +                       yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->checkpointBlockList[i]);
811 +                       if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
812                                 bi->blockState = YAFFS_BLOCK_STATE_CHECKPOINT;
813                         else {
814 -                               // Todo this looks odd...
815 +                               /* Todo this looks odd... */
816                         }
817                 }
818                 YFREE(dev->checkpointBlockList);
819 @@ -374,27 +366,25 @@ int yaffs_CheckpointClose(yaffs_Device *
820         dev->nErasedBlocks -= dev->blocksInCheckpoint;
821  
822  
823 -       T(YAFFS_TRACE_CHECKPOINT,(TSTR("checkpoint byte count %d" TENDSTR),
824 +       T(YAFFS_TRACE_CHECKPOINT, (TSTR("checkpoint byte count %d" TENDSTR),
825                         dev->checkpointByteCount));
826  
827 -       if(dev->checkpointBuffer){
828 +       if (dev->checkpointBuffer) {
829                 /* free the buffer */
830                 YFREE(dev->checkpointBuffer);
831                 dev->checkpointBuffer = NULL;
832                 return 1;
833 -       }
834 -       else
835 +       } else
836                 return 0;
837 -
838  }
839  
840  int yaffs_CheckpointInvalidateStream(yaffs_Device *dev)
841  {
842         /* Erase the first checksum block */
843  
844 -       T(YAFFS_TRACE_CHECKPOINT,(TSTR("checkpoint invalidate"TENDSTR)));
845 +       T(YAFFS_TRACE_CHECKPOINT, (TSTR("checkpoint invalidate"TENDSTR)));
846  
847 -       if(!yaffs_CheckpointSpaceOk(dev))
848 +       if (!yaffs_CheckpointSpaceOk(dev))
849                 return 0;
850  
851         return yaffs_CheckpointErase(dev);
852 --- a/fs/yaffs2/yaffs_checkptrw.h
853 +++ b/fs/yaffs2/yaffs_checkptrw.h
854 @@ -20,9 +20,9 @@
855  
856  int yaffs_CheckpointOpen(yaffs_Device *dev, int forWriting);
857  
858 -int yaffs_CheckpointWrite(yaffs_Device *dev,const void *data, int nBytes);
859 +int yaffs_CheckpointWrite(yaffs_Device *dev, const void *data, int nBytes);
860  
861 -int yaffs_CheckpointRead(yaffs_Device *dev,void *data, int nBytes);
862 +int yaffs_CheckpointRead(yaffs_Device *dev, void *data, int nBytes);
863  
864  int yaffs_GetCheckpointSum(yaffs_Device *dev, __u32 *sum);
865  
866 --- a/fs/yaffs2/yaffs_ecc.c
867 +++ b/fs/yaffs2/yaffs_ecc.c
868 @@ -29,7 +29,7 @@
869   */
870  
871  const char *yaffs_ecc_c_version =
872 -    "$Id: yaffs_ecc.c,v 1.9 2007-02-14 01:09:06 wookey Exp $";
873 +       "$Id: yaffs_ecc.c,v 1.11 2009-03-06 17:20:50 wookey Exp $";
874  
875  #include "yportenv.h"
876  
877 @@ -109,12 +109,10 @@ void yaffs_ECCCalculate(const unsigned c
878                 b = column_parity_table[*data++];
879                 col_parity ^= b;
880  
881 -               if (b & 0x01)   // odd number of bits in the byte
882 -               {
883 +               if (b & 0x01) {         /* odd number of bits in the byte */
884                         line_parity ^= i;
885                         line_parity_prime ^= ~i;
886                 }
887 -
888         }
889  
890         ecc[2] = (~col_parity) | 0x03;
891 @@ -158,7 +156,7 @@ void yaffs_ECCCalculate(const unsigned c
892         ecc[0] = ~t;
893  
894  #ifdef CONFIG_YAFFS_ECC_WRONG_ORDER
895 -       // Swap the bytes into the wrong order
896 +       /* Swap the bytes into the wrong order */
897         t = ecc[0];
898         ecc[0] = ecc[1];
899         ecc[1] = t;
900 @@ -189,7 +187,7 @@ int yaffs_ECCCorrect(unsigned char *data
901                 unsigned bit;
902  
903  #ifdef CONFIG_YAFFS_ECC_WRONG_ORDER
904 -               // swap the bytes to correct for the wrong order
905 +               /* swap the bytes to correct for the wrong order */
906                 unsigned char t;
907  
908                 t = d0;
909 @@ -251,7 +249,7 @@ int yaffs_ECCCorrect(unsigned char *data
910   * ECCxxxOther does ECC calcs on arbitrary n bytes of data
911   */
912  void yaffs_ECCCalculateOther(const unsigned char *data, unsigned nBytes,
913 -                            yaffs_ECCOther * eccOther)
914 +                               yaffs_ECCOther *eccOther)
915  {
916         unsigned int i;
917  
918 @@ -278,8 +276,8 @@ void yaffs_ECCCalculateOther(const unsig
919  }
920  
921  int yaffs_ECCCorrectOther(unsigned char *data, unsigned nBytes,
922 -                         yaffs_ECCOther * read_ecc,
923 -                         const yaffs_ECCOther * test_ecc)
924 +                       yaffs_ECCOther *read_ecc,
925 +                       const yaffs_ECCOther *test_ecc)
926  {
927         unsigned char cDelta;   /* column parity delta */
928         unsigned lDelta;        /* line parity delta */
929 @@ -294,8 +292,7 @@ int yaffs_ECCCorrectOther(unsigned char
930                 return 0; /* no error */
931  
932         if (lDelta == ~lDeltaPrime &&
933 -           (((cDelta ^ (cDelta >> 1)) & 0x15) == 0x15))
934 -       {
935 +           (((cDelta ^ (cDelta >> 1)) & 0x15) == 0x15)) {
936                 /* Single bit (recoverable) error in data */
937  
938                 bit = 0;
939 @@ -307,7 +304,7 @@ int yaffs_ECCCorrectOther(unsigned char
940                 if (cDelta & 0x02)
941                         bit |= 0x01;
942  
943 -               if(lDelta >= nBytes)
944 +               if (lDelta >= nBytes)
945                         return -1;
946  
947                 data[lDelta] ^= (1 << bit);
948 @@ -316,7 +313,7 @@ int yaffs_ECCCorrectOther(unsigned char
949         }
950  
951         if ((yaffs_CountBits32(lDelta) + yaffs_CountBits32(lDeltaPrime) +
952 -            yaffs_CountBits(cDelta)) == 1) {
953 +                       yaffs_CountBits(cDelta)) == 1) {
954                 /* Reccoverable error in ecc */
955  
956                 *read_ecc = *test_ecc;
957 @@ -326,6 +323,4 @@ int yaffs_ECCCorrectOther(unsigned char
958         /* Unrecoverable error */
959  
960         return -1;
961 -
962  }
963 -
964 --- a/fs/yaffs2/yaffs_ecc.h
965 +++ b/fs/yaffs2/yaffs_ecc.h
966 @@ -13,15 +13,15 @@
967   * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL.
968   */
969  
970 - /*
971 -  * This code implements the ECC algorithm used in SmartMedia.
972 -  *
973 -  * The ECC comprises 22 bits of parity information and is stuffed into 3 bytes.
974 -  * The two unused bit are set to 1.
975 -  * The ECC can correct single bit errors in a 256-byte page of data. Thus, two such ECC
976 -  * blocks are used on a 512-byte NAND page.
977 -  *
978 -  */
979 +/*
980 + * This code implements the ECC algorithm used in SmartMedia.
981 + *
982 + * The ECC comprises 22 bits of parity information and is stuffed into 3 bytes.
983 + * The two unused bit are set to 1.
984 + * The ECC can correct single bit errors in a 256-byte page of data. Thus, two such ECC
985 + * blocks are used on a 512-byte NAND page.
986 + *
987 + */
988  
989  #ifndef __YAFFS_ECC_H__
990  #define __YAFFS_ECC_H__
991 @@ -34,11 +34,11 @@ typedef struct {
992  
993  void yaffs_ECCCalculate(const unsigned char *data, unsigned char *ecc);
994  int yaffs_ECCCorrect(unsigned char *data, unsigned char *read_ecc,
995 -                    const unsigned char *test_ecc);
996 +               const unsigned char *test_ecc);
997  
998  void yaffs_ECCCalculateOther(const unsigned char *data, unsigned nBytes,
999 -                            yaffs_ECCOther * ecc);
1000 +                       yaffs_ECCOther *ecc);
1001  int yaffs_ECCCorrectOther(unsigned char *data, unsigned nBytes,
1002 -                         yaffs_ECCOther * read_ecc,
1003 -                         const yaffs_ECCOther * test_ecc);
1004 +                       yaffs_ECCOther *read_ecc,
1005 +                       const yaffs_ECCOther *test_ecc);
1006  #endif
1007 --- a/fs/yaffs2/yaffs_fs.c
1008 +++ b/fs/yaffs2/yaffs_fs.c
1009 @@ -1,7 +1,7 @@
1010  /*
1011   * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
1012   *
1013 - * Copyright (C) 2002-2007 Aleph One Ltd.
1014 + * Copyright (C) 2002-2009 Aleph One Ltd.
1015   *   for Toby Churchill Ltd and Brightstar Engineering
1016   *
1017   * Created by Charles Manning <charles@aleph1.co.uk>
1018 @@ -32,18 +32,17 @@
1019   */
1020  
1021  const char *yaffs_fs_c_version =
1022 -    "$Id: yaffs_fs.c,v 1.63 2007-09-19 20:35:40 imcd Exp $";
1023 +    "$Id: yaffs_fs.c,v 1.79 2009-03-17 01:12:00 wookey Exp $";
1024  extern const char *yaffs_guts_c_version;
1025  
1026  #include <linux/version.h>
1027 -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19))
1028 +#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 19))
1029  #include <linux/config.h>
1030  #endif
1031  #include <linux/kernel.h>
1032  #include <linux/module.h>
1033  #include <linux/slab.h>
1034  #include <linux/init.h>
1035 -#include <linux/list.h>
1036  #include <linux/fs.h>
1037  #include <linux/proc_fs.h>
1038  #include <linux/smp_lock.h>
1039 @@ -53,10 +52,12 @@ extern const char *yaffs_guts_c_version;
1040  #include <linux/string.h>
1041  #include <linux/ctype.h>
1042  
1043 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1044 +#include "asm/div64.h"
1045 +
1046 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1047  
1048  #include <linux/statfs.h>      /* Added NCB 15-8-2003 */
1049 -#include <asm/statfs.h>
1050 +#include <linux/statfs.h>
1051  #define UnlockPage(p) unlock_page(p)
1052  #define Page_Uptodate(page)    test_bit(PG_uptodate, &(page)->flags)
1053  
1054 @@ -69,22 +70,45 @@ extern const char *yaffs_guts_c_version;
1055  #define        BDEVNAME_SIZE           0
1056  #define        yaffs_devname(sb, buf)  kdevname(sb->s_dev)
1057  
1058 -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
1059 +#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 5, 0))
1060  /* added NCB 26/5/2006 for 2.4.25-vrs2-tcl1 kernel */
1061  #define __user
1062  #endif
1063  
1064  #endif
1065  
1066 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
1067 +#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26))
1068 +#define YPROC_ROOT  (&proc_root)
1069 +#else
1070 +#define YPROC_ROOT  NULL
1071 +#endif
1072 +
1073 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
1074  #define WRITE_SIZE_STR "writesize"
1075 -#define WRITE_SIZE(mtd) (mtd)->writesize
1076 +#define WRITE_SIZE(mtd) ((mtd)->writesize)
1077  #else
1078  #define WRITE_SIZE_STR "oobblock"
1079 -#define WRITE_SIZE(mtd) (mtd)->oobblock
1080 +#define WRITE_SIZE(mtd) ((mtd)->oobblock)
1081  #endif
1082  
1083 -#include <asm/uaccess.h>
1084 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 27))
1085 +#define YAFFS_USE_WRITE_BEGIN_END 1
1086 +#else
1087 +#define YAFFS_USE_WRITE_BEGIN_END 0
1088 +#endif
1089 +
1090 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 28))
1091 +static uint32_t YCALCBLOCKS(uint64_t partition_size, uint32_t block_size)
1092 +{
1093 +       uint64_t result = partition_size;
1094 +       do_div(result, block_size);
1095 +       return (uint32_t)result;
1096 +}
1097 +#else
1098 +#define YCALCBLOCKS(s, b) ((s)/(b))
1099 +#endif
1100 +
1101 +#include <linux/uaccess.h>
1102  
1103  #include "yportenv.h"
1104  #include "yaffs_guts.h"
1105 @@ -96,28 +120,44 @@ extern const char *yaffs_guts_c_version;
1106  
1107  unsigned int yaffs_traceMask = YAFFS_TRACE_BAD_BLOCKS;
1108  unsigned int yaffs_wr_attempts = YAFFS_WR_ATTEMPTS;
1109 +unsigned int yaffs_auto_checkpoint = 1;
1110  
1111  /* Module Parameters */
1112 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1113 -module_param(yaffs_traceMask,uint,0644);
1114 -module_param(yaffs_wr_attempts,uint,0644);
1115 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1116 +module_param(yaffs_traceMask, uint, 0644);
1117 +module_param(yaffs_wr_attempts, uint, 0644);
1118 +module_param(yaffs_auto_checkpoint, uint, 0644);
1119 +#else
1120 +MODULE_PARM(yaffs_traceMask, "i");
1121 +MODULE_PARM(yaffs_wr_attempts, "i");
1122 +MODULE_PARM(yaffs_auto_checkpoint, "i");
1123 +#endif
1124 +
1125 +#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 25))
1126 +/* use iget and read_inode */
1127 +#define Y_IGET(sb, inum) iget((sb), (inum))
1128 +static void yaffs_read_inode(struct inode *inode);
1129 +
1130  #else
1131 -MODULE_PARM(yaffs_traceMask,"i");
1132 -MODULE_PARM(yaffs_wr_attempts,"i");
1133 +/* Call local equivalent */
1134 +#define YAFFS_USE_OWN_IGET
1135 +#define Y_IGET(sb, inum) yaffs_iget((sb), (inum))
1136 +
1137 +static struct inode *yaffs_iget(struct super_block *sb, unsigned long ino);
1138  #endif
1139  
1140  /*#define T(x) printk x */
1141  
1142 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,18))
1143 -#define yaffs_InodeToObjectLV(iptr) (iptr)->i_private
1144 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 18))
1145 +#define yaffs_InodeToObjectLV(iptr) ((iptr)->i_private)
1146  #else
1147 -#define yaffs_InodeToObjectLV(iptr) (iptr)->u.generic_ip
1148 +#define yaffs_InodeToObjectLV(iptr) ((iptr)->u.generic_ip)
1149  #endif
1150  
1151  #define yaffs_InodeToObject(iptr) ((yaffs_Object *)(yaffs_InodeToObjectLV(iptr)))
1152  #define yaffs_DentryToObject(dptr) yaffs_InodeToObject((dptr)->d_inode)
1153  
1154 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1155 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1156  #define yaffs_SuperToDevice(sb)        ((yaffs_Device *)sb->s_fs_info)
1157  #else
1158  #define yaffs_SuperToDevice(sb)        ((yaffs_Device *)sb->u.generic_sbp)
1159 @@ -126,47 +166,49 @@ MODULE_PARM(yaffs_wr_attempts,"i");
1160  static void yaffs_put_super(struct super_block *sb);
1161  
1162  static ssize_t yaffs_file_write(struct file *f, const char *buf, size_t n,
1163 -                               loff_t * pos);
1164 +                               loff_t *pos);
1165 +static ssize_t yaffs_hold_space(struct file *f);
1166 +static void yaffs_release_space(struct file *f);
1167  
1168 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
1169 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
1170  static int yaffs_file_flush(struct file *file, fl_owner_t id);
1171  #else
1172  static int yaffs_file_flush(struct file *file);
1173  #endif
1174  
1175  static int yaffs_sync_object(struct file *file, struct dentry *dentry,
1176 -                            int datasync);
1177 +                               int datasync);
1178  
1179  static int yaffs_readdir(struct file *f, void *dirent, filldir_t filldir);
1180  
1181 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1182 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1183  static int yaffs_create(struct inode *dir, struct dentry *dentry, int mode,
1184                         struct nameidata *n);
1185  static struct dentry *yaffs_lookup(struct inode *dir, struct dentry *dentry,
1186 -                                  struct nameidata *n);
1187 +                                       struct nameidata *n);
1188  #else
1189  static int yaffs_create(struct inode *dir, struct dentry *dentry, int mode);
1190  static struct dentry *yaffs_lookup(struct inode *dir, struct dentry *dentry);
1191  #endif
1192  static int yaffs_link(struct dentry *old_dentry, struct inode *dir,
1193 -                     struct dentry *dentry);
1194 +                       struct dentry *dentry);
1195  static int yaffs_unlink(struct inode *dir, struct dentry *dentry);
1196  static int yaffs_symlink(struct inode *dir, struct dentry *dentry,
1197 -                        const char *symname);
1198 +                       const char *symname);
1199  static int yaffs_mkdir(struct inode *dir, struct dentry *dentry, int mode);
1200  
1201 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1202 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1203  static int yaffs_mknod(struct inode *dir, struct dentry *dentry, int mode,
1204 -                      dev_t dev);
1205 +                       dev_t dev);
1206  #else
1207  static int yaffs_mknod(struct inode *dir, struct dentry *dentry, int mode,
1208 -                      int dev);
1209 +                       int dev);
1210  #endif
1211  static int yaffs_rename(struct inode *old_dir, struct dentry *old_dentry,
1212                         struct inode *new_dir, struct dentry *new_dentry);
1213  static int yaffs_setattr(struct dentry *dentry, struct iattr *attr);
1214  
1215 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
1216 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
1217  static int yaffs_sync_fs(struct super_block *sb, int wait);
1218  static void yaffs_write_super(struct super_block *sb);
1219  #else
1220 @@ -174,33 +216,47 @@ static int yaffs_sync_fs(struct super_bl
1221  static int yaffs_write_super(struct super_block *sb);
1222  #endif
1223  
1224 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
1225 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
1226  static int yaffs_statfs(struct dentry *dentry, struct kstatfs *buf);
1227 -#elif (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1228 +#elif (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1229  static int yaffs_statfs(struct super_block *sb, struct kstatfs *buf);
1230  #else
1231  static int yaffs_statfs(struct super_block *sb, struct statfs *buf);
1232  #endif
1233 -static void yaffs_read_inode(struct inode *inode);
1234  
1235 +#ifdef YAFFS_HAS_PUT_INODE
1236  static void yaffs_put_inode(struct inode *inode);
1237 +#endif
1238 +
1239  static void yaffs_delete_inode(struct inode *);
1240  static void yaffs_clear_inode(struct inode *);
1241  
1242  static int yaffs_readpage(struct file *file, struct page *page);
1243 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1244 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1245  static int yaffs_writepage(struct page *page, struct writeback_control *wbc);
1246  #else
1247  static int yaffs_writepage(struct page *page);
1248  #endif
1249 +
1250 +
1251 +#if (YAFFS_USE_WRITE_BEGIN_END != 0)
1252 +static int yaffs_write_begin(struct file *filp, struct address_space *mapping,
1253 +                               loff_t pos, unsigned len, unsigned flags,
1254 +                               struct page **pagep, void **fsdata);
1255 +static int yaffs_write_end(struct file *filp, struct address_space *mapping,
1256 +                               loff_t pos, unsigned len, unsigned copied,
1257 +                               struct page *pg, void *fsdadata);
1258 +#else
1259  static int yaffs_prepare_write(struct file *f, struct page *pg,
1260 -                              unsigned offset, unsigned to);
1261 +                               unsigned offset, unsigned to);
1262  static int yaffs_commit_write(struct file *f, struct page *pg, unsigned offset,
1263 -                             unsigned to);
1264 +                               unsigned to);
1265  
1266 -static int yaffs_readlink(struct dentry *dentry, char __user * buffer,
1267 -                         int buflen);
1268 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,13))
1269 +#endif
1270 +
1271 +static int yaffs_readlink(struct dentry *dentry, char __user *buffer,
1272 +                               int buflen);
1273 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 13))
1274  static void *yaffs_follow_link(struct dentry *dentry, struct nameidata *nd);
1275  #else
1276  static int yaffs_follow_link(struct dentry *dentry, struct nameidata *nd);
1277 @@ -209,12 +265,17 @@ static int yaffs_follow_link(struct dent
1278  static struct address_space_operations yaffs_file_address_operations = {
1279         .readpage = yaffs_readpage,
1280         .writepage = yaffs_writepage,
1281 +#if (YAFFS_USE_WRITE_BEGIN_END > 0)
1282 +       .write_begin = yaffs_write_begin,
1283 +       .write_end = yaffs_write_end,
1284 +#else
1285         .prepare_write = yaffs_prepare_write,
1286         .commit_write = yaffs_commit_write,
1287 +#endif
1288  };
1289  
1290 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,22))
1291 -static struct file_operations yaffs_file_operations = {
1292 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 22))
1293 +static const struct file_operations yaffs_file_operations = {
1294         .read = do_sync_read,
1295         .write = do_sync_write,
1296         .aio_read = generic_file_aio_read,
1297 @@ -224,11 +285,12 @@ static struct file_operations yaffs_file
1298         .fsync = yaffs_sync_object,
1299         .splice_read = generic_file_splice_read,
1300         .splice_write = generic_file_splice_write,
1301 +       .llseek = generic_file_llseek,
1302  };
1303  
1304 -#elif (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,18))
1305 +#elif (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 18))
1306  
1307 -static struct file_operations yaffs_file_operations = {
1308 +static const struct file_operations yaffs_file_operations = {
1309         .read = do_sync_read,
1310         .write = do_sync_write,
1311         .aio_read = generic_file_aio_read,
1312 @@ -241,29 +303,29 @@ static struct file_operations yaffs_file
1313  
1314  #else
1315  
1316 -static struct file_operations yaffs_file_operations = {
1317 +static const struct file_operations yaffs_file_operations = {
1318         .read = generic_file_read,
1319         .write = generic_file_write,
1320         .mmap = generic_file_mmap,
1321         .flush = yaffs_file_flush,
1322         .fsync = yaffs_sync_object,
1323 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1324 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1325         .sendfile = generic_file_sendfile,
1326  #endif
1327  };
1328  #endif
1329  
1330 -static struct inode_operations yaffs_file_inode_operations = {
1331 +static const struct inode_operations yaffs_file_inode_operations = {
1332         .setattr = yaffs_setattr,
1333  };
1334  
1335 -static struct inode_operations yaffs_symlink_inode_operations = {
1336 +static const struct inode_operations yaffs_symlink_inode_operations = {
1337         .readlink = yaffs_readlink,
1338         .follow_link = yaffs_follow_link,
1339         .setattr = yaffs_setattr,
1340  };
1341  
1342 -static struct inode_operations yaffs_dir_inode_operations = {
1343 +static const struct inode_operations yaffs_dir_inode_operations = {
1344         .create = yaffs_create,
1345         .lookup = yaffs_lookup,
1346         .link = yaffs_link,
1347 @@ -276,16 +338,21 @@ static struct inode_operations yaffs_dir
1348         .setattr = yaffs_setattr,
1349  };
1350  
1351 -static struct file_operations yaffs_dir_operations = {
1352 +static const struct file_operations yaffs_dir_operations = {
1353         .read = generic_read_dir,
1354         .readdir = yaffs_readdir,
1355         .fsync = yaffs_sync_object,
1356  };
1357  
1358 -static struct super_operations yaffs_super_ops = {
1359 +static const struct super_operations yaffs_super_ops = {
1360         .statfs = yaffs_statfs,
1361 +
1362 +#ifndef YAFFS_USE_OWN_IGET
1363         .read_inode = yaffs_read_inode,
1364 +#endif
1365 +#ifdef YAFFS_HAS_PUT_INODE
1366         .put_inode = yaffs_put_inode,
1367 +#endif
1368         .put_super = yaffs_put_super,
1369         .delete_inode = yaffs_delete_inode,
1370         .clear_inode = yaffs_clear_inode,
1371 @@ -293,22 +360,21 @@ static struct super_operations yaffs_sup
1372         .write_super = yaffs_write_super,
1373  };
1374  
1375 -static void yaffs_GrossLock(yaffs_Device * dev)
1376 +static void yaffs_GrossLock(yaffs_Device *dev)
1377  {
1378 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs locking\n"));
1379 -
1380 +       T(YAFFS_TRACE_OS, ("yaffs locking %p\n", current));
1381         down(&dev->grossLock);
1382 +       T(YAFFS_TRACE_OS, ("yaffs locked %p\n", current));
1383  }
1384  
1385 -static void yaffs_GrossUnlock(yaffs_Device * dev)
1386 +static void yaffs_GrossUnlock(yaffs_Device *dev)
1387  {
1388 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs unlocking\n"));
1389 +       T(YAFFS_TRACE_OS, ("yaffs unlocking %p\n", current));
1390         up(&dev->grossLock);
1391 -
1392  }
1393  
1394 -static int yaffs_readlink(struct dentry *dentry, char __user * buffer,
1395 -                         int buflen)
1396 +static int yaffs_readlink(struct dentry *dentry, char __user *buffer,
1397 +                       int buflen)
1398  {
1399         unsigned char *alias;
1400         int ret;
1401 @@ -329,7 +395,7 @@ static int yaffs_readlink(struct dentry
1402         return ret;
1403  }
1404  
1405 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,13))
1406 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 13))
1407  static void *yaffs_follow_link(struct dentry *dentry, struct nameidata *nd)
1408  #else
1409  static int yaffs_follow_link(struct dentry *dentry, struct nameidata *nd)
1410 @@ -345,32 +411,31 @@ static int yaffs_follow_link(struct dent
1411  
1412         yaffs_GrossUnlock(dev);
1413  
1414 -       if (!alias)
1415 -        {
1416 +       if (!alias) {
1417                 ret = -ENOMEM;
1418                 goto out;
1419 -        }
1420 +       }
1421  
1422         ret = vfs_follow_link(nd, alias);
1423         kfree(alias);
1424  out:
1425 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,13))
1426 -       return ERR_PTR (ret);
1427 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 13))
1428 +       return ERR_PTR(ret);
1429  #else
1430         return ret;
1431  #endif
1432  }
1433  
1434  struct inode *yaffs_get_inode(struct super_block *sb, int mode, int dev,
1435 -                             yaffs_Object * obj);
1436 +                               yaffs_Object *obj);
1437  
1438  /*
1439   * Lookup is used to find objects in the fs
1440   */
1441 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1442 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1443  
1444  static struct dentry *yaffs_lookup(struct inode *dir, struct dentry *dentry,
1445 -                                  struct nameidata *n)
1446 +                               struct nameidata *n)
1447  #else
1448  static struct dentry *yaffs_lookup(struct inode *dir, struct dentry *dentry)
1449  #endif
1450 @@ -383,12 +448,11 @@ static struct dentry *yaffs_lookup(struc
1451         yaffs_GrossLock(dev);
1452  
1453         T(YAFFS_TRACE_OS,
1454 -         (KERN_DEBUG "yaffs_lookup for %d:%s\n",
1455 -          yaffs_InodeToObject(dir)->objectId, dentry->d_name.name));
1456 +               ("yaffs_lookup for %d:%s\n",
1457 +               yaffs_InodeToObject(dir)->objectId, dentry->d_name.name));
1458  
1459 -       obj =
1460 -           yaffs_FindObjectByName(yaffs_InodeToObject(dir),
1461 -                                  dentry->d_name.name);
1462 +       obj = yaffs_FindObjectByName(yaffs_InodeToObject(dir),
1463 +                                       dentry->d_name.name);
1464  
1465         obj = yaffs_GetEquivalentObject(obj);   /* in case it was a hardlink */
1466  
1467 @@ -397,13 +461,13 @@ static struct dentry *yaffs_lookup(struc
1468  
1469         if (obj) {
1470                 T(YAFFS_TRACE_OS,
1471 -                 (KERN_DEBUG "yaffs_lookup found %d\n", obj->objectId));
1472 +                       ("yaffs_lookup found %d\n", obj->objectId));
1473  
1474                 inode = yaffs_get_inode(dir->i_sb, obj->yst_mode, 0, obj);
1475  
1476                 if (inode) {
1477                         T(YAFFS_TRACE_OS,
1478 -                         (KERN_DEBUG "yaffs_loookup dentry \n"));
1479 +                               ("yaffs_loookup dentry \n"));
1480  /* #if 0 asserted by NCB for 2.5/6 compatability - falls through to
1481   * d_add even if NULL inode */
1482  #if 0
1483 @@ -416,7 +480,7 @@ static struct dentry *yaffs_lookup(struc
1484                 }
1485  
1486         } else {
1487 -               T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_lookup not found\n"));
1488 +               T(YAFFS_TRACE_OS, ("yaffs_lookup not found\n"));
1489  
1490         }
1491  
1492 @@ -425,20 +489,22 @@ static struct dentry *yaffs_lookup(struc
1493         d_add(dentry, inode);
1494  
1495         return NULL;
1496 -       /*      return (ERR_PTR(-EIO)); */
1497 -
1498  }
1499  
1500 +
1501 +#ifdef YAFFS_HAS_PUT_INODE
1502 +
1503  /* For now put inode is just for debugging
1504   * Put inode is called when the inode **structure** is put.
1505   */
1506  static void yaffs_put_inode(struct inode *inode)
1507  {
1508         T(YAFFS_TRACE_OS,
1509 -         ("yaffs_put_inode: ino %d, count %d\n", (int)inode->i_ino,
1510 -          atomic_read(&inode->i_count)));
1511 +               ("yaffs_put_inode: ino %d, count %d\n", (int)inode->i_ino,
1512 +               atomic_read(&inode->i_count)));
1513  
1514  }
1515 +#endif
1516  
1517  /* clear is called to tell the fs to release any per-inode data it holds */
1518  static void yaffs_clear_inode(struct inode *inode)
1519 @@ -449,9 +515,9 @@ static void yaffs_clear_inode(struct ino
1520         obj = yaffs_InodeToObject(inode);
1521  
1522         T(YAFFS_TRACE_OS,
1523 -         ("yaffs_clear_inode: ino %d, count %d %s\n", (int)inode->i_ino,
1524 -          atomic_read(&inode->i_count),
1525 -          obj ? "object exists" : "null object"));
1526 +               ("yaffs_clear_inode: ino %d, count %d %s\n", (int)inode->i_ino,
1527 +               atomic_read(&inode->i_count),
1528 +               obj ? "object exists" : "null object"));
1529  
1530         if (obj) {
1531                 dev = obj->myDev;
1532 @@ -486,23 +552,23 @@ static void yaffs_delete_inode(struct in
1533         yaffs_Device *dev;
1534  
1535         T(YAFFS_TRACE_OS,
1536 -         ("yaffs_delete_inode: ino %d, count %d %s\n", (int)inode->i_ino,
1537 -          atomic_read(&inode->i_count),
1538 -          obj ? "object exists" : "null object"));
1539 +               ("yaffs_delete_inode: ino %d, count %d %s\n", (int)inode->i_ino,
1540 +               atomic_read(&inode->i_count),
1541 +               obj ? "object exists" : "null object"));
1542  
1543         if (obj) {
1544                 dev = obj->myDev;
1545                 yaffs_GrossLock(dev);
1546 -               yaffs_DeleteFile(obj);
1547 +               yaffs_DeleteObject(obj);
1548                 yaffs_GrossUnlock(dev);
1549         }
1550 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,13))
1551 -        truncate_inode_pages (&inode->i_data, 0);
1552 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 13))
1553 +       truncate_inode_pages(&inode->i_data, 0);
1554  #endif
1555         clear_inode(inode);
1556  }
1557  
1558 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
1559 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
1560  static int yaffs_file_flush(struct file *file, fl_owner_t id)
1561  #else
1562  static int yaffs_file_flush(struct file *file)
1563 @@ -513,8 +579,8 @@ static int yaffs_file_flush(struct file
1564         yaffs_Device *dev = obj->myDev;
1565  
1566         T(YAFFS_TRACE_OS,
1567 -         (KERN_DEBUG "yaffs_file_flush object %d (%s)\n", obj->objectId,
1568 -          obj->dirty ? "dirty" : "clean"));
1569 +               ("yaffs_file_flush object %d (%s)\n", obj->objectId,
1570 +               obj->dirty ? "dirty" : "clean"));
1571  
1572         yaffs_GrossLock(dev);
1573  
1574 @@ -535,15 +601,15 @@ static int yaffs_readpage_nolock(struct
1575  
1576         yaffs_Device *dev;
1577  
1578 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_readpage at %08x, size %08x\n",
1579 -                          (unsigned)(pg->index << PAGE_CACHE_SHIFT),
1580 -                          (unsigned)PAGE_CACHE_SIZE));
1581 +       T(YAFFS_TRACE_OS, ("yaffs_readpage at %08x, size %08x\n",
1582 +                       (unsigned)(pg->index << PAGE_CACHE_SHIFT),
1583 +                       (unsigned)PAGE_CACHE_SIZE));
1584  
1585         obj = yaffs_DentryToObject(f->f_dentry);
1586  
1587         dev = obj->myDev;
1588  
1589 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1590 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1591         BUG_ON(!PageLocked(pg));
1592  #else
1593         if (!PageLocked(pg))
1594 @@ -555,9 +621,9 @@ static int yaffs_readpage_nolock(struct
1595  
1596         yaffs_GrossLock(dev);
1597  
1598 -       ret =
1599 -           yaffs_ReadDataFromFile(obj, pg_buf, pg->index << PAGE_CACHE_SHIFT,
1600 -                                  PAGE_CACHE_SIZE);
1601 +       ret = yaffs_ReadDataFromFile(obj, pg_buf,
1602 +                               pg->index << PAGE_CACHE_SHIFT,
1603 +                               PAGE_CACHE_SIZE);
1604  
1605         yaffs_GrossUnlock(dev);
1606  
1607 @@ -575,7 +641,7 @@ static int yaffs_readpage_nolock(struct
1608         flush_dcache_page(pg);
1609         kunmap(pg);
1610  
1611 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_readpage done\n"));
1612 +       T(YAFFS_TRACE_OS, ("yaffs_readpage done\n"));
1613         return ret;
1614  }
1615  
1616 @@ -593,7 +659,7 @@ static int yaffs_readpage(struct file *f
1617  
1618  /* writepage inspired by/stolen from smbfs */
1619  
1620 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1621 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1622  static int yaffs_writepage(struct page *page, struct writeback_control *wbc)
1623  #else
1624  static int yaffs_writepage(struct page *page)
1625 @@ -616,12 +682,11 @@ static int yaffs_writepage(struct page *
1626  
1627         if (offset > inode->i_size) {
1628                 T(YAFFS_TRACE_OS,
1629 -                 (KERN_DEBUG
1630 -                  "yaffs_writepage at %08x, inode size = %08x!!!\n",
1631 -                  (unsigned)(page->index << PAGE_CACHE_SHIFT),
1632 -                  (unsigned)inode->i_size));
1633 +                       ("yaffs_writepage at %08x, inode size = %08x!!!\n",
1634 +                       (unsigned)(page->index << PAGE_CACHE_SHIFT),
1635 +                       (unsigned)inode->i_size));
1636                 T(YAFFS_TRACE_OS,
1637 -                 (KERN_DEBUG "                -> don't care!!\n"));
1638 +                       ("                -> don't care!!\n"));
1639                 unlock_page(page);
1640                 return 0;
1641         }
1642 @@ -629,11 +694,10 @@ static int yaffs_writepage(struct page *
1643         end_index = inode->i_size >> PAGE_CACHE_SHIFT;
1644  
1645         /* easy case */
1646 -       if (page->index < end_index) {
1647 +       if (page->index < end_index)
1648                 nBytes = PAGE_CACHE_SIZE;
1649 -       } else {
1650 +       else
1651                 nBytes = inode->i_size & (PAGE_CACHE_SIZE - 1);
1652 -       }
1653  
1654         get_page(page);
1655  
1656 @@ -643,19 +707,18 @@ static int yaffs_writepage(struct page *
1657         yaffs_GrossLock(obj->myDev);
1658  
1659         T(YAFFS_TRACE_OS,
1660 -         (KERN_DEBUG "yaffs_writepage at %08x, size %08x\n",
1661 -          (unsigned)(page->index << PAGE_CACHE_SHIFT), nBytes));
1662 +               ("yaffs_writepage at %08x, size %08x\n",
1663 +               (unsigned)(page->index << PAGE_CACHE_SHIFT), nBytes));
1664         T(YAFFS_TRACE_OS,
1665 -         (KERN_DEBUG "writepag0: obj = %05x, ino = %05x\n",
1666 -          (int)obj->variant.fileVariant.fileSize, (int)inode->i_size));
1667 +               ("writepag0: obj = %05x, ino = %05x\n",
1668 +               (int)obj->variant.fileVariant.fileSize, (int)inode->i_size));
1669  
1670 -       nWritten =
1671 -           yaffs_WriteDataToFile(obj, buffer, page->index << PAGE_CACHE_SHIFT,
1672 -                                 nBytes, 0);
1673 +       nWritten = yaffs_WriteDataToFile(obj, buffer,
1674 +                       page->index << PAGE_CACHE_SHIFT, nBytes, 0);
1675  
1676         T(YAFFS_TRACE_OS,
1677 -         (KERN_DEBUG "writepag1: obj = %05x, ino = %05x\n",
1678 -          (int)obj->variant.fileVariant.fileSize, (int)inode->i_size));
1679 +               ("writepag1: obj = %05x, ino = %05x\n",
1680 +               (int)obj->variant.fileVariant.fileSize, (int)inode->i_size));
1681  
1682         yaffs_GrossUnlock(obj->myDev);
1683  
1684 @@ -667,100 +730,207 @@ static int yaffs_writepage(struct page *
1685         return (nWritten == nBytes) ? 0 : -ENOSPC;
1686  }
1687  
1688 +
1689 +#if (YAFFS_USE_WRITE_BEGIN_END > 0)
1690 +static int yaffs_write_begin(struct file *filp, struct address_space *mapping,
1691 +                               loff_t pos, unsigned len, unsigned flags,
1692 +                               struct page **pagep, void **fsdata)
1693 +{
1694 +       struct page *pg = NULL;
1695 +       pgoff_t index = pos >> PAGE_CACHE_SHIFT;
1696 +       uint32_t offset = pos & (PAGE_CACHE_SIZE - 1);
1697 +       uint32_t to = offset + len;
1698 +
1699 +       int ret = 0;
1700 +       int space_held = 0;
1701 +
1702 +       T(YAFFS_TRACE_OS, ("start yaffs_write_begin\n"));
1703 +       /* Get a page */
1704 +#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 28)
1705 +       pg = grab_cache_page_write_begin(mapping, index, flags);
1706 +#else
1707 +       pg = __grab_cache_page(mapping, index);
1708 +#endif
1709 +
1710 +       *pagep = pg;
1711 +       if (!pg) {
1712 +               ret =  -ENOMEM;
1713 +               goto out;
1714 +       }
1715 +       /* Get fs space */
1716 +       space_held = yaffs_hold_space(filp);
1717 +
1718 +       if (!space_held) {
1719 +               ret = -ENOSPC;
1720 +               goto out;
1721 +       }
1722 +
1723 +       /* Update page if required */
1724 +
1725 +       if (!Page_Uptodate(pg) && (offset || to < PAGE_CACHE_SIZE))
1726 +               ret = yaffs_readpage_nolock(filp, pg);
1727 +
1728 +       if (ret)
1729 +               goto out;
1730 +
1731 +       /* Happy path return */
1732 +       T(YAFFS_TRACE_OS, ("end yaffs_write_begin - ok\n"));
1733 +
1734 +       return 0;
1735 +
1736 +out:
1737 +       T(YAFFS_TRACE_OS, ("end yaffs_write_begin fail returning %d\n", ret));
1738 +       if (space_held)
1739 +               yaffs_release_space(filp);
1740 +       if (pg) {
1741 +               unlock_page(pg);
1742 +               page_cache_release(pg);
1743 +       }
1744 +       return ret;
1745 +}
1746 +
1747 +#else
1748 +
1749  static int yaffs_prepare_write(struct file *f, struct page *pg,
1750 -                              unsigned offset, unsigned to)
1751 +                               unsigned offset, unsigned to)
1752  {
1753 +       T(YAFFS_TRACE_OS, ("yaffs_prepair_write\n"));
1754  
1755 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_prepair_write\n"));
1756         if (!Page_Uptodate(pg) && (offset || to < PAGE_CACHE_SIZE))
1757                 return yaffs_readpage_nolock(f, pg);
1758 -
1759         return 0;
1760 +}
1761 +#endif
1762 +
1763 +#if (YAFFS_USE_WRITE_BEGIN_END > 0)
1764 +static int yaffs_write_end(struct file *filp, struct address_space *mapping,
1765 +                               loff_t pos, unsigned len, unsigned copied,
1766 +                               struct page *pg, void *fsdadata)
1767 +{
1768 +       int ret = 0;
1769 +       void *addr, *kva;
1770 +       uint32_t offset_into_page = pos & (PAGE_CACHE_SIZE - 1);
1771 +
1772 +       kva = kmap(pg);
1773 +       addr = kva + offset_into_page;
1774 +
1775 +       T(YAFFS_TRACE_OS,
1776 +               ("yaffs_write_end addr %x pos %x nBytes %d\n",
1777 +               (unsigned) addr,
1778 +               (int)pos, copied));
1779 +
1780 +       ret = yaffs_file_write(filp, addr, copied, &pos);
1781 +
1782 +       if (ret != copied) {
1783 +               T(YAFFS_TRACE_OS,
1784 +                       ("yaffs_write_end not same size ret %d  copied %d\n",
1785 +                       ret, copied));
1786 +               SetPageError(pg);
1787 +               ClearPageUptodate(pg);
1788 +       } else {
1789 +               SetPageUptodate(pg);
1790 +       }
1791 +
1792 +       kunmap(pg);
1793  
1794 +       yaffs_release_space(filp);
1795 +       unlock_page(pg);
1796 +       page_cache_release(pg);
1797 +       return ret;
1798  }
1799 +#else
1800  
1801  static int yaffs_commit_write(struct file *f, struct page *pg, unsigned offset,
1802 -                             unsigned to)
1803 +                               unsigned to)
1804  {
1805 +       void *addr, *kva;
1806  
1807 -       void *addr = page_address(pg) + offset;
1808         loff_t pos = (((loff_t) pg->index) << PAGE_CACHE_SHIFT) + offset;
1809         int nBytes = to - offset;
1810         int nWritten;
1811  
1812         unsigned spos = pos;
1813 -       unsigned saddr = (unsigned)addr;
1814 +       unsigned saddr;
1815 +
1816 +       kva = kmap(pg);
1817 +       addr = kva + offset;
1818 +
1819 +       saddr = (unsigned) addr;
1820  
1821         T(YAFFS_TRACE_OS,
1822 -         (KERN_DEBUG "yaffs_commit_write addr %x pos %x nBytes %d\n", saddr,
1823 -          spos, nBytes));
1824 +               ("yaffs_commit_write addr %x pos %x nBytes %d\n",
1825 +               saddr, spos, nBytes));
1826  
1827         nWritten = yaffs_file_write(f, addr, nBytes, &pos);
1828  
1829         if (nWritten != nBytes) {
1830                 T(YAFFS_TRACE_OS,
1831 -                 (KERN_DEBUG
1832 -                  "yaffs_commit_write not same size nWritten %d  nBytes %d\n",
1833 -                  nWritten, nBytes));
1834 +                       ("yaffs_commit_write not same size nWritten %d  nBytes %d\n",
1835 +                       nWritten, nBytes));
1836                 SetPageError(pg);
1837                 ClearPageUptodate(pg);
1838         } else {
1839                 SetPageUptodate(pg);
1840         }
1841  
1842 +       kunmap(pg);
1843 +
1844         T(YAFFS_TRACE_OS,
1845 -         (KERN_DEBUG "yaffs_commit_write returning %d\n",
1846 -          nWritten == nBytes ? 0 : nWritten));
1847 +               ("yaffs_commit_write returning %d\n",
1848 +               nWritten == nBytes ? 0 : nWritten));
1849  
1850         return nWritten == nBytes ? 0 : nWritten;
1851 -
1852  }
1853 +#endif
1854 +
1855  
1856 -static void yaffs_FillInodeFromObject(struct inode *inode, yaffs_Object * obj)
1857 +static void yaffs_FillInodeFromObject(struct inode *inode, yaffs_Object *obj)
1858  {
1859         if (inode && obj) {
1860  
1861  
1862                 /* Check mode against the variant type and attempt to repair if broken. */
1863 -               __u32 mode = obj->yst_mode;
1864 -               switch( obj->variantType ){
1865 -               case YAFFS_OBJECT_TYPE_FILE :
1866 -                       if( ! S_ISREG(mode) ){
1867 -                               obj->yst_mode &= ~S_IFMT;
1868 -                               obj->yst_mode |= S_IFREG;
1869 -                       }
1870 -
1871 -                       break;
1872 -               case YAFFS_OBJECT_TYPE_SYMLINK :
1873 -                       if( ! S_ISLNK(mode) ){
1874 -                               obj->yst_mode &= ~S_IFMT;
1875 -                               obj->yst_mode |= S_IFLNK;
1876 -                       }
1877 -
1878 -                       break;
1879 -               case YAFFS_OBJECT_TYPE_DIRECTORY :
1880 -                       if( ! S_ISDIR(mode) ){
1881 -                               obj->yst_mode &= ~S_IFMT;
1882 -                               obj->yst_mode |= S_IFDIR;
1883 -                       }
1884 -
1885 -                       break;
1886 -               case YAFFS_OBJECT_TYPE_UNKNOWN :
1887 -               case YAFFS_OBJECT_TYPE_HARDLINK :
1888 -               case YAFFS_OBJECT_TYPE_SPECIAL :
1889 -               default:
1890 -                       /* TODO? */
1891 -                       break;
1892 -               }
1893 +               __u32 mode = obj->yst_mode;
1894 +               switch (obj->variantType) {
1895 +               case YAFFS_OBJECT_TYPE_FILE:
1896 +                       if (!S_ISREG(mode)) {
1897 +                               obj->yst_mode &= ~S_IFMT;
1898 +                               obj->yst_mode |= S_IFREG;
1899 +                       }
1900 +
1901 +                       break;
1902 +               case YAFFS_OBJECT_TYPE_SYMLINK:
1903 +                       if (!S_ISLNK(mode)) {
1904 +                               obj->yst_mode &= ~S_IFMT;
1905 +                               obj->yst_mode |= S_IFLNK;
1906 +                       }
1907 +
1908 +                       break;
1909 +               case YAFFS_OBJECT_TYPE_DIRECTORY:
1910 +                       if (!S_ISDIR(mode)) {
1911 +                               obj->yst_mode &= ~S_IFMT;
1912 +                               obj->yst_mode |= S_IFDIR;
1913 +                       }
1914 +
1915 +                       break;
1916 +               case YAFFS_OBJECT_TYPE_UNKNOWN:
1917 +               case YAFFS_OBJECT_TYPE_HARDLINK:
1918 +               case YAFFS_OBJECT_TYPE_SPECIAL:
1919 +               default:
1920 +                       /* TODO? */
1921 +                       break;
1922 +               }
1923 +
1924 +               inode->i_flags |= S_NOATIME;
1925  
1926                 inode->i_ino = obj->objectId;
1927                 inode->i_mode = obj->yst_mode;
1928                 inode->i_uid = obj->yst_uid;
1929                 inode->i_gid = obj->yst_gid;
1930 -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19))
1931 +#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 19))
1932                 inode->i_blksize = inode->i_sb->s_blocksize;
1933  #endif
1934 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1935 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1936  
1937                 inode->i_rdev = old_decode_dev(obj->yst_rdev);
1938                 inode->i_atime.tv_sec = (time_t) (obj->yst_atime);
1939 @@ -781,26 +951,25 @@ static void yaffs_FillInodeFromObject(st
1940                 inode->i_nlink = yaffs_GetObjectLinkCount(obj);
1941  
1942                 T(YAFFS_TRACE_OS,
1943 -                 (KERN_DEBUG
1944 -                  "yaffs_FillInode mode %x uid %d gid %d size %d count %d\n",
1945 -                  inode->i_mode, inode->i_uid, inode->i_gid,
1946 -                  (int)inode->i_size, atomic_read(&inode->i_count)));
1947 +                       ("yaffs_FillInode mode %x uid %d gid %d size %d count %d\n",
1948 +                       inode->i_mode, inode->i_uid, inode->i_gid,
1949 +                       (int)inode->i_size, atomic_read(&inode->i_count)));
1950  
1951                 switch (obj->yst_mode & S_IFMT) {
1952                 default:        /* fifo, device or socket */
1953 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1954 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1955                         init_special_inode(inode, obj->yst_mode,
1956 -                                          old_decode_dev(obj->yst_rdev));
1957 +                                       old_decode_dev(obj->yst_rdev));
1958  #else
1959                         init_special_inode(inode, obj->yst_mode,
1960 -                                          (dev_t) (obj->yst_rdev));
1961 +                                       (dev_t) (obj->yst_rdev));
1962  #endif
1963                         break;
1964                 case S_IFREG:   /* file */
1965                         inode->i_op = &yaffs_file_inode_operations;
1966                         inode->i_fop = &yaffs_file_operations;
1967                         inode->i_mapping->a_ops =
1968 -                           &yaffs_file_address_operations;
1969 +                               &yaffs_file_address_operations;
1970                         break;
1971                 case S_IFDIR:   /* directory */
1972                         inode->i_op = &yaffs_dir_inode_operations;
1973 @@ -817,34 +986,36 @@ static void yaffs_FillInodeFromObject(st
1974  
1975         } else {
1976                 T(YAFFS_TRACE_OS,
1977 -                 (KERN_DEBUG "yaffs_FileInode invalid parameters\n"));
1978 +                       ("yaffs_FileInode invalid parameters\n"));
1979         }
1980  
1981  }
1982  
1983  struct inode *yaffs_get_inode(struct super_block *sb, int mode, int dev,
1984 -                             yaffs_Object * obj)
1985 +                               yaffs_Object *obj)
1986  {
1987         struct inode *inode;
1988  
1989         if (!sb) {
1990                 T(YAFFS_TRACE_OS,
1991 -                 (KERN_DEBUG "yaffs_get_inode for NULL super_block!!\n"));
1992 +                       ("yaffs_get_inode for NULL super_block!!\n"));
1993                 return NULL;
1994  
1995         }
1996  
1997         if (!obj) {
1998                 T(YAFFS_TRACE_OS,
1999 -                 (KERN_DEBUG "yaffs_get_inode for NULL object!!\n"));
2000 +                       ("yaffs_get_inode for NULL object!!\n"));
2001                 return NULL;
2002  
2003         }
2004  
2005         T(YAFFS_TRACE_OS,
2006 -         (KERN_DEBUG "yaffs_get_inode for object %d\n", obj->objectId));
2007 +               ("yaffs_get_inode for object %d\n", obj->objectId));
2008  
2009 -       inode = iget(sb, obj->objectId);
2010 +       inode = Y_IGET(sb, obj->objectId);
2011 +       if (IS_ERR(inode))
2012 +               return NULL;
2013  
2014         /* NB Side effect: iget calls back to yaffs_read_inode(). */
2015         /* iget also increments the inode's i_count */
2016 @@ -854,7 +1025,7 @@ struct inode *yaffs_get_inode(struct sup
2017  }
2018  
2019  static ssize_t yaffs_file_write(struct file *f, const char *buf, size_t n,
2020 -                               loff_t * pos)
2021 +                               loff_t *pos)
2022  {
2023         yaffs_Object *obj;
2024         int nWritten, ipos;
2025 @@ -869,28 +1040,26 @@ static ssize_t yaffs_file_write(struct f
2026  
2027         inode = f->f_dentry->d_inode;
2028  
2029 -       if (!S_ISBLK(inode->i_mode) && f->f_flags & O_APPEND) {
2030 +       if (!S_ISBLK(inode->i_mode) && f->f_flags & O_APPEND)
2031                 ipos = inode->i_size;
2032 -       } else {
2033 +       else
2034                 ipos = *pos;
2035 -       }
2036  
2037 -       if (!obj) {
2038 +       if (!obj)
2039                 T(YAFFS_TRACE_OS,
2040 -                 (KERN_DEBUG "yaffs_file_write: hey obj is null!\n"));
2041 -       } else {
2042 +                       ("yaffs_file_write: hey obj is null!\n"));
2043 +       else
2044                 T(YAFFS_TRACE_OS,
2045 -                 (KERN_DEBUG
2046 -                  "yaffs_file_write about to write writing %d bytes"
2047 -                  "to object %d at %d\n",
2048 -                  n, obj->objectId, ipos));
2049 -       }
2050 +                       ("yaffs_file_write about to write writing %zu bytes"
2051 +                       "to object %d at %d\n",
2052 +                       n, obj->objectId, ipos));
2053  
2054         nWritten = yaffs_WriteDataToFile(obj, buf, ipos, n, 0);
2055  
2056         T(YAFFS_TRACE_OS,
2057 -         (KERN_DEBUG "yaffs_file_write writing %d bytes, %d written at %d\n",
2058 -          n, nWritten, ipos));
2059 +               ("yaffs_file_write writing %zu bytes, %d written at %d\n",
2060 +               n, nWritten, ipos));
2061 +
2062         if (nWritten > 0) {
2063                 ipos += nWritten;
2064                 *pos = ipos;
2065 @@ -899,10 +1068,9 @@ static ssize_t yaffs_file_write(struct f
2066                         inode->i_blocks = (ipos + 511) >> 9;
2067  
2068                         T(YAFFS_TRACE_OS,
2069 -                         (KERN_DEBUG
2070 -                          "yaffs_file_write size updated to %d bytes, "
2071 -                          "%d blocks\n",
2072 -                          ipos, (int)(inode->i_blocks)));
2073 +                               ("yaffs_file_write size updated to %d bytes, "
2074 +                               "%d blocks\n",
2075 +                               ipos, (int)(inode->i_blocks)));
2076                 }
2077  
2078         }
2079 @@ -910,13 +1078,54 @@ static ssize_t yaffs_file_write(struct f
2080         return nWritten == 0 ? -ENOSPC : nWritten;
2081  }
2082  
2083 +/* Space holding and freeing is done to ensure we have space available for write_begin/end */
2084 +/* For now we just assume few parallel writes and check against a small number. */
2085 +/* Todo: need to do this with a counter to handle parallel reads better */
2086 +
2087 +static ssize_t yaffs_hold_space(struct file *f)
2088 +{
2089 +       yaffs_Object *obj;
2090 +       yaffs_Device *dev;
2091 +
2092 +       int nFreeChunks;
2093 +
2094 +
2095 +       obj = yaffs_DentryToObject(f->f_dentry);
2096 +
2097 +       dev = obj->myDev;
2098 +
2099 +       yaffs_GrossLock(dev);
2100 +
2101 +       nFreeChunks = yaffs_GetNumberOfFreeChunks(dev);
2102 +
2103 +       yaffs_GrossUnlock(dev);
2104 +
2105 +       return (nFreeChunks > 20) ? 1 : 0;
2106 +}
2107 +
2108 +static void yaffs_release_space(struct file *f)
2109 +{
2110 +       yaffs_Object *obj;
2111 +       yaffs_Device *dev;
2112 +
2113 +
2114 +       obj = yaffs_DentryToObject(f->f_dentry);
2115 +
2116 +       dev = obj->myDev;
2117 +
2118 +       yaffs_GrossLock(dev);
2119 +
2120 +
2121 +       yaffs_GrossUnlock(dev);
2122 +}
2123 +
2124  static int yaffs_readdir(struct file *f, void *dirent, filldir_t filldir)
2125  {
2126         yaffs_Object *obj;
2127         yaffs_Device *dev;
2128         struct inode *inode = f->f_dentry->d_inode;
2129         unsigned long offset, curoffs;
2130 -       struct list_head *i;
2131 +       struct ylist_head *i;
2132         yaffs_Object *l;
2133  
2134         char name[YAFFS_MAX_NAME_LENGTH + 1];
2135 @@ -932,24 +1141,20 @@ static int yaffs_readdir(struct file *f,
2136  
2137         if (offset == 0) {
2138                 T(YAFFS_TRACE_OS,
2139 -                 (KERN_DEBUG "yaffs_readdir: entry . ino %d \n",
2140 -                  (int)inode->i_ino));
2141 -               if (filldir(dirent, ".", 1, offset, inode->i_ino, DT_DIR)
2142 -                   < 0) {
2143 +                       ("yaffs_readdir: entry . ino %d \n",
2144 +                       (int)inode->i_ino));
2145 +               if (filldir(dirent, ".", 1, offset, inode->i_ino, DT_DIR) < 0)
2146                         goto out;
2147 -               }
2148                 offset++;
2149                 f->f_pos++;
2150         }
2151         if (offset == 1) {
2152                 T(YAFFS_TRACE_OS,
2153 -                 (KERN_DEBUG "yaffs_readdir: entry .. ino %d \n",
2154 -                  (int)f->f_dentry->d_parent->d_inode->i_ino));
2155 -               if (filldir
2156 -                   (dirent, "..", 2, offset,
2157 -                    f->f_dentry->d_parent->d_inode->i_ino, DT_DIR) < 0) {
2158 +                       ("yaffs_readdir: entry .. ino %d \n",
2159 +                       (int)f->f_dentry->d_parent->d_inode->i_ino));
2160 +               if (filldir(dirent, "..", 2, offset,
2161 +                       f->f_dentry->d_parent->d_inode->i_ino, DT_DIR) < 0)
2162                         goto out;
2163 -               }
2164                 offset++;
2165                 f->f_pos++;
2166         }
2167 @@ -965,35 +1170,32 @@ static int yaffs_readdir(struct file *f,
2168                 f->f_version = inode->i_version;
2169         }
2170  
2171 -       list_for_each(i, &obj->variant.directoryVariant.children) {
2172 +       ylist_for_each(i, &obj->variant.directoryVariant.children) {
2173                 curoffs++;
2174                 if (curoffs >= offset) {
2175 -                       l = list_entry(i, yaffs_Object, siblings);
2176 +                       l = ylist_entry(i, yaffs_Object, siblings);
2177  
2178                         yaffs_GetObjectName(l, name,
2179                                             YAFFS_MAX_NAME_LENGTH + 1);
2180                         T(YAFFS_TRACE_OS,
2181 -                         (KERN_DEBUG "yaffs_readdir: %s inode %d\n", name,
2182 +                         ("yaffs_readdir: %s inode %d\n", name,
2183                            yaffs_GetObjectInode(l)));
2184  
2185                         if (filldir(dirent,
2186 -                                   name,
2187 -                                   strlen(name),
2188 -                                   offset,
2189 -                                   yaffs_GetObjectInode(l),
2190 -                                   yaffs_GetObjectType(l))
2191 -                           < 0) {
2192 +                                       name,
2193 +                                       strlen(name),
2194 +                                       offset,
2195 +                                       yaffs_GetObjectInode(l),
2196 +                                       yaffs_GetObjectType(l)) < 0)
2197                                 goto up_and_out;
2198 -                       }
2199  
2200                         offset++;
2201                         f->f_pos++;
2202                 }
2203         }
2204  
2205 -      up_and_out:
2206 -      out:
2207 -
2208 +up_and_out:
2209 +out:
2210         yaffs_GrossUnlock(dev);
2211  
2212         return 0;
2213 @@ -1002,12 +1204,19 @@ static int yaffs_readdir(struct file *f,
2214  /*
2215   * File creation. Allocate an inode, and we're done..
2216   */
2217 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
2218 +
2219 +#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 29)
2220 +#define YCRED(x) x
2221 +#else
2222 +#define YCRED(x) (x->cred)
2223 +#endif
2224 +
2225 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
2226  static int yaffs_mknod(struct inode *dir, struct dentry *dentry, int mode,
2227 -                      dev_t rdev)
2228 +                       dev_t rdev)
2229  #else
2230  static int yaffs_mknod(struct inode *dir, struct dentry *dentry, int mode,
2231 -                      int rdev)
2232 +                       int rdev)
2233  #endif
2234  {
2235         struct inode *inode;
2236 @@ -1018,25 +1227,25 @@ static int yaffs_mknod(struct inode *dir
2237         yaffs_Object *parent = yaffs_InodeToObject(dir);
2238  
2239         int error = -ENOSPC;
2240 -       uid_t uid = current->fsuid;
2241 -       gid_t gid = (dir->i_mode & S_ISGID) ? dir->i_gid : current->fsgid;
2242 +       uid_t uid = YCRED(current)->fsuid;
2243 +       gid_t gid = (dir->i_mode & S_ISGID) ? dir->i_gid : YCRED(current)->fsgid;
2244  
2245 -       if((dir->i_mode & S_ISGID) && S_ISDIR(mode))
2246 +       if ((dir->i_mode & S_ISGID) && S_ISDIR(mode))
2247                 mode |= S_ISGID;
2248  
2249         if (parent) {
2250                 T(YAFFS_TRACE_OS,
2251 -                 (KERN_DEBUG "yaffs_mknod: parent object %d type %d\n",
2252 -                  parent->objectId, parent->variantType));
2253 +                       ("yaffs_mknod: parent object %d type %d\n",
2254 +                       parent->objectId, parent->variantType));
2255         } else {
2256                 T(YAFFS_TRACE_OS,
2257 -                 (KERN_DEBUG "yaffs_mknod: could not get parent object\n"));
2258 +                       ("yaffs_mknod: could not get parent object\n"));
2259                 return -EPERM;
2260         }
2261  
2262         T(YAFFS_TRACE_OS, ("yaffs_mknod: making oject for %s, "
2263 -                          "mode %x dev %x\n",
2264 -                          dentry->d_name.name, mode, rdev));
2265 +                       "mode %x dev %x\n",
2266 +                       dentry->d_name.name, mode, rdev));
2267  
2268         dev = parent->myDev;
2269  
2270 @@ -1045,33 +1254,28 @@ static int yaffs_mknod(struct inode *dir
2271         switch (mode & S_IFMT) {
2272         default:
2273                 /* Special (socket, fifo, device...) */
2274 -               T(YAFFS_TRACE_OS, (KERN_DEBUG
2275 -                                  "yaffs_mknod: making special\n"));
2276 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
2277 -               obj =
2278 -                   yaffs_MknodSpecial(parent, dentry->d_name.name, mode, uid,
2279 -                                      gid, old_encode_dev(rdev));
2280 -#else
2281 -               obj =
2282 -                   yaffs_MknodSpecial(parent, dentry->d_name.name, mode, uid,
2283 -                                      gid, rdev);
2284 +               T(YAFFS_TRACE_OS, ("yaffs_mknod: making special\n"));
2285 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
2286 +               obj = yaffs_MknodSpecial(parent, dentry->d_name.name, mode, uid,
2287 +                               gid, old_encode_dev(rdev));
2288 +#else
2289 +               obj = yaffs_MknodSpecial(parent, dentry->d_name.name, mode, uid,
2290 +                               gid, rdev);
2291  #endif
2292                 break;
2293         case S_IFREG:           /* file          */
2294 -               T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_mknod: making file\n"));
2295 -               obj =
2296 -                   yaffs_MknodFile(parent, dentry->d_name.name, mode, uid,
2297 -                                   gid);
2298 +               T(YAFFS_TRACE_OS, ("yaffs_mknod: making file\n"));
2299 +               obj = yaffs_MknodFile(parent, dentry->d_name.name, mode, uid,
2300 +                               gid);
2301                 break;
2302         case S_IFDIR:           /* directory */
2303                 T(YAFFS_TRACE_OS,
2304 -                 (KERN_DEBUG "yaffs_mknod: making directory\n"));
2305 -               obj =
2306 -                   yaffs_MknodDirectory(parent, dentry->d_name.name, mode,
2307 -                                        uid, gid);
2308 +                       ("yaffs_mknod: making directory\n"));
2309 +               obj = yaffs_MknodDirectory(parent, dentry->d_name.name, mode,
2310 +                                       uid, gid);
2311                 break;
2312         case S_IFLNK:           /* symlink */
2313 -               T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_mknod: making file\n"));
2314 +               T(YAFFS_TRACE_OS, ("yaffs_mknod: making symlink\n"));
2315                 obj = NULL;     /* Do we ever get here? */
2316                 break;
2317         }
2318 @@ -1083,12 +1287,12 @@ static int yaffs_mknod(struct inode *dir
2319                 inode = yaffs_get_inode(dir->i_sb, mode, rdev, obj);
2320                 d_instantiate(dentry, inode);
2321                 T(YAFFS_TRACE_OS,
2322 -                 (KERN_DEBUG "yaffs_mknod created object %d count = %d\n",
2323 -                  obj->objectId, atomic_read(&inode->i_count)));
2324 +                       ("yaffs_mknod created object %d count = %d\n",
2325 +                       obj->objectId, atomic_read(&inode->i_count)));
2326                 error = 0;
2327         } else {
2328                 T(YAFFS_TRACE_OS,
2329 -                 (KERN_DEBUG "yaffs_mknod failed making object\n"));
2330 +                       ("yaffs_mknod failed making object\n"));
2331                 error = -ENOMEM;
2332         }
2333  
2334 @@ -1098,25 +1302,19 @@ static int yaffs_mknod(struct inode *dir
2335  static int yaffs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2336  {
2337         int retVal;
2338 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_mkdir\n"));
2339 +       T(YAFFS_TRACE_OS, ("yaffs_mkdir\n"));
2340         retVal = yaffs_mknod(dir, dentry, mode | S_IFDIR, 0);
2341 -#if 0
2342 -       /* attempt to fix dir bug - didn't work */
2343 -       if (!retVal) {
2344 -               dget(dentry);
2345 -       }
2346 -#endif
2347         return retVal;
2348  }
2349  
2350 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
2351 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
2352  static int yaffs_create(struct inode *dir, struct dentry *dentry, int mode,
2353                         struct nameidata *n)
2354  #else
2355  static int yaffs_create(struct inode *dir, struct dentry *dentry, int mode)
2356  #endif
2357  {
2358 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_create\n"));
2359 +       T(YAFFS_TRACE_OS, ("yaffs_create\n"));
2360         return yaffs_mknod(dir, dentry, mode | S_IFREG, 0);
2361  }
2362  
2363 @@ -1127,8 +1325,8 @@ static int yaffs_unlink(struct inode *di
2364         yaffs_Device *dev;
2365  
2366         T(YAFFS_TRACE_OS,
2367 -         (KERN_DEBUG "yaffs_unlink %d:%s\n", (int)(dir->i_ino),
2368 -          dentry->d_name.name));
2369 +               ("yaffs_unlink %d:%s\n", (int)(dir->i_ino),
2370 +               dentry->d_name.name));
2371  
2372         dev = yaffs_InodeToObject(dir)->myDev;
2373  
2374 @@ -1151,82 +1349,74 @@ static int yaffs_unlink(struct inode *di
2375   * Create a link...
2376   */
2377  static int yaffs_link(struct dentry *old_dentry, struct inode *dir,
2378 -                     struct dentry *dentry)
2379 +                       struct dentry *dentry)
2380  {
2381         struct inode *inode = old_dentry->d_inode;
2382         yaffs_Object *obj = NULL;
2383         yaffs_Object *link = NULL;
2384         yaffs_Device *dev;
2385  
2386 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_link\n"));
2387 +       T(YAFFS_TRACE_OS, ("yaffs_link\n"));
2388  
2389         obj = yaffs_InodeToObject(inode);
2390         dev = obj->myDev;
2391  
2392         yaffs_GrossLock(dev);
2393  
2394 -       if (!S_ISDIR(inode->i_mode))    /* Don't link directories */
2395 -       {
2396 -               link =
2397 -                   yaffs_Link(yaffs_InodeToObject(dir), dentry->d_name.name,
2398 -                              obj);
2399 -       }
2400 +       if (!S_ISDIR(inode->i_mode))            /* Don't link directories */
2401 +               link = yaffs_Link(yaffs_InodeToObject(dir), dentry->d_name.name,
2402 +                       obj);
2403  
2404         if (link) {
2405                 old_dentry->d_inode->i_nlink = yaffs_GetObjectLinkCount(obj);
2406                 d_instantiate(dentry, old_dentry->d_inode);
2407                 atomic_inc(&old_dentry->d_inode->i_count);
2408                 T(YAFFS_TRACE_OS,
2409 -                 (KERN_DEBUG "yaffs_link link count %d i_count %d\n",
2410 -                  old_dentry->d_inode->i_nlink,
2411 -                  atomic_read(&old_dentry->d_inode->i_count)));
2412 -
2413 +                       ("yaffs_link link count %d i_count %d\n",
2414 +                       old_dentry->d_inode->i_nlink,
2415 +                       atomic_read(&old_dentry->d_inode->i_count)));
2416         }
2417  
2418         yaffs_GrossUnlock(dev);
2419  
2420 -       if (link) {
2421 -
2422 +       if (link)
2423                 return 0;
2424 -       }
2425  
2426         return -EPERM;
2427  }
2428  
2429  static int yaffs_symlink(struct inode *dir, struct dentry *dentry,
2430 -                        const char *symname)
2431 +                               const char *symname)
2432  {
2433         yaffs_Object *obj;
2434         yaffs_Device *dev;
2435 -       uid_t uid = current->fsuid;
2436 -       gid_t gid = (dir->i_mode & S_ISGID) ? dir->i_gid : current->fsgid;
2437 +       uid_t uid = YCRED(current)->fsuid;
2438 +       gid_t gid = (dir->i_mode & S_ISGID) ? dir->i_gid : YCRED(current)->fsgid;
2439  
2440 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_symlink\n"));
2441 +       T(YAFFS_TRACE_OS, ("yaffs_symlink\n"));
2442  
2443         dev = yaffs_InodeToObject(dir)->myDev;
2444         yaffs_GrossLock(dev);
2445         obj = yaffs_MknodSymLink(yaffs_InodeToObject(dir), dentry->d_name.name,
2446 -                                S_IFLNK | S_IRWXUGO, uid, gid, symname);
2447 +                               S_IFLNK | S_IRWXUGO, uid, gid, symname);
2448         yaffs_GrossUnlock(dev);
2449  
2450         if (obj) {
2451 -
2452                 struct inode *inode;
2453  
2454                 inode = yaffs_get_inode(dir->i_sb, obj->yst_mode, 0, obj);
2455                 d_instantiate(dentry, inode);
2456 -               T(YAFFS_TRACE_OS, (KERN_DEBUG "symlink created OK\n"));
2457 +               T(YAFFS_TRACE_OS, ("symlink created OK\n"));
2458                 return 0;
2459         } else {
2460 -               T(YAFFS_TRACE_OS, (KERN_DEBUG "symlink not created\n"));
2461 -
2462 +               T(YAFFS_TRACE_OS, ("symlink not created\n"));
2463         }
2464  
2465         return -ENOMEM;
2466  }
2467  
2468  static int yaffs_sync_object(struct file *file, struct dentry *dentry,
2469 -                            int datasync)
2470 +                               int datasync)
2471  {
2472  
2473         yaffs_Object *obj;
2474 @@ -1236,7 +1426,7 @@ static int yaffs_sync_object(struct file
2475  
2476         dev = obj->myDev;
2477  
2478 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_sync_object\n"));
2479 +       T(YAFFS_TRACE_OS, ("yaffs_sync_object\n"));
2480         yaffs_GrossLock(dev);
2481         yaffs_FlushFile(obj, 1);
2482         yaffs_GrossUnlock(dev);
2483 @@ -1255,41 +1445,36 @@ static int yaffs_rename(struct inode *ol
2484         int retVal = YAFFS_FAIL;
2485         yaffs_Object *target;
2486  
2487 -        T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_rename\n"));
2488 +       T(YAFFS_TRACE_OS, ("yaffs_rename\n"));
2489         dev = yaffs_InodeToObject(old_dir)->myDev;
2490  
2491         yaffs_GrossLock(dev);
2492  
2493         /* Check if the target is an existing directory that is not empty. */
2494 -       target =
2495 -           yaffs_FindObjectByName(yaffs_InodeToObject(new_dir),
2496 -                                  new_dentry->d_name.name);
2497 +       target = yaffs_FindObjectByName(yaffs_InodeToObject(new_dir),
2498 +                               new_dentry->d_name.name);
2499  
2500  
2501  
2502 -       if (target &&
2503 -           target->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2504 -           !list_empty(&target->variant.directoryVariant.children)) {
2505 +       if (target && target->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2506 +               !ylist_empty(&target->variant.directoryVariant.children)) {
2507  
2508 -               T(YAFFS_TRACE_OS, (KERN_DEBUG "target is non-empty dir\n"));
2509 +               T(YAFFS_TRACE_OS, ("target is non-empty dir\n"));
2510  
2511                 retVal = YAFFS_FAIL;
2512         } else {
2513 -
2514                 /* Now does unlinking internally using shadowing mechanism */
2515 -               T(YAFFS_TRACE_OS, (KERN_DEBUG "calling yaffs_RenameObject\n"));
2516 -
2517 -               retVal =
2518 -                   yaffs_RenameObject(yaffs_InodeToObject(old_dir),
2519 -                                      old_dentry->d_name.name,
2520 -                                      yaffs_InodeToObject(new_dir),
2521 -                                      new_dentry->d_name.name);
2522 +               T(YAFFS_TRACE_OS, ("calling yaffs_RenameObject\n"));
2523  
2524 +               retVal = yaffs_RenameObject(yaffs_InodeToObject(old_dir),
2525 +                               old_dentry->d_name.name,
2526 +                               yaffs_InodeToObject(new_dir),
2527 +                               new_dentry->d_name.name);
2528         }
2529         yaffs_GrossUnlock(dev);
2530  
2531         if (retVal == YAFFS_OK) {
2532 -               if(target) {
2533 +               if (target) {
2534                         new_dentry->d_inode->i_nlink--;
2535                         mark_inode_dirty(new_dentry->d_inode);
2536                 }
2537 @@ -1298,7 +1483,6 @@ static int yaffs_rename(struct inode *ol
2538         } else {
2539                 return -ENOTEMPTY;
2540         }
2541 -
2542  }
2543  
2544  static int yaffs_setattr(struct dentry *dentry, struct iattr *attr)
2545 @@ -1308,15 +1492,15 @@ static int yaffs_setattr(struct dentry *
2546         yaffs_Device *dev;
2547  
2548         T(YAFFS_TRACE_OS,
2549 -         (KERN_DEBUG "yaffs_setattr of object %d\n",
2550 -          yaffs_InodeToObject(inode)->objectId));
2551 -
2552 -       if ((error = inode_change_ok(inode, attr)) == 0) {
2553 +               ("yaffs_setattr of object %d\n",
2554 +               yaffs_InodeToObject(inode)->objectId));
2555  
2556 +       error = inode_change_ok(inode, attr);
2557 +       if (error == 0) {
2558                 dev = yaffs_InodeToObject(inode)->myDev;
2559                 yaffs_GrossLock(dev);
2560                 if (yaffs_SetAttributes(yaffs_InodeToObject(inode), attr) ==
2561 -                   YAFFS_OK) {
2562 +                               YAFFS_OK) {
2563                         error = 0;
2564                 } else {
2565                         error = -EPERM;
2566 @@ -1328,12 +1512,12 @@ static int yaffs_setattr(struct dentry *
2567         return error;
2568  }
2569  
2570 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
2571 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2572  static int yaffs_statfs(struct dentry *dentry, struct kstatfs *buf)
2573  {
2574         yaffs_Device *dev = yaffs_DentryToObject(dentry)->myDev;
2575         struct super_block *sb = dentry->d_sb;
2576 -#elif (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
2577 +#elif (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
2578  static int yaffs_statfs(struct super_block *sb, struct kstatfs *buf)
2579  {
2580         yaffs_Device *dev = yaffs_SuperToDevice(sb);
2581 @@ -1343,32 +1527,53 @@ static int yaffs_statfs(struct super_blo
2582         yaffs_Device *dev = yaffs_SuperToDevice(sb);
2583  #endif
2584  
2585 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_statfs\n"));
2586 +       T(YAFFS_TRACE_OS, ("yaffs_statfs\n"));
2587  
2588         yaffs_GrossLock(dev);
2589  
2590         buf->f_type = YAFFS_MAGIC;
2591         buf->f_bsize = sb->s_blocksize;
2592         buf->f_namelen = 255;
2593 -       if (sb->s_blocksize > dev->nDataBytesPerChunk) {
2594 +
2595 +       if (dev->nDataBytesPerChunk & (dev->nDataBytesPerChunk - 1)) {
2596 +               /* Do this if chunk size is not a power of 2 */
2597 +
2598 +               uint64_t bytesInDev;
2599 +               uint64_t bytesFree;
2600 +
2601 +               bytesInDev = ((uint64_t)((dev->endBlock - dev->startBlock + 1))) *
2602 +                       ((uint64_t)(dev->nChunksPerBlock * dev->nDataBytesPerChunk));
2603 +
2604 +               do_div(bytesInDev, sb->s_blocksize); /* bytesInDev becomes the number of blocks */
2605 +               buf->f_blocks = bytesInDev;
2606 +
2607 +               bytesFree  = ((uint64_t)(yaffs_GetNumberOfFreeChunks(dev))) *
2608 +                       ((uint64_t)(dev->nDataBytesPerChunk));
2609 +
2610 +               do_div(bytesFree, sb->s_blocksize);
2611 +
2612 +               buf->f_bfree = bytesFree;
2613 +
2614 +       } else if (sb->s_blocksize > dev->nDataBytesPerChunk) {
2615  
2616                 buf->f_blocks =
2617 -                   (dev->endBlock - dev->startBlock +
2618 -                    1) * dev->nChunksPerBlock / (sb->s_blocksize /
2619 -                                                 dev->nDataBytesPerChunk);
2620 +                       (dev->endBlock - dev->startBlock + 1) *
2621 +                       dev->nChunksPerBlock /
2622 +                       (sb->s_blocksize / dev->nDataBytesPerChunk);
2623                 buf->f_bfree =
2624 -                   yaffs_GetNumberOfFreeChunks(dev) / (sb->s_blocksize /
2625 -                                                       dev->nDataBytesPerChunk);
2626 +                       yaffs_GetNumberOfFreeChunks(dev) /
2627 +                       (sb->s_blocksize / dev->nDataBytesPerChunk);
2628         } else {
2629 -
2630                 buf->f_blocks =
2631 -                   (dev->endBlock - dev->startBlock +
2632 -                    1) * dev->nChunksPerBlock * (dev->nDataBytesPerChunk /
2633 -                                                 sb->s_blocksize);
2634 +                       (dev->endBlock - dev->startBlock + 1) *
2635 +                       dev->nChunksPerBlock *
2636 +                       (dev->nDataBytesPerChunk / sb->s_blocksize);
2637 +
2638                 buf->f_bfree =
2639 -                   yaffs_GetNumberOfFreeChunks(dev) * (dev->nDataBytesPerChunk /
2640 -                                                       sb->s_blocksize);
2641 +                       yaffs_GetNumberOfFreeChunks(dev) *
2642 +                       (dev->nDataBytesPerChunk / sb->s_blocksize);
2643         }
2644 +
2645         buf->f_files = 0;
2646         buf->f_ffree = 0;
2647         buf->f_bavail = buf->f_bfree;
2648 @@ -1378,18 +1583,19 @@ static int yaffs_statfs(struct super_blo
2649  }
2650  
2651  
2652 -/**
2653  static int yaffs_do_sync_fs(struct super_block *sb)
2654  {
2655  
2656         yaffs_Device *dev = yaffs_SuperToDevice(sb);
2657 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_do_sync_fs\n"));
2658 +       T(YAFFS_TRACE_OS, ("yaffs_do_sync_fs\n"));
2659  
2660 -       if(sb->s_dirt) {
2661 +       if (sb->s_dirt) {
2662                 yaffs_GrossLock(dev);
2663  
2664 -               if(dev)
2665 +               if (dev) {
2666 +                       yaffs_FlushEntireDeviceCache(dev);
2667                         yaffs_CheckpointSave(dev);
2668 +               }
2669  
2670                 yaffs_GrossUnlock(dev);
2671  
2672 @@ -1397,35 +1603,73 @@ static int yaffs_do_sync_fs(struct super
2673         }
2674         return 0;
2675  }
2676 -**/
2677  
2678 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
2679 +
2680 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2681  static void yaffs_write_super(struct super_block *sb)
2682  #else
2683  static int yaffs_write_super(struct super_block *sb)
2684  #endif
2685  {
2686  
2687 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_write_super\n"));
2688 -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,18))
2689 -       return 0; /* yaffs_do_sync_fs(sb);*/
2690 +       T(YAFFS_TRACE_OS, ("yaffs_write_super\n"));
2691 +       if (yaffs_auto_checkpoint >= 2)
2692 +               yaffs_do_sync_fs(sb);
2693 +#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 18))
2694 +       return 0;
2695  #endif
2696  }
2697  
2698  
2699 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
2700 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2701  static int yaffs_sync_fs(struct super_block *sb, int wait)
2702  #else
2703  static int yaffs_sync_fs(struct super_block *sb)
2704  #endif
2705  {
2706 +       T(YAFFS_TRACE_OS, ("yaffs_sync_fs\n"));
2707 +
2708 +       if (yaffs_auto_checkpoint >= 1)
2709 +               yaffs_do_sync_fs(sb);
2710 +
2711 +       return 0;
2712 +}
2713 +
2714 +#ifdef YAFFS_USE_OWN_IGET
2715 +
2716 +static struct inode *yaffs_iget(struct super_block *sb, unsigned long ino)
2717 +{
2718 +       struct inode *inode;
2719 +       yaffs_Object *obj;
2720 +       yaffs_Device *dev = yaffs_SuperToDevice(sb);
2721 +
2722 +       T(YAFFS_TRACE_OS,
2723 +               ("yaffs_iget for %lu\n", ino));
2724  
2725 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_sync_fs\n"));
2726 +       inode = iget_locked(sb, ino);
2727 +       if (!inode)
2728 +               return ERR_PTR(-ENOMEM);
2729 +       if (!(inode->i_state & I_NEW))
2730 +               return inode;
2731 +
2732 +       /* NB This is called as a side effect of other functions, but
2733 +        * we had to release the lock to prevent deadlocks, so
2734 +        * need to lock again.
2735 +        */
2736  
2737 -       return 0; /* yaffs_do_sync_fs(sb);*/
2738 +       yaffs_GrossLock(dev);
2739  
2740 +       obj = yaffs_FindObjectByNumber(dev, inode->i_ino);
2741 +
2742 +       yaffs_FillInodeFromObject(inode, obj);
2743 +
2744 +       yaffs_GrossUnlock(dev);
2745 +
2746 +       unlock_new_inode(inode);
2747 +       return inode;
2748  }
2749  
2750 +#else
2751  
2752  static void yaffs_read_inode(struct inode *inode)
2753  {
2754 @@ -1438,7 +1682,7 @@ static void yaffs_read_inode(struct inod
2755         yaffs_Device *dev = yaffs_SuperToDevice(inode->i_sb);
2756  
2757         T(YAFFS_TRACE_OS,
2758 -         (KERN_DEBUG "yaffs_read_inode for %d\n", (int)inode->i_ino));
2759 +               ("yaffs_read_inode for %d\n", (int)inode->i_ino));
2760  
2761         yaffs_GrossLock(dev);
2762  
2763 @@ -1449,18 +1693,20 @@ static void yaffs_read_inode(struct inod
2764         yaffs_GrossUnlock(dev);
2765  }
2766  
2767 -static LIST_HEAD(yaffs_dev_list);
2768 +#endif
2769 +
2770 +static YLIST_HEAD(yaffs_dev_list);
2771  
2772 -#if 0 // not used
2773 +#if 0 /* not used */
2774  static int yaffs_remount_fs(struct super_block *sb, int *flags, char *data)
2775  {
2776         yaffs_Device    *dev = yaffs_SuperToDevice(sb);
2777  
2778 -       if( *flags & MS_RDONLY ) {
2779 +       if (*flags & MS_RDONLY) {
2780                 struct mtd_info *mtd = yaffs_SuperToDevice(sb)->genericDevice;
2781  
2782                 T(YAFFS_TRACE_OS,
2783 -                       (KERN_DEBUG "yaffs_remount_fs: %s: RO\n", dev->name ));
2784 +                       ("yaffs_remount_fs: %s: RO\n", dev->name));
2785  
2786                 yaffs_GrossLock(dev);
2787  
2788 @@ -1472,10 +1718,9 @@ static int yaffs_remount_fs(struct super
2789                         mtd->sync(mtd);
2790  
2791                 yaffs_GrossUnlock(dev);
2792 -       }
2793 -       else {
2794 +       } else {
2795                 T(YAFFS_TRACE_OS,
2796 -                       (KERN_DEBUG "yaffs_remount_fs: %s: RW\n", dev->name ));
2797 +                       ("yaffs_remount_fs: %s: RW\n", dev->name));
2798         }
2799  
2800         return 0;
2801 @@ -1486,7 +1731,7 @@ static void yaffs_put_super(struct super
2802  {
2803         yaffs_Device *dev = yaffs_SuperToDevice(sb);
2804  
2805 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_put_super\n"));
2806 +       T(YAFFS_TRACE_OS, ("yaffs_put_super\n"));
2807  
2808         yaffs_GrossLock(dev);
2809  
2810 @@ -1494,18 +1739,17 @@ static void yaffs_put_super(struct super
2811  
2812         yaffs_CheckpointSave(dev);
2813  
2814 -       if (dev->putSuperFunc) {
2815 +       if (dev->putSuperFunc)
2816                 dev->putSuperFunc(sb);
2817 -       }
2818  
2819         yaffs_Deinitialise(dev);
2820  
2821         yaffs_GrossUnlock(dev);
2822  
2823         /* we assume this is protected by lock_kernel() in mount/umount */
2824 -       list_del(&dev->devList);
2825 +       ylist_del(&dev->devList);
2826  
2827 -       if(dev->spareBuffer){
2828 +       if (dev->spareBuffer) {
2829                 YFREE(dev->spareBuffer);
2830                 dev->spareBuffer = NULL;
2831         }
2832 @@ -1516,12 +1760,10 @@ static void yaffs_put_super(struct super
2833  
2834  static void yaffs_MTDPutSuper(struct super_block *sb)
2835  {
2836 -
2837         struct mtd_info *mtd = yaffs_SuperToDevice(sb)->genericDevice;
2838  
2839 -       if (mtd->sync) {
2840 +       if (mtd->sync)
2841                 mtd->sync(mtd);
2842 -       }
2843  
2844         put_mtd_device(mtd);
2845  }
2846 @@ -1531,9 +1773,9 @@ static void yaffs_MarkSuperBlockDirty(vo
2847  {
2848         struct super_block *sb = (struct super_block *)vsb;
2849  
2850 -       T(YAFFS_TRACE_OS, (KERN_DEBUG "yaffs_MarkSuperBlockDirty() sb = %p\n",sb));
2851 -//     if(sb)
2852 -//             sb->s_dirt = 1;
2853 +       T(YAFFS_TRACE_OS, ("yaffs_MarkSuperBlockDirty() sb = %p\n", sb));
2854 +       if (sb)
2855 +               sb->s_dirt = 1;
2856  }
2857  
2858  typedef struct {
2859 @@ -1546,48 +1788,48 @@ typedef struct {
2860  #define MAX_OPT_LEN 20
2861  static int yaffs_parse_options(yaffs_options *options, const char *options_str)
2862  {
2863 -       char cur_opt[MAX_OPT_LEN+1];
2864 +       char cur_opt[MAX_OPT_LEN + 1];
2865         int p;
2866         int error = 0;
2867  
2868         /* Parse through the options which is a comma seperated list */
2869  
2870 -       while(options_str && *options_str && !error){
2871 -               memset(cur_opt,0,MAX_OPT_LEN+1);
2872 +       while (options_str && *options_str && !error) {
2873 +               memset(cur_opt, 0, MAX_OPT_LEN + 1);
2874                 p = 0;
2875  
2876 -               while(*options_str && *options_str != ','){
2877 -                       if(p < MAX_OPT_LEN){
2878 +               while (*options_str && *options_str != ',') {
2879 +                       if (p < MAX_OPT_LEN) {
2880                                 cur_opt[p] = *options_str;
2881                                 p++;
2882                         }
2883                         options_str++;
2884                 }
2885  
2886 -               if(!strcmp(cur_opt,"inband-tags"))
2887 +               if (!strcmp(cur_opt, "inband-tags"))
2888                         options->inband_tags = 1;
2889 -               else if(!strcmp(cur_opt,"no-cache"))
2890 +               else if (!strcmp(cur_opt, "no-cache"))
2891                         options->no_cache = 1;
2892 -               else if(!strcmp(cur_opt,"no-checkpoint-read"))
2893 +               else if (!strcmp(cur_opt, "no-checkpoint-read"))
2894                         options->skip_checkpoint_read = 1;
2895 -               else if(!strcmp(cur_opt,"no-checkpoint-write"))
2896 +               else if (!strcmp(cur_opt, "no-checkpoint-write"))
2897                         options->skip_checkpoint_write = 1;
2898 -               else if(!strcmp(cur_opt,"no-checkpoint")){
2899 +               else if (!strcmp(cur_opt, "no-checkpoint")) {
2900                         options->skip_checkpoint_read = 1;
2901                         options->skip_checkpoint_write = 1;
2902                 } else {
2903 -                       printk(KERN_INFO "yaffs: Bad mount option \"%s\"\n",cur_opt);
2904 +                       printk(KERN_INFO "yaffs: Bad mount option \"%s\"\n",
2905 +                                       cur_opt);
2906                         error = 1;
2907                 }
2908 -
2909         }
2910  
2911         return error;
2912  }
2913  
2914  static struct super_block *yaffs_internal_read_super(int yaffsVersion,
2915 -                                                    struct super_block *sb,
2916 -                                                    void *data, int silent)
2917 +                                               struct super_block *sb,
2918 +                                               void *data, int silent)
2919  {
2920         int nBlocks;
2921         struct inode *inode = NULL;
2922 @@ -1602,6 +1844,7 @@ static struct super_block *yaffs_interna
2923  
2924         sb->s_magic = YAFFS_MAGIC;
2925         sb->s_op = &yaffs_super_ops;
2926 +       sb->s_flags |= MS_NOATIME;
2927  
2928         if (!sb)
2929                 printk(KERN_INFO "yaffs: sb is NULL\n");
2930 @@ -1614,14 +1857,14 @@ static struct super_block *yaffs_interna
2931                        sb->s_dev,
2932                        yaffs_devname(sb, devname_buf));
2933  
2934 -       if(!data_str)
2935 +       if (!data_str)
2936                 data_str = "";
2937  
2938 -       printk(KERN_INFO "yaffs: passed flags \"%s\"\n",data_str);
2939 +       printk(KERN_INFO "yaffs: passed flags \"%s\"\n", data_str);
2940  
2941 -       memset(&options,0,sizeof(options));
2942 +       memset(&options, 0, sizeof(options));
2943  
2944 -       if(yaffs_parse_options(&options,data_str)){
2945 +       if (yaffs_parse_options(&options, data_str)) {
2946                 /* Option parsing failed */
2947                 return NULL;
2948         }
2949 @@ -1645,9 +1888,9 @@ static struct super_block *yaffs_interna
2950                                yaffs_devname(sb, devname_buf)));
2951  
2952         /* Check it's an mtd device..... */
2953 -       if (MAJOR(sb->s_dev) != MTD_BLOCK_MAJOR) {
2954 +       if (MAJOR(sb->s_dev) != MTD_BLOCK_MAJOR)
2955                 return NULL;    /* This isn't an mtd device */
2956 -       }
2957 +
2958         /* Get the device */
2959         mtd = get_mtd_device(NULL, MINOR(sb->s_dev));
2960         if (!mtd) {
2961 @@ -1673,29 +1916,23 @@ static struct super_block *yaffs_interna
2962         T(YAFFS_TRACE_OS, (" %s %d\n", WRITE_SIZE_STR, WRITE_SIZE(mtd)));
2963         T(YAFFS_TRACE_OS, (" oobsize %d\n", mtd->oobsize));
2964         T(YAFFS_TRACE_OS, (" erasesize %d\n", mtd->erasesize));
2965 -       T(YAFFS_TRACE_OS, (" size %d\n", mtd->size));
2966 +#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 29)
2967 +       T(YAFFS_TRACE_OS, (" size %u\n", mtd->size));
2968 +#else
2969 +       T(YAFFS_TRACE_OS, (" size %lld\n", mtd->size));
2970 +#endif
2971  
2972  #ifdef CONFIG_YAFFS_AUTO_YAFFS2
2973  
2974 -       if (yaffsVersion == 1 &&
2975 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
2976 -           mtd->writesize >= 2048) {
2977 -#else
2978 -           mtd->oobblock >= 2048) {
2979 -#endif
2980 -           T(YAFFS_TRACE_ALWAYS,("yaffs: auto selecting yaffs2\n"));
2981 -           yaffsVersion = 2;
2982 +       if (yaffsVersion == 1 && WRITE_SIZE(mtd) >= 2048) {
2983 +               T(YAFFS_TRACE_ALWAYS, ("yaffs: auto selecting yaffs2\n"));
2984 +               yaffsVersion = 2;
2985         }
2986  
2987         /* Added NCB 26/5/2006 for completeness */
2988 -       if (yaffsVersion == 2 &&
2989 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
2990 -           mtd->writesize == 512) {
2991 -#else
2992 -           mtd->oobblock == 512) {
2993 -#endif
2994 -           T(YAFFS_TRACE_ALWAYS,("yaffs: auto selecting yaffs1\n"));
2995 -           yaffsVersion = 1;
2996 +       if (yaffsVersion == 2 && !options.inband_tags && WRITE_SIZE(mtd) == 512) {
2997 +               T(YAFFS_TRACE_ALWAYS, ("yaffs: auto selecting yaffs1\n"));
2998 +               yaffsVersion = 1;
2999         }
3000  
3001  #endif
3002 @@ -1707,7 +1944,7 @@ static struct super_block *yaffs_interna
3003                     !mtd->block_markbad ||
3004                     !mtd->read ||
3005                     !mtd->write ||
3006 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
3007 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
3008                     !mtd->read_oob || !mtd->write_oob) {
3009  #else
3010                     !mtd->write_ecc ||
3011 @@ -1719,12 +1956,9 @@ static struct super_block *yaffs_interna
3012                         return NULL;
3013                 }
3014  
3015 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
3016 -               if (mtd->writesize < YAFFS_MIN_YAFFS2_CHUNK_SIZE ||
3017 -#else
3018 -               if (mtd->oobblock < YAFFS_MIN_YAFFS2_CHUNK_SIZE ||
3019 -#endif
3020 -                   mtd->oobsize < YAFFS_MIN_YAFFS2_SPARE_SIZE) {
3021 +               if ((WRITE_SIZE(mtd) < YAFFS_MIN_YAFFS2_CHUNK_SIZE ||
3022 +                   mtd->oobsize < YAFFS_MIN_YAFFS2_SPARE_SIZE) &&
3023 +                   !options.inband_tags) {
3024                         T(YAFFS_TRACE_ALWAYS,
3025                           ("yaffs: MTD device does not have the "
3026                            "right page sizes\n"));
3027 @@ -1735,7 +1969,7 @@ static struct super_block *yaffs_interna
3028                 if (!mtd->erase ||
3029                     !mtd->read ||
3030                     !mtd->write ||
3031 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
3032 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
3033                     !mtd->read_oob || !mtd->write_oob) {
3034  #else
3035                     !mtd->write_ecc ||
3036 @@ -1761,7 +1995,7 @@ static struct super_block *yaffs_interna
3037          * Set the yaffs_Device up for mtd
3038          */
3039  
3040 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
3041 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
3042         sb->s_fs_info = dev = kmalloc(sizeof(yaffs_Device), GFP_KERNEL);
3043  #else
3044         sb->u.generic_sbp = dev = kmalloc(sizeof(yaffs_Device), GFP_KERNEL);
3045 @@ -1780,13 +2014,15 @@ static struct super_block *yaffs_interna
3046  
3047         /* Set up the memory size parameters.... */
3048  
3049 -       nBlocks = mtd->size / (YAFFS_CHUNKS_PER_BLOCK * YAFFS_BYTES_PER_CHUNK);
3050 +       nBlocks = YCALCBLOCKS(mtd->size, (YAFFS_CHUNKS_PER_BLOCK * YAFFS_BYTES_PER_CHUNK));
3051 +
3052         dev->startBlock = 0;
3053         dev->endBlock = nBlocks - 1;
3054         dev->nChunksPerBlock = YAFFS_CHUNKS_PER_BLOCK;
3055 -       dev->nDataBytesPerChunk = YAFFS_BYTES_PER_CHUNK;
3056 +       dev->totalBytesPerChunk = YAFFS_BYTES_PER_CHUNK;
3057         dev->nReservedBlocks = 5;
3058         dev->nShortOpCaches = (options.no_cache) ? 0 : 10;
3059 +       dev->inbandTags = options.inband_tags;
3060  
3061         /* ... and the functions. */
3062         if (yaffsVersion == 2) {
3063 @@ -1798,20 +2034,19 @@ static struct super_block *yaffs_interna
3064                 dev->queryNANDBlock = nandmtd2_QueryNANDBlock;
3065                 dev->spareBuffer = YMALLOC(mtd->oobsize);
3066                 dev->isYaffs2 = 1;
3067 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
3068 -               dev->nDataBytesPerChunk = mtd->writesize;
3069 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
3070 +               dev->totalBytesPerChunk = mtd->writesize;
3071                 dev->nChunksPerBlock = mtd->erasesize / mtd->writesize;
3072  #else
3073 -               dev->nDataBytesPerChunk = mtd->oobblock;
3074 +               dev->totalBytesPerChunk = mtd->oobblock;
3075                 dev->nChunksPerBlock = mtd->erasesize / mtd->oobblock;
3076  #endif
3077 -               nBlocks = mtd->size / mtd->erasesize;
3078 +               nBlocks = YCALCBLOCKS(mtd->size, mtd->erasesize);
3079  
3080 -               dev->nCheckpointReservedBlocks = CONFIG_YAFFS_CHECKPOINT_RESERVED_BLOCKS;
3081                 dev->startBlock = 0;
3082                 dev->endBlock = nBlocks - 1;
3083         } else {
3084 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
3085 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
3086                 /* use the MTD interface in yaffs_mtdif1.c */
3087                 dev->writeChunkWithTagsToNAND =
3088                         nandmtd1_WriteChunkWithTagsToNAND;
3089 @@ -1847,7 +2082,7 @@ static struct super_block *yaffs_interna
3090         dev->skipCheckpointWrite = options.skip_checkpoint_write;
3091  
3092         /* we assume this is protected by lock_kernel() in mount/umount */
3093 -       list_add_tail(&dev->devList, &yaffs_dev_list);
3094 +       ylist_add_tail(&dev->devList, &yaffs_dev_list);
3095  
3096         init_MUTEX(&dev->grossLock);
3097  
3098 @@ -1884,20 +2119,23 @@ static struct super_block *yaffs_interna
3099                 return NULL;
3100         }
3101         sb->s_root = root;
3102 +       sb->s_dirt = !dev->isCheckpointed;
3103 +       T(YAFFS_TRACE_ALWAYS,
3104 +         ("yaffs_read_super: isCheckpointed %d\n", dev->isCheckpointed));
3105  
3106         T(YAFFS_TRACE_OS, ("yaffs_read_super: done\n"));
3107         return sb;
3108  }
3109  
3110  
3111 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
3112 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
3113  static int yaffs_internal_read_super_mtd(struct super_block *sb, void *data,
3114                                          int silent)
3115  {
3116         return yaffs_internal_read_super(1, sb, data, silent) ? 0 : -EINVAL;
3117  }
3118  
3119 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
3120 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
3121  static int yaffs_read_super(struct file_system_type *fs,
3122                             int flags, const char *dev_name,
3123                             void *data, struct vfsmount *mnt)
3124 @@ -1938,14 +2176,14 @@ static DECLARE_FSTYPE(yaffs_fs_type, "ya
3125  
3126  #ifdef CONFIG_YAFFS_YAFFS2
3127  
3128 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
3129 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
3130  static int yaffs2_internal_read_super_mtd(struct super_block *sb, void *data,
3131                                           int silent)
3132  {
3133         return yaffs_internal_read_super(2, sb, data, silent) ? 0 : -EINVAL;
3134  }
3135  
3136 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
3137 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
3138  static int yaffs2_read_super(struct file_system_type *fs,
3139                         int flags, const char *dev_name, void *data,
3140                         struct vfsmount *mnt)
3141 @@ -1990,12 +2228,12 @@ static char *yaffs_dump_dev(char *buf, y
3142  {
3143         buf += sprintf(buf, "startBlock......... %d\n", dev->startBlock);
3144         buf += sprintf(buf, "endBlock........... %d\n", dev->endBlock);
3145 +       buf += sprintf(buf, "totalBytesPerChunk. %d\n", dev->totalBytesPerChunk);
3146         buf += sprintf(buf, "nDataBytesPerChunk. %d\n", dev->nDataBytesPerChunk);
3147         buf += sprintf(buf, "chunkGroupBits..... %d\n", dev->chunkGroupBits);
3148         buf += sprintf(buf, "chunkGroupSize..... %d\n", dev->chunkGroupSize);
3149         buf += sprintf(buf, "nErasedBlocks...... %d\n", dev->nErasedBlocks);
3150         buf += sprintf(buf, "nReservedBlocks.... %d\n", dev->nReservedBlocks);
3151 -       buf += sprintf(buf, "nCheckptResBlocks.. %d\n", dev->nCheckpointReservedBlocks);
3152         buf += sprintf(buf, "blocksInCheckpoint. %d\n", dev->blocksInCheckpoint);
3153         buf += sprintf(buf, "nTnodesCreated..... %d\n", dev->nTnodesCreated);
3154         buf += sprintf(buf, "nFreeTnodes........ %d\n", dev->nFreeTnodes);
3155 @@ -2006,10 +2244,8 @@ static char *yaffs_dump_dev(char *buf, y
3156         buf += sprintf(buf, "nPageReads......... %d\n", dev->nPageReads);
3157         buf += sprintf(buf, "nBlockErasures..... %d\n", dev->nBlockErasures);
3158         buf += sprintf(buf, "nGCCopies.......... %d\n", dev->nGCCopies);
3159 -       buf +=
3160 -           sprintf(buf, "garbageCollections. %d\n", dev->garbageCollections);
3161 -       buf +=
3162 -           sprintf(buf, "passiveGCs......... %d\n",
3163 +       buf += sprintf(buf, "garbageCollections. %d\n", dev->garbageCollections);
3164 +       buf += sprintf(buf, "passiveGCs......... %d\n",
3165                     dev->passiveGarbageCollections);
3166         buf += sprintf(buf, "nRetriedWrites..... %d\n", dev->nRetriedWrites);
3167         buf += sprintf(buf, "nShortOpCaches..... %d\n", dev->nShortOpCaches);
3168 @@ -2025,6 +2261,7 @@ static char *yaffs_dump_dev(char *buf, y
3169             sprintf(buf, "nBackgroudDeletions %d\n", dev->nBackgroundDeletions);
3170         buf += sprintf(buf, "useNANDECC......... %d\n", dev->useNANDECC);
3171         buf += sprintf(buf, "isYaffs2........... %d\n", dev->isYaffs2);
3172 +       buf += sprintf(buf, "inbandTags......... %d\n", dev->inbandTags);
3173  
3174         return buf;
3175  }
3176 @@ -2033,7 +2270,7 @@ static int yaffs_proc_read(char *page,
3177                            char **start,
3178                            off_t offset, int count, int *eof, void *data)
3179  {
3180 -       struct list_head *item;
3181 +       struct ylist_head *item;
3182         char *buf = page;
3183         int step = offset;
3184         int n = 0;
3185 @@ -2057,8 +2294,8 @@ static int yaffs_proc_read(char *page,
3186         lock_kernel();
3187  
3188         /* Locate and print the Nth entry.  Order N-squared but N is small. */
3189 -       list_for_each(item, &yaffs_dev_list) {
3190 -               yaffs_Device *dev = list_entry(item, yaffs_Device, devList);
3191 +       ylist_for_each(item, &yaffs_dev_list) {
3192 +               yaffs_Device *dev = ylist_entry(item, yaffs_Device, devList);
3193                 if (n < step) {
3194                         n++;
3195                         continue;
3196 @@ -2119,7 +2356,7 @@ static int yaffs_proc_write(struct file
3197         char *end;
3198         char *mask_name;
3199         const char *x;
3200 -       char substring[MAX_MASK_NAME_LENGTH+1];
3201 +       char substring[MAX_MASK_NAME_LENGTH + 1];
3202         int i;
3203         int done = 0;
3204         int add, len = 0;
3205 @@ -2129,9 +2366,8 @@ static int yaffs_proc_write(struct file
3206  
3207         while (!done && (pos < count)) {
3208                 done = 1;
3209 -               while ((pos < count) && isspace(buf[pos])) {
3210 +               while ((pos < count) && isspace(buf[pos]))
3211                         pos++;
3212 -               }
3213  
3214                 switch (buf[pos]) {
3215                 case '+':
3216 @@ -2148,20 +2384,21 @@ static int yaffs_proc_write(struct file
3217                 mask_name = NULL;
3218  
3219                 mask_bitfield = simple_strtoul(buf + pos, &end, 0);
3220 +
3221                 if (end > buf + pos) {
3222                         mask_name = "numeral";
3223                         len = end - (buf + pos);
3224                         pos += len;
3225                         done = 0;
3226                 } else {
3227 -                       for(x = buf + pos, i = 0;
3228 -                           (*x == '_' || (*x >='a' && *x <= 'z')) &&
3229 -                           i <MAX_MASK_NAME_LENGTH; x++, i++, pos++)
3230 -                           substring[i] = *x;
3231 +                       for (x = buf + pos, i = 0;
3232 +                           (*x == '_' || (*x >= 'a' && *x <= 'z')) &&
3233 +                           i < MAX_MASK_NAME_LENGTH; x++, i++, pos++)
3234 +                               substring[i] = *x;
3235                         substring[i] = '\0';
3236  
3237                         for (i = 0; mask_flags[i].mask_name != NULL; i++) {
3238 -                               if(strcmp(substring,mask_flags[i].mask_name) == 0){
3239 +                               if (strcmp(substring, mask_flags[i].mask_name) == 0) {
3240                                         mask_name = mask_flags[i].mask_name;
3241                                         mask_bitfield = mask_flags[i].mask_bitfield;
3242                                         done = 0;
3243 @@ -2172,7 +2409,7 @@ static int yaffs_proc_write(struct file
3244  
3245                 if (mask_name != NULL) {
3246                         done = 0;
3247 -                       switch(add) {
3248 +                       switch (add) {
3249                         case '-':
3250                                 rg &= ~mask_bitfield;
3251                                 break;
3252 @@ -2191,13 +2428,13 @@ static int yaffs_proc_write(struct file
3253  
3254         yaffs_traceMask = rg | YAFFS_TRACE_ALWAYS;
3255  
3256 -       printk("new trace = 0x%08X\n",yaffs_traceMask);
3257 +       printk(KERN_DEBUG "new trace = 0x%08X\n", yaffs_traceMask);
3258  
3259         if (rg & YAFFS_TRACE_ALWAYS) {
3260                 for (i = 0; mask_flags[i].mask_name != NULL; i++) {
3261                         char flag;
3262                         flag = ((rg & mask_flags[i].mask_bitfield) == mask_flags[i].mask_bitfield) ? '+' : '-';
3263 -                       printk("%c%s\n", flag, mask_flags[i].mask_name);
3264 +                       printk(KERN_DEBUG "%c%s\n", flag, mask_flags[i].mask_name);
3265                 }
3266         }
3267  
3268 @@ -2211,12 +2448,8 @@ struct file_system_to_install {
3269  };
3270  
3271  static struct file_system_to_install fs_to_install[] = {
3272 -//#ifdef CONFIG_YAFFS_YAFFS1
3273         {&yaffs_fs_type, 0},
3274 -//#endif
3275 -//#ifdef CONFIG_YAFFS_YAFFS2
3276         {&yaffs2_fs_type, 0},
3277 -//#endif
3278         {NULL, 0}
3279  };
3280  
3281 @@ -2231,15 +2464,14 @@ static int __init init_yaffs_fs(void)
3282         /* Install the proc_fs entry */
3283         my_proc_entry = create_proc_entry("yaffs",
3284                                                S_IRUGO | S_IFREG,
3285 -                                              &proc_root);
3286 +                                              YPROC_ROOT);
3287  
3288         if (my_proc_entry) {
3289                 my_proc_entry->write_proc = yaffs_proc_write;
3290                 my_proc_entry->read_proc = yaffs_proc_read;
3291                 my_proc_entry->data = NULL;
3292 -       } else {
3293 +       } else
3294                 return -ENOMEM;
3295 -       }
3296  
3297         /* Now add the file system entries */
3298  
3299 @@ -2247,9 +2479,8 @@ static int __init init_yaffs_fs(void)
3300  
3301         while (fsinst->fst && !error) {
3302                 error = register_filesystem(fsinst->fst);
3303 -               if (!error) {
3304 +               if (!error)
3305                         fsinst->installed = 1;
3306 -               }
3307                 fsinst++;
3308         }
3309  
3310 @@ -2277,7 +2508,7 @@ static void __exit exit_yaffs_fs(void)
3311         T(YAFFS_TRACE_ALWAYS, ("yaffs " __DATE__ " " __TIME__
3312                                " removing. \n"));
3313  
3314 -       remove_proc_entry("yaffs", &proc_root);
3315 +       remove_proc_entry("yaffs", YPROC_ROOT);
3316  
3317         fsinst = fs_to_install;
3318  
3319 @@ -2288,7 +2519,6 @@ static void __exit exit_yaffs_fs(void)
3320                 }
3321                 fsinst++;
3322         }
3323 -
3324  }
3325  
3326  module_init(init_yaffs_fs)
3327 --- /dev/null
3328 +++ b/fs/yaffs2/yaffs_getblockinfo.h
3329 @@ -0,0 +1,34 @@
3330 +/*
3331 + * YAFFS: Yet another Flash File System . A NAND-flash specific file system.
3332 + *
3333 + * Copyright (C) 2002-2007 Aleph One Ltd.
3334 + *   for Toby Churchill Ltd and Brightstar Engineering
3335 + *
3336 + * Created by Charles Manning <charles@aleph1.co.uk>
3337 + *
3338 + * This program is free software; you can redistribute it and/or modify
3339 + * it under the terms of the GNU Lesser General Public License version 2.1 as
3340 + * published by the Free Software Foundation.
3341 + *
3342 + * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL.
3343 + */
3344 +
3345 +#ifndef __YAFFS_GETBLOCKINFO_H__
3346 +#define __YAFFS_GETBLOCKINFO_H__
3347 +
3348 +#include "yaffs_guts.h"
3349 +
3350 +/* Function to manipulate block info */
3351 +static Y_INLINE yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blk)
3352 +{
3353 +       if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
3354 +               T(YAFFS_TRACE_ERROR,
3355 +                 (TSTR
3356 +                  ("**>> yaffs: getBlockInfo block %d is not valid" TENDSTR),
3357 +                  blk));
3358 +               YBUG();
3359 +       }
3360 +       return &dev->blockInfo[blk - dev->internalStartBlock];
3361 +}
3362 +
3363 +#endif
3364 --- a/fs/yaffs2/yaffs_guts.c
3365 +++ b/fs/yaffs2/yaffs_guts.c
3366 @@ -12,16 +12,17 @@
3367   */
3368  
3369  const char *yaffs_guts_c_version =
3370 -    "$Id: yaffs_guts.c,v 1.49 2007-05-15 20:07:40 charles Exp $";
3371 +    "$Id: yaffs_guts.c,v 1.82 2009-03-09 04:24:17 charles Exp $";
3372  
3373  #include "yportenv.h"
3374  
3375  #include "yaffsinterface.h"
3376  #include "yaffs_guts.h"
3377  #include "yaffs_tagsvalidity.h"
3378 +#include "yaffs_getblockinfo.h"
3379  
3380  #include "yaffs_tagscompat.h"
3381 -#ifndef  CONFIG_YAFFS_USE_OWN_SORT
3382 +#ifndef CONFIG_YAFFS_USE_OWN_SORT
3383  #include "yaffs_qsort.h"
3384  #endif
3385  #include "yaffs_nand.h"
3386 @@ -32,116 +33,116 @@ const char *yaffs_guts_c_version =
3387  #include "yaffs_packedtags2.h"
3388  
3389  
3390 -#ifdef CONFIG_YAFFS_WINCE
3391 -void yfsd_LockYAFFS(BOOL fsLockOnly);
3392 -void yfsd_UnlockYAFFS(BOOL fsLockOnly);
3393 -#endif
3394 -
3395  #define YAFFS_PASSIVE_GC_CHUNKS 2
3396  
3397  #include "yaffs_ecc.h"
3398  
3399  
3400  /* Robustification (if it ever comes about...) */
3401 -static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
3402 -static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
3403 -static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
3404 -                                    const __u8 * data,
3405 -                                    const yaffs_ExtendedTags * tags);
3406 -static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
3407 -                                   const yaffs_ExtendedTags * tags);
3408 +static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
3409 +static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
3410 +               int erasedOk);
3411 +static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
3412 +                               const __u8 *data,
3413 +                               const yaffs_ExtendedTags *tags);
3414 +static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
3415 +                               const yaffs_ExtendedTags *tags);
3416  
3417  /* Other local prototypes */
3418 -static int yaffs_UnlinkObject( yaffs_Object *obj);
3419 +static int yaffs_UnlinkObject(yaffs_Object *obj);
3420  static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
3421  
3422  static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
3423  
3424 -static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
3425 -                                            const __u8 * buffer,
3426 -                                            yaffs_ExtendedTags * tags,
3427 -                                            int useReserve);
3428 -static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3429 -                                 int chunkInNAND, int inScan);
3430 -
3431 -static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
3432 -                                          yaffs_ObjectType type);
3433 -static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
3434 -                                      yaffs_Object * obj);
3435 -static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
3436 -                                   int force, int isShrink, int shadows);
3437 -static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
3438 +static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
3439 +                                       const __u8 *buffer,
3440 +                                       yaffs_ExtendedTags *tags,
3441 +                                       int useReserve);
3442 +static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3443 +                               int chunkInNAND, int inScan);
3444 +
3445 +static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
3446 +                                       yaffs_ObjectType type);
3447 +static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
3448 +                               yaffs_Object *obj);
3449 +static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
3450 +                               int force, int isShrink, int shadows);
3451 +static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
3452  static int yaffs_CheckStructures(void);
3453 -static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
3454 -                             int chunkOffset, int *limit);
3455 -static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
3456 -
3457 -static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
3458 -
3459 -static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
3460 -static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
3461 -                                   int lineNo);
3462 +static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
3463 +                       int chunkOffset, int *limit);
3464 +static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
3465 +
3466 +static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
3467  
3468 -static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
3469 -                                 int chunkInNAND);
3470  
3471 -static int yaffs_UnlinkWorker(yaffs_Object * obj);
3472 -static void yaffs_DestroyObject(yaffs_Object * obj);
3473 +static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
3474 +                               int chunkInNAND);
3475  
3476 -static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3477 -                          int chunkInObject);
3478 +static int yaffs_UnlinkWorker(yaffs_Object *obj);
3479  
3480 -loff_t yaffs_GetFileSize(yaffs_Object * obj);
3481 +static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3482 +                       int chunkInObject);
3483  
3484 -static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
3485 +static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3486 +                               yaffs_BlockInfo **blockUsedPtr);
3487  
3488 -static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
3489 +static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
3490  
3491  static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
3492  
3493 +static void yaffs_VerifyDirectory(yaffs_Object *directory);
3494  #ifdef YAFFS_PARANOID
3495 -static int yaffs_CheckFileSanity(yaffs_Object * in);
3496 +static int yaffs_CheckFileSanity(yaffs_Object *in);
3497  #else
3498  #define yaffs_CheckFileSanity(in)
3499  #endif
3500  
3501 -static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
3502 -static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
3503 +static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
3504 +static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
3505  
3506  static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
3507  
3508 -static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3509 -                                yaffs_ExtendedTags * tags);
3510 +static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3511 +                               yaffs_ExtendedTags *tags);
3512  
3513 -static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
3514 -static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
3515 -                                         yaffs_FileStructure * fStruct,
3516 -                                         __u32 chunkId);
3517 +static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
3518 +               unsigned pos);
3519 +static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
3520 +                                       yaffs_FileStructure *fStruct,
3521 +                                       __u32 chunkId);
3522  
3523  
3524  /* Function to calculate chunk and offset */
3525  
3526 -static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
3527 +static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
3528 +               __u32 *offsetOut)
3529  {
3530 -       if(dev->chunkShift){
3531 -               /* Easy-peasy power of 2 case */
3532 -               *chunk  = (__u32)(addr >> dev->chunkShift);
3533 -               *offset = (__u32)(addr & dev->chunkMask);
3534 -       }
3535 -       else if(dev->crumbsPerChunk)
3536 -       {
3537 -               /* Case where we're using "crumbs" */
3538 -               *offset = (__u32)(addr & dev->crumbMask);
3539 -               addr >>= dev->crumbShift;
3540 -               *chunk = ((__u32)addr)/dev->crumbsPerChunk;
3541 -               *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
3542 +       int chunk;
3543 +       __u32 offset;
3544 +
3545 +       chunk  = (__u32)(addr >> dev->chunkShift);
3546 +
3547 +       if (dev->chunkDiv == 1) {
3548 +               /* easy power of 2 case */
3549 +               offset = (__u32)(addr & dev->chunkMask);
3550 +       } else {
3551 +               /* Non power-of-2 case */
3552 +
3553 +               loff_t chunkBase;
3554 +
3555 +               chunk /= dev->chunkDiv;
3556 +
3557 +               chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
3558 +               offset = (__u32)(addr - chunkBase);
3559         }
3560 -       else
3561 -               YBUG();
3562 +
3563 +       *chunkOut = chunk;
3564 +       *offsetOut = offset;
3565  }
3566  
3567 -/* Function to return the number of shifts for a power of 2 greater than or equal
3568 - * to the given number
3569 +/* Function to return the number of shifts for a power of 2 greater than or
3570 + * equal to the given number
3571   * Note we don't try to cater for all possible numbers and this does not have to
3572   * be hellishly efficient.
3573   */
3574 @@ -153,13 +154,14 @@ static __u32 ShiftsGE(__u32 x)
3575  
3576         nShifts = extraBits = 0;
3577  
3578 -       while(x>1){
3579 -               if(x & 1) extraBits++;
3580 -               x>>=1;
3581 +       while (x > 1) {
3582 +               if (x & 1)
3583 +                       extraBits++;
3584 +               x >>= 1;
3585                 nShifts++;
3586         }
3587  
3588 -       if(extraBits)
3589 +       if (extraBits)
3590                 nShifts++;
3591  
3592         return nShifts;
3593 @@ -168,16 +170,17 @@ static __u32 ShiftsGE(__u32 x)
3594  /* Function to return the number of shifts to get a 1 in bit 0
3595   */
3596  
3597 -static __u32 ShiftDiv(__u32 x)
3598 +static __u32 Shifts(__u32 x)
3599  {
3600         int nShifts;
3601  
3602         nShifts =  0;
3603  
3604 -       if(!x) return 0;
3605 +       if (!x)
3606 +               return 0;
3607  
3608 -       while( !(x&1)){
3609 -               x>>=1;
3610 +       while (!(x&1)) {
3611 +               x >>= 1;
3612                 nShifts++;
3613         }
3614  
3615 @@ -195,21 +198,25 @@ static int yaffs_InitialiseTempBuffers(y
3616         int i;
3617         __u8 *buf = (__u8 *)1;
3618  
3619 -       memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
3620 +       memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
3621  
3622         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
3623                 dev->tempBuffer[i].line = 0;    /* not in use */
3624                 dev->tempBuffer[i].buffer = buf =
3625 -                   YMALLOC_DMA(dev->nDataBytesPerChunk);
3626 +                   YMALLOC_DMA(dev->totalBytesPerChunk);
3627         }
3628  
3629         return buf ? YAFFS_OK : YAFFS_FAIL;
3630 -
3631  }
3632  
3633 -static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
3634 +__u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
3635  {
3636         int i, j;
3637 +
3638 +       dev->tempInUse++;
3639 +       if (dev->tempInUse > dev->maxTemp)
3640 +               dev->maxTemp = dev->tempInUse;
3641 +
3642         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
3643                 if (dev->tempBuffer[i].line == 0) {
3644                         dev->tempBuffer[i].line = lineNo;
3645 @@ -227,9 +234,9 @@ static __u8 *yaffs_GetTempBuffer(yaffs_D
3646         T(YAFFS_TRACE_BUFFERS,
3647           (TSTR("Out of temp buffers at line %d, other held by lines:"),
3648            lineNo));
3649 -       for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
3650 +       for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
3651                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
3652 -       }
3653 +
3654         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
3655  
3656         /*
3657 @@ -242,10 +249,13 @@ static __u8 *yaffs_GetTempBuffer(yaffs_D
3658  
3659  }
3660  
3661 -static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
3662 +void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
3663                                     int lineNo)
3664  {
3665         int i;
3666 +
3667 +       dev->tempInUse--;
3668 +
3669         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
3670                 if (dev->tempBuffer[i].buffer == buffer) {
3671                         dev->tempBuffer[i].line = 0;
3672 @@ -267,27 +277,26 @@ static void yaffs_ReleaseTempBuffer(yaff
3673  /*
3674   * Determine if we have a managed buffer.
3675   */
3676 -int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
3677 +int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
3678  {
3679         int i;
3680 +
3681         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
3682                 if (dev->tempBuffer[i].buffer == buffer)
3683                         return 1;
3684 +       }
3685  
3686 +       for (i = 0; i < dev->nShortOpCaches; i++) {
3687 +               if (dev->srCache[i].data == buffer)
3688 +                       return 1;
3689         }
3690  
3691 -    for (i = 0; i < dev->nShortOpCaches; i++) {
3692 -        if( dev->srCache[i].data == buffer )
3693 -            return 1;
3694 -
3695 -    }
3696 -
3697 -    if (buffer == dev->checkpointBuffer)
3698 -      return 1;
3699 -
3700 -    T(YAFFS_TRACE_ALWAYS,
3701 -         (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
3702 -    return 0;
3703 +       if (buffer == dev->checkpointBuffer)
3704 +               return 1;
3705 +
3706 +       T(YAFFS_TRACE_ALWAYS,
3707 +               (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
3708 +       return 0;
3709  }
3710  
3711  
3712 @@ -296,62 +305,63 @@ int yaffs_IsManagedTempBuffer(yaffs_Devi
3713   * Chunk bitmap manipulations
3714   */
3715  
3716 -static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
3717 +static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
3718  {
3719         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
3720                 T(YAFFS_TRACE_ERROR,
3721 -                 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
3722 -                  blk));
3723 +                       (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
3724 +                       blk));
3725                 YBUG();
3726         }
3727         return dev->chunkBits +
3728 -           (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
3729 +               (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
3730  }
3731  
3732  static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
3733  {
3734 -       if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
3735 -          chunk < 0 || chunk >= dev->nChunksPerBlock) {
3736 -          T(YAFFS_TRACE_ERROR,
3737 -           (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
3738 -           YBUG();
3739 +       if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
3740 +                       chunk < 0 || chunk >= dev->nChunksPerBlock) {
3741 +               T(YAFFS_TRACE_ERROR,
3742 +               (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
3743 +                       blk, chunk));
3744 +               YBUG();
3745         }
3746  }
3747  
3748 -static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
3749 +static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
3750  {
3751         __u8 *blkBits = yaffs_BlockBits(dev, blk);
3752  
3753         memset(blkBits, 0, dev->chunkBitmapStride);
3754  }
3755  
3756 -static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
3757 +static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
3758  {
3759         __u8 *blkBits = yaffs_BlockBits(dev, blk);
3760  
3761 -       yaffs_VerifyChunkBitId(dev,blk,chunk);
3762 +       yaffs_VerifyChunkBitId(dev, blk, chunk);
3763  
3764         blkBits[chunk / 8] &= ~(1 << (chunk & 7));
3765  }
3766  
3767 -static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
3768 +static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
3769  {
3770         __u8 *blkBits = yaffs_BlockBits(dev, blk);
3771  
3772 -       yaffs_VerifyChunkBitId(dev,blk,chunk);
3773 +       yaffs_VerifyChunkBitId(dev, blk, chunk);
3774  
3775         blkBits[chunk / 8] |= (1 << (chunk & 7));
3776  }
3777  
3778 -static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
3779 +static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
3780  {
3781         __u8 *blkBits = yaffs_BlockBits(dev, blk);
3782 -       yaffs_VerifyChunkBitId(dev,blk,chunk);
3783 +       yaffs_VerifyChunkBitId(dev, blk, chunk);
3784  
3785         return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
3786  }
3787  
3788 -static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
3789 +static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
3790  {
3791         __u8 *blkBits = yaffs_BlockBits(dev, blk);
3792         int i;
3793 @@ -363,17 +373,17 @@ static Y_INLINE int yaffs_StillSomeChunk
3794         return 0;
3795  }
3796  
3797 -static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
3798 +static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
3799  {
3800         __u8 *blkBits = yaffs_BlockBits(dev, blk);
3801         int i;
3802         int n = 0;
3803         for (i = 0; i < dev->chunkBitmapStride; i++) {
3804                 __u8 x = *blkBits;
3805 -               while(x){
3806 -                       if(x & 1)
3807 +               while (x) {
3808 +                       if (x & 1)
3809                                 n++;
3810 -                       x >>=1;
3811 +                       x >>= 1;
3812                 }
3813  
3814                 blkBits++;
3815 @@ -400,7 +410,7 @@ static int yaffs_SkipNANDVerification(ya
3816         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
3817  }
3818  
3819 -static const char * blockStateName[] = {
3820 +static const char *blockStateName[] = {
3821  "Unknown",
3822  "Needs scanning",
3823  "Scanning",
3824 @@ -413,64 +423,65 @@ static const char * blockStateName[] = {
3825  "Dead"
3826  };
3827  
3828 -static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
3829 +static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
3830  {
3831         int actuallyUsed;
3832         int inUse;
3833  
3834 -       if(yaffs_SkipVerification(dev))
3835 +       if (yaffs_SkipVerification(dev))
3836                 return;
3837  
3838         /* Report illegal runtime states */
3839 -       if(bi->blockState <0 || bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
3840 -               T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
3841 +       if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
3842 +               T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
3843  
3844 -       switch(bi->blockState){
3845 -        case YAFFS_BLOCK_STATE_UNKNOWN:
3846 -        case YAFFS_BLOCK_STATE_SCANNING:
3847 -        case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
3848 -               T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
3849 -               n,blockStateName[bi->blockState]));
3850 +       switch (bi->blockState) {
3851 +       case YAFFS_BLOCK_STATE_UNKNOWN:
3852 +       case YAFFS_BLOCK_STATE_SCANNING:
3853 +       case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
3854 +               T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
3855 +               n, blockStateName[bi->blockState]));
3856         }
3857  
3858         /* Check pages in use and soft deletions are legal */
3859  
3860         actuallyUsed = bi->pagesInUse - bi->softDeletions;
3861  
3862 -       if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
3863 +       if (bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
3864            bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
3865            actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
3866 -               T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
3867 -               n,bi->pagesInUse,bi->softDeletions));
3868 +               T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
3869 +               n, bi->pagesInUse, bi->softDeletions));
3870  
3871  
3872         /* Check chunk bitmap legal */
3873 -       inUse = yaffs_CountChunkBits(dev,n);
3874 -       if(inUse != bi->pagesInUse)
3875 -               T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
3876 -                       n,bi->pagesInUse,inUse));
3877 +       inUse = yaffs_CountChunkBits(dev, n);
3878 +       if (inUse != bi->pagesInUse)
3879 +               T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
3880 +                       n, bi->pagesInUse, inUse));
3881  
3882         /* Check that the sequence number is valid.
3883          * Ten million is legal, but is very unlikely
3884          */
3885 -       if(dev->isYaffs2 &&
3886 +       if (dev->isYaffs2 &&
3887            (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
3888 -          (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
3889 -               T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
3890 -               n,bi->sequenceNumber));
3891 -
3892 +          (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
3893 +               T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
3894 +               n, bi->sequenceNumber));
3895  }
3896  
3897 -static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
3898 +static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
3899 +               int n)
3900  {
3901 -       yaffs_VerifyBlock(dev,bi,n);
3902 +       yaffs_VerifyBlock(dev, bi, n);
3903  
3904         /* After collection the block should be in the erased state */
3905 -       /* TODO: This will need to change if we do partial gc */
3906 +       /* This will need to change if we do partial gc */
3907  
3908 -       if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
3909 -               T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
3910 -                       n,bi->blockState));
3911 +       if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
3912 +                       bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
3913 +               T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
3914 +                       n, bi->blockState));
3915         }
3916  }
3917  
3918 @@ -480,52 +491,49 @@ static void yaffs_VerifyBlocks(yaffs_Dev
3919         int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
3920         int nIllegalBlockStates = 0;
3921  
3922 -
3923 -       if(yaffs_SkipVerification(dev))
3924 +       if (yaffs_SkipVerification(dev))
3925                 return;
3926  
3927 -       memset(nBlocksPerState,0,sizeof(nBlocksPerState));
3928 -
3929 +       memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
3930  
3931 -       for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
3932 -               yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
3933 -               yaffs_VerifyBlock(dev,bi,i);
3934 +       for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
3935 +               yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
3936 +               yaffs_VerifyBlock(dev, bi, i);
3937  
3938 -               if(bi->blockState >=0 && bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
3939 +               if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
3940                         nBlocksPerState[bi->blockState]++;
3941                 else
3942                         nIllegalBlockStates++;
3943 -
3944         }
3945  
3946 -       T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
3947 -       T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
3948 +       T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
3949 +       T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
3950  
3951 -       T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
3952 -       if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
3953 -               T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
3954 +       T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
3955 +       if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
3956 +               T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
3957  
3958 -       for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
3959 +       for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
3960                 T(YAFFS_TRACE_VERIFY,
3961                   (TSTR("%s %d blocks"TENDSTR),
3962 -                 blockStateName[i],nBlocksPerState[i]));
3963 +                 blockStateName[i], nBlocksPerState[i]));
3964  
3965 -       if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
3966 +       if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
3967                 T(YAFFS_TRACE_VERIFY,
3968                  (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
3969                  dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
3970  
3971 -       if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
3972 +       if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
3973                 T(YAFFS_TRACE_VERIFY,
3974                  (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
3975                  dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
3976  
3977 -       if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
3978 +       if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
3979                 T(YAFFS_TRACE_VERIFY,
3980                  (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
3981                  nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
3982  
3983 -       T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
3984 +       T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
3985  
3986  }
3987  
3988 @@ -535,26 +543,26 @@ static void yaffs_VerifyBlocks(yaffs_Dev
3989   */
3990  static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
3991  {
3992 -       if(yaffs_SkipVerification(obj->myDev))
3993 +       if (obj && yaffs_SkipVerification(obj->myDev))
3994                 return;
3995  
3996 -       if(!(tags && obj && oh)){
3997 -               T(YAFFS_TRACE_VERIFY,
3998 -                               (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
3999 -                               (__u32)tags,(__u32)obj,(__u32)oh));
4000 +       if (!(tags && obj && oh)) {
4001 +               T(YAFFS_TRACE_VERIFY,
4002 +                               (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
4003 +                               (__u32)tags, (__u32)obj, (__u32)oh));
4004                 return;
4005         }
4006  
4007 -       if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
4008 -          oh->type > YAFFS_OBJECT_TYPE_MAX)
4009 -               T(YAFFS_TRACE_VERIFY,
4010 -                (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
4011 -                tags->objectId, oh->type));
4012 -
4013 -       if(tags->objectId != obj->objectId)
4014 -               T(YAFFS_TRACE_VERIFY,
4015 -                (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
4016 -                tags->objectId, obj->objectId));
4017 +       if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
4018 +                       oh->type > YAFFS_OBJECT_TYPE_MAX)
4019 +               T(YAFFS_TRACE_VERIFY,
4020 +                       (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
4021 +                       tags->objectId, oh->type));
4022 +
4023 +       if (tags->objectId != obj->objectId)
4024 +               T(YAFFS_TRACE_VERIFY,
4025 +                       (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
4026 +                       tags->objectId, obj->objectId));
4027  
4028  
4029         /*
4030 @@ -563,46 +571,43 @@ static void yaffs_VerifyObjectHeader(yaf
4031          * Tests do not apply to the root object.
4032          */
4033  
4034 -       if(parentCheck && tags->objectId > 1 && !obj->parent)
4035 -               T(YAFFS_TRACE_VERIFY,
4036 -                (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
4037 -                tags->objectId, oh->parentObjectId));
4038 -
4039 -
4040 -       if(parentCheck && obj->parent &&
4041 -          oh->parentObjectId != obj->parent->objectId &&
4042 -          (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
4043 -           obj->parent->objectId != YAFFS_OBJECTID_DELETED))
4044 -               T(YAFFS_TRACE_VERIFY,
4045 -                (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
4046 -                tags->objectId, oh->parentObjectId, obj->parent->objectId));
4047 +       if (parentCheck && tags->objectId > 1 && !obj->parent)
4048 +               T(YAFFS_TRACE_VERIFY,
4049 +                       (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
4050 +                       tags->objectId, oh->parentObjectId));
4051  
4052 +       if (parentCheck && obj->parent &&
4053 +                       oh->parentObjectId != obj->parent->objectId &&
4054 +                       (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
4055 +                       obj->parent->objectId != YAFFS_OBJECTID_DELETED))
4056 +               T(YAFFS_TRACE_VERIFY,
4057 +                       (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
4058 +                       tags->objectId, oh->parentObjectId, obj->parent->objectId));
4059  
4060 -       if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
4061 +       if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
4062                 T(YAFFS_TRACE_VERIFY,
4063 -               (TSTR("Obj %d header name is NULL"TENDSTR),
4064 -                obj->objectId));
4065 +                       (TSTR("Obj %d header name is NULL"TENDSTR),
4066 +                       obj->objectId));
4067  
4068 -       if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
4069 +       if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
4070                 T(YAFFS_TRACE_VERIFY,
4071 -               (TSTR("Obj %d header name is 0xFF"TENDSTR),
4072 -                obj->objectId));
4073 +                       (TSTR("Obj %d header name is 0xFF"TENDSTR),
4074 +                       obj->objectId));
4075  }
4076  
4077  
4078  
4079 -static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
4080 -                                       __u32 level, int chunkOffset)
4081 +static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
4082 +                                       __u32 level, int chunkOffset)
4083  {
4084         int i;
4085         yaffs_Device *dev = obj->myDev;
4086         int ok = 1;
4087 -       int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4088  
4089         if (tn) {
4090                 if (level > 0) {
4091  
4092 -                       for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4093 +                       for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4094                                 if (tn->internal[i]) {
4095                                         ok = yaffs_VerifyTnodeWorker(obj,
4096                                                         tn->internal[i],
4097 @@ -611,20 +616,19 @@ static int yaffs_VerifyTnodeWorker(yaffs
4098                                 }
4099                         }
4100                 } else if (level == 0) {
4101 -                       int i;
4102                         yaffs_ExtendedTags tags;
4103                         __u32 objectId = obj->objectId;
4104  
4105                         chunkOffset <<=  YAFFS_TNODES_LEVEL0_BITS;
4106  
4107 -                       for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
4108 -                               __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
4109 +                       for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
4110 +                               __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
4111  
4112 -                               if(theChunk > 0){
4113 +                               if (theChunk > 0) {
4114                                         /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
4115 -                                       yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
4116 -                                       if(tags.objectId != objectId || tags.chunkId != chunkOffset){
4117 -                                               T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
4118 +                                       yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
4119 +                                       if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
4120 +                                               T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
4121                                                         objectId, chunkOffset, theChunk,
4122                                                         tags.objectId, tags.chunkId));
4123                                         }
4124 @@ -646,13 +650,15 @@ static void yaffs_VerifyFile(yaffs_Objec
4125         __u32 lastChunk;
4126         __u32 x;
4127         __u32 i;
4128 -       int ok;
4129         yaffs_Device *dev;
4130         yaffs_ExtendedTags tags;
4131         yaffs_Tnode *tn;
4132         __u32 objectId;
4133  
4134 -       if(obj && yaffs_SkipVerification(obj->myDev))
4135 +       if (!obj)
4136 +               return;
4137 +
4138 +       if (yaffs_SkipVerification(obj->myDev))
4139                 return;
4140  
4141         dev = obj->myDev;
4142 @@ -662,17 +668,17 @@ static void yaffs_VerifyFile(yaffs_Objec
4143         lastChunk =  obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
4144         x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
4145         requiredTallness = 0;
4146 -       while (x> 0) {
4147 +       while (x > 0) {
4148                 x >>= YAFFS_TNODES_INTERNAL_BITS;
4149                 requiredTallness++;
4150         }
4151  
4152         actualTallness = obj->variant.fileVariant.topLevel;
4153  
4154 -       if(requiredTallness > actualTallness )
4155 +       if (requiredTallness > actualTallness)
4156                 T(YAFFS_TRACE_VERIFY,
4157                 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
4158 -                obj->objectId,actualTallness, requiredTallness));
4159 +                obj->objectId, actualTallness, requiredTallness));
4160  
4161  
4162         /* Check that the chunks in the tnode tree are all correct.
4163 @@ -680,39 +686,31 @@ static void yaffs_VerifyFile(yaffs_Objec
4164          * checking the tags for every chunk match.
4165          */
4166  
4167 -       if(yaffs_SkipNANDVerification(dev))
4168 +       if (yaffs_SkipNANDVerification(dev))
4169                 return;
4170  
4171 -       for(i = 1; i <= lastChunk; i++){
4172 -               tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
4173 +       for (i = 1; i <= lastChunk; i++) {
4174 +               tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
4175  
4176                 if (tn) {
4177 -                       __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
4178 -                       if(theChunk > 0){
4179 +                       __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
4180 +                       if (theChunk > 0) {
4181                                 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
4182 -                               yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
4183 -                               if(tags.objectId != objectId || tags.chunkId != i){
4184 -                                       T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
4185 +                               yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
4186 +                               if (tags.objectId != objectId || tags.chunkId != i) {
4187 +                                       T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
4188                                                 objectId, i, theChunk,
4189                                                 tags.objectId, tags.chunkId));
4190                                 }
4191                         }
4192                 }
4193 -
4194         }
4195 -
4196  }
4197  
4198 -static void yaffs_VerifyDirectory(yaffs_Object *obj)
4199 -{
4200 -       if(obj && yaffs_SkipVerification(obj->myDev))
4201 -               return;
4202 -
4203 -}
4204  
4205  static void yaffs_VerifyHardLink(yaffs_Object *obj)
4206  {
4207 -       if(obj && yaffs_SkipVerification(obj->myDev))
4208 +       if (obj && yaffs_SkipVerification(obj->myDev))
4209                 return;
4210  
4211         /* Verify sane equivalent object */
4212 @@ -720,7 +718,7 @@ static void yaffs_VerifyHardLink(yaffs_O
4213  
4214  static void yaffs_VerifySymlink(yaffs_Object *obj)
4215  {
4216 -       if(obj && yaffs_SkipVerification(obj->myDev))
4217 +       if (obj && yaffs_SkipVerification(obj->myDev))
4218                 return;
4219  
4220         /* Verify symlink string */
4221 @@ -728,7 +726,7 @@ static void yaffs_VerifySymlink(yaffs_Ob
4222  
4223  static void yaffs_VerifySpecial(yaffs_Object *obj)
4224  {
4225 -       if(obj && yaffs_SkipVerification(obj->myDev))
4226 +       if (obj && yaffs_SkipVerification(obj->myDev))
4227                 return;
4228  }
4229  
4230 @@ -740,14 +738,19 @@ static void yaffs_VerifyObject(yaffs_Obj
4231         __u32 chunkMax;
4232  
4233         __u32 chunkIdOk;
4234 -       __u32 chunkIsLive;
4235 +       __u32 chunkInRange;
4236 +       __u32 chunkShouldNotBeDeleted;
4237 +       __u32 chunkValid;
4238 +
4239 +       if (!obj)
4240 +               return;
4241  
4242 -       if(!obj)
4243 +       if (obj->beingCreated)
4244                 return;
4245  
4246         dev = obj->myDev;
4247  
4248 -       if(yaffs_SkipVerification(dev))
4249 +       if (yaffs_SkipVerification(dev))
4250                 return;
4251  
4252         /* Check sane object header chunk */
4253 @@ -755,50 +758,54 @@ static void yaffs_VerifyObject(yaffs_Obj
4254         chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
4255         chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
4256  
4257 -       chunkIdOk = (obj->chunkId >= chunkMin && obj->chunkId <= chunkMax);
4258 -       chunkIsLive = chunkIdOk &&
4259 +       chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
4260 +       chunkIdOk = chunkInRange || obj->hdrChunk == 0;
4261 +       chunkValid = chunkInRange &&
4262                         yaffs_CheckChunkBit(dev,
4263 -                                           obj->chunkId / dev->nChunksPerBlock,
4264 -                                           obj->chunkId % dev->nChunksPerBlock);
4265 -       if(!obj->fake &&
4266 -           (!chunkIdOk || !chunkIsLive)) {
4267 -          T(YAFFS_TRACE_VERIFY,
4268 -          (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
4269 -          obj->objectId,obj->chunkId,
4270 -          chunkIdOk ? "" : ",out of range",
4271 -          chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
4272 +                                       obj->hdrChunk / dev->nChunksPerBlock,
4273 +                                       obj->hdrChunk % dev->nChunksPerBlock);
4274 +       chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
4275 +
4276 +       if (!obj->fake &&
4277 +                       (!chunkIdOk || chunkShouldNotBeDeleted)) {
4278 +               T(YAFFS_TRACE_VERIFY,
4279 +                       (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
4280 +                       obj->objectId, obj->hdrChunk,
4281 +                       chunkIdOk ? "" : ",out of range",
4282 +                       chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
4283         }
4284  
4285 -       if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
4286 +       if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
4287                 yaffs_ExtendedTags tags;
4288                 yaffs_ObjectHeader *oh;
4289 -               __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
4290 +               __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
4291  
4292                 oh = (yaffs_ObjectHeader *)buffer;
4293  
4294 -               yaffs_ReadChunkWithTagsFromNAND(dev, obj->chunkId,buffer, &tags);
4295 +               yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
4296 +                               &tags);
4297  
4298 -               yaffs_VerifyObjectHeader(obj,oh,&tags,1);
4299 +               yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
4300  
4301 -               yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
4302 +               yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4303         }
4304  
4305         /* Verify it has a parent */
4306 -       if(obj && !obj->fake &&
4307 -          (!obj->parent || obj->parent->myDev != dev)){
4308 -          T(YAFFS_TRACE_VERIFY,
4309 -          (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
4310 -          obj->objectId,obj->parent));
4311 +       if (obj && !obj->fake &&
4312 +                       (!obj->parent || obj->parent->myDev != dev)) {
4313 +               T(YAFFS_TRACE_VERIFY,
4314 +                       (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
4315 +                       obj->objectId, obj->parent));
4316         }
4317  
4318         /* Verify parent is a directory */
4319 -       if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
4320 -          T(YAFFS_TRACE_VERIFY,
4321 -          (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
4322 -          obj->objectId,obj->parent->variantType));
4323 +       if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4324 +               T(YAFFS_TRACE_VERIFY,
4325 +                       (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
4326 +                       obj->objectId, obj->parent->variantType));
4327         }
4328  
4329 -       switch(obj->variantType){
4330 +       switch (obj->variantType) {
4331         case YAFFS_OBJECT_TYPE_FILE:
4332                 yaffs_VerifyFile(obj);
4333                 break;
4334 @@ -818,33 +825,30 @@ static void yaffs_VerifyObject(yaffs_Obj
4335         default:
4336                 T(YAFFS_TRACE_VERIFY,
4337                 (TSTR("Obj %d has illegaltype %d"TENDSTR),
4338 -               obj->objectId,obj->variantType));
4339 +               obj->objectId, obj->variantType));
4340                 break;
4341         }
4342 -
4343 -
4344  }
4345  
4346  static void yaffs_VerifyObjects(yaffs_Device *dev)
4347  {
4348         yaffs_Object *obj;
4349         int i;
4350 -       struct list_head *lh;
4351 +       struct ylist_head *lh;
4352  
4353 -       if(yaffs_SkipVerification(dev))
4354 +       if (yaffs_SkipVerification(dev))
4355                 return;
4356  
4357         /* Iterate through the objects in each hash entry */
4358  
4359 -        for(i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++){
4360 -               list_for_each(lh, &dev->objectBucket[i].list) {
4361 +       for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
4362 +               ylist_for_each(lh, &dev->objectBucket[i].list) {
4363                         if (lh) {
4364 -                               obj = list_entry(lh, yaffs_Object, hashLink);
4365 +                               obj = ylist_entry(lh, yaffs_Object, hashLink);
4366                                 yaffs_VerifyObject(obj);
4367                         }
4368                 }
4369 -        }
4370 -
4371 +       }
4372  }
4373  
4374  
4375 @@ -855,19 +859,20 @@ static void yaffs_VerifyObjects(yaffs_De
4376  static Y_INLINE int yaffs_HashFunction(int n)
4377  {
4378         n = abs(n);
4379 -       return (n % YAFFS_NOBJECT_BUCKETS);
4380 +       return n % YAFFS_NOBJECT_BUCKETS;
4381  }
4382  
4383  /*
4384 - * Access functions to useful fake objects
4385 + * Access functions to useful fake objects.
4386 + * Note that root might have a presence in NAND if permissions are set.
4387   */
4388  
4389 -yaffs_Object *yaffs_Root(yaffs_Device * dev)
4390 +yaffs_Object *yaffs_Root(yaffs_Device *dev)
4391  {
4392         return dev->rootDir;
4393  }
4394  
4395 -yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
4396 +yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
4397  {
4398         return dev->lostNFoundDir;
4399  }
4400 @@ -877,7 +882,7 @@ yaffs_Object *yaffs_LostNFound(yaffs_Dev
4401   *  Erased NAND checking functions
4402   */
4403  
4404 -int yaffs_CheckFF(__u8 * buffer, int nBytes)
4405 +int yaffs_CheckFF(__u8 *buffer, int nBytes)
4406  {
4407         /* Horrible, slow implementation */
4408         while (nBytes--) {
4409 @@ -889,9 +894,8 @@ int yaffs_CheckFF(__u8 * buffer, int nBy
4410  }
4411  
4412  static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
4413 -                                 int chunkInNAND)
4414 +                               int chunkInNAND)
4415  {
4416 -
4417         int retval = YAFFS_OK;
4418         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
4419         yaffs_ExtendedTags tags;
4420 @@ -899,10 +903,9 @@ static int yaffs_CheckChunkErased(struct
4421  
4422         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
4423  
4424 -       if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
4425 +       if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
4426                 retval = YAFFS_FAIL;
4427  
4428 -
4429         if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
4430                 T(YAFFS_TRACE_NANDACCESS,
4431                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
4432 @@ -915,11 +918,10 @@ static int yaffs_CheckChunkErased(struct
4433  
4434  }
4435  
4436 -
4437  static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
4438 -                                            const __u8 * data,
4439 -                                            yaffs_ExtendedTags * tags,
4440 -                                            int useReserve)
4441 +                                       const __u8 *data,
4442 +                                       yaffs_ExtendedTags *tags,
4443 +                                       int useReserve)
4444  {
4445         int attempts = 0;
4446         int writeOk = 0;
4447 @@ -972,7 +974,7 @@ static int yaffs_WriteNewChunkWithTagsTo
4448                         erasedOk = yaffs_CheckChunkErased(dev, chunk);
4449                         if (erasedOk != YAFFS_OK) {
4450                                 T(YAFFS_TRACE_ERROR,
4451 -                               (TSTR ("**>> yaffs chunk %d was not erased"
4452 +                               (TSTR("**>> yaffs chunk %d was not erased"
4453                                 TENDSTR), chunk));
4454  
4455                                 /* try another chunk */
4456 @@ -992,7 +994,11 @@ static int yaffs_WriteNewChunkWithTagsTo
4457                 /* Copy the data into the robustification buffer */
4458                 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
4459  
4460 -       } while (writeOk != YAFFS_OK && attempts < yaffs_wr_attempts);
4461 +       } while (writeOk != YAFFS_OK &&
4462 +               (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
4463 +
4464 +       if (!writeOk)
4465 +               chunk = -1;
4466  
4467         if (attempts > 1) {
4468                 T(YAFFS_TRACE_ERROR,
4469 @@ -1009,13 +1015,35 @@ static int yaffs_WriteNewChunkWithTagsTo
4470   * Block retiring for handling a broken block.
4471   */
4472  
4473 -static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
4474 +static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
4475  {
4476         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
4477  
4478         yaffs_InvalidateCheckpoint(dev);
4479  
4480 -       yaffs_MarkBlockBad(dev, blockInNAND);
4481 +       if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
4482 +               if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
4483 +                       T(YAFFS_TRACE_ALWAYS, (TSTR(
4484 +                               "yaffs: Failed to mark bad and erase block %d"
4485 +                               TENDSTR), blockInNAND));
4486 +               } else {
4487 +                       yaffs_ExtendedTags tags;
4488 +                       int chunkId = blockInNAND * dev->nChunksPerBlock;
4489 +
4490 +                       __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
4491 +
4492 +                       memset(buffer, 0xff, dev->nDataBytesPerChunk);
4493 +                       yaffs_InitialiseTags(&tags);
4494 +                       tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
4495 +                       if (dev->writeChunkWithTagsToNAND(dev, chunkId -
4496 +                               dev->chunkOffset, buffer, &tags) != YAFFS_OK)
4497 +                               T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
4498 +                                       TCONT("write bad block marker to block %d")
4499 +                                       TENDSTR), blockInNAND));
4500 +
4501 +                       yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4502 +               }
4503 +       }
4504  
4505         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
4506         bi->gcPrioritise = 0;
4507 @@ -1029,49 +1057,45 @@ static void yaffs_RetireBlock(yaffs_Devi
4508   *
4509   */
4510  
4511 -static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
4512 -                                    const __u8 * data,
4513 -                                    const yaffs_ExtendedTags * tags)
4514 +static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
4515 +                               const __u8 *data,
4516 +                               const yaffs_ExtendedTags *tags)
4517  {
4518  }
4519  
4520 -static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
4521 -                                   const yaffs_ExtendedTags * tags)
4522 +static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
4523 +                               const yaffs_ExtendedTags *tags)
4524  {
4525  }
4526  
4527  void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
4528  {
4529 -       if(!bi->gcPrioritise){
4530 +       if (!bi->gcPrioritise) {
4531                 bi->gcPrioritise = 1;
4532                 dev->hasPendingPrioritisedGCs = 1;
4533 -               bi->chunkErrorStrikes ++;
4534 +               bi->chunkErrorStrikes++;
4535  
4536 -               if(bi->chunkErrorStrikes > 3){
4537 +               if (bi->chunkErrorStrikes > 3) {
4538                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
4539                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
4540  
4541                 }
4542 -
4543         }
4544  }
4545  
4546 -static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
4547 +static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
4548 +               int erasedOk)
4549  {
4550 -
4551         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
4552         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
4553  
4554 -       yaffs_HandleChunkError(dev,bi);
4555 +       yaffs_HandleChunkError(dev, bi);
4556  
4557 -
4558 -       if(erasedOk ) {
4559 +       if (erasedOk) {
4560                 /* Was an actual write failure, so mark the block for retirement  */
4561                 bi->needsRetiring = 1;
4562                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
4563                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
4564 -
4565 -
4566         }
4567  
4568         /* Delete the chunk */
4569 @@ -1081,12 +1105,12 @@ static void yaffs_HandleWriteChunkError(
4570  
4571  /*---------------- Name handling functions ------------*/
4572  
4573 -static __u16 yaffs_CalcNameSum(const YCHAR * name)
4574 +static __u16 yaffs_CalcNameSum(const YCHAR *name)
4575  {
4576         __u16 sum = 0;
4577         __u16 i = 1;
4578  
4579 -       YUCHAR *bname = (YUCHAR *) name;
4580 +       const YUCHAR *bname = (const YUCHAR *) name;
4581         if (bname) {
4582                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
4583  
4584 @@ -1102,14 +1126,14 @@ static __u16 yaffs_CalcNameSum(const YCH
4585         return sum;
4586  }
4587  
4588 -static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
4589 +static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
4590  {
4591  #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4592 -       if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
4593 +       memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
4594 +       if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
4595                 yaffs_strcpy(obj->shortName, name);
4596 -       } else {
4597 +       else
4598                 obj->shortName[0] = _Y('\0');
4599 -       }
4600  #endif
4601         obj->sum = yaffs_CalcNameSum(name);
4602  }
4603 @@ -1126,7 +1150,7 @@ static void yaffs_SetObjectName(yaffs_Ob
4604   * Don't use this function directly
4605   */
4606  
4607 -static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
4608 +static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
4609  {
4610         int i;
4611         int tnodeSize;
4612 @@ -1143,6 +1167,9 @@ static int yaffs_CreateTnodes(yaffs_Devi
4613          * Must be a multiple of 32-bits  */
4614         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4615  
4616 +       if (tnodeSize < sizeof(yaffs_Tnode))
4617 +               tnodeSize = sizeof(yaffs_Tnode);
4618 +
4619         /* make these things */
4620  
4621         newTnodes = YMALLOC(nTnodes * tnodeSize);
4622 @@ -1150,7 +1177,7 @@ static int yaffs_CreateTnodes(yaffs_Devi
4623  
4624         if (!newTnodes) {
4625                 T(YAFFS_TRACE_ERROR,
4626 -                 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
4627 +                       (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
4628                 return YAFFS_FAIL;
4629         }
4630  
4631 @@ -1170,7 +1197,7 @@ static int yaffs_CreateTnodes(yaffs_Devi
4632         dev->freeTnodes = newTnodes;
4633  #else
4634         /* New hookup for wide tnodes */
4635 -       for(i = 0; i < nTnodes -1; i++) {
4636 +       for (i = 0; i < nTnodes - 1; i++) {
4637                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
4638                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
4639                 curr->internal[0] = next;
4640 @@ -1197,7 +1224,6 @@ static int yaffs_CreateTnodes(yaffs_Devi
4641                   (TSTR
4642                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
4643                    return YAFFS_FAIL;
4644 -
4645         } else {
4646                 tnl->tnodes = newTnodes;
4647                 tnl->next = dev->allocatedTnodeList;
4648 @@ -1211,14 +1237,13 @@ static int yaffs_CreateTnodes(yaffs_Devi
4649  
4650  /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
4651  
4652 -static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
4653 +static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
4654  {
4655         yaffs_Tnode *tn = NULL;
4656  
4657         /* If there are none left make more */
4658 -       if (!dev->freeTnodes) {
4659 +       if (!dev->freeTnodes)
4660                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
4661 -       }
4662  
4663         if (dev->freeTnodes) {
4664                 tn = dev->freeTnodes;
4665 @@ -1233,21 +1258,27 @@ static yaffs_Tnode *yaffs_GetTnodeRaw(ya
4666                 dev->nFreeTnodes--;
4667         }
4668  
4669 +       dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
4670 +
4671         return tn;
4672  }
4673  
4674 -static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
4675 +static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
4676  {
4677         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
4678 +       int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4679  
4680 -       if(tn)
4681 -               memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
4682 +       if (tnodeSize < sizeof(yaffs_Tnode))
4683 +               tnodeSize = sizeof(yaffs_Tnode);
4684 +
4685 +       if (tn)
4686 +               memset(tn, 0, tnodeSize);
4687  
4688         return tn;
4689  }
4690  
4691  /* FreeTnode frees up a tnode and puts it back on the free list */
4692 -static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
4693 +static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
4694  {
4695         if (tn) {
4696  #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
4697 @@ -1262,9 +1293,10 @@ static void yaffs_FreeTnode(yaffs_Device
4698                 dev->freeTnodes = tn;
4699                 dev->nFreeTnodes++;
4700         }
4701 +       dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
4702  }
4703  
4704 -static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
4705 +static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
4706  {
4707         /* Free the list of allocated tnodes */
4708         yaffs_TnodeList *tmp;
4709 @@ -1282,71 +1314,72 @@ static void yaffs_DeinitialiseTnodes(yaf
4710         dev->nFreeTnodes = 0;
4711  }
4712  
4713 -static void yaffs_InitialiseTnodes(yaffs_Device * dev)
4714 +static void yaffs_InitialiseTnodes(yaffs_Device *dev)
4715  {
4716         dev->allocatedTnodeList = NULL;
4717         dev->freeTnodes = NULL;
4718         dev->nFreeTnodes = 0;
4719         dev->nTnodesCreated = 0;
4720 -
4721  }
4722  
4723  
4724 -void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
4725 +void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
4726 +               unsigned val)
4727  {
4728 -  __u32 *map = (__u32 *)tn;
4729 -  __u32 bitInMap;
4730 -  __u32 bitInWord;
4731 -  __u32 wordInMap;
4732 -  __u32 mask;
4733 +       __u32 *map = (__u32 *)tn;
4734 +       __u32 bitInMap;
4735 +       __u32 bitInWord;
4736 +       __u32 wordInMap;
4737 +       __u32 mask;
4738  
4739 -  pos &= YAFFS_TNODES_LEVEL0_MASK;
4740 -  val >>= dev->chunkGroupBits;
4741 +       pos &= YAFFS_TNODES_LEVEL0_MASK;
4742 +       val >>= dev->chunkGroupBits;
4743  
4744 -  bitInMap = pos * dev->tnodeWidth;
4745 -  wordInMap = bitInMap /32;
4746 -  bitInWord = bitInMap & (32 -1);
4747 +       bitInMap = pos * dev->tnodeWidth;
4748 +       wordInMap = bitInMap / 32;
4749 +       bitInWord = bitInMap & (32 - 1);
4750  
4751 -  mask = dev->tnodeMask << bitInWord;
4752 +       mask = dev->tnodeMask << bitInWord;
4753  
4754 -  map[wordInMap] &= ~mask;
4755 -  map[wordInMap] |= (mask & (val << bitInWord));
4756 +       map[wordInMap] &= ~mask;
4757 +       map[wordInMap] |= (mask & (val << bitInWord));
4758  
4759 -  if(dev->tnodeWidth > (32-bitInWord)) {
4760 -    bitInWord = (32 - bitInWord);
4761 -    wordInMap++;;
4762 -    mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
4763 -    map[wordInMap] &= ~mask;
4764 -    map[wordInMap] |= (mask & (val >> bitInWord));
4765 -  }
4766 +       if (dev->tnodeWidth > (32 - bitInWord)) {
4767 +               bitInWord = (32 - bitInWord);
4768 +               wordInMap++;;
4769 +               mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
4770 +               map[wordInMap] &= ~mask;
4771 +               map[wordInMap] |= (mask & (val >> bitInWord));
4772 +       }
4773  }
4774  
4775 -static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
4776 +static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
4777 +               unsigned pos)
4778  {
4779 -  __u32 *map = (__u32 *)tn;
4780 -  __u32 bitInMap;
4781 -  __u32 bitInWord;
4782 -  __u32 wordInMap;
4783 -  __u32 val;
4784 +       __u32 *map = (__u32 *)tn;
4785 +       __u32 bitInMap;
4786 +       __u32 bitInWord;
4787 +       __u32 wordInMap;
4788 +       __u32 val;
4789  
4790 -  pos &= YAFFS_TNODES_LEVEL0_MASK;
4791 +       pos &= YAFFS_TNODES_LEVEL0_MASK;
4792  
4793 -  bitInMap = pos * dev->tnodeWidth;
4794 -  wordInMap = bitInMap /32;
4795 -  bitInWord = bitInMap & (32 -1);
4796 +       bitInMap = pos * dev->tnodeWidth;
4797 +       wordInMap = bitInMap / 32;
4798 +       bitInWord = bitInMap & (32 - 1);
4799  
4800 -  val = map[wordInMap] >> bitInWord;
4801 +       val = map[wordInMap] >> bitInWord;
4802  
4803 -  if(dev->tnodeWidth > (32-bitInWord)) {
4804 -    bitInWord = (32 - bitInWord);
4805 -    wordInMap++;;
4806 -    val |= (map[wordInMap] << bitInWord);
4807 -  }
4808 +       if      (dev->tnodeWidth > (32 - bitInWord)) {
4809 +               bitInWord = (32 - bitInWord);
4810 +               wordInMap++;;
4811 +               val |= (map[wordInMap] << bitInWord);
4812 +       }
4813  
4814 -  val &= dev->tnodeMask;
4815 -  val <<= dev->chunkGroupBits;
4816 +       val &= dev->tnodeMask;
4817 +       val <<= dev->chunkGroupBits;
4818  
4819 -  return val;
4820 +       return val;
4821  }
4822  
4823  /* ------------------- End of individual tnode manipulation -----------------*/
4824 @@ -1357,24 +1390,21 @@ static __u32 yaffs_GetChunkGroupBase(yaf
4825   */
4826  
4827  /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
4828 -static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
4829 -                                         yaffs_FileStructure * fStruct,
4830 -                                         __u32 chunkId)
4831 +static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
4832 +                                       yaffs_FileStructure *fStruct,
4833 +                                       __u32 chunkId)
4834  {
4835 -
4836         yaffs_Tnode *tn = fStruct->top;
4837         __u32 i;
4838         int requiredTallness;
4839         int level = fStruct->topLevel;
4840  
4841         /* Check sane level and chunk Id */
4842 -       if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
4843 +       if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
4844                 return NULL;
4845 -       }
4846  
4847 -       if (chunkId > YAFFS_MAX_CHUNK_ID) {
4848 +       if (chunkId > YAFFS_MAX_CHUNK_ID)
4849                 return NULL;
4850 -       }
4851  
4852         /* First check we're tall enough (ie enough topLevel) */
4853  
4854 @@ -1385,22 +1415,17 @@ static yaffs_Tnode *yaffs_FindLevel0Tnod
4855                 requiredTallness++;
4856         }
4857  
4858 -       if (requiredTallness > fStruct->topLevel) {
4859 -               /* Not tall enough, so we can't find it, return NULL. */
4860 -               return NULL;
4861 -       }
4862 +       if (requiredTallness > fStruct->topLevel)
4863 +               return NULL; /* Not tall enough, so we can't find it */
4864  
4865         /* Traverse down to level 0 */
4866         while (level > 0 && tn) {
4867 -               tn = tn->
4868 -                   internal[(chunkId >>
4869 -                              ( YAFFS_TNODES_LEVEL0_BITS +
4870 -                                (level - 1) *
4871 -                                YAFFS_TNODES_INTERNAL_BITS)
4872 -                             ) &
4873 -                            YAFFS_TNODES_INTERNAL_MASK];
4874 +               tn = tn->internal[(chunkId >>
4875 +                       (YAFFS_TNODES_LEVEL0_BITS +
4876 +                               (level - 1) *
4877 +                               YAFFS_TNODES_INTERNAL_BITS)) &
4878 +                       YAFFS_TNODES_INTERNAL_MASK];
4879                 level--;
4880 -
4881         }
4882  
4883         return tn;
4884 @@ -1417,12 +1442,11 @@ static yaffs_Tnode *yaffs_FindLevel0Tnod
4885   *  be plugged into the ttree.
4886   */
4887  
4888 -static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
4889 -                                              yaffs_FileStructure * fStruct,
4890 -                                              __u32 chunkId,
4891 -                                              yaffs_Tnode *passedTn)
4892 +static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
4893 +                                       yaffs_FileStructure *fStruct,
4894 +                                       __u32 chunkId,
4895 +                                       yaffs_Tnode *passedTn)
4896  {
4897 -
4898         int requiredTallness;
4899         int i;
4900         int l;
4901 @@ -1432,13 +1456,11 @@ static yaffs_Tnode *yaffs_AddOrFindLevel
4902  
4903  
4904         /* Check sane level and page Id */
4905 -       if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
4906 +       if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
4907                 return NULL;
4908 -       }
4909  
4910 -       if (chunkId > YAFFS_MAX_CHUNK_ID) {
4911 +       if (chunkId > YAFFS_MAX_CHUNK_ID)
4912                 return NULL;
4913 -       }
4914  
4915         /* First check we're tall enough (ie enough topLevel) */
4916  
4917 @@ -1451,7 +1473,7 @@ static yaffs_Tnode *yaffs_AddOrFindLevel
4918  
4919  
4920         if (requiredTallness > fStruct->topLevel) {
4921 -               /* Not tall enough,gotta make the tree taller */
4922 +               /* Not tall enough, gotta make the tree taller */
4923                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
4924  
4925                         tn = yaffs_GetTnode(dev);
4926 @@ -1473,27 +1495,27 @@ static yaffs_Tnode *yaffs_AddOrFindLevel
4927         l = fStruct->topLevel;
4928         tn = fStruct->top;
4929  
4930 -       if(l > 0) {
4931 +       if (l > 0) {
4932                 while (l > 0 && tn) {
4933                         x = (chunkId >>
4934 -                            ( YAFFS_TNODES_LEVEL0_BITS +
4935 +                            (YAFFS_TNODES_LEVEL0_BITS +
4936                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
4937                             YAFFS_TNODES_INTERNAL_MASK;
4938  
4939  
4940 -                       if((l>1) && !tn->internal[x]){
4941 +                       if ((l > 1) && !tn->internal[x]) {
4942                                 /* Add missing non-level-zero tnode */
4943                                 tn->internal[x] = yaffs_GetTnode(dev);
4944  
4945 -                       } else if(l == 1) {
4946 +                       } else if (l == 1) {
4947                                 /* Looking from level 1 at level 0 */
4948 -                               if (passedTn) {
4949 +                               if (passedTn) {
4950                                         /* If we already have one, then release it.*/
4951 -                                       if(tn->internal[x])
4952 -                                               yaffs_FreeTnode(dev,tn->internal[x]);
4953 +                                       if (tn->internal[x])
4954 +                                               yaffs_FreeTnode(dev, tn->internal[x]);
4955                                         tn->internal[x] = passedTn;
4956  
4957 -                               } else if(!tn->internal[x]) {
4958 +                               } else if (!tn->internal[x]) {
4959                                         /* Don't have one, none passed in */
4960                                         tn->internal[x] = yaffs_GetTnode(dev);
4961                                 }
4962 @@ -1504,31 +1526,29 @@ static yaffs_Tnode *yaffs_AddOrFindLevel
4963                 }
4964         } else {
4965                 /* top is level 0 */
4966 -               if(passedTn) {
4967 -                       memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
4968 -                       yaffs_FreeTnode(dev,passedTn);
4969 +               if (passedTn) {
4970 +                       memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
4971 +                       yaffs_FreeTnode(dev, passedTn);
4972                 }
4973         }
4974  
4975         return tn;
4976  }
4977  
4978 -static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
4979 -                                 yaffs_ExtendedTags * tags, int objectId,
4980 -                                 int chunkInInode)
4981 +static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
4982 +                               yaffs_ExtendedTags *tags, int objectId,
4983 +                               int chunkInInode)
4984  {
4985         int j;
4986  
4987         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
4988 -               if (yaffs_CheckChunkBit
4989 -                   (dev, theChunk / dev->nChunksPerBlock,
4990 -                    theChunk % dev->nChunksPerBlock)) {
4991 +               if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
4992 +                               theChunk % dev->nChunksPerBlock)) {
4993                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
4994                                                         tags);
4995                         if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
4996                                 /* found it; */
4997                                 return theChunk;
4998 -
4999                         }
5000                 }
5001                 theChunk++;
5002 @@ -1543,7 +1563,7 @@ static int yaffs_FindChunkInGroup(yaffs_
5003   * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
5004   */
5005  
5006 -static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
5007 +static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
5008                               int chunkOffset, int *limit)
5009  {
5010         int i;
5011 @@ -1557,7 +1577,6 @@ static int yaffs_DeleteWorker(yaffs_Obje
5012  
5013         if (tn) {
5014                 if (level > 0) {
5015 -
5016                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
5017                              i--) {
5018                                 if (tn->internal[i]) {
5019 @@ -1565,17 +1584,17 @@ static int yaffs_DeleteWorker(yaffs_Obje
5020                                                 allDone = 0;
5021                                         } else {
5022                                                 allDone =
5023 -                                                   yaffs_DeleteWorker(in,
5024 -                                                                      tn->
5025 -                                                                      internal
5026 -                                                                      [i],
5027 -                                                                      level -
5028 -                                                                      1,
5029 -                                                                      (chunkOffset
5030 +                                                       yaffs_DeleteWorker(in,
5031 +                                                               tn->
5032 +                                                               internal
5033 +                                                               [i],
5034 +                                                               level -
5035 +                                                               1,
5036 +                                                               (chunkOffset
5037                                                                         <<
5038                                                                         YAFFS_TNODES_INTERNAL_BITS)
5039 -                                                                      + i,
5040 -                                                                      limit);
5041 +                                                               + i,
5042 +                                                               limit);
5043                                         }
5044                                         if (allDone) {
5045                                                 yaffs_FreeTnode(dev,
5046 @@ -1584,27 +1603,25 @@ static int yaffs_DeleteWorker(yaffs_Obje
5047                                                 tn->internal[i] = NULL;
5048                                         }
5049                                 }
5050 -
5051                         }
5052                         return (allDone) ? 1 : 0;
5053                 } else if (level == 0) {
5054                         int hitLimit = 0;
5055  
5056                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
5057 -                            i--) {
5058 -                               theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
5059 +                                       i--) {
5060 +                               theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
5061                                 if (theChunk) {
5062  
5063 -                                       chunkInInode =
5064 -                                           (chunkOffset <<
5065 -                                            YAFFS_TNODES_LEVEL0_BITS) + i;
5066 +                                       chunkInInode = (chunkOffset <<
5067 +                                               YAFFS_TNODES_LEVEL0_BITS) + i;
5068  
5069                                         foundChunk =
5070 -                                           yaffs_FindChunkInGroup(dev,
5071 -                                                                  theChunk,
5072 -                                                                  &tags,
5073 -                                                                  in->objectId,
5074 -                                                                  chunkInInode);
5075 +                                               yaffs_FindChunkInGroup(dev,
5076 +                                                               theChunk,
5077 +                                                               &tags,
5078 +                                                               in->objectId,
5079 +                                                               chunkInInode);
5080  
5081                                         if (foundChunk > 0) {
5082                                                 yaffs_DeleteChunk(dev,
5083 @@ -1613,14 +1630,13 @@ static int yaffs_DeleteWorker(yaffs_Obje
5084                                                 in->nDataChunks--;
5085                                                 if (limit) {
5086                                                         *limit = *limit - 1;
5087 -                                                       if (*limit <= 0) {
5088 +                                                       if (*limit <= 0)
5089                                                                 hitLimit = 1;
5090 -                                                       }
5091                                                 }
5092  
5093                                         }
5094  
5095 -                                       yaffs_PutLevel0Tnode(dev,tn,i,0);
5096 +                                       yaffs_PutLevel0Tnode(dev, tn, i, 0);
5097                                 }
5098  
5099                         }
5100 @@ -1634,9 +1650,8 @@ static int yaffs_DeleteWorker(yaffs_Obje
5101  
5102  }
5103  
5104 -static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
5105 +static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
5106  {
5107 -
5108         yaffs_BlockInfo *theBlock;
5109  
5110         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
5111 @@ -1654,7 +1669,7 @@ static void yaffs_SoftDeleteChunk(yaffs_
5112   * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
5113   */
5114  
5115 -static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
5116 +static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
5117                                   __u32 level, int chunkOffset)
5118  {
5119         int i;
5120 @@ -1691,14 +1706,14 @@ static int yaffs_SoftDeleteWorker(yaffs_
5121                 } else if (level == 0) {
5122  
5123                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
5124 -                               theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
5125 +                               theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
5126                                 if (theChunk) {
5127                                         /* Note this does not find the real chunk, only the chunk group.
5128                                          * We make an assumption that a chunk group is not larger than
5129                                          * a block.
5130                                          */
5131                                         yaffs_SoftDeleteChunk(dev, theChunk);
5132 -                                       yaffs_PutLevel0Tnode(dev,tn,i,0);
5133 +                                       yaffs_PutLevel0Tnode(dev, tn, i, 0);
5134                                 }
5135  
5136                         }
5137 @@ -1712,7 +1727,7 @@ static int yaffs_SoftDeleteWorker(yaffs_
5138  
5139  }
5140  
5141 -static void yaffs_SoftDeleteFile(yaffs_Object * obj)
5142 +static void yaffs_SoftDeleteFile(yaffs_Object *obj)
5143  {
5144         if (obj->deleted &&
5145             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
5146 @@ -1746,8 +1761,8 @@ static void yaffs_SoftDeleteFile(yaffs_O
5147   * by a special case.
5148   */
5149  
5150 -static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
5151 -                                     __u32 level, int del0)
5152 +static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
5153 +                               __u32 level, int del0)
5154  {
5155         int i;
5156         int hasData;
5157 @@ -1763,9 +1778,8 @@ static yaffs_Tnode *yaffs_PruneWorker(ya
5158                                                       (i == 0) ? del0 : 1);
5159                         }
5160  
5161 -                       if (tn->internal[i]) {
5162 +                       if (tn->internal[i])
5163                                 hasData++;
5164 -                       }
5165                 }
5166  
5167                 if (hasData == 0 && del0) {
5168 @@ -1781,8 +1795,8 @@ static yaffs_Tnode *yaffs_PruneWorker(ya
5169  
5170  }
5171  
5172 -static int yaffs_PruneFileStructure(yaffs_Device * dev,
5173 -                                   yaffs_FileStructure * fStruct)
5174 +static int yaffs_PruneFileStructure(yaffs_Device *dev,
5175 +                               yaffs_FileStructure *fStruct)
5176  {
5177         int i;
5178         int hasData;
5179 @@ -1805,9 +1819,8 @@ static int yaffs_PruneFileStructure(yaff
5180  
5181                         hasData = 0;
5182                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
5183 -                               if (tn->internal[i]) {
5184 +                               if (tn->internal[i])
5185                                         hasData++;
5186 -                               }
5187                         }
5188  
5189                         if (!hasData) {
5190 @@ -1828,7 +1841,7 @@ static int yaffs_PruneFileStructure(yaff
5191  /* yaffs_CreateFreeObjects creates a bunch more objects and
5192   * adds them to the object free list.
5193   */
5194 -static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
5195 +static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
5196  {
5197         int i;
5198         yaffs_Object *newObjects;
5199 @@ -1842,9 +1855,9 @@ static int yaffs_CreateFreeObjects(yaffs
5200         list = YMALLOC(sizeof(yaffs_ObjectList));
5201  
5202         if (!newObjects || !list) {
5203 -               if(newObjects)
5204 +               if (newObjects)
5205                         YFREE(newObjects);
5206 -               if(list)
5207 +               if (list)
5208                         YFREE(list);
5209                 T(YAFFS_TRACE_ALLOCATE,
5210                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
5211 @@ -1854,7 +1867,7 @@ static int yaffs_CreateFreeObjects(yaffs
5212         /* Hook them into the free list */
5213         for (i = 0; i < nObjects - 1; i++) {
5214                 newObjects[i].siblings.next =
5215 -                   (struct list_head *)(&newObjects[i + 1]);
5216 +                               (struct ylist_head *)(&newObjects[i + 1]);
5217         }
5218  
5219         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
5220 @@ -1873,85 +1886,109 @@ static int yaffs_CreateFreeObjects(yaffs
5221  
5222  
5223  /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
5224 -static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
5225 +static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
5226  {
5227         yaffs_Object *tn = NULL;
5228  
5229 +#ifdef VALGRIND_TEST
5230 +       tn = YMALLOC(sizeof(yaffs_Object));
5231 +#else
5232         /* If there are none left make more */
5233 -       if (!dev->freeObjects) {
5234 +       if (!dev->freeObjects)
5235                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
5236 -       }
5237  
5238         if (dev->freeObjects) {
5239                 tn = dev->freeObjects;
5240                 dev->freeObjects =
5241 -                   (yaffs_Object *) (dev->freeObjects->siblings.next);
5242 +                       (yaffs_Object *) (dev->freeObjects->siblings.next);
5243                 dev->nFreeObjects--;
5244 -
5245 +       }
5246 +#endif
5247 +       if (tn) {
5248                 /* Now sweeten it up... */
5249  
5250                 memset(tn, 0, sizeof(yaffs_Object));
5251 +               tn->beingCreated = 1;
5252 +
5253                 tn->myDev = dev;
5254 -               tn->chunkId = -1;
5255 +               tn->hdrChunk = 0;
5256                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
5257 -               INIT_LIST_HEAD(&(tn->hardLinks));
5258 -               INIT_LIST_HEAD(&(tn->hashLink));
5259 -               INIT_LIST_HEAD(&tn->siblings);
5260 +               YINIT_LIST_HEAD(&(tn->hardLinks));
5261 +               YINIT_LIST_HEAD(&(tn->hashLink));
5262 +               YINIT_LIST_HEAD(&tn->siblings);
5263 +
5264 +
5265 +               /* Now make the directory sane */
5266 +               if (dev->rootDir) {
5267 +                       tn->parent = dev->rootDir;
5268 +                       ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
5269 +               }
5270  
5271                 /* Add it to the lost and found directory.
5272                  * NB Can't put root or lostNFound in lostNFound so
5273                  * check if lostNFound exists first
5274                  */
5275 -               if (dev->lostNFoundDir) {
5276 +               if (dev->lostNFoundDir)
5277                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
5278 -               }
5279 +
5280 +               tn->beingCreated = 0;
5281         }
5282  
5283 +       dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
5284 +
5285         return tn;
5286  }
5287  
5288 -static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
5289 +static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
5290                                                __u32 mode)
5291  {
5292  
5293         yaffs_Object *obj =
5294             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
5295         if (obj) {
5296 -               obj->fake = 1;          /* it is fake so it has no NAND presence... */
5297 +               obj->fake = 1;          /* it is fake so it might have no NAND presence... */
5298                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
5299                 obj->unlinkAllowed = 0; /* ... or unlink it */
5300                 obj->deleted = 0;
5301                 obj->unlinked = 0;
5302                 obj->yst_mode = mode;
5303                 obj->myDev = dev;
5304 -               obj->chunkId = 0;       /* Not a valid chunk. */
5305 +               obj->hdrChunk = 0;      /* Not a valid chunk. */
5306         }
5307  
5308         return obj;
5309  
5310  }
5311  
5312 -static void yaffs_UnhashObject(yaffs_Object * tn)
5313 +static void yaffs_UnhashObject(yaffs_Object *tn)
5314  {
5315         int bucket;
5316         yaffs_Device *dev = tn->myDev;
5317  
5318         /* If it is still linked into the bucket list, free from the list */
5319 -       if (!list_empty(&tn->hashLink)) {
5320 -               list_del_init(&tn->hashLink);
5321 +       if (!ylist_empty(&tn->hashLink)) {
5322 +               ylist_del_init(&tn->hashLink);
5323                 bucket = yaffs_HashFunction(tn->objectId);
5324                 dev->objectBucket[bucket].count--;
5325         }
5326 -
5327  }
5328  
5329  /*  FreeObject frees up a Object and puts it back on the free list */
5330 -static void yaffs_FreeObject(yaffs_Object * tn)
5331 +static void yaffs_FreeObject(yaffs_Object *tn)
5332  {
5333 -
5334         yaffs_Device *dev = tn->myDev;
5335  
5336 -#ifdef  __KERNEL__
5337 +#ifdef __KERNEL__
5338 +       T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
5339 +#endif
5340 +
5341 +       if (tn->parent)
5342 +               YBUG();
5343 +       if (!ylist_empty(&tn->siblings))
5344 +               YBUG();
5345 +
5346 +
5347 +#ifdef __KERNEL__
5348         if (tn->myInode) {
5349                 /* We're still hooked up to a cached inode.
5350                  * Don't delete now, but mark for later deletion
5351 @@ -1963,24 +2000,28 @@ static void yaffs_FreeObject(yaffs_Objec
5352  
5353         yaffs_UnhashObject(tn);
5354  
5355 +#ifdef VALGRIND_TEST
5356 +       YFREE(tn);
5357 +#else
5358         /* Link into the free list. */
5359 -       tn->siblings.next = (struct list_head *)(dev->freeObjects);
5360 +       tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
5361         dev->freeObjects = tn;
5362         dev->nFreeObjects++;
5363 +#endif
5364 +       dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
5365  }
5366  
5367  #ifdef __KERNEL__
5368  
5369 -void yaffs_HandleDeferedFree(yaffs_Object * obj)
5370 +void yaffs_HandleDeferedFree(yaffs_Object *obj)
5371  {
5372 -       if (obj->deferedFree) {
5373 +       if (obj->deferedFree)
5374                 yaffs_FreeObject(obj);
5375 -       }
5376  }
5377  
5378  #endif
5379  
5380 -static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
5381 +static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
5382  {
5383         /* Free the list of allocated Objects */
5384  
5385 @@ -1998,7 +2039,7 @@ static void yaffs_DeinitialiseObjects(ya
5386         dev->nFreeObjects = 0;
5387  }
5388  
5389 -static void yaffs_InitialiseObjects(yaffs_Device * dev)
5390 +static void yaffs_InitialiseObjects(yaffs_Device *dev)
5391  {
5392         int i;
5393  
5394 @@ -2007,15 +2048,14 @@ static void yaffs_InitialiseObjects(yaff
5395         dev->nFreeObjects = 0;
5396  
5397         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5398 -               INIT_LIST_HEAD(&dev->objectBucket[i].list);
5399 +               YINIT_LIST_HEAD(&dev->objectBucket[i].list);
5400                 dev->objectBucket[i].count = 0;
5401         }
5402 -
5403  }
5404  
5405 -static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
5406 +static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
5407  {
5408 -       static int x = 0;
5409 +       static int x;
5410         int i;
5411         int l = 999;
5412         int lowest = 999999;
5413 @@ -2049,7 +2089,7 @@ static int yaffs_FindNiceObjectBucket(ya
5414         return l;
5415  }
5416  
5417 -static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
5418 +static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
5419  {
5420         int bucket = yaffs_FindNiceObjectBucket(dev);
5421  
5422 @@ -2058,7 +2098,7 @@ static int yaffs_CreateNewObjectNumber(y
5423          */
5424  
5425         int found = 0;
5426 -       struct list_head *i;
5427 +       struct ylist_head *i;
5428  
5429         __u32 n = (__u32) bucket;
5430  
5431 @@ -2068,41 +2108,38 @@ static int yaffs_CreateNewObjectNumber(y
5432                 found = 1;
5433                 n += YAFFS_NOBJECT_BUCKETS;
5434                 if (1 || dev->objectBucket[bucket].count > 0) {
5435 -                       list_for_each(i, &dev->objectBucket[bucket].list) {
5436 +                       ylist_for_each(i, &dev->objectBucket[bucket].list) {
5437                                 /* If there is already one in the list */
5438 -                               if (i
5439 -                                   && list_entry(i, yaffs_Object,
5440 -                                                 hashLink)->objectId == n) {
5441 +                               if (i && ylist_entry(i, yaffs_Object,
5442 +                                               hashLink)->objectId == n) {
5443                                         found = 0;
5444                                 }
5445                         }
5446                 }
5447         }
5448  
5449 -
5450         return n;
5451  }
5452  
5453 -static void yaffs_HashObject(yaffs_Object * in)
5454 +static void yaffs_HashObject(yaffs_Object *in)
5455  {
5456         int bucket = yaffs_HashFunction(in->objectId);
5457         yaffs_Device *dev = in->myDev;
5458  
5459 -       list_add(&in->hashLink, &dev->objectBucket[bucket].list);
5460 +       ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
5461         dev->objectBucket[bucket].count++;
5462 -
5463  }
5464  
5465 -yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
5466 +yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
5467  {
5468         int bucket = yaffs_HashFunction(number);
5469 -       struct list_head *i;
5470 +       struct ylist_head *i;
5471         yaffs_Object *in;
5472  
5473 -       list_for_each(i, &dev->objectBucket[bucket].list) {
5474 +       ylist_for_each(i, &dev->objectBucket[bucket].list) {
5475                 /* Look if it is in the list */
5476                 if (i) {
5477 -                       in = list_entry(i, yaffs_Object, hashLink);
5478 +                       in = ylist_entry(i, yaffs_Object, hashLink);
5479                         if (in->objectId == number) {
5480  #ifdef __KERNEL__
5481                                 /* Don't tell the VFS about this one if it is defered free */
5482 @@ -2118,31 +2155,27 @@ yaffs_Object *yaffs_FindObjectByNumber(y
5483         return NULL;
5484  }
5485  
5486 -yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
5487 +yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
5488                                     yaffs_ObjectType type)
5489  {
5490 -
5491         yaffs_Object *theObject;
5492 -       yaffs_Tnode *tn;
5493 +       yaffs_Tnode *tn = NULL;
5494  
5495 -       if (number < 0) {
5496 +       if (number < 0)
5497                 number = yaffs_CreateNewObjectNumber(dev);
5498 -       }
5499  
5500         theObject = yaffs_AllocateEmptyObject(dev);
5501 -       if(!theObject)
5502 +       if (!theObject)
5503                 return NULL;
5504  
5505 -       if(type == YAFFS_OBJECT_TYPE_FILE){
5506 +       if (type == YAFFS_OBJECT_TYPE_FILE) {
5507                 tn = yaffs_GetTnode(dev);
5508 -               if(!tn){
5509 +               if (!tn) {
5510                         yaffs_FreeObject(theObject);
5511                         return NULL;
5512                 }
5513         }
5514  
5515 -
5516 -
5517         if (theObject) {
5518                 theObject->fake = 0;
5519                 theObject->renameAllowed = 1;
5520 @@ -2171,8 +2204,8 @@ yaffs_Object *yaffs_CreateNewObject(yaff
5521                         theObject->variant.fileVariant.top = tn;
5522                         break;
5523                 case YAFFS_OBJECT_TYPE_DIRECTORY:
5524 -                       INIT_LIST_HEAD(&theObject->variant.directoryVariant.
5525 -                                      children);
5526 +                       YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
5527 +                                       children);
5528                         break;
5529                 case YAFFS_OBJECT_TYPE_SYMLINK:
5530                 case YAFFS_OBJECT_TYPE_HARDLINK:
5531 @@ -2188,32 +2221,30 @@ yaffs_Object *yaffs_CreateNewObject(yaff
5532         return theObject;
5533  }
5534  
5535 -static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
5536 +static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
5537                                                       int number,
5538                                                       yaffs_ObjectType type)
5539  {
5540         yaffs_Object *theObject = NULL;
5541  
5542 -       if (number > 0) {
5543 +       if (number > 0)
5544                 theObject = yaffs_FindObjectByNumber(dev, number);
5545 -       }
5546  
5547 -       if (!theObject) {
5548 +       if (!theObject)
5549                 theObject = yaffs_CreateNewObject(dev, number, type);
5550 -       }
5551  
5552         return theObject;
5553  
5554  }
5555  
5556  
5557 -static YCHAR *yaffs_CloneString(const YCHAR * str)
5558 +static YCHAR *yaffs_CloneString(const YCHAR *str)
5559  {
5560         YCHAR *newStr = NULL;
5561  
5562         if (str && *str) {
5563                 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
5564 -               if(newStr)
5565 +               if (newStr)
5566                         yaffs_strcpy(newStr, str);
5567         }
5568  
5569 @@ -2229,29 +2260,31 @@ static YCHAR *yaffs_CloneString(const YC
5570   */
5571  
5572  static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
5573 -                                      yaffs_Object * parent,
5574 -                                      const YCHAR * name,
5575 +                                      yaffs_Object *parent,
5576 +                                      const YCHAR *name,
5577                                        __u32 mode,
5578                                        __u32 uid,
5579                                        __u32 gid,
5580 -                                      yaffs_Object * equivalentObject,
5581 -                                      const YCHAR * aliasString, __u32 rdev)
5582 +                                      yaffs_Object *equivalentObject,
5583 +                                      const YCHAR *aliasString, __u32 rdev)
5584  {
5585         yaffs_Object *in;
5586 -       YCHAR *str;
5587 +       YCHAR *str = NULL;
5588  
5589         yaffs_Device *dev = parent->myDev;
5590  
5591         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
5592 -       if (yaffs_FindObjectByName(parent, name)) {
5593 +       if (yaffs_FindObjectByName(parent, name))
5594                 return NULL;
5595 -       }
5596  
5597         in = yaffs_CreateNewObject(dev, -1, type);
5598  
5599 -       if(type == YAFFS_OBJECT_TYPE_SYMLINK){
5600 +       if (!in)
5601 +               return YAFFS_FAIL;
5602 +
5603 +       if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
5604                 str = yaffs_CloneString(aliasString);
5605 -               if(!str){
5606 +               if (!str) {
5607                         yaffs_FreeObject(in);
5608                         return NULL;
5609                 }
5610 @@ -2260,7 +2293,7 @@ static yaffs_Object *yaffs_MknodObject(y
5611  
5612  
5613         if (in) {
5614 -               in->chunkId = -1;
5615 +               in->hdrChunk = 0;
5616                 in->valid = 1;
5617                 in->variantType = type;
5618  
5619 @@ -2293,10 +2326,10 @@ static yaffs_Object *yaffs_MknodObject(y
5620                         break;
5621                 case YAFFS_OBJECT_TYPE_HARDLINK:
5622                         in->variant.hardLinkVariant.equivalentObject =
5623 -                           equivalentObject;
5624 +                               equivalentObject;
5625                         in->variant.hardLinkVariant.equivalentObjectId =
5626 -                           equivalentObject->objectId;
5627 -                       list_add(&in->hardLinks, &equivalentObject->hardLinks);
5628 +                               equivalentObject->objectId;
5629 +                       ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
5630                         break;
5631                 case YAFFS_OBJECT_TYPE_FILE:
5632                 case YAFFS_OBJECT_TYPE_DIRECTORY:
5633 @@ -2308,7 +2341,7 @@ static yaffs_Object *yaffs_MknodObject(y
5634  
5635                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
5636                         /* Could not create the object header, fail the creation */
5637 -                       yaffs_DestroyObject(in);
5638 +                       yaffs_DeleteObject(in);
5639                         in = NULL;
5640                 }
5641  
5642 @@ -2317,38 +2350,38 @@ static yaffs_Object *yaffs_MknodObject(y
5643         return in;
5644  }
5645  
5646 -yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
5647 -                             __u32 mode, __u32 uid, __u32 gid)
5648 +yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
5649 +                       __u32 mode, __u32 uid, __u32 gid)
5650  {
5651         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
5652 -                                uid, gid, NULL, NULL, 0);
5653 +                               uid, gid, NULL, NULL, 0);
5654  }
5655  
5656 -yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
5657 -                                  __u32 mode, __u32 uid, __u32 gid)
5658 +yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
5659 +                               __u32 mode, __u32 uid, __u32 gid)
5660  {
5661         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
5662                                  mode, uid, gid, NULL, NULL, 0);
5663  }
5664  
5665 -yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
5666 -                                __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
5667 +yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
5668 +                               __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
5669  {
5670         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
5671                                  uid, gid, NULL, NULL, rdev);
5672  }
5673  
5674 -yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
5675 -                                __u32 mode, __u32 uid, __u32 gid,
5676 -                                const YCHAR * alias)
5677 +yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
5678 +                               __u32 mode, __u32 uid, __u32 gid,
5679 +                               const YCHAR *alias)
5680  {
5681         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
5682 -                                uid, gid, NULL, alias, 0);
5683 +                               uid, gid, NULL, alias, 0);
5684  }
5685  
5686  /* yaffs_Link returns the object id of the equivalent object.*/
5687 -yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
5688 -                        yaffs_Object * equivalentObject)
5689 +yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
5690 +                       yaffs_Object *equivalentObject)
5691  {
5692         /* Get the real object in case we were fed a hard link as an equivalent object */
5693         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
5694 @@ -2363,33 +2396,31 @@ yaffs_Object *yaffs_Link(yaffs_Object *
5695  
5696  }
5697  
5698 -static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
5699 -                                 const YCHAR * newName, int force, int shadows)
5700 +static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
5701 +                               const YCHAR *newName, int force, int shadows)
5702  {
5703         int unlinkOp;
5704         int deleteOp;
5705  
5706         yaffs_Object *existingTarget;
5707  
5708 -       if (newDir == NULL) {
5709 +       if (newDir == NULL)
5710                 newDir = obj->parent;   /* use the old directory */
5711 -       }
5712  
5713         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5714                 T(YAFFS_TRACE_ALWAYS,
5715                   (TSTR
5716 -                  ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
5717 +                  ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
5718                     TENDSTR)));
5719                 YBUG();
5720         }
5721  
5722         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
5723 -       if (obj->myDev->isYaffs2) {
5724 +       if (obj->myDev->isYaffs2)
5725                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
5726 -       } else {
5727 +       else
5728                 unlinkOp = (newDir == obj->myDev->unlinkedDir
5729                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
5730 -       }
5731  
5732         deleteOp = (newDir == obj->myDev->deletedDir);
5733  
5734 @@ -2415,40 +2446,40 @@ static int yaffs_ChangeObjectName(yaffs_
5735                         obj->unlinked = 1;
5736  
5737                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
5738 -               if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
5739 +               if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
5740                         return YAFFS_OK;
5741         }
5742  
5743         return YAFFS_FAIL;
5744  }
5745  
5746 -int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
5747 -                      yaffs_Object * newDir, const YCHAR * newName)
5748 +int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
5749 +               yaffs_Object *newDir, const YCHAR *newName)
5750  {
5751 -       yaffs_Object *obj;
5752 -       yaffs_Object *existingTarget;
5753 +       yaffs_Object *obj = NULL;
5754 +       yaffs_Object *existingTarget = NULL;
5755         int force = 0;
5756  
5757 +
5758 +       if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5759 +               YBUG();
5760 +       if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5761 +               YBUG();
5762 +
5763  #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
5764         /* Special case for case insemsitive systems (eg. WinCE).
5765          * While look-up is case insensitive, the name isn't.
5766          * Therefore we might want to change x.txt to X.txt
5767         */
5768 -       if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
5769 +       if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
5770                 force = 1;
5771 -       }
5772  #endif
5773  
5774 +       else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
5775 +               /* ENAMETOOLONG */
5776 +               return YAFFS_FAIL;
5777 +
5778         obj = yaffs_FindObjectByName(oldDir, oldName);
5779 -       /* Check new name to long. */
5780 -       if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
5781 -           yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
5782 -         /* ENAMETOOLONG */
5783 -         return YAFFS_FAIL;
5784 -       else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
5785 -                yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
5786 -         /* ENAMETOOLONG */
5787 -         return YAFFS_FAIL;
5788  
5789         if (obj && obj->renameAllowed) {
5790  
5791 @@ -2456,8 +2487,8 @@ int yaffs_RenameObject(yaffs_Object * ol
5792  
5793                 existingTarget = yaffs_FindObjectByName(newDir, newName);
5794                 if (existingTarget &&
5795 -                   existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5796 -                   !list_empty(&existingTarget->variant.directoryVariant.children)) {
5797 +                       existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5798 +                       !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
5799                         /* There is a target that is a non-empty directory, so we fail */
5800                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
5801                 } else if (existingTarget && existingTarget != obj) {
5802 @@ -2465,7 +2496,7 @@ int yaffs_RenameObject(yaffs_Object * ol
5803                          * but only if it isn't the same object
5804                          */
5805                         yaffs_ChangeObjectName(obj, newDir, newName, force,
5806 -                                              existingTarget->objectId);
5807 +                                               existingTarget->objectId);
5808                         yaffs_UnlinkObject(existingTarget);
5809                 }
5810  
5811 @@ -2476,7 +2507,7 @@ int yaffs_RenameObject(yaffs_Object * ol
5812  
5813  /*------------------------- Block Management and Page Allocation ----------------*/
5814  
5815 -static int yaffs_InitialiseBlocks(yaffs_Device * dev)
5816 +static int yaffs_InitialiseBlocks(yaffs_Device *dev)
5817  {
5818         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5819  
5820 @@ -2487,23 +2518,20 @@ static int yaffs_InitialiseBlocks(yaffs_
5821  
5822         /* If the first allocation strategy fails, thry the alternate one */
5823         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
5824 -       if(!dev->blockInfo){
5825 +       if (!dev->blockInfo) {
5826                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
5827                 dev->blockInfoAlt = 1;
5828 -       }
5829 -       else
5830 +       } else
5831                 dev->blockInfoAlt = 0;
5832  
5833 -       if(dev->blockInfo){
5834 -
5835 +       if (dev->blockInfo) {
5836                 /* Set up dynamic blockinfo stuff. */
5837                 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
5838                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
5839 -               if(!dev->chunkBits){
5840 +               if (!dev->chunkBits) {
5841                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
5842                         dev->chunkBitsAlt = 1;
5843 -               }
5844 -               else
5845 +               } else
5846                         dev->chunkBitsAlt = 0;
5847         }
5848  
5849 @@ -2514,30 +2542,29 @@ static int yaffs_InitialiseBlocks(yaffs_
5850         }
5851  
5852         return YAFFS_FAIL;
5853 -
5854  }
5855  
5856 -static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
5857 +static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
5858  {
5859 -       if(dev->blockInfoAlt && dev->blockInfo)
5860 +       if (dev->blockInfoAlt && dev->blockInfo)
5861                 YFREE_ALT(dev->blockInfo);
5862 -       else if(dev->blockInfo)
5863 +       else if (dev->blockInfo)
5864                 YFREE(dev->blockInfo);
5865  
5866         dev->blockInfoAlt = 0;
5867  
5868         dev->blockInfo = NULL;
5869  
5870 -       if(dev->chunkBitsAlt && dev->chunkBits)
5871 +       if (dev->chunkBitsAlt && dev->chunkBits)
5872                 YFREE_ALT(dev->chunkBits);
5873 -       else if(dev->chunkBits)
5874 +       else if (dev->chunkBits)
5875                 YFREE(dev->chunkBits);
5876         dev->chunkBitsAlt = 0;
5877         dev->chunkBits = NULL;
5878  }
5879  
5880 -static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
5881 -                                           yaffs_BlockInfo * bi)
5882 +static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
5883 +                                       yaffs_BlockInfo *bi)
5884  {
5885         int i;
5886         __u32 seq;
5887 @@ -2556,7 +2583,7 @@ static int yaffs_BlockNotDisqualifiedFro
5888                 seq = dev->sequenceNumber;
5889  
5890                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
5891 -                    i++) {
5892 +                               i++) {
5893                         b = yaffs_GetBlockInfo(dev, i);
5894                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
5895                             (b->pagesInUse - b->softDeletions) <
5896 @@ -2571,38 +2598,36 @@ static int yaffs_BlockNotDisqualifiedFro
5897          * discarded pages.
5898          */
5899         return (bi->sequenceNumber <= dev->oldestDirtySequence);
5900 -
5901  }
5902  
5903  /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
5904   * for garbage collection.
5905   */
5906  
5907 -static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
5908 -                                              int aggressive)
5909 +static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
5910 +                                       int aggressive)
5911  {
5912 -
5913         int b = dev->currentDirtyChecker;
5914  
5915         int i;
5916         int iterations;
5917         int dirtiest = -1;
5918         int pagesInUse = 0;
5919 -       int prioritised=0;
5920 +       int prioritised = 0;
5921         yaffs_BlockInfo *bi;
5922         int pendingPrioritisedExist = 0;
5923  
5924         /* First let's see if we need to grab a prioritised block */
5925 -       if(dev->hasPendingPrioritisedGCs){
5926 -               for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
5927 +       if (dev->hasPendingPrioritisedGCs) {
5928 +               for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
5929  
5930                         bi = yaffs_GetBlockInfo(dev, i);
5931 -                       //yaffs_VerifyBlock(dev,bi,i);
5932 +                       /* yaffs_VerifyBlock(dev,bi,i); */
5933  
5934 -                       if(bi->gcPrioritise) {
5935 +                       if (bi->gcPrioritise) {
5936                                 pendingPrioritisedExist = 1;
5937 -                               if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
5938 -                                  yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
5939 +                               if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
5940 +                                  yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
5941                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
5942                                         dirtiest = i;
5943                                         prioritised = 1;
5944 @@ -2611,7 +2636,7 @@ static int yaffs_FindBlockForGarbageColl
5945                         }
5946                 }
5947  
5948 -               if(!pendingPrioritisedExist) /* None found, so we can clear this */
5949 +               if (!pendingPrioritisedExist) /* None found, so we can clear this */
5950                         dev->hasPendingPrioritisedGCs = 0;
5951         }
5952  
5953 @@ -2623,31 +2648,28 @@ static int yaffs_FindBlockForGarbageColl
5954  
5955         dev->nonAggressiveSkip--;
5956  
5957 -       if (!aggressive && (dev->nonAggressiveSkip > 0)) {
5958 +       if (!aggressive && (dev->nonAggressiveSkip > 0))
5959                 return -1;
5960 -       }
5961  
5962 -       if(!prioritised)
5963 +       if (!prioritised)
5964                 pagesInUse =
5965 -                       (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
5966 +                       (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
5967  
5968 -       if (aggressive) {
5969 +       if (aggressive)
5970                 iterations =
5971                     dev->internalEndBlock - dev->internalStartBlock + 1;
5972 -       } else {
5973 +       else {
5974                 iterations =
5975                     dev->internalEndBlock - dev->internalStartBlock + 1;
5976                 iterations = iterations / 16;
5977 -               if (iterations > 200) {
5978 +               if (iterations > 200)
5979                         iterations = 200;
5980 -               }
5981         }
5982  
5983         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
5984                 b++;
5985 -               if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
5986 +               if (b < dev->internalStartBlock || b > dev->internalEndBlock)
5987                         b = dev->internalStartBlock;
5988 -               }
5989  
5990                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
5991                         T(YAFFS_TRACE_ERROR,
5992 @@ -2657,17 +2679,9 @@ static int yaffs_FindBlockForGarbageColl
5993  
5994                 bi = yaffs_GetBlockInfo(dev, b);
5995  
5996 -#if 0
5997 -               if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
5998 -                       dirtiest = b;
5999 -                       pagesInUse = 0;
6000 -               }
6001 -               else
6002 -#endif
6003 -
6004                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
6005 -                      (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
6006 -                       yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
6007 +                       (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
6008 +                               yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
6009                         dirtiest = b;
6010                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
6011                 }
6012 @@ -2678,19 +2692,18 @@ static int yaffs_FindBlockForGarbageColl
6013         if (dirtiest > 0) {
6014                 T(YAFFS_TRACE_GC,
6015                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
6016 -                  dev->nChunksPerBlock - pagesInUse,prioritised));
6017 +                  dev->nChunksPerBlock - pagesInUse, prioritised));
6018         }
6019  
6020         dev->oldestDirtySequence = 0;
6021  
6022 -       if (dirtiest > 0) {
6023 +       if (dirtiest > 0)
6024                 dev->nonAggressiveSkip = 4;
6025 -       }
6026  
6027         return dirtiest;
6028  }
6029  
6030 -static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
6031 +static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
6032  {
6033         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
6034  
6035 @@ -2752,7 +2765,7 @@ static void yaffs_BlockBecameDirty(yaffs
6036         }
6037  }
6038  
6039 -static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
6040 +static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
6041  {
6042         int i;
6043  
6044 @@ -2763,7 +2776,7 @@ static int yaffs_FindBlockForAllocation(
6045                  * Can't get space to gc
6046                  */
6047                 T(YAFFS_TRACE_ERROR,
6048 -                 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
6049 +                 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
6050  
6051                 return -1;
6052         }
6053 @@ -2794,31 +2807,74 @@ static int yaffs_FindBlockForAllocation(
6054  
6055         T(YAFFS_TRACE_ALWAYS,
6056           (TSTR
6057 -          ("yaffs tragedy: no more eraased blocks, but there should have been %d"
6058 +          ("yaffs tragedy: no more erased blocks, but there should have been %d"
6059             TENDSTR), dev->nErasedBlocks));
6060  
6061         return -1;
6062  }
6063  
6064  
6065 -// Check if there's space to allocate...
6066 -// Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
6067 -static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
6068 +
6069 +static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
6070 +{
6071 +       if (!dev->nCheckpointBlocksRequired &&
6072 +          dev->isYaffs2) {
6073 +               /* Not a valid value so recalculate */
6074 +               int nBytes = 0;
6075 +               int nBlocks;
6076 +               int devBlocks = (dev->endBlock - dev->startBlock + 1);
6077 +               int tnodeSize;
6078 +
6079 +               tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
6080 +
6081 +               if (tnodeSize < sizeof(yaffs_Tnode))
6082 +                       tnodeSize = sizeof(yaffs_Tnode);
6083 +
6084 +               nBytes += sizeof(yaffs_CheckpointValidity);
6085 +               nBytes += sizeof(yaffs_CheckpointDevice);
6086 +               nBytes += devBlocks * sizeof(yaffs_BlockInfo);
6087 +               nBytes += devBlocks * dev->chunkBitmapStride;
6088 +               nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
6089 +               nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
6090 +               nBytes += sizeof(yaffs_CheckpointValidity);
6091 +               nBytes += sizeof(__u32); /* checksum*/
6092 +
6093 +               /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
6094 +
6095 +               nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
6096 +
6097 +               dev->nCheckpointBlocksRequired = nBlocks;
6098 +       }
6099 +
6100 +       return dev->nCheckpointBlocksRequired;
6101 +}
6102 +
6103 +/*
6104 + * Check if there's space to allocate...
6105 + * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
6106 + */
6107 +static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
6108  {
6109         int reservedChunks;
6110         int reservedBlocks = dev->nReservedBlocks;
6111         int checkpointBlocks;
6112  
6113 -       checkpointBlocks =  dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6114 -       if(checkpointBlocks < 0)
6115 +       if (dev->isYaffs2) {
6116 +               checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) -
6117 +                                   dev->blocksInCheckpoint;
6118 +               if (checkpointBlocks < 0)
6119 +                       checkpointBlocks = 0;
6120 +       } else {
6121                 checkpointBlocks = 0;
6122 +       }
6123  
6124         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
6125  
6126         return (dev->nFreeChunks > reservedChunks);
6127  }
6128  
6129 -static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
6130 +static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
6131 +               yaffs_BlockInfo **blockUsedPtr)
6132  {
6133         int retVal;
6134         yaffs_BlockInfo *bi;
6135 @@ -2835,7 +2891,7 @@ static int yaffs_AllocateChunk(yaffs_Dev
6136         }
6137  
6138         if (dev->nErasedBlocks < dev->nReservedBlocks
6139 -           && dev->allocationPage == 0) {
6140 +                       && dev->allocationPage == 0) {
6141                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
6142         }
6143  
6144 @@ -2844,10 +2900,10 @@ static int yaffs_AllocateChunk(yaffs_Dev
6145                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
6146  
6147                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
6148 -                   dev->allocationPage;
6149 +                       dev->allocationPage;
6150                 bi->pagesInUse++;
6151                 yaffs_SetChunkBit(dev, dev->allocationBlock,
6152 -                                 dev->allocationPage);
6153 +                               dev->allocationPage);
6154  
6155                 dev->allocationPage++;
6156  
6157 @@ -2859,43 +2915,43 @@ static int yaffs_AllocateChunk(yaffs_Dev
6158                         dev->allocationBlock = -1;
6159                 }
6160  
6161 -               if(blockUsedPtr)
6162 +               if (blockUsedPtr)
6163                         *blockUsedPtr = bi;
6164  
6165                 return retVal;
6166         }
6167  
6168         T(YAFFS_TRACE_ERROR,
6169 -         (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
6170 +                       (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
6171  
6172         return -1;
6173  }
6174  
6175 -static int yaffs_GetErasedChunks(yaffs_Device * dev)
6176 +static int yaffs_GetErasedChunks(yaffs_Device *dev)
6177  {
6178         int n;
6179  
6180         n = dev->nErasedBlocks * dev->nChunksPerBlock;
6181  
6182 -       if (dev->allocationBlock > 0) {
6183 +       if (dev->allocationBlock > 0)
6184                 n += (dev->nChunksPerBlock - dev->allocationPage);
6185 -       }
6186  
6187         return n;
6188  
6189  }
6190  
6191 -static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
6192 +static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
6193 +               int wholeBlock)
6194  {
6195         int oldChunk;
6196         int newChunk;
6197 -       int chunkInBlock;
6198         int markNAND;
6199         int retVal = YAFFS_OK;
6200         int cleanups = 0;
6201         int i;
6202         int isCheckpointBlock;
6203         int matchingChunk;
6204 +       int maxCopies;
6205  
6206         int chunksBefore = yaffs_GetErasedChunks(dev);
6207         int chunksAfter;
6208 @@ -2911,8 +2967,11 @@ static int yaffs_GarbageCollectBlock(yaf
6209         bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
6210  
6211         T(YAFFS_TRACE_TRACING,
6212 -         (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
6213 -          bi->pagesInUse, bi->hasShrinkHeader));
6214 +                       (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
6215 +                        block,
6216 +                        bi->pagesInUse,
6217 +                        bi->hasShrinkHeader,
6218 +                        wholeBlock));
6219  
6220         /*yaffs_VerifyFreeChunks(dev); */
6221  
6222 @@ -2926,26 +2985,33 @@ static int yaffs_GarbageCollectBlock(yaf
6223         dev->isDoingGC = 1;
6224  
6225         if (isCheckpointBlock ||
6226 -           !yaffs_StillSomeChunkBits(dev, block)) {
6227 +                       !yaffs_StillSomeChunkBits(dev, block)) {
6228                 T(YAFFS_TRACE_TRACING,
6229 -                 (TSTR
6230 -                  ("Collecting block %d that has no chunks in use" TENDSTR),
6231 -                  block));
6232 +                               (TSTR
6233 +                                ("Collecting block %d that has no chunks in use" TENDSTR),
6234 +                                block));
6235                 yaffs_BlockBecameDirty(dev, block);
6236         } else {
6237  
6238                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
6239  
6240 -               yaffs_VerifyBlock(dev,bi,block);
6241 +               yaffs_VerifyBlock(dev, bi, block);
6242  
6243 -               for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
6244 -                    chunkInBlock < dev->nChunksPerBlock
6245 -                    && yaffs_StillSomeChunkBits(dev, block);
6246 -                    chunkInBlock++, oldChunk++) {
6247 -                       if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
6248 +               maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
6249 +               oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
6250 +
6251 +               for (/* init already done */;
6252 +                    retVal == YAFFS_OK &&
6253 +                    dev->gcChunk < dev->nChunksPerBlock &&
6254 +                    (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
6255 +                    maxCopies > 0;
6256 +                    dev->gcChunk++, oldChunk++) {
6257 +                       if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
6258  
6259                                 /* This page is in use and might need to be copied off */
6260  
6261 +                               maxCopies--;
6262 +
6263                                 markNAND = 1;
6264  
6265                                 yaffs_InitialiseTags(&tags);
6266 @@ -2959,22 +3025,22 @@ static int yaffs_GarbageCollectBlock(yaf
6267  
6268                                 T(YAFFS_TRACE_GC_DETAIL,
6269                                   (TSTR
6270 -                                  ("Collecting page %d, %d %d %d " TENDSTR),
6271 -                                  chunkInBlock, tags.objectId, tags.chunkId,
6272 +                                  ("Collecting chunk in block %d, %d %d %d " TENDSTR),
6273 +                                  dev->gcChunk, tags.objectId, tags.chunkId,
6274                                    tags.byteCount));
6275  
6276 -                               if(object && !yaffs_SkipVerification(dev)){
6277 -                                       if(tags.chunkId == 0)
6278 -                                               matchingChunk = object->chunkId;
6279 -                                       else if(object->softDeleted)
6280 +                               if (object && !yaffs_SkipVerification(dev)) {
6281 +                                       if (tags.chunkId == 0)
6282 +                                               matchingChunk = object->hdrChunk;
6283 +                                       else if (object->softDeleted)
6284                                                 matchingChunk = oldChunk; /* Defeat the test */
6285                                         else
6286 -                                               matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
6287 +                                               matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
6288  
6289 -                                       if(oldChunk != matchingChunk)
6290 +                                       if (oldChunk != matchingChunk)
6291                                                 T(YAFFS_TRACE_ERROR,
6292                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
6293 -                                                 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
6294 +                                                 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
6295  
6296                                 }
6297  
6298 @@ -2986,9 +3052,11 @@ static int yaffs_GarbageCollectBlock(yaf
6299                                             tags.objectId, tags.chunkId, tags.byteCount));
6300                                 }
6301  
6302 -                               if (object && object->deleted
6303 -                                   && tags.chunkId != 0) {
6304 -                                       /* Data chunk in a deleted file, throw it away
6305 +                               if (object &&
6306 +                                   object->deleted &&
6307 +                                   object->softDeleted &&
6308 +                                   tags.chunkId != 0) {
6309 +                                       /* Data chunk in a soft deleted file, throw it away
6310                                          * It's a soft deleted data chunk,
6311                                          * No need to copy this, just forget about it and
6312                                          * fix up the object.
6313 @@ -3003,13 +3071,12 @@ static int yaffs_GarbageCollectBlock(yaf
6314                                                 cleanups++;
6315                                         }
6316                                         markNAND = 0;
6317 -                               } else if (0
6318 -                                          /* Todo object && object->deleted && object->nDataChunks == 0 */
6319 -                                          ) {
6320 +                               } else if (0) {
6321 +                                       /* Todo object && object->deleted && object->nDataChunks == 0 */
6322                                         /* Deleted object header with no data chunks.
6323                                          * Can be discarded and the file deleted.
6324                                          */
6325 -                                       object->chunkId = 0;
6326 +                                       object->hdrChunk = 0;
6327                                         yaffs_FreeTnode(object->myDev,
6328                                                         object->variant.
6329                                                         fileVariant.top);
6330 @@ -3031,17 +3098,14 @@ static int yaffs_GarbageCollectBlock(yaf
6331                                                  * We need to nuke the shrinkheader flags first
6332                                                  * We no longer want the shrinkHeader flag since its work is done
6333                                                  * and if it is left in place it will mess up scanning.
6334 -                                                * Also, clear out any shadowing stuff
6335                                                  */
6336  
6337                                                 yaffs_ObjectHeader *oh;
6338                                                 oh = (yaffs_ObjectHeader *)buffer;
6339                                                 oh->isShrink = 0;
6340 -                                               oh->shadowsObject = -1;
6341 -                                               tags.extraShadows = 0;
6342                                                 tags.extraIsShrinkHeader = 0;
6343  
6344 -                                               yaffs_VerifyObjectHeader(object,oh,&tags,1);
6345 +                                               yaffs_VerifyObjectHeader(object, oh, &tags, 1);
6346                                         }
6347  
6348                                         newChunk =
6349 @@ -3055,7 +3119,7 @@ static int yaffs_GarbageCollectBlock(yaf
6350  
6351                                                 if (tags.chunkId == 0) {
6352                                                         /* It's a header */
6353 -                                                       object->chunkId =  newChunk;
6354 +                                                       object->hdrChunk =  newChunk;
6355                                                         object->serial =   tags.serialNumber;
6356                                                 } else {
6357                                                         /* It's a data chunk */
6358 @@ -3067,7 +3131,8 @@ static int yaffs_GarbageCollectBlock(yaf
6359                                         }
6360                                 }
6361  
6362 -                               yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
6363 +                               if (retVal == YAFFS_OK)
6364 +                                       yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
6365  
6366                         }
6367                 }
6368 @@ -3098,18 +3163,25 @@ static int yaffs_GarbageCollectBlock(yaf
6369  
6370         }
6371  
6372 -       yaffs_VerifyCollectedBlock(dev,bi,block);
6373 +       yaffs_VerifyCollectedBlock(dev, bi, block);
6374  
6375 -       if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
6376 +       chunksAfter = yaffs_GetErasedChunks(dev);
6377 +       if (chunksBefore >= chunksAfter) {
6378                 T(YAFFS_TRACE_GC,
6379                   (TSTR
6380                    ("gc did not increase free chunks before %d after %d"
6381                     TENDSTR), chunksBefore, chunksAfter));
6382         }
6383  
6384 +       /* If the gc completed then clear the current gcBlock so that we find another. */
6385 +       if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
6386 +               dev->gcBlock = -1;
6387 +               dev->gcChunk = 0;
6388 +       }
6389 +
6390         dev->isDoingGC = 0;
6391  
6392 -       return YAFFS_OK;
6393 +       return retVal;
6394  }
6395  
6396  /* New garbage collector
6397 @@ -3121,7 +3193,7 @@ static int yaffs_GarbageCollectBlock(yaf
6398   * The idea is to help clear out space in a more spread-out manner.
6399   * Dunno if it really does anything useful.
6400   */
6401 -static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
6402 +static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
6403  {
6404         int block;
6405         int aggressive;
6406 @@ -3142,8 +3214,8 @@ static int yaffs_CheckGarbageCollection(
6407         do {
6408                 maxTries++;
6409  
6410 -               checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
6411 -               if(checkpointBlockAdjust < 0)
6412 +               checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
6413 +               if (checkpointBlockAdjust < 0)
6414                         checkpointBlockAdjust = 0;
6415  
6416                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
6417 @@ -3154,20 +3226,24 @@ static int yaffs_CheckGarbageCollection(
6418                         aggressive = 0;
6419                 }
6420  
6421 -               block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
6422 +               if (dev->gcBlock <= 0) {
6423 +                       dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
6424 +                       dev->gcChunk = 0;
6425 +               }
6426 +
6427 +               block = dev->gcBlock;
6428  
6429                 if (block > 0) {
6430                         dev->garbageCollections++;
6431 -                       if (!aggressive) {
6432 +                       if (!aggressive)
6433                                 dev->passiveGarbageCollections++;
6434 -                       }
6435  
6436                         T(YAFFS_TRACE_GC,
6437                           (TSTR
6438                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
6439                            dev->nErasedBlocks, aggressive));
6440  
6441 -                       gcOk = yaffs_GarbageCollectBlock(dev, block);
6442 +                       gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
6443                 }
6444  
6445                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
6446 @@ -3176,15 +3252,16 @@ static int yaffs_CheckGarbageCollection(
6447                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
6448                             TENDSTR), dev->nErasedBlocks, maxTries, block));
6449                 }
6450 -       } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
6451 -                && (maxTries < 2));
6452 +       } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
6453 +                (block > 0) &&
6454 +                (maxTries < 2));
6455  
6456         return aggressive ? gcOk : YAFFS_OK;
6457  }
6458  
6459  /*-------------------------  TAGS --------------------------------*/
6460  
6461 -static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
6462 +static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
6463                            int chunkInObject)
6464  {
6465         return (tags->chunkId == chunkInObject &&
6466 @@ -3195,8 +3272,8 @@ static int yaffs_TagsMatch(const yaffs_E
6467  
6468  /*-------------------- Data file manipulation -----------------*/
6469  
6470 -static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
6471 -                                yaffs_ExtendedTags * tags)
6472 +static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
6473 +                                yaffs_ExtendedTags *tags)
6474  {
6475         /*Get the Tnode, then get the level 0 offset chunk offset */
6476         yaffs_Tnode *tn;
6477 @@ -3214,7 +3291,7 @@ static int yaffs_FindChunkInFile(yaffs_O
6478         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
6479  
6480         if (tn) {
6481 -               theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
6482 +               theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
6483  
6484                 retVal =
6485                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
6486 @@ -3223,8 +3300,8 @@ static int yaffs_FindChunkInFile(yaffs_O
6487         return retVal;
6488  }
6489  
6490 -static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
6491 -                                         yaffs_ExtendedTags * tags)
6492 +static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
6493 +                                         yaffs_ExtendedTags *tags)
6494  {
6495         /* Get the Tnode, then get the level 0 offset chunk offset */
6496         yaffs_Tnode *tn;
6497 @@ -3243,29 +3320,23 @@ static int yaffs_FindAndDeleteChunkInFil
6498  
6499         if (tn) {
6500  
6501 -               theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
6502 +               theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
6503  
6504                 retVal =
6505                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
6506                                            chunkInInode);
6507  
6508                 /* Delete the entry in the filestructure (if found) */
6509 -               if (retVal != -1) {
6510 -                       yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
6511 -               }
6512 -       } else {
6513 -               /*T(("No level 0 found for %d\n", chunkInInode)); */
6514 +               if (retVal != -1)
6515 +                       yaffs_PutLevel0Tnode(dev, tn, chunkInInode, 0);
6516         }
6517  
6518 -       if (retVal == -1) {
6519 -               /* T(("Could not find %d to delete\n",chunkInInode)); */
6520 -       }
6521         return retVal;
6522  }
6523  
6524  #ifdef YAFFS_PARANOID
6525  
6526 -static int yaffs_CheckFileSanity(yaffs_Object * in)
6527 +static int yaffs_CheckFileSanity(yaffs_Object *in)
6528  {
6529         int chunk;
6530         int nChunks;
6531 @@ -3278,10 +3349,8 @@ static int yaffs_CheckFileSanity(yaffs_O
6532         int theChunk;
6533         int chunkDeleted;
6534  
6535 -       if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
6536 -               /* T(("Object not a file\n")); */
6537 +       if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
6538                 return YAFFS_FAIL;
6539 -       }
6540  
6541         objId = in->objectId;
6542         fSize = in->variant.fileVariant.fileSize;
6543 @@ -3294,7 +3363,7 @@ static int yaffs_CheckFileSanity(yaffs_O
6544  
6545                 if (tn) {
6546  
6547 -                       theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
6548 +                       theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
6549  
6550                         if (yaffs_CheckChunkBits
6551                             (dev, theChunk / dev->nChunksPerBlock,
6552 @@ -3323,7 +3392,7 @@ static int yaffs_CheckFileSanity(yaffs_O
6553  
6554  #endif
6555  
6556 -static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
6557 +static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
6558                                   int chunkInNAND, int inScan)
6559  {
6560         /* NB inScan is zero unless scanning.
6561 @@ -3358,11 +3427,10 @@ static int yaffs_PutChunkIntoFile(yaffs_
6562                                         &in->variant.fileVariant,
6563                                         chunkInInode,
6564                                         NULL);
6565 -       if (!tn) {
6566 +       if (!tn)
6567                 return YAFFS_FAIL;
6568 -       }
6569  
6570 -       existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
6571 +       existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
6572  
6573         if (inScan != 0) {
6574                 /* If we're scanning then we need to test for duplicates
6575 @@ -3374,7 +3442,7 @@ static int yaffs_PutChunkIntoFile(yaffs_
6576                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
6577                  */
6578  
6579 -               if (existingChunk != 0) {
6580 +               if (existingChunk > 0) {
6581                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
6582                          *    thus we have to do a FindChunkInFile to get the real chunk id.
6583                          *
6584 @@ -3411,8 +3479,10 @@ static int yaffs_PutChunkIntoFile(yaffs_
6585                          * not be loaded during a scan
6586                          */
6587  
6588 -                       newSerial = newTags.serialNumber;
6589 -                       existingSerial = existingTags.serialNumber;
6590 +                       if (inScan > 0) {
6591 +                               newSerial = newTags.serialNumber;
6592 +                               existingSerial = existingTags.serialNumber;
6593 +                       }
6594  
6595                         if ((inScan > 0) &&
6596                             (in->myDev->isYaffs2 ||
6597 @@ -3437,24 +3507,23 @@ static int yaffs_PutChunkIntoFile(yaffs_
6598  
6599         }
6600  
6601 -       if (existingChunk == 0) {
6602 +       if (existingChunk == 0)
6603                 in->nDataChunks++;
6604 -       }
6605  
6606 -       yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
6607 +       yaffs_PutLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
6608  
6609         return YAFFS_OK;
6610  }
6611  
6612 -static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
6613 -                                        __u8 * buffer)
6614 +static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
6615 +                                       __u8 *buffer)
6616  {
6617         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
6618  
6619 -       if (chunkInNAND >= 0) {
6620 +       if (chunkInNAND >= 0)
6621                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
6622 -                                                      buffer,NULL);
6623 -       } else {
6624 +                                               buffer, NULL);
6625 +       else {
6626                 T(YAFFS_TRACE_NANDACCESS,
6627                   (TSTR("Chunk %d not found zero instead" TENDSTR),
6628                    chunkInNAND));
6629 @@ -3465,7 +3534,7 @@ static int yaffs_ReadChunkDataFromObject
6630  
6631  }
6632  
6633 -void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
6634 +void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
6635  {
6636         int block;
6637         int page;
6638 @@ -3475,16 +3544,15 @@ void yaffs_DeleteChunk(yaffs_Device * de
6639         if (chunkId <= 0)
6640                 return;
6641  
6642 -
6643         dev->nDeletions++;
6644         block = chunkId / dev->nChunksPerBlock;
6645         page = chunkId % dev->nChunksPerBlock;
6646  
6647  
6648 -       if(!yaffs_CheckChunkBit(dev,block,page))
6649 +       if (!yaffs_CheckChunkBit(dev, block, page))
6650                 T(YAFFS_TRACE_VERIFY,
6651 -                       (TSTR("Deleting invalid chunk %d"TENDSTR),
6652 -                        chunkId));
6653 +                       (TSTR("Deleting invalid chunk %d"TENDSTR),
6654 +                        chunkId));
6655  
6656         bi = yaffs_GetBlockInfo(dev, block);
6657  
6658 @@ -3524,14 +3592,12 @@ void yaffs_DeleteChunk(yaffs_Device * de
6659                         yaffs_BlockBecameDirty(dev, block);
6660                 }
6661  
6662 -       } else {
6663 -               /* T(("Bad news deleting chunk %d\n",chunkId)); */
6664         }
6665  
6666  }
6667  
6668 -static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
6669 -                                       const __u8 * buffer, int nBytes,
6670 +static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
6671 +                                       const __u8 *buffer, int nBytes,
6672                                         int useReserve)
6673  {
6674         /* Find old chunk Need to do this to get serial number
6675 @@ -3561,6 +3627,12 @@ static int yaffs_WriteChunkDataToObject(
6676             (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
6677         newTags.byteCount = nBytes;
6678  
6679 +       if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
6680 +               T(YAFFS_TRACE_ERROR,
6681 +               (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
6682 +               YBUG();
6683 +       }
6684 +
6685         newChunkId =
6686             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
6687                                               useReserve);
6688 @@ -3568,11 +3640,9 @@ static int yaffs_WriteChunkDataToObject(
6689         if (newChunkId >= 0) {
6690                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
6691  
6692 -               if (prevChunkId >= 0) {
6693 +               if (prevChunkId >= 0)
6694                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
6695  
6696 -               }
6697 -
6698                 yaffs_CheckFileSanity(in);
6699         }
6700         return newChunkId;
6701 @@ -3582,7 +3652,7 @@ static int yaffs_WriteChunkDataToObject(
6702  /* UpdateObjectHeader updates the header on NAND for an object.
6703   * If name is not NULL, then that new name is used.
6704   */
6705 -int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
6706 +int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
6707                              int isShrink, int shadows)
6708  {
6709  
6710 @@ -3603,9 +3673,12 @@ int yaffs_UpdateObjectHeader(yaffs_Objec
6711  
6712         yaffs_ObjectHeader *oh = NULL;
6713  
6714 -       yaffs_strcpy(oldName,"silly old name");
6715 +       yaffs_strcpy(oldName, _Y("silly old name"));
6716  
6717 -       if (!in->fake || force) {
6718 +
6719 +       if (!in->fake ||
6720 +               in == dev->rootDir || /* The rootDir should also be saved */
6721 +               force) {
6722  
6723                 yaffs_CheckGarbageCollection(dev);
6724                 yaffs_CheckObjectDetailsLoaded(in);
6725 @@ -3613,13 +3686,13 @@ int yaffs_UpdateObjectHeader(yaffs_Objec
6726                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
6727                 oh = (yaffs_ObjectHeader *) buffer;
6728  
6729 -               prevChunkId = in->chunkId;
6730 +               prevChunkId = in->hdrChunk;
6731  
6732 -               if (prevChunkId >= 0) {
6733 +               if (prevChunkId > 0) {
6734                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
6735                                                         buffer, &oldTags);
6736  
6737 -                       yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
6738 +                       yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
6739  
6740                         memcpy(oldName, oh->name, sizeof(oh->name));
6741                 }
6742 @@ -3628,7 +3701,7 @@ int yaffs_UpdateObjectHeader(yaffs_Objec
6743  
6744                 oh->type = in->variantType;
6745                 oh->yst_mode = in->yst_mode;
6746 -               oh->shadowsObject = shadows;
6747 +               oh->shadowsObject = oh->inbandShadowsObject = shadows;
6748  
6749  #ifdef CONFIG_YAFFS_WINCE
6750                 oh->win_atime[0] = in->win_atime[0];
6751 @@ -3645,20 +3718,18 @@ int yaffs_UpdateObjectHeader(yaffs_Objec
6752                 oh->yst_ctime = in->yst_ctime;
6753                 oh->yst_rdev = in->yst_rdev;
6754  #endif
6755 -               if (in->parent) {
6756 +               if (in->parent)
6757                         oh->parentObjectId = in->parent->objectId;
6758 -               } else {
6759 +               else
6760                         oh->parentObjectId = 0;
6761 -               }
6762  
6763                 if (name && *name) {
6764                         memset(oh->name, 0, sizeof(oh->name));
6765                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
6766 -               } else if (prevChunkId>=0) {
6767 +               } else if (prevChunkId >= 0)
6768                         memcpy(oh->name, oldName, sizeof(oh->name));
6769 -               } else {
6770 +               else
6771                         memset(oh->name, 0, sizeof(oh->name));
6772 -               }
6773  
6774                 oh->isShrink = isShrink;
6775  
6776 @@ -3708,7 +3779,7 @@ int yaffs_UpdateObjectHeader(yaffs_Objec
6777                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
6778                 newTags.extraObjectType = in->variantType;
6779  
6780 -               yaffs_VerifyObjectHeader(in,oh,&newTags,1);
6781 +               yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
6782  
6783                 /* Create new chunk in NAND */
6784                 newChunkId =
6785 @@ -3717,20 +3788,20 @@ int yaffs_UpdateObjectHeader(yaffs_Objec
6786  
6787                 if (newChunkId >= 0) {
6788  
6789 -                       in->chunkId = newChunkId;
6790 +                       in->hdrChunk = newChunkId;
6791  
6792                         if (prevChunkId >= 0) {
6793                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
6794                                                   __LINE__);
6795                         }
6796  
6797 -                       if(!yaffs_ObjectHasCachedWriteData(in))
6798 +                       if (!yaffs_ObjectHasCachedWriteData(in))
6799                                 in->dirty = 0;
6800  
6801                         /* If this was a shrink, then mark the block that the chunk lives on */
6802                         if (isShrink) {
6803                                 bi = yaffs_GetBlockInfo(in->myDev,
6804 -                                                       newChunkId /in->myDev-> nChunksPerBlock);
6805 +                                       newChunkId / in->myDev->nChunksPerBlock);
6806                                 bi->hasShrinkHeader = 1;
6807                         }
6808  
6809 @@ -3766,7 +3837,7 @@ static int yaffs_ObjectHasCachedWriteDat
6810         yaffs_ChunkCache *cache;
6811         int nCaches = obj->myDev->nShortOpCaches;
6812  
6813 -       for(i = 0; i < nCaches; i++){
6814 +       for (i = 0; i < nCaches; i++) {
6815                 cache = &dev->srCache[i];
6816                 if (cache->object == obj &&
6817                     cache->dirty)
6818 @@ -3777,7 +3848,7 @@ static int yaffs_ObjectHasCachedWriteDat
6819  }
6820  
6821  
6822 -static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
6823 +static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
6824  {
6825         yaffs_Device *dev = obj->myDev;
6826         int lowest = -99;       /* Stop compiler whining. */
6827 @@ -3844,16 +3915,16 @@ void yaffs_FlushEntireDeviceCache(yaffs_
6828          */
6829         do {
6830                 obj = NULL;
6831 -               for( i = 0; i < nCaches && !obj; i++) {
6832 +               for (i = 0; i < nCaches && !obj; i++) {
6833                         if (dev->srCache[i].object &&
6834                             dev->srCache[i].dirty)
6835                                 obj = dev->srCache[i].object;
6836  
6837                 }
6838 -               if(obj)
6839 +               if (obj)
6840                         yaffs_FlushFilesChunkCache(obj);
6841  
6842 -       } while(obj);
6843 +       } while (obj);
6844  
6845  }
6846  
6847 @@ -3863,41 +3934,21 @@ void yaffs_FlushEntireDeviceCache(yaffs_
6848   * Then look for the least recently used non-dirty one.
6849   * Then look for the least recently used dirty one...., flush and look again.
6850   */
6851 -static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
6852 +static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
6853  {
6854         int i;
6855 -       int usage;
6856 -       int theOne;
6857  
6858         if (dev->nShortOpCaches > 0) {
6859                 for (i = 0; i < dev->nShortOpCaches; i++) {
6860                         if (!dev->srCache[i].object)
6861                                 return &dev->srCache[i];
6862                 }
6863 +       }
6864  
6865 -               return NULL;
6866 +       return NULL;
6867 +}
6868  
6869 -               theOne = -1;
6870 -               usage = 0;      /* just to stop the compiler grizzling */
6871 -
6872 -               for (i = 0; i < dev->nShortOpCaches; i++) {
6873 -                       if (!dev->srCache[i].dirty &&
6874 -                           ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
6875 -                            theOne < 0)) {
6876 -                               usage = dev->srCache[i].lastUse;
6877 -                               theOne = i;
6878 -                       }
6879 -               }
6880 -
6881 -
6882 -               return theOne >= 0 ? &dev->srCache[theOne] : NULL;
6883 -       } else {
6884 -               return NULL;
6885 -       }
6886 -
6887 -}
6888 -
6889 -static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
6890 +static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
6891  {
6892         yaffs_ChunkCache *cache;
6893         yaffs_Object *theObj;
6894 @@ -3927,8 +3978,7 @@ static yaffs_ChunkCache *yaffs_GrabChunk
6895                         for (i = 0; i < dev->nShortOpCaches; i++) {
6896                                 if (dev->srCache[i].object &&
6897                                     !dev->srCache[i].locked &&
6898 -                                   (dev->srCache[i].lastUse < usage || !cache))
6899 -                               {
6900 +                                   (dev->srCache[i].lastUse < usage || !cache)) {
6901                                         usage = dev->srCache[i].lastUse;
6902                                         theObj = dev->srCache[i].object;
6903                                         cache = &dev->srCache[i];
6904 @@ -3950,7 +4000,7 @@ static yaffs_ChunkCache *yaffs_GrabChunk
6905  }
6906  
6907  /* Find a cached chunk */
6908 -static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
6909 +static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
6910                                               int chunkId)
6911  {
6912         yaffs_Device *dev = obj->myDev;
6913 @@ -3969,7 +4019,7 @@ static yaffs_ChunkCache *yaffs_FindChunk
6914  }
6915  
6916  /* Mark the chunk for the least recently used algorithym */
6917 -static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
6918 +static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
6919                                 int isAWrite)
6920  {
6921  
6922 @@ -3977,9 +4027,9 @@ static void yaffs_UseChunkCache(yaffs_De
6923                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
6924                         /* Reset the cache usages */
6925                         int i;
6926 -                       for (i = 1; i < dev->nShortOpCaches; i++) {
6927 +                       for (i = 1; i < dev->nShortOpCaches; i++)
6928                                 dev->srCache[i].lastUse = 0;
6929 -                       }
6930 +
6931                         dev->srLastUse = 0;
6932                 }
6933  
6934 @@ -3987,9 +4037,8 @@ static void yaffs_UseChunkCache(yaffs_De
6935  
6936                 cache->lastUse = dev->srLastUse;
6937  
6938 -               if (isAWrite) {
6939 +               if (isAWrite)
6940                         cache->dirty = 1;
6941 -               }
6942         }
6943  }
6944  
6945 @@ -3997,21 +4046,20 @@ static void yaffs_UseChunkCache(yaffs_De
6946   * Do this when a whole page gets written,
6947   * ie the short cache for this page is no longer valid.
6948   */
6949 -static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
6950 +static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
6951  {
6952         if (object->myDev->nShortOpCaches > 0) {
6953                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
6954  
6955 -               if (cache) {
6956 +               if (cache)
6957                         cache->object = NULL;
6958 -               }
6959         }
6960  }
6961  
6962  /* Invalidate all the cache pages associated with this object
6963   * Do this whenever ther file is deleted or resized.
6964   */
6965 -static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
6966 +static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
6967  {
6968         int i;
6969         yaffs_Device *dev = in->myDev;
6970 @@ -4019,9 +4067,8 @@ static void yaffs_InvalidateWholeChunkCa
6971         if (dev->nShortOpCaches > 0) {
6972                 /* Invalidate it. */
6973                 for (i = 0; i < dev->nShortOpCaches; i++) {
6974 -                       if (dev->srCache[i].object == in) {
6975 +                       if (dev->srCache[i].object == in)
6976                                 dev->srCache[i].object = NULL;
6977 -                       }
6978                 }
6979         }
6980  }
6981 @@ -4029,18 +4076,18 @@ static void yaffs_InvalidateWholeChunkCa
6982  /*--------------------- Checkpointing --------------------*/
6983  
6984  
6985 -static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
6986 +static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
6987  {
6988         yaffs_CheckpointValidity cp;
6989  
6990 -       memset(&cp,0,sizeof(cp));
6991 +       memset(&cp, 0, sizeof(cp));
6992  
6993         cp.structType = sizeof(cp);
6994         cp.magic = YAFFS_MAGIC;
6995         cp.version = YAFFS_CHECKPOINT_VERSION;
6996         cp.head = (head) ? 1 : 0;
6997  
6998 -       return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
6999 +       return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
7000                 1 : 0;
7001  }
7002  
7003 @@ -4049,9 +4096,9 @@ static int yaffs_ReadCheckpointValidityM
7004         yaffs_CheckpointValidity cp;
7005         int ok;
7006  
7007 -       ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
7008 +       ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
7009  
7010 -       if(ok)
7011 +       if (ok)
7012                 ok = (cp.structType == sizeof(cp)) &&
7013                      (cp.magic == YAFFS_MAGIC) &&
7014                      (cp.version == YAFFS_CHECKPOINT_VERSION) &&
7015 @@ -4100,21 +4147,21 @@ static int yaffs_WriteCheckpointDevice(y
7016         int ok;
7017  
7018         /* Write device runtime values*/
7019 -       yaffs_DeviceToCheckpointDevice(&cp,dev);
7020 +       yaffs_DeviceToCheckpointDevice(&cp, dev);
7021         cp.structType = sizeof(cp);
7022  
7023 -       ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
7024 +       ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
7025  
7026         /* Write block info */
7027 -       if(ok) {
7028 +       if (ok) {
7029                 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
7030 -               ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
7031 +               ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
7032         }
7033  
7034         /* Write chunk bits */
7035 -       if(ok) {
7036 +       if (ok) {
7037                 nBytes = nBlocks * dev->chunkBitmapStride;
7038 -               ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
7039 +               ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
7040         }
7041         return   ok ? 1 : 0;
7042  
7043 @@ -4128,25 +4175,25 @@ static int yaffs_ReadCheckpointDevice(ya
7044  
7045         int ok;
7046  
7047 -       ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
7048 -       if(!ok)
7049 +       ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
7050 +       if (!ok)
7051                 return 0;
7052  
7053 -       if(cp.structType != sizeof(cp))
7054 +       if (cp.structType != sizeof(cp))
7055                 return 0;
7056  
7057  
7058 -       yaffs_CheckpointDeviceToDevice(dev,&cp);
7059 +       yaffs_CheckpointDeviceToDevice(dev, &cp);
7060  
7061         nBytes = nBlocks * sizeof(yaffs_BlockInfo);
7062  
7063 -       ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
7064 +       ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
7065  
7066 -       if(!ok)
7067 +       if (!ok)
7068                 return 0;
7069         nBytes = nBlocks * dev->chunkBitmapStride;
7070  
7071 -       ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
7072 +       ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
7073  
7074         return ok ? 1 : 0;
7075  }
7076 @@ -4157,7 +4204,7 @@ static void yaffs_ObjectToCheckpointObje
7077  
7078         cp->objectId = obj->objectId;
7079         cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
7080 -       cp->chunkId = obj->chunkId;
7081 +       cp->hdrChunk = obj->hdrChunk;
7082         cp->variantType = obj->variantType;
7083         cp->deleted = obj->deleted;
7084         cp->softDeleted = obj->softDeleted;
7085 @@ -4168,20 +4215,28 @@ static void yaffs_ObjectToCheckpointObje
7086         cp->serial = obj->serial;
7087         cp->nDataChunks = obj->nDataChunks;
7088  
7089 -       if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7090 +       if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7091                 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
7092 -       else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
7093 +       else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
7094                 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
7095  }
7096  
7097 -static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
7098 +static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
7099  {
7100  
7101         yaffs_Object *parent;
7102  
7103 +       if (obj->variantType != cp->variantType) {
7104 +               T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
7105 +                       TCONT("chunk %d does not match existing object type %d")
7106 +                       TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
7107 +                       obj->variantType));
7108 +               return 0;
7109 +       }
7110 +
7111         obj->objectId = cp->objectId;
7112  
7113 -       if(cp->parentId)
7114 +       if (cp->parentId)
7115                 parent = yaffs_FindOrCreateObjectByNumber(
7116                                         obj->myDev,
7117                                         cp->parentId,
7118 @@ -4189,10 +4244,19 @@ static void yaffs_CheckpointObjectToObje
7119         else
7120                 parent = NULL;
7121  
7122 -       if(parent)
7123 +       if (parent) {
7124 +               if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7125 +                       T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
7126 +                               TCONT(" chunk %d Parent type, %d, not directory")
7127 +                               TENDSTR),
7128 +                               cp->objectId, cp->parentId, cp->variantType,
7129 +                               cp->hdrChunk, parent->variantType));
7130 +                       return 0;
7131 +               }
7132                 yaffs_AddObjectToDirectory(parent, obj);
7133 +       }
7134  
7135 -       obj->chunkId = cp->chunkId;
7136 +       obj->hdrChunk = cp->hdrChunk;
7137         obj->variantType = cp->variantType;
7138         obj->deleted = cp->deleted;
7139         obj->softDeleted = cp->softDeleted;
7140 @@ -4203,29 +4267,34 @@ static void yaffs_CheckpointObjectToObje
7141         obj->serial = cp->serial;
7142         obj->nDataChunks = cp->nDataChunks;
7143  
7144 -       if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7145 +       if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7146                 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
7147 -       else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
7148 +       else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
7149                 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
7150  
7151 -       if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
7152 +       if (obj->hdrChunk > 0)
7153                 obj->lazyLoaded = 1;
7154 +       return 1;
7155  }
7156  
7157  
7158  
7159 -static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
7160 -                                       __u32 level, int chunkOffset)
7161 +static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
7162 +                                       __u32 level, int chunkOffset)
7163  {
7164         int i;
7165         yaffs_Device *dev = in->myDev;
7166         int ok = 1;
7167 -       int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
7168 +       int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
7169 +
7170 +       if (tnodeSize < sizeof(yaffs_Tnode))
7171 +               tnodeSize = sizeof(yaffs_Tnode);
7172 +
7173  
7174         if (tn) {
7175                 if (level > 0) {
7176  
7177 -                       for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
7178 +                       for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
7179                                 if (tn->internal[i]) {
7180                                         ok = yaffs_CheckpointTnodeWorker(in,
7181                                                         tn->internal[i],
7182 @@ -4235,10 +4304,9 @@ static int yaffs_CheckpointTnodeWorker(y
7183                         }
7184                 } else if (level == 0) {
7185                         __u32 baseOffset = chunkOffset <<  YAFFS_TNODES_LEVEL0_BITS;
7186 -                       /* printf("write tnode at %d\n",baseOffset); */
7187 -                       ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
7188 -                       if(ok)
7189 -                               ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
7190 +                       ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
7191 +                       if (ok)
7192 +                               ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
7193                 }
7194         }
7195  
7196 @@ -4251,13 +4319,13 @@ static int yaffs_WriteCheckpointTnodes(y
7197         __u32 endMarker = ~0;
7198         int ok = 1;
7199  
7200 -       if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
7201 +       if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
7202                 ok = yaffs_CheckpointTnodeWorker(obj,
7203                                             obj->variant.fileVariant.top,
7204                                             obj->variant.fileVariant.topLevel,
7205                                             0);
7206 -               if(ok)
7207 -                       ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
7208 +               if (ok)
7209 +                       ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
7210                                 sizeof(endMarker));
7211         }
7212  
7213 @@ -4272,38 +4340,38 @@ static int yaffs_ReadCheckpointTnodes(ya
7214         yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
7215         yaffs_Tnode *tn;
7216         int nread = 0;
7217 +       int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
7218  
7219 -       ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
7220 +       if (tnodeSize < sizeof(yaffs_Tnode))
7221 +               tnodeSize = sizeof(yaffs_Tnode);
7222  
7223 -       while(ok && (~baseChunk)){
7224 +       ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
7225 +
7226 +       while (ok && (~baseChunk)) {
7227                 nread++;
7228                 /* Read level 0 tnode */
7229  
7230  
7231 -               /* printf("read  tnode at %d\n",baseChunk); */
7232                 tn = yaffs_GetTnodeRaw(dev);
7233 -               if(tn)
7234 -                       ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
7235 -                             (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
7236 +               if (tn)
7237 +                       ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
7238                 else
7239                         ok = 0;
7240  
7241 -               if(tn && ok){
7242 +               if (tn && ok)
7243                         ok = yaffs_AddOrFindLevel0Tnode(dev,
7244 -                                                       fileStructPtr,
7245 -                                                       baseChunk,
7246 -                                                       tn) ? 1 : 0;
7247 +                                                       fileStructPtr,
7248 +                                                       baseChunk,
7249 +                                                       tn) ? 1 : 0;
7250  
7251 -               }
7252 -
7253 -               if(ok)
7254 -                       ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
7255 +               if (ok)
7256 +                       ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
7257  
7258         }
7259  
7260 -       T(YAFFS_TRACE_CHECKPOINT,(
7261 +       T(YAFFS_TRACE_CHECKPOINT, (
7262                 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
7263 -               nread,baseChunk,ok));
7264 +               nread, baseChunk, ok));
7265  
7266         return ok ? 1 : 0;
7267  }
7268 @@ -4315,41 +4383,40 @@ static int yaffs_WriteCheckpointObjects(
7269         yaffs_CheckpointObject cp;
7270         int i;
7271         int ok = 1;
7272 -       struct list_head *lh;
7273 +       struct ylist_head *lh;
7274  
7275  
7276         /* Iterate through the objects in each hash entry,
7277          * dumping them to the checkpointing stream.
7278          */
7279  
7280 -        for(i = 0; ok &&  i <  YAFFS_NOBJECT_BUCKETS; i++){
7281 -               list_for_each(lh, &dev->objectBucket[i].list) {
7282 +       for (i = 0; ok &&  i <  YAFFS_NOBJECT_BUCKETS; i++) {
7283 +               ylist_for_each(lh, &dev->objectBucket[i].list) {
7284                         if (lh) {
7285 -                               obj = list_entry(lh, yaffs_Object, hashLink);
7286 +                               obj = ylist_entry(lh, yaffs_Object, hashLink);
7287                                 if (!obj->deferedFree) {
7288 -                                       yaffs_ObjectToCheckpointObject(&cp,obj);
7289 +                                       yaffs_ObjectToCheckpointObject(&cp, obj);
7290                                         cp.structType = sizeof(cp);
7291  
7292 -                                       T(YAFFS_TRACE_CHECKPOINT,(
7293 +                                       T(YAFFS_TRACE_CHECKPOINT, (
7294                                                 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
7295 -                                               cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
7296 +                                               cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, (unsigned) obj));
7297  
7298 -                                       ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
7299 +                                       ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
7300  
7301 -                                       if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
7302 +                                       if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7303                                                 ok = yaffs_WriteCheckpointTnodes(obj);
7304 -                                       }
7305                                 }
7306                         }
7307                 }
7308 -        }
7309 +       }
7310  
7311 -        /* Dump end of list */
7312 -       memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
7313 +       /* Dump end of list */
7314 +       memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
7315         cp.structType = sizeof(cp);
7316  
7317 -       if(ok)
7318 -               ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
7319 +       if (ok)
7320 +               ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
7321  
7322         return ok ? 1 : 0;
7323  }
7324 @@ -4362,38 +4429,39 @@ static int yaffs_ReadCheckpointObjects(y
7325         int done = 0;
7326         yaffs_Object *hardList = NULL;
7327  
7328 -       while(ok && !done) {
7329 -               ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
7330 -               if(cp.structType != sizeof(cp)) {
7331 -                       T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
7332 -                               cp.structType,sizeof(cp),ok));
7333 +       while (ok && !done) {
7334 +               ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
7335 +               if (cp.structType != sizeof(cp)) {
7336 +                       T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
7337 +                               cp.structType, sizeof(cp), ok));
7338                         ok = 0;
7339                 }
7340  
7341 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
7342 -                       cp.objectId,cp.parentId,cp.variantType,cp.chunkId));
7343 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
7344 +                       cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
7345  
7346 -               if(ok && cp.objectId == ~0)
7347 +               if (ok && cp.objectId == ~0)
7348                         done = 1;
7349 -               else if(ok){
7350 -                       obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
7351 -                       if(obj) {
7352 -                               yaffs_CheckpointObjectToObject(obj,&cp);
7353 -                               if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
7354 +               else if (ok) {
7355 +                       obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
7356 +                       if (obj) {
7357 +                               ok = yaffs_CheckpointObjectToObject(obj, &cp);
7358 +                               if (!ok)
7359 +                                       break;
7360 +                               if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
7361                                         ok = yaffs_ReadCheckpointTnodes(obj);
7362 -                               } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7363 +                               } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7364                                         obj->hardLinks.next =
7365 -                                                   (struct list_head *)
7366 -                                                   hardList;
7367 +                                               (struct ylist_head *) hardList;
7368                                         hardList = obj;
7369                                 }
7370 -
7371 -                       }
7372 +                       } else
7373 +                               ok = 0;
7374                 }
7375         }
7376  
7377 -       if(ok)
7378 -               yaffs_HardlinkFixup(dev,hardList);
7379 +       if (ok)
7380 +               yaffs_HardlinkFixup(dev, hardList);
7381  
7382         return ok ? 1 : 0;
7383  }
7384 @@ -4403,11 +4471,11 @@ static int yaffs_WriteCheckpointSum(yaff
7385         __u32 checkpointSum;
7386         int ok;
7387  
7388 -       yaffs_GetCheckpointSum(dev,&checkpointSum);
7389 +       yaffs_GetCheckpointSum(dev, &checkpointSum);
7390  
7391 -       ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
7392 +       ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
7393  
7394 -       if(!ok)
7395 +       if (!ok)
7396                 return 0;
7397  
7398         return 1;
7399 @@ -4419,14 +4487,14 @@ static int yaffs_ReadCheckpointSum(yaffs
7400         __u32 checkpointSum1;
7401         int ok;
7402  
7403 -       yaffs_GetCheckpointSum(dev,&checkpointSum0);
7404 +       yaffs_GetCheckpointSum(dev, &checkpointSum0);
7405  
7406 -       ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
7407 +       ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
7408  
7409 -       if(!ok)
7410 +       if (!ok)
7411                 return 0;
7412  
7413 -       if(checkpointSum0 != checkpointSum1)
7414 +       if (checkpointSum0 != checkpointSum1)
7415                 return 0;
7416  
7417         return 1;
7418 @@ -4435,46 +4503,43 @@ static int yaffs_ReadCheckpointSum(yaffs
7419  
7420  static int yaffs_WriteCheckpointData(yaffs_Device *dev)
7421  {
7422 -
7423         int ok = 1;
7424  
7425 -       if(dev->skipCheckpointWrite || !dev->isYaffs2){
7426 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
7427 +       if (dev->skipCheckpointWrite || !dev->isYaffs2) {
7428 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
7429                 ok = 0;
7430         }
7431  
7432 -       if(ok)
7433 -               ok = yaffs_CheckpointOpen(dev,1);
7434 +       if (ok)
7435 +               ok = yaffs_CheckpointOpen(dev, 1);
7436  
7437 -       if(ok){
7438 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
7439 -               ok = yaffs_WriteCheckpointValidityMarker(dev,1);
7440 +       if (ok) {
7441 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
7442 +               ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
7443         }
7444 -       if(ok){
7445 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
7446 +       if (ok) {
7447 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
7448                 ok = yaffs_WriteCheckpointDevice(dev);
7449         }
7450 -       if(ok){
7451 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
7452 +       if (ok) {
7453 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
7454                 ok = yaffs_WriteCheckpointObjects(dev);
7455         }
7456 -       if(ok){
7457 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
7458 -               ok = yaffs_WriteCheckpointValidityMarker(dev,0);
7459 +       if (ok) {
7460 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
7461 +               ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
7462         }
7463  
7464 -       if(ok){
7465 +       if (ok)
7466                 ok = yaffs_WriteCheckpointSum(dev);
7467 -       }
7468 -
7469  
7470 -       if(!yaffs_CheckpointClose(dev))
7471 -                ok = 0;
7472 +       if (!yaffs_CheckpointClose(dev))
7473 +               ok = 0;
7474  
7475 -       if(ok)
7476 -               dev->isCheckpointed = 1;
7477 -        else
7478 -               dev->isCheckpointed = 0;
7479 +       if (ok)
7480 +               dev->isCheckpointed = 1;
7481 +       else
7482 +               dev->isCheckpointed = 0;
7483  
7484         return dev->isCheckpointed;
7485  }
7486 @@ -4483,43 +4548,43 @@ static int yaffs_ReadCheckpointData(yaff
7487  {
7488         int ok = 1;
7489  
7490 -       if(dev->skipCheckpointRead || !dev->isYaffs2){
7491 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
7492 +       if (dev->skipCheckpointRead || !dev->isYaffs2) {
7493 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
7494                 ok = 0;
7495         }
7496  
7497 -       if(ok)
7498 -               ok = yaffs_CheckpointOpen(dev,0); /* open for read */
7499 +       if (ok)
7500 +               ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
7501  
7502 -       if(ok){
7503 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
7504 -               ok = yaffs_ReadCheckpointValidityMarker(dev,1);
7505 +       if (ok) {
7506 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
7507 +               ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
7508         }
7509 -       if(ok){
7510 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
7511 +       if (ok) {
7512 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
7513                 ok = yaffs_ReadCheckpointDevice(dev);
7514         }
7515 -       if(ok){
7516 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
7517 +       if (ok) {
7518 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
7519                 ok = yaffs_ReadCheckpointObjects(dev);
7520         }
7521 -       if(ok){
7522 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
7523 -               ok = yaffs_ReadCheckpointValidityMarker(dev,0);
7524 +       if (ok) {
7525 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
7526 +               ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
7527         }
7528  
7529 -       if(ok){
7530 +       if (ok) {
7531                 ok = yaffs_ReadCheckpointSum(dev);
7532 -               T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
7533 +               T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
7534         }
7535  
7536 -       if(!yaffs_CheckpointClose(dev))
7537 +       if (!yaffs_CheckpointClose(dev))
7538                 ok = 0;
7539  
7540 -       if(ok)
7541 -               dev->isCheckpointed = 1;
7542 -        else
7543 -               dev->isCheckpointed = 0;
7544 +       if (ok)
7545 +               dev->isCheckpointed = 1;
7546 +       else
7547 +               dev->isCheckpointed = 0;
7548  
7549         return ok ? 1 : 0;
7550  
7551 @@ -4527,11 +4592,11 @@ static int yaffs_ReadCheckpointData(yaff
7552  
7553  static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
7554  {
7555 -       if(dev->isCheckpointed ||
7556 -          dev->blocksInCheckpoint > 0){
7557 +       if (dev->isCheckpointed ||
7558 +                       dev->blocksInCheckpoint > 0) {
7559                 dev->isCheckpointed = 0;
7560                 yaffs_CheckpointInvalidateStream(dev);
7561 -               if(dev->superBlock && dev->markSuperBlockDirty)
7562 +               if (dev->superBlock && dev->markSuperBlockDirty)
7563                         dev->markSuperBlockDirty(dev->superBlock);
7564         }
7565  }
7566 @@ -4540,18 +4605,18 @@ static void yaffs_InvalidateCheckpoint(y
7567  int yaffs_CheckpointSave(yaffs_Device *dev)
7568  {
7569  
7570 -       T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
7571 +       T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
7572  
7573         yaffs_VerifyObjects(dev);
7574         yaffs_VerifyBlocks(dev);
7575         yaffs_VerifyFreeChunks(dev);
7576  
7577 -       if(!dev->isCheckpointed) {
7578 +       if (!dev->isCheckpointed) {
7579                 yaffs_InvalidateCheckpoint(dev);
7580                 yaffs_WriteCheckpointData(dev);
7581         }
7582  
7583 -       T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
7584 +       T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
7585  
7586         return dev->isCheckpointed;
7587  }
7588 @@ -4559,17 +4624,17 @@ int yaffs_CheckpointSave(yaffs_Device *d
7589  int yaffs_CheckpointRestore(yaffs_Device *dev)
7590  {
7591         int retval;
7592 -       T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
7593 +       T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
7594  
7595         retval = yaffs_ReadCheckpointData(dev);
7596  
7597 -       if(dev->isCheckpointed){
7598 +       if (dev->isCheckpointed) {
7599                 yaffs_VerifyObjects(dev);
7600                 yaffs_VerifyBlocks(dev);
7601                 yaffs_VerifyFreeChunks(dev);
7602         }
7603  
7604 -       T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
7605 +       T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
7606  
7607         return retval;
7608  }
7609 @@ -4584,12 +4649,12 @@ int yaffs_CheckpointRestore(yaffs_Device
7610   * Curve-balls: the first chunk might also be the last chunk.
7611   */
7612  
7613 -int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
7614 -                          int nBytes)
7615 +int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
7616 +                       int nBytes)
7617  {
7618  
7619         int chunk;
7620 -       int start;
7621 +       __u32 start;
7622         int nToCopy;
7623         int n = nBytes;
7624         int nDone = 0;
7625 @@ -4600,27 +4665,26 @@ int yaffs_ReadDataFromFile(yaffs_Object
7626         dev = in->myDev;
7627  
7628         while (n > 0) {
7629 -               //chunk = offset / dev->nDataBytesPerChunk + 1;
7630 -               //start = offset % dev->nDataBytesPerChunk;
7631 -               yaffs_AddrToChunk(dev,offset,&chunk,&start);
7632 +               /* chunk = offset / dev->nDataBytesPerChunk + 1; */
7633 +               /* start = offset % dev->nDataBytesPerChunk; */
7634 +               yaffs_AddrToChunk(dev, offset, &chunk, &start);
7635                 chunk++;
7636  
7637                 /* OK now check for the curveball where the start and end are in
7638                  * the same chunk.
7639                  */
7640 -               if ((start + n) < dev->nDataBytesPerChunk) {
7641 +               if ((start + n) < dev->nDataBytesPerChunk)
7642                         nToCopy = n;
7643 -               } else {
7644 +               else
7645                         nToCopy = dev->nDataBytesPerChunk - start;
7646 -               }
7647  
7648                 cache = yaffs_FindChunkCache(in, chunk);
7649  
7650                 /* If the chunk is already in the cache or it is less than a whole chunk
7651 -                * then use the cache (if there is caching)
7652 +                * or we're using inband tags then use the cache (if there is caching)
7653                  * else bypass the cache.
7654                  */
7655 -               if (cache || nToCopy != dev->nDataBytesPerChunk) {
7656 +               if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
7657                         if (dev->nShortOpCaches > 0) {
7658  
7659                                 /* If we can't find the data in the cache, then load it up. */
7660 @@ -4641,14 +4705,9 @@ int yaffs_ReadDataFromFile(yaffs_Object
7661  
7662                                 cache->locked = 1;
7663  
7664 -#ifdef CONFIG_YAFFS_WINCE
7665 -                               yfsd_UnlockYAFFS(TRUE);
7666 -#endif
7667 +
7668                                 memcpy(buffer, &cache->data[start], nToCopy);
7669  
7670 -#ifdef CONFIG_YAFFS_WINCE
7671 -                               yfsd_LockYAFFS(TRUE);
7672 -#endif
7673                                 cache->locked = 0;
7674                         } else {
7675                                 /* Read into the local buffer then copy..*/
7676 @@ -4657,41 +4716,19 @@ int yaffs_ReadDataFromFile(yaffs_Object
7677                                     yaffs_GetTempBuffer(dev, __LINE__);
7678                                 yaffs_ReadChunkDataFromObject(in, chunk,
7679                                                               localBuffer);
7680 -#ifdef CONFIG_YAFFS_WINCE
7681 -                               yfsd_UnlockYAFFS(TRUE);
7682 -#endif
7683 +
7684                                 memcpy(buffer, &localBuffer[start], nToCopy);
7685  
7686 -#ifdef CONFIG_YAFFS_WINCE
7687 -                               yfsd_LockYAFFS(TRUE);
7688 -#endif
7689 +
7690                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
7691                                                         __LINE__);
7692                         }
7693  
7694                 } else {
7695 -#ifdef CONFIG_YAFFS_WINCE
7696 -                       __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
7697 -
7698 -                       /* Under WinCE can't do direct transfer. Need to use a local buffer.
7699 -                        * This is because we otherwise screw up WinCE's memory mapper
7700 -                        */
7701 -                       yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
7702 -
7703 -#ifdef CONFIG_YAFFS_WINCE
7704 -                       yfsd_UnlockYAFFS(TRUE);
7705 -#endif
7706 -                       memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
7707  
7708 -#ifdef CONFIG_YAFFS_WINCE
7709 -                       yfsd_LockYAFFS(TRUE);
7710 -                       yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
7711 -#endif
7712 -
7713 -#else
7714                         /* A full chunk. Read directly into the supplied buffer. */
7715                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
7716 -#endif
7717 +
7718                 }
7719  
7720                 n -= nToCopy;
7721 @@ -4704,28 +4741,37 @@ int yaffs_ReadDataFromFile(yaffs_Object
7722         return nDone;
7723  }
7724  
7725 -int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
7726 -                         int nBytes, int writeThrough)
7727 +int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
7728 +                       int nBytes, int writeThrough)
7729  {
7730  
7731         int chunk;
7732 -       int start;
7733 +       __u32 start;
7734         int nToCopy;
7735         int n = nBytes;
7736         int nDone = 0;
7737         int nToWriteBack;
7738         int startOfWrite = offset;
7739         int chunkWritten = 0;
7740 -       int nBytesRead;
7741 +       __u32 nBytesRead;
7742 +       __u32 chunkStart;
7743  
7744         yaffs_Device *dev;
7745  
7746         dev = in->myDev;
7747  
7748         while (n > 0 && chunkWritten >= 0) {
7749 -               //chunk = offset / dev->nDataBytesPerChunk + 1;
7750 -               //start = offset % dev->nDataBytesPerChunk;
7751 -               yaffs_AddrToChunk(dev,offset,&chunk,&start);
7752 +               /* chunk = offset / dev->nDataBytesPerChunk + 1; */
7753 +               /* start = offset % dev->nDataBytesPerChunk; */
7754 +               yaffs_AddrToChunk(dev, offset, &chunk, &start);
7755 +
7756 +               if (chunk * dev->nDataBytesPerChunk + start != offset ||
7757 +                               start >= dev->nDataBytesPerChunk) {
7758 +                       T(YAFFS_TRACE_ERROR, (
7759 +                          TSTR("AddrToChunk of offset %d gives chunk %d start %d"
7760 +                          TENDSTR),
7761 +                          (int)offset, chunk, start));
7762 +               }
7763                 chunk++;
7764  
7765                 /* OK now check for the curveball where the start and end are in
7766 @@ -4740,25 +4786,32 @@ int yaffs_WriteDataToFile(yaffs_Object *
7767                          * we need to write back as much as was there before.
7768                          */
7769  
7770 -                       nBytesRead =
7771 -                           in->variant.fileVariant.fileSize -
7772 -                           ((chunk - 1) * dev->nDataBytesPerChunk);
7773 +                       chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
7774 +
7775 +                       if (chunkStart > in->variant.fileVariant.fileSize)
7776 +                               nBytesRead = 0; /* Past end of file */
7777 +                       else
7778 +                               nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
7779  
7780 -                       if (nBytesRead > dev->nDataBytesPerChunk) {
7781 +                       if (nBytesRead > dev->nDataBytesPerChunk)
7782                                 nBytesRead = dev->nDataBytesPerChunk;
7783 -                       }
7784  
7785                         nToWriteBack =
7786                             (nBytesRead >
7787                              (start + n)) ? nBytesRead : (start + n);
7788  
7789 +                       if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
7790 +                               YBUG();
7791 +
7792                 } else {
7793                         nToCopy = dev->nDataBytesPerChunk - start;
7794                         nToWriteBack = dev->nDataBytesPerChunk;
7795                 }
7796  
7797 -               if (nToCopy != dev->nDataBytesPerChunk) {
7798 -                       /* An incomplete start or end chunk (or maybe both start and end chunk) */
7799 +               if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
7800 +                       /* An incomplete start or end chunk (or maybe both start and end chunk),
7801 +                        * or we're using inband tags, so we want to use the cache buffers.
7802 +                        */
7803                         if (dev->nShortOpCaches > 0) {
7804                                 yaffs_ChunkCache *cache;
7805                                 /* If we can't find the data in the cache, then load the cache */
7806 @@ -4775,10 +4828,9 @@ int yaffs_WriteDataToFile(yaffs_Object *
7807                                         yaffs_ReadChunkDataFromObject(in, chunk,
7808                                                                       cache->
7809                                                                       data);
7810 -                               }
7811 -                               else if(cache &&
7812 -                                       !cache->dirty &&
7813 -                                       !yaffs_CheckSpaceForAllocation(in->myDev)){
7814 +                               } else if (cache &&
7815 +                                       !cache->dirty &&
7816 +                                       !yaffs_CheckSpaceForAllocation(in->myDev)) {
7817                                         /* Drop the cache if it was a read cache item and
7818                                          * no space check has been made for it.
7819                                          */
7820 @@ -4788,16 +4840,12 @@ int yaffs_WriteDataToFile(yaffs_Object *
7821                                 if (cache) {
7822                                         yaffs_UseChunkCache(dev, cache, 1);
7823                                         cache->locked = 1;
7824 -#ifdef CONFIG_YAFFS_WINCE
7825 -                                       yfsd_UnlockYAFFS(TRUE);
7826 -#endif
7827 +
7828  
7829                                         memcpy(&cache->data[start], buffer,
7830                                                nToCopy);
7831  
7832 -#ifdef CONFIG_YAFFS_WINCE
7833 -                                       yfsd_LockYAFFS(TRUE);
7834 -#endif
7835 +
7836                                         cache->locked = 0;
7837                                         cache->nBytes = nToWriteBack;
7838  
7839 @@ -4825,15 +4873,10 @@ int yaffs_WriteDataToFile(yaffs_Object *
7840                                 yaffs_ReadChunkDataFromObject(in, chunk,
7841                                                               localBuffer);
7842  
7843 -#ifdef CONFIG_YAFFS_WINCE
7844 -                               yfsd_UnlockYAFFS(TRUE);
7845 -#endif
7846 +
7847  
7848                                 memcpy(&localBuffer[start], buffer, nToCopy);
7849  
7850 -#ifdef CONFIG_YAFFS_WINCE
7851 -                               yfsd_LockYAFFS(TRUE);
7852 -#endif
7853                                 chunkWritten =
7854                                     yaffs_WriteChunkDataToObject(in, chunk,
7855                                                                  localBuffer,
7856 @@ -4846,31 +4889,15 @@ int yaffs_WriteDataToFile(yaffs_Object *
7857                         }
7858  
7859                 } else {
7860 -
7861 -#ifdef CONFIG_YAFFS_WINCE
7862 -                       /* Under WinCE can't do direct transfer. Need to use a local buffer.
7863 -                        * This is because we otherwise screw up WinCE's memory mapper
7864 -                        */
7865 -                       __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
7866 -#ifdef CONFIG_YAFFS_WINCE
7867 -                       yfsd_UnlockYAFFS(TRUE);
7868 -#endif
7869 -                       memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
7870 -#ifdef CONFIG_YAFFS_WINCE
7871 -                       yfsd_LockYAFFS(TRUE);
7872 -#endif
7873 -                       chunkWritten =
7874 -                           yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
7875 -                                                        dev->nDataBytesPerChunk,
7876 -                                                        0);
7877 -                       yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
7878 -#else
7879                         /* A full chunk. Write directly from the supplied buffer. */
7880 +
7881 +
7882 +
7883                         chunkWritten =
7884                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
7885                                                          dev->nDataBytesPerChunk,
7886                                                          0);
7887 -#endif
7888 +
7889                         /* Since we've overwritten the cached data, we better invalidate it. */
7890                         yaffs_InvalidateChunkCache(in, chunk);
7891                 }
7892 @@ -4886,9 +4913,8 @@ int yaffs_WriteDataToFile(yaffs_Object *
7893  
7894         /* Update file object */
7895  
7896 -       if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
7897 +       if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
7898                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
7899 -       }
7900  
7901         in->dirty = 1;
7902  
7903 @@ -4898,7 +4924,7 @@ int yaffs_WriteDataToFile(yaffs_Object *
7904  
7905  /* ---------------------- File resizing stuff ------------------ */
7906  
7907 -static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
7908 +static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
7909  {
7910  
7911         yaffs_Device *dev = in->myDev;
7912 @@ -4939,11 +4965,11 @@ static void yaffs_PruneResizedChunks(yaf
7913  
7914  }
7915  
7916 -int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
7917 +int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
7918  {
7919  
7920         int oldFileSize = in->variant.fileVariant.fileSize;
7921 -       int newSizeOfPartialChunk;
7922 +       __u32 newSizeOfPartialChunk;
7923         int newFullChunks;
7924  
7925         yaffs_Device *dev = in->myDev;
7926 @@ -4955,13 +4981,11 @@ int yaffs_ResizeFile(yaffs_Object * in,
7927  
7928         yaffs_CheckGarbageCollection(dev);
7929  
7930 -       if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
7931 -               return yaffs_GetFileSize(in);
7932 -       }
7933 +       if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
7934 +               return YAFFS_FAIL;
7935  
7936 -       if (newSize == oldFileSize) {
7937 -               return oldFileSize;
7938 -       }
7939 +       if (newSize == oldFileSize)
7940 +               return YAFFS_OK;
7941  
7942         if (newSize < oldFileSize) {
7943  
7944 @@ -4994,21 +5018,20 @@ int yaffs_ResizeFile(yaffs_Object * in,
7945         }
7946  
7947  
7948 -
7949         /* Write a new object header.
7950          * show we've shrunk the file, if need be
7951          * Do this only if the file is not in the deleted directories.
7952          */
7953 -       if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
7954 -           in->parent->objectId != YAFFS_OBJECTID_DELETED) {
7955 +       if (in->parent &&
7956 +           in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
7957 +           in->parent->objectId != YAFFS_OBJECTID_DELETED)
7958                 yaffs_UpdateObjectHeader(in, NULL, 0,
7959                                          (newSize < oldFileSize) ? 1 : 0, 0);
7960 -       }
7961  
7962 -       return newSize;
7963 +       return YAFFS_OK;
7964  }
7965  
7966 -loff_t yaffs_GetFileSize(yaffs_Object * obj)
7967 +loff_t yaffs_GetFileSize(yaffs_Object *obj)
7968  {
7969         obj = yaffs_GetEquivalentObject(obj);
7970  
7971 @@ -5024,7 +5047,7 @@ loff_t yaffs_GetFileSize(yaffs_Object *
7972  
7973  
7974  
7975 -int yaffs_FlushFile(yaffs_Object * in, int updateTime)
7976 +int yaffs_FlushFile(yaffs_Object *in, int updateTime)
7977  {
7978         int retVal;
7979         if (in->dirty) {
7980 @@ -5039,9 +5062,8 @@ int yaffs_FlushFile(yaffs_Object * in, i
7981  #endif
7982                 }
7983  
7984 -               retVal =
7985 -                   (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
7986 -                    0) ? YAFFS_OK : YAFFS_FAIL;
7987 +               retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
7988 +                       0) ? YAFFS_OK : YAFFS_FAIL;
7989         } else {
7990                 retVal = YAFFS_OK;
7991         }
7992 @@ -5050,7 +5072,7 @@ int yaffs_FlushFile(yaffs_Object * in, i
7993  
7994  }
7995  
7996 -static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
7997 +static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
7998  {
7999  
8000         /* First off, invalidate the file's data in the cache, without flushing. */
8001 @@ -5058,13 +5080,13 @@ static int yaffs_DoGenericObjectDeletion
8002  
8003         if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
8004                 /* Move to the unlinked directory so we have a record that it was deleted. */
8005 -               yaffs_ChangeObjectName(in, in->myDev->deletedDir,"deleted", 0, 0);
8006 +               yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
8007  
8008         }
8009  
8010         yaffs_RemoveObjectFromDirectory(in);
8011 -       yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
8012 -       in->chunkId = -1;
8013 +       yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
8014 +       in->hdrChunk = 0;
8015  
8016         yaffs_FreeObject(in);
8017         return YAFFS_OK;
8018 @@ -5075,62 +5097,63 @@ static int yaffs_DoGenericObjectDeletion
8019   * and the inode associated with the file.
8020   * It does not delete the links associated with the file.
8021   */
8022 -static int yaffs_UnlinkFile(yaffs_Object * in)
8023 +static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
8024  {
8025  
8026         int retVal;
8027         int immediateDeletion = 0;
8028  
8029 -       if (1) {
8030  #ifdef __KERNEL__
8031 -               if (!in->myInode) {
8032 -                       immediateDeletion = 1;
8033 -
8034 -               }
8035 +       if (!in->myInode)
8036 +               immediateDeletion = 1;
8037  #else
8038 -               if (in->inUse <= 0) {
8039 -                       immediateDeletion = 1;
8040 -
8041 -               }
8042 +       if (in->inUse <= 0)
8043 +               immediateDeletion = 1;
8044  #endif
8045 -               if (immediateDeletion) {
8046 -                       retVal =
8047 -                           yaffs_ChangeObjectName(in, in->myDev->deletedDir,
8048 -                                                  "deleted", 0, 0);
8049 -                       T(YAFFS_TRACE_TRACING,
8050 -                         (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
8051 -                          in->objectId));
8052 -                       in->deleted = 1;
8053 -                       in->myDev->nDeletedFiles++;
8054 -                       if (0 && in->myDev->isYaffs2) {
8055 -                               yaffs_ResizeFile(in, 0);
8056 -                       }
8057 -                       yaffs_SoftDeleteFile(in);
8058 -               } else {
8059 -                       retVal =
8060 -                           yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
8061 -                                                  "unlinked", 0, 0);
8062 -               }
8063  
8064 +       if (immediateDeletion) {
8065 +               retVal =
8066 +                   yaffs_ChangeObjectName(in, in->myDev->deletedDir,
8067 +                                          _Y("deleted"), 0, 0);
8068 +               T(YAFFS_TRACE_TRACING,
8069 +                 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
8070 +                  in->objectId));
8071 +               in->deleted = 1;
8072 +               in->myDev->nDeletedFiles++;
8073 +               if (1 || in->myDev->isYaffs2)
8074 +                       yaffs_ResizeFile(in, 0);
8075 +               yaffs_SoftDeleteFile(in);
8076 +       } else {
8077 +               retVal =
8078 +                   yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
8079 +                                          _Y("unlinked"), 0, 0);
8080         }
8081 +
8082 +
8083         return retVal;
8084  }
8085  
8086 -int yaffs_DeleteFile(yaffs_Object * in)
8087 +int yaffs_DeleteFile(yaffs_Object *in)
8088  {
8089         int retVal = YAFFS_OK;
8090 +       int deleted = in->deleted;
8091 +
8092 +       yaffs_ResizeFile(in, 0);
8093  
8094         if (in->nDataChunks > 0) {
8095 -               /* Use soft deletion if there is data in the file */
8096 -               if (!in->unlinked) {
8097 -                       retVal = yaffs_UnlinkFile(in);
8098 -               }
8099 +               /* Use soft deletion if there is data in the file.
8100 +                * That won't be the case if it has been resized to zero.
8101 +                */
8102 +               if (!in->unlinked)
8103 +                       retVal = yaffs_UnlinkFileIfNeeded(in);
8104 +
8105                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
8106                         in->deleted = 1;
8107 +                       deleted = 1;
8108                         in->myDev->nDeletedFiles++;
8109                         yaffs_SoftDeleteFile(in);
8110                 }
8111 -               return in->deleted ? YAFFS_OK : YAFFS_FAIL;
8112 +               return deleted ? YAFFS_OK : YAFFS_FAIL;
8113         } else {
8114                 /* The file has no data chunks so we toss it immediately */
8115                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
8116 @@ -5141,62 +5164,75 @@ int yaffs_DeleteFile(yaffs_Object * in)
8117         }
8118  }
8119  
8120 -static int yaffs_DeleteDirectory(yaffs_Object * in)
8121 +static int yaffs_DeleteDirectory(yaffs_Object *in)
8122  {
8123         /* First check that the directory is empty. */
8124 -       if (list_empty(&in->variant.directoryVariant.children)) {
8125 +       if (ylist_empty(&in->variant.directoryVariant.children))
8126                 return yaffs_DoGenericObjectDeletion(in);
8127 -       }
8128  
8129         return YAFFS_FAIL;
8130  
8131  }
8132  
8133 -static int yaffs_DeleteSymLink(yaffs_Object * in)
8134 +static int yaffs_DeleteSymLink(yaffs_Object *in)
8135  {
8136         YFREE(in->variant.symLinkVariant.alias);
8137  
8138         return yaffs_DoGenericObjectDeletion(in);
8139  }
8140  
8141 -static int yaffs_DeleteHardLink(yaffs_Object * in)
8142 +static int yaffs_DeleteHardLink(yaffs_Object *in)
8143  {
8144         /* remove this hardlink from the list assocaited with the equivalent
8145          * object
8146          */
8147 -       list_del(&in->hardLinks);
8148 +       ylist_del_init(&in->hardLinks);
8149         return yaffs_DoGenericObjectDeletion(in);
8150  }
8151  
8152 -static void yaffs_DestroyObject(yaffs_Object * obj)
8153 +int yaffs_DeleteObject(yaffs_Object *obj)
8154  {
8155 +int retVal = -1;
8156         switch (obj->variantType) {
8157         case YAFFS_OBJECT_TYPE_FILE:
8158 -               yaffs_DeleteFile(obj);
8159 +               retVal = yaffs_DeleteFile(obj);
8160                 break;
8161         case YAFFS_OBJECT_TYPE_DIRECTORY:
8162 -               yaffs_DeleteDirectory(obj);
8163 +               return yaffs_DeleteDirectory(obj);
8164                 break;
8165         case YAFFS_OBJECT_TYPE_SYMLINK:
8166 -               yaffs_DeleteSymLink(obj);
8167 +               retVal = yaffs_DeleteSymLink(obj);
8168                 break;
8169         case YAFFS_OBJECT_TYPE_HARDLINK:
8170 -               yaffs_DeleteHardLink(obj);
8171 +               retVal = yaffs_DeleteHardLink(obj);
8172                 break;
8173         case YAFFS_OBJECT_TYPE_SPECIAL:
8174 -               yaffs_DoGenericObjectDeletion(obj);
8175 +               retVal = yaffs_DoGenericObjectDeletion(obj);
8176                 break;
8177         case YAFFS_OBJECT_TYPE_UNKNOWN:
8178 +               retVal = 0;
8179                 break;          /* should not happen. */
8180         }
8181 +
8182 +       return retVal;
8183  }
8184  
8185 -static int yaffs_UnlinkWorker(yaffs_Object * obj)
8186 +static int yaffs_UnlinkWorker(yaffs_Object *obj)
8187  {
8188  
8189 +       int immediateDeletion = 0;
8190 +
8191 +#ifdef __KERNEL__
8192 +       if (!obj->myInode)
8193 +               immediateDeletion = 1;
8194 +#else
8195 +       if (obj->inUse <= 0)
8196 +               immediateDeletion = 1;
8197 +#endif
8198 +
8199         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
8200                 return yaffs_DeleteHardLink(obj);
8201 -       } else if (!list_empty(&obj->hardLinks)) {
8202 +       } else if (!ylist_empty(&obj->hardLinks)) {
8203                 /* Curve ball: We're unlinking an object that has a hardlink.
8204                  *
8205                  * This problem arises because we are not strictly following
8206 @@ -5215,24 +5251,24 @@ static int yaffs_UnlinkWorker(yaffs_Obje
8207                 int retVal;
8208                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
8209  
8210 -               hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
8211 +               hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
8212  
8213 -               list_del_init(&hl->hardLinks);
8214 -               list_del_init(&hl->siblings);
8215 +               ylist_del_init(&hl->hardLinks);
8216 +               ylist_del_init(&hl->siblings);
8217  
8218                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
8219  
8220                 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
8221  
8222 -               if (retVal == YAFFS_OK) {
8223 +               if (retVal == YAFFS_OK)
8224                         retVal = yaffs_DoGenericObjectDeletion(hl);
8225 -               }
8226 +
8227                 return retVal;
8228  
8229 -       } else {
8230 +       } else if (immediateDeletion) {
8231                 switch (obj->variantType) {
8232                 case YAFFS_OBJECT_TYPE_FILE:
8233 -                       return yaffs_UnlinkFile(obj);
8234 +                       return yaffs_DeleteFile(obj);
8235                         break;
8236                 case YAFFS_OBJECT_TYPE_DIRECTORY:
8237                         return yaffs_DeleteDirectory(obj);
8238 @@ -5248,21 +5284,22 @@ static int yaffs_UnlinkWorker(yaffs_Obje
8239                 default:
8240                         return YAFFS_FAIL;
8241                 }
8242 -       }
8243 +       } else
8244 +               return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
8245 +                                          _Y("unlinked"), 0, 0);
8246  }
8247  
8248  
8249 -static int yaffs_UnlinkObject( yaffs_Object *obj)
8250 +static int yaffs_UnlinkObject(yaffs_Object *obj)
8251  {
8252  
8253 -       if (obj && obj->unlinkAllowed) {
8254 +       if (obj && obj->unlinkAllowed)
8255                 return yaffs_UnlinkWorker(obj);
8256 -       }
8257  
8258         return YAFFS_FAIL;
8259  
8260  }
8261 -int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
8262 +int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
8263  {
8264         yaffs_Object *obj;
8265  
8266 @@ -5272,8 +5309,8 @@ int yaffs_Unlink(yaffs_Object * dir, con
8267  
8268  /*----------------------- Initialisation Scanning ---------------------- */
8269  
8270 -static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
8271 -                                      int backwardScanning)
8272 +static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
8273 +                               int backwardScanning)
8274  {
8275         yaffs_Object *obj;
8276  
8277 @@ -5286,9 +5323,8 @@ static void yaffs_HandleShadowedObject(y
8278                 /* Handle YAFFS2 case (backward scanning)
8279                  * If the shadowed object exists then ignore.
8280                  */
8281 -               if (yaffs_FindObjectByNumber(dev, objId)) {
8282 +               if (yaffs_FindObjectByNumber(dev, objId))
8283                         return;
8284 -               }
8285         }
8286  
8287         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
8288 @@ -5297,6 +5333,8 @@ static void yaffs_HandleShadowedObject(y
8289         obj =
8290             yaffs_FindOrCreateObjectByNumber(dev, objId,
8291                                              YAFFS_OBJECT_TYPE_FILE);
8292 +       if (!obj)
8293 +               return;
8294         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
8295         obj->variant.fileVariant.shrinkSize = 0;
8296         obj->valid = 1;         /* So that we don't read any other info for this file */
8297 @@ -5325,44 +5363,77 @@ static void yaffs_HardlinkFixup(yaffs_De
8298                 if (in) {
8299                         /* Add the hardlink pointers */
8300                         hl->variant.hardLinkVariant.equivalentObject = in;
8301 -                       list_add(&hl->hardLinks, &in->hardLinks);
8302 +                       ylist_add(&hl->hardLinks, &in->hardLinks);
8303                 } else {
8304                         /* Todo Need to report/handle this better.
8305                          * Got a problem... hardlink to a non-existant object
8306                          */
8307                         hl->variant.hardLinkVariant.equivalentObject = NULL;
8308 -                       INIT_LIST_HEAD(&hl->hardLinks);
8309 +                       YINIT_LIST_HEAD(&hl->hardLinks);
8310  
8311                 }
8312 -
8313         }
8314 +}
8315 +
8316 +
8317  
8318 +
8319 +
8320 +static int ybicmp(const void *a, const void *b)
8321 +{
8322 +       register int aseq = ((yaffs_BlockIndex *)a)->seq;
8323 +       register int bseq = ((yaffs_BlockIndex *)b)->seq;
8324 +       register int ablock = ((yaffs_BlockIndex *)a)->block;
8325 +       register int bblock = ((yaffs_BlockIndex *)b)->block;
8326 +       if (aseq == bseq)
8327 +               return ablock - bblock;
8328 +       else
8329 +               return aseq - bseq;
8330  }
8331  
8332  
8333 +struct yaffs_ShadowFixerStruct {
8334 +       int objectId;
8335 +       int shadowedId;
8336 +       struct yaffs_ShadowFixerStruct *next;
8337 +};
8338 +
8339  
8340 +static void yaffs_StripDeletedObjects(yaffs_Device *dev)
8341 +{
8342 +       /*
8343 +       *  Sort out state of unlinked and deleted objects after scanning.
8344 +       */
8345 +       struct ylist_head *i;
8346 +       struct ylist_head *n;
8347 +       yaffs_Object *l;
8348  
8349 +       /* Soft delete all the unlinked files */
8350 +       ylist_for_each_safe(i, n,
8351 +               &dev->unlinkedDir->variant.directoryVariant.children) {
8352 +               if (i) {
8353 +                       l = ylist_entry(i, yaffs_Object, siblings);
8354 +                       yaffs_DeleteObject(l);
8355 +               }
8356 +       }
8357  
8358 -static int ybicmp(const void *a, const void *b){
8359 -    register int aseq = ((yaffs_BlockIndex *)a)->seq;
8360 -    register int bseq = ((yaffs_BlockIndex *)b)->seq;
8361 -    register int ablock = ((yaffs_BlockIndex *)a)->block;
8362 -    register int bblock = ((yaffs_BlockIndex *)b)->block;
8363 -    if( aseq == bseq )
8364 -        return ablock - bblock;
8365 -    else
8366 -        return aseq - bseq;
8367 +       ylist_for_each_safe(i, n,
8368 +               &dev->deletedDir->variant.directoryVariant.children) {
8369 +               if (i) {
8370 +                       l = ylist_entry(i, yaffs_Object, siblings);
8371 +                       yaffs_DeleteObject(l);
8372 +               }
8373 +       }
8374  
8375  }
8376  
8377 -static int yaffs_Scan(yaffs_Device * dev)
8378 +static int yaffs_Scan(yaffs_Device *dev)
8379  {
8380         yaffs_ExtendedTags tags;
8381         int blk;
8382         int blockIterator;
8383         int startIterator;
8384         int endIterator;
8385 -       int nBlocksToScan = 0;
8386         int result;
8387  
8388         int chunk;
8389 @@ -5371,26 +5442,19 @@ static int yaffs_Scan(yaffs_Device * dev
8390         yaffs_BlockState state;
8391         yaffs_Object *hardList = NULL;
8392         yaffs_BlockInfo *bi;
8393 -       int sequenceNumber;
8394 +       __u32 sequenceNumber;
8395         yaffs_ObjectHeader *oh;
8396         yaffs_Object *in;
8397         yaffs_Object *parent;
8398 -       int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
8399  
8400         int alloc_failed = 0;
8401  
8402 +       struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
8403 +
8404  
8405         __u8 *chunkData;
8406  
8407 -       yaffs_BlockIndex *blockIndex = NULL;
8408  
8409 -       if (dev->isYaffs2) {
8410 -               T(YAFFS_TRACE_SCAN,
8411 -                 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
8412 -               return YAFFS_FAIL;
8413 -       }
8414 -
8415 -       //TODO  Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
8416  
8417         T(YAFFS_TRACE_SCAN,
8418           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
8419 @@ -5400,12 +5464,6 @@ static int yaffs_Scan(yaffs_Device * dev
8420  
8421         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
8422  
8423 -       if (dev->isYaffs2) {
8424 -               blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
8425 -               if(!blockIndex)
8426 -                       return YAFFS_FAIL;
8427 -       }
8428 -
8429         /* Scan all the blocks to determine their state */
8430         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
8431                 bi = yaffs_GetBlockInfo(dev, blk);
8432 @@ -5418,6 +5476,9 @@ static int yaffs_Scan(yaffs_Device * dev
8433                 bi->blockState = state;
8434                 bi->sequenceNumber = sequenceNumber;
8435  
8436 +               if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
8437 +                       bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
8438 +
8439                 T(YAFFS_TRACE_SCAN_DEBUG,
8440                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
8441                    state, sequenceNumber));
8442 @@ -5430,70 +5491,21 @@ static int yaffs_Scan(yaffs_Device * dev
8443                           (TSTR("Block empty " TENDSTR)));
8444                         dev->nErasedBlocks++;
8445                         dev->nFreeChunks += dev->nChunksPerBlock;
8446 -               } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
8447 -
8448 -                       /* Determine the highest sequence number */
8449 -                       if (dev->isYaffs2 &&
8450 -                           sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
8451 -                           sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
8452 -
8453 -                               blockIndex[nBlocksToScan].seq = sequenceNumber;
8454 -                               blockIndex[nBlocksToScan].block = blk;
8455 -
8456 -                               nBlocksToScan++;
8457 -
8458 -                               if (sequenceNumber >= dev->sequenceNumber) {
8459 -                                       dev->sequenceNumber = sequenceNumber;
8460 -                               }
8461 -                       } else if (dev->isYaffs2) {
8462 -                               /* TODO: Nasty sequence number! */
8463 -                               T(YAFFS_TRACE_SCAN,
8464 -                                 (TSTR
8465 -                                  ("Block scanning block %d has bad sequence number %d"
8466 -                                   TENDSTR), blk, sequenceNumber));
8467 -
8468 -                       }
8469                 }
8470         }
8471  
8472 -       /* Sort the blocks
8473 -        * Dungy old bubble sort for now...
8474 -        */
8475 -       if (dev->isYaffs2) {
8476 -               yaffs_BlockIndex temp;
8477 -               int i;
8478 -               int j;
8479 -
8480 -               for (i = 0; i < nBlocksToScan; i++)
8481 -                       for (j = i + 1; j < nBlocksToScan; j++)
8482 -                               if (blockIndex[i].seq > blockIndex[j].seq) {
8483 -                                       temp = blockIndex[j];
8484 -                                       blockIndex[j] = blockIndex[i];
8485 -                                       blockIndex[i] = temp;
8486 -                               }
8487 -       }
8488 -
8489 -       /* Now scan the blocks looking at the data. */
8490 -       if (dev->isYaffs2) {
8491 -               startIterator = 0;
8492 -               endIterator = nBlocksToScan - 1;
8493 -               T(YAFFS_TRACE_SCAN_DEBUG,
8494 -                 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
8495 -       } else {
8496 -               startIterator = dev->internalStartBlock;
8497 -               endIterator = dev->internalEndBlock;
8498 -       }
8499 +       startIterator = dev->internalStartBlock;
8500 +       endIterator = dev->internalEndBlock;
8501  
8502         /* For each block.... */
8503         for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
8504              blockIterator++) {
8505  
8506 -               if (dev->isYaffs2) {
8507 -                       /* get the block to scan in the correct order */
8508 -                       blk = blockIndex[blockIterator].block;
8509 -               } else {
8510 -                       blk = blockIterator;
8511 -               }
8512 +               YYIELD();
8513 +
8514 +               YYIELD();
8515 +
8516 +               blk = blockIterator;
8517  
8518                 bi = yaffs_GetBlockInfo(dev, blk);
8519                 state = bi->blockState;
8520 @@ -5511,7 +5523,7 @@ static int yaffs_Scan(yaffs_Device * dev
8521  
8522                         /* Let's have a good look at this chunk... */
8523  
8524 -                       if (!dev->isYaffs2 && tags.chunkDeleted) {
8525 +                       if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
8526                                 /* YAFFS1 only...
8527                                  * A deleted chunk
8528                                  */
8529 @@ -5540,18 +5552,6 @@ static int yaffs_Scan(yaffs_Device * dev
8530                                         dev->allocationBlockFinder = blk;
8531                                         /* Set it to here to encourage the allocator to go forth from here. */
8532  
8533 -                                       /* Yaffs2 sanity check:
8534 -                                        * This should be the one with the highest sequence number
8535 -                                        */
8536 -                                       if (dev->isYaffs2
8537 -                                           && (dev->sequenceNumber !=
8538 -                                               bi->sequenceNumber)) {
8539 -                                               T(YAFFS_TRACE_ALWAYS,
8540 -                                                 (TSTR
8541 -                                                  ("yaffs: Allocation block %d was not highest sequence id:"
8542 -                                                   " block seq = %d, dev seq = %d"
8543 -                                                   TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
8544 -                                       }
8545                                 }
8546  
8547                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
8548 @@ -5570,11 +5570,11 @@ static int yaffs_Scan(yaffs_Device * dev
8549                                  * the same chunkId).
8550                                  */
8551  
8552 -                               if(!in)
8553 +                               if (!in)
8554                                         alloc_failed = 1;
8555  
8556 -                               if(in){
8557 -                                       if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
8558 +                               if (in) {
8559 +                                       if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
8560                                                 alloc_failed = 1;
8561                                 }
8562  
8563 @@ -5617,7 +5617,7 @@ static int yaffs_Scan(yaffs_Device * dev
8564                                          * deleted, and worse still it has changed type. Delete the old object.
8565                                          */
8566  
8567 -                                       yaffs_DestroyObject(in);
8568 +                                       yaffs_DeleteObject(in);
8569  
8570                                         in = 0;
8571                                 }
8572 @@ -5627,14 +5627,20 @@ static int yaffs_Scan(yaffs_Device * dev
8573                                                                       objectId,
8574                                                                       oh->type);
8575  
8576 -                               if(!in)
8577 +                               if (!in)
8578                                         alloc_failed = 1;
8579  
8580                                 if (in && oh->shadowsObject > 0) {
8581 -                                       yaffs_HandleShadowedObject(dev,
8582 -                                                                  oh->
8583 -                                                                  shadowsObject,
8584 -                                                                  0);
8585 +
8586 +                                       struct yaffs_ShadowFixerStruct *fixer;
8587 +                                       fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
8588 +                                       if (fixer) {
8589 +                                               fixer->next = shadowFixerList;
8590 +                                               shadowFixerList = fixer;
8591 +                                               fixer->objectId = tags.objectId;
8592 +                                               fixer->shadowedId = oh->shadowsObject;
8593 +                                       }
8594 +
8595                                 }
8596  
8597                                 if (in && in->valid) {
8598 @@ -5643,12 +5649,10 @@ static int yaffs_Scan(yaffs_Device * dev
8599                                         unsigned existingSerial = in->serial;
8600                                         unsigned newSerial = tags.serialNumber;
8601  
8602 -                                       if (dev->isYaffs2 ||
8603 -                                           ((existingSerial + 1) & 3) ==
8604 -                                           newSerial) {
8605 +                                       if (((existingSerial + 1) & 3) == newSerial) {
8606                                                 /* Use new one - destroy the exisiting one */
8607                                                 yaffs_DeleteChunk(dev,
8608 -                                                                 in->chunkId,
8609 +                                                                 in->hdrChunk,
8610                                                                   1, __LINE__);
8611                                                 in->valid = 0;
8612                                         } else {
8613 @@ -5681,7 +5685,8 @@ static int yaffs_Scan(yaffs_Device * dev
8614                                         in->yst_ctime = oh->yst_ctime;
8615                                         in->yst_rdev = oh->yst_rdev;
8616  #endif
8617 -                                       in->chunkId = chunk;
8618 +                                       in->hdrChunk = chunk;
8619 +                                       in->serial = tags.serialNumber;
8620  
8621                                 } else if (in && !in->valid) {
8622                                         /* we need to load this info */
8623 @@ -5705,7 +5710,8 @@ static int yaffs_Scan(yaffs_Device * dev
8624                                         in->yst_ctime = oh->yst_ctime;
8625                                         in->yst_rdev = oh->yst_rdev;
8626  #endif
8627 -                                       in->chunkId = chunk;
8628 +                                       in->hdrChunk = chunk;
8629 +                                       in->serial = tags.serialNumber;
8630  
8631                                         yaffs_SetObjectName(in, oh->name);
8632                                         in->dirty = 0;
8633 @@ -5718,25 +5724,25 @@ static int yaffs_Scan(yaffs_Device * dev
8634                                             yaffs_FindOrCreateObjectByNumber
8635                                             (dev, oh->parentObjectId,
8636                                              YAFFS_OBJECT_TYPE_DIRECTORY);
8637 -                                       if (parent->variantType ==
8638 +                                       if (!parent)
8639 +                                               alloc_failed = 1;
8640 +                                       if (parent && parent->variantType ==
8641                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
8642                                                 /* Set up as a directory */
8643                                                 parent->variantType =
8644 -                                                   YAFFS_OBJECT_TYPE_DIRECTORY;
8645 -                                               INIT_LIST_HEAD(&parent->variant.
8646 -                                                              directoryVariant.
8647 -                                                              children);
8648 -                                       } else if (parent->variantType !=
8649 -                                                  YAFFS_OBJECT_TYPE_DIRECTORY)
8650 -                                       {
8651 +                                                       YAFFS_OBJECT_TYPE_DIRECTORY;
8652 +                                               YINIT_LIST_HEAD(&parent->variant.
8653 +                                                               directoryVariant.
8654 +                                                               children);
8655 +                                       } else if (!parent || parent->variantType !=
8656 +                                                  YAFFS_OBJECT_TYPE_DIRECTORY) {
8657                                                 /* Hoosterman, another problem....
8658                                                  * We're trying to use a non-directory as a directory
8659                                                  */
8660  
8661                                                 T(YAFFS_TRACE_ERROR,
8662                                                   (TSTR
8663 -                                                  ("yaffs tragedy: attempting to use non-directory as"
8664 -                                                   " a directory in scan. Put in lost+found."
8665 +                                                  ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
8666                                                     TENDSTR)));
8667                                                 parent = dev->lostNFoundDir;
8668                                         }
8669 @@ -5760,15 +5766,6 @@ static int yaffs_Scan(yaffs_Device * dev
8670                                                 /* Todo got a problem */
8671                                                 break;
8672                                         case YAFFS_OBJECT_TYPE_FILE:
8673 -                                               if (dev->isYaffs2
8674 -                                                   && oh->isShrink) {
8675 -                                                       /* Prune back the shrunken chunks */
8676 -                                                       yaffs_PruneResizedChunks
8677 -                                                           (in, oh->fileSize);
8678 -                                                       /* Mark the block as having a shrinkHeader */
8679 -                                                       bi->hasShrinkHeader = 1;
8680 -                                               }
8681 -
8682                                                 if (dev->useHeaderFileSize)
8683  
8684                                                         in->variant.fileVariant.
8685 @@ -5778,11 +5775,11 @@ static int yaffs_Scan(yaffs_Device * dev
8686                                                 break;
8687                                         case YAFFS_OBJECT_TYPE_HARDLINK:
8688                                                 in->variant.hardLinkVariant.
8689 -                                                   equivalentObjectId =
8690 -                                                   oh->equivalentObjectId;
8691 +                                                       equivalentObjectId =
8692 +                                                       oh->equivalentObjectId;
8693                                                 in->hardLinks.next =
8694 -                                                   (struct list_head *)
8695 -                                                   hardList;
8696 +                                                       (struct ylist_head *)
8697 +                                                       hardList;
8698                                                 hardList = in;
8699                                                 break;
8700                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
8701 @@ -5794,15 +5791,17 @@ static int yaffs_Scan(yaffs_Device * dev
8702                                         case YAFFS_OBJECT_TYPE_SYMLINK:
8703                                                 in->variant.symLinkVariant.alias =
8704                                                     yaffs_CloneString(oh->alias);
8705 -                                               if(!in->variant.symLinkVariant.alias)
8706 +                                               if (!in->variant.symLinkVariant.alias)
8707                                                         alloc_failed = 1;
8708                                                 break;
8709                                         }
8710  
8711 +/*
8712                                         if (parent == dev->deletedDir) {
8713                                                 yaffs_DestroyObject(in);
8714                                                 bi->hasShrinkHeader = 1;
8715                                         }
8716 +*/
8717                                 }
8718                         }
8719                 }
8720 @@ -5823,10 +5822,6 @@ static int yaffs_Scan(yaffs_Device * dev
8721  
8722         }
8723  
8724 -       if (blockIndex) {
8725 -               YFREE(blockIndex);
8726 -       }
8727 -
8728  
8729         /* Ok, we've done all the scanning.
8730          * Fix up the hard link chains.
8731 @@ -5834,32 +5829,36 @@ static int yaffs_Scan(yaffs_Device * dev
8732          * hardlinks.
8733          */
8734  
8735 -       yaffs_HardlinkFixup(dev,hardList);
8736 +       yaffs_HardlinkFixup(dev, hardList);
8737  
8738 -       /* Handle the unlinked files. Since they were left in an unlinked state we should
8739 -        * just delete them.
8740 -        */
8741 +       /* Fix up any shadowed objects */
8742         {
8743 -               struct list_head *i;
8744 -               struct list_head *n;
8745 +               struct yaffs_ShadowFixerStruct *fixer;
8746 +               yaffs_Object *obj;
8747  
8748 -               yaffs_Object *l;
8749 -               /* Soft delete all the unlinked files */
8750 -               list_for_each_safe(i, n,
8751 -                                  &dev->unlinkedDir->variant.directoryVariant.
8752 -                                  children) {
8753 -                       if (i) {
8754 -                               l = list_entry(i, yaffs_Object, siblings);
8755 -                               yaffs_DestroyObject(l);
8756 -                       }
8757 +               while (shadowFixerList) {
8758 +                       fixer = shadowFixerList;
8759 +                       shadowFixerList = fixer->next;
8760 +                       /* Complete the rename transaction by deleting the shadowed object
8761 +                        * then setting the object header to unshadowed.
8762 +                        */
8763 +                       obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
8764 +                       if (obj)
8765 +                               yaffs_DeleteObject(obj);
8766 +
8767 +                       obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
8768 +
8769 +                       if (obj)
8770 +                               yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
8771 +
8772 +                       YFREE(fixer);
8773                 }
8774         }
8775  
8776         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
8777  
8778 -       if(alloc_failed){
8779 +       if (alloc_failed)
8780                 return YAFFS_FAIL;
8781 -       }
8782  
8783         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
8784  
8785 @@ -5871,25 +5870,27 @@ static void yaffs_CheckObjectDetailsLoad
8786  {
8787         __u8 *chunkData;
8788         yaffs_ObjectHeader *oh;
8789 -       yaffs_Device *dev = in->myDev;
8790 +       yaffs_Device *dev;
8791         yaffs_ExtendedTags tags;
8792         int result;
8793         int alloc_failed = 0;
8794  
8795 -       if(!in)
8796 +       if (!in)
8797                 return;
8798  
8799 +       dev = in->myDev;
8800 +
8801  #if 0
8802 -       T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
8803 +       T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
8804                 in->objectId,
8805                 in->lazyLoaded ? "not yet" : "already"));
8806  #endif
8807  
8808 -       if(in->lazyLoaded){
8809 +       if (in->lazyLoaded && in->hdrChunk > 0) {
8810                 in->lazyLoaded = 0;
8811                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
8812  
8813 -               result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
8814 +               result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
8815                 oh = (yaffs_ObjectHeader *) chunkData;
8816  
8817                 in->yst_mode = oh->yst_mode;
8818 @@ -5911,18 +5912,18 @@ static void yaffs_CheckObjectDetailsLoad
8819  #endif
8820                 yaffs_SetObjectName(in, oh->name);
8821  
8822 -               if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
8823 -                        in->variant.symLinkVariant.alias =
8824 +               if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
8825 +                       in->variant.symLinkVariant.alias =
8826                                                     yaffs_CloneString(oh->alias);
8827 -                       if(!in->variant.symLinkVariant.alias)
8828 +                       if (!in->variant.symLinkVariant.alias)
8829                                 alloc_failed = 1; /* Not returned to caller */
8830                 }
8831  
8832 -               yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
8833 +               yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
8834         }
8835  }
8836  
8837 -static int yaffs_ScanBackwards(yaffs_Device * dev)
8838 +static int yaffs_ScanBackwards(yaffs_Device *dev)
8839  {
8840         yaffs_ExtendedTags tags;
8841         int blk;
8842 @@ -5938,7 +5939,7 @@ static int yaffs_ScanBackwards(yaffs_Dev
8843         yaffs_BlockState state;
8844         yaffs_Object *hardList = NULL;
8845         yaffs_BlockInfo *bi;
8846 -       int sequenceNumber;
8847 +       __u32 sequenceNumber;
8848         yaffs_ObjectHeader *oh;
8849         yaffs_Object *in;
8850         yaffs_Object *parent;
8851 @@ -5972,12 +5973,12 @@ static int yaffs_ScanBackwards(yaffs_Dev
8852  
8853         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
8854  
8855 -       if(!blockIndex) {
8856 +       if (!blockIndex) {
8857                 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
8858                 altBlockIndex = 1;
8859         }
8860  
8861 -       if(!blockIndex) {
8862 +       if (!blockIndex) {
8863                 T(YAFFS_TRACE_SCAN,
8864                   (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
8865                 return YAFFS_FAIL;
8866 @@ -5999,15 +6000,17 @@ static int yaffs_ScanBackwards(yaffs_Dev
8867                 bi->blockState = state;
8868                 bi->sequenceNumber = sequenceNumber;
8869  
8870 -               if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
8871 +               if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
8872                         bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
8873 +               if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
8874 +                       bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
8875  
8876                 T(YAFFS_TRACE_SCAN_DEBUG,
8877                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
8878                    state, sequenceNumber));
8879  
8880  
8881 -               if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
8882 +               if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
8883                         dev->blocksInCheckpoint++;
8884  
8885                 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
8886 @@ -6021,8 +6024,7 @@ static int yaffs_ScanBackwards(yaffs_Dev
8887                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
8888  
8889                         /* Determine the highest sequence number */
8890 -                       if (dev->isYaffs2 &&
8891 -                           sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
8892 +                       if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
8893                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
8894  
8895                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
8896 @@ -6030,10 +6032,9 @@ static int yaffs_ScanBackwards(yaffs_Dev
8897  
8898                                 nBlocksToScan++;
8899  
8900 -                               if (sequenceNumber >= dev->sequenceNumber) {
8901 +                               if (sequenceNumber >= dev->sequenceNumber)
8902                                         dev->sequenceNumber = sequenceNumber;
8903 -                               }
8904 -                       } else if (dev->isYaffs2) {
8905 +                       } else {
8906                                 /* TODO: Nasty sequence number! */
8907                                 T(YAFFS_TRACE_SCAN,
8908                                   (TSTR
8909 @@ -6053,11 +6054,13 @@ static int yaffs_ScanBackwards(yaffs_Dev
8910  
8911         /* Sort the blocks */
8912  #ifndef CONFIG_YAFFS_USE_OWN_SORT
8913 -       yaffs_qsort(blockIndex, nBlocksToScan,
8914 -               sizeof(yaffs_BlockIndex), ybicmp);
8915 +       {
8916 +               /* Use qsort now. */
8917 +               yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
8918 +       }
8919  #else
8920         {
8921 -               /* Dungy old bubble sort... */
8922 +               /* Dungy old bubble sort... */
8923  
8924                 yaffs_BlockIndex temp;
8925                 int i;
8926 @@ -6075,7 +6078,7 @@ static int yaffs_ScanBackwards(yaffs_Dev
8927  
8928         YYIELD();
8929  
8930 -       T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
8931 +       T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
8932  
8933         /* Now scan the blocks looking at the data. */
8934         startIterator = 0;
8935 @@ -6085,10 +6088,10 @@ static int yaffs_ScanBackwards(yaffs_Dev
8936  
8937         /* For each block.... backwards */
8938         for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
8939 -            blockIterator--) {
8940 -               /* Cooperative multitasking! This loop can run for so
8941 +                       blockIterator--) {
8942 +               /* Cooperative multitasking! This loop can run for so
8943                    long that watchdog timers expire. */
8944 -               YYIELD();
8945 +               YYIELD();
8946  
8947                 /* get the block to scan in the correct order */
8948                 blk = blockIndex[blockIterator].block;
8949 @@ -6127,10 +6130,8 @@ static int yaffs_ScanBackwards(yaffs_Dev
8950                                  * this is the one being allocated from
8951                                  */
8952  
8953 -                               if(foundChunksInBlock)
8954 -                               {
8955 +                               if (foundChunksInBlock) {
8956                                         /* This is a chunk that was skipped due to failing the erased check */
8957 -
8958                                 } else if (c == 0) {
8959                                         /* We're looking at the first chunk in the block so the block is unused */
8960                                         state = YAFFS_BLOCK_STATE_EMPTY;
8961 @@ -6138,7 +6139,7 @@ static int yaffs_ScanBackwards(yaffs_Dev
8962                                 } else {
8963                                         if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
8964                                             state == YAFFS_BLOCK_STATE_ALLOCATING) {
8965 -                                               if(dev->sequenceNumber == bi->sequenceNumber) {
8966 +                                               if (dev->sequenceNumber == bi->sequenceNumber) {
8967                                                         /* this is the block being allocated from */
8968  
8969                                                         T(YAFFS_TRACE_SCAN,
8970 @@ -6150,27 +6151,31 @@ static int yaffs_ScanBackwards(yaffs_Dev
8971                                                         dev->allocationBlock = blk;
8972                                                         dev->allocationPage = c;
8973                                                         dev->allocationBlockFinder = blk;
8974 -                                               }
8975 -                                               else {
8976 +                                               } else {
8977                                                         /* This is a partially written block that is not
8978                                                          * the current allocation block. This block must have
8979                                                          * had a write failure, so set up for retirement.
8980                                                          */
8981  
8982 -                                                        bi->needsRetiring = 1;
8983 +                                                        /* bi->needsRetiring = 1; ??? TODO */
8984                                                          bi->gcPrioritise = 1;
8985  
8986                                                          T(YAFFS_TRACE_ALWAYS,
8987 -                                                        (TSTR("Partially written block %d being set for retirement" TENDSTR),
8988 +                                                        (TSTR("Partially written block %d detected" TENDSTR),
8989                                                          blk));
8990                                                 }
8991 -
8992                                         }
8993 -
8994                                 }
8995  
8996                                 dev->nFreeChunks++;
8997  
8998 +                       } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
8999 +                               T(YAFFS_TRACE_SCAN,
9000 +                                 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
9001 +                                 blk, c));
9002 +
9003 +                                 dev->nFreeChunks++;
9004 +
9005                         } else if (tags.chunkId > 0) {
9006                                 /* chunkId > 0 so it is a data chunk... */
9007                                 unsigned int endpos;
9008 @@ -6187,7 +6192,7 @@ static int yaffs_ScanBackwards(yaffs_Dev
9009                                                                       tags.
9010                                                                       objectId,
9011                                                                       YAFFS_OBJECT_TYPE_FILE);
9012 -                               if(!in){
9013 +                               if (!in) {
9014                                         /* Out of memory */
9015                                         alloc_failed = 1;
9016                                 }
9017 @@ -6197,8 +6202,8 @@ static int yaffs_ScanBackwards(yaffs_Dev
9018                                     && chunkBase <
9019                                     in->variant.fileVariant.shrinkSize) {
9020                                         /* This has not been invalidated by a resize */
9021 -                                       if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
9022 -                                                              chunk, -1)){
9023 +                                       if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
9024 +                                                              chunk, -1)) {
9025                                                 alloc_failed = 1;
9026                                         }
9027  
9028 @@ -6221,7 +6226,7 @@ static int yaffs_ScanBackwards(yaffs_Dev
9029                                                     scannedFileSize;
9030                                         }
9031  
9032 -                               } else if(in) {
9033 +                               } else if (in) {
9034                                         /* This chunk has been invalidated by a resize, so delete */
9035                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
9036  
9037 @@ -6242,6 +6247,8 @@ static int yaffs_ScanBackwards(yaffs_Dev
9038                                         in = yaffs_FindOrCreateObjectByNumber
9039                                             (dev, tags.objectId,
9040                                              tags.extraObjectType);
9041 +                                       if (!in)
9042 +                                               alloc_failed = 1;
9043                                 }
9044  
9045                                 if (!in ||
9046 @@ -6251,8 +6258,7 @@ static int yaffs_ScanBackwards(yaffs_Dev
9047                                     tags.extraShadows ||
9048                                     (!in->valid &&
9049                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
9050 -                                    tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
9051 -                                   ) {
9052 +                                    tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
9053  
9054                                         /* If we don't have  valid info then we need to read the chunk
9055                                          * TODO In future we can probably defer reading the chunk and
9056 @@ -6266,8 +6272,17 @@ static int yaffs_ScanBackwards(yaffs_Dev
9057  
9058                                         oh = (yaffs_ObjectHeader *) chunkData;
9059  
9060 -                                       if (!in)
9061 +                                       if (dev->inbandTags) {
9062 +                                               /* Fix up the header if they got corrupted by inband tags */
9063 +                                               oh->shadowsObject = oh->inbandShadowsObject;
9064 +                                               oh->isShrink = oh->inbandIsShrink;
9065 +                                       }
9066 +
9067 +                                       if (!in) {
9068                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
9069 +                                               if (!in)
9070 +                                                       alloc_failed = 1;
9071 +                                       }
9072  
9073                                 }
9074  
9075 @@ -6275,10 +6290,9 @@ static int yaffs_ScanBackwards(yaffs_Dev
9076                                         /* TODO Hoosterman we have a problem! */
9077                                         T(YAFFS_TRACE_ERROR,
9078                                           (TSTR
9079 -                                          ("yaffs tragedy: Could not make object for object  %d  "
9080 -                                           "at chunk %d during scan"
9081 +                                          ("yaffs tragedy: Could not make object for object  %d at chunk %d during scan"
9082                                             TENDSTR), tags.objectId, chunk));
9083 -
9084 +                                       continue;
9085                                 }
9086  
9087                                 if (in->valid) {
9088 @@ -6289,10 +6303,9 @@ static int yaffs_ScanBackwards(yaffs_Dev
9089  
9090                                         if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
9091                                              ((oh &&
9092 -                                              oh-> type == YAFFS_OBJECT_TYPE_FILE)||
9093 +                                              oh->type == YAFFS_OBJECT_TYPE_FILE) ||
9094                                               (tags.extraHeaderInfoAvailable  &&
9095 -                                              tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
9096 -                                           ) {
9097 +                                              tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
9098                                                 __u32 thisSize =
9099                                                     (oh) ? oh->fileSize : tags.
9100                                                     extraFileLength;
9101 @@ -6300,7 +6313,9 @@ static int yaffs_ScanBackwards(yaffs_Dev
9102                                                     (oh) ? oh->
9103                                                     parentObjectId : tags.
9104                                                     extraParentObjectId;
9105 -                                               unsigned isShrink =
9106 +
9107 +
9108 +                                               isShrink =
9109                                                     (oh) ? oh->isShrink : tags.
9110                                                     extraIsShrinkHeader;
9111  
9112 @@ -6323,9 +6338,8 @@ static int yaffs_ScanBackwards(yaffs_Dev
9113                                                             thisSize;
9114                                                 }
9115  
9116 -                                               if (isShrink) {
9117 +                                               if (isShrink)
9118                                                         bi->hasShrinkHeader = 1;
9119 -                                               }
9120  
9121                                         }
9122                                         /* Use existing - destroy this one. */
9123 @@ -6333,6 +6347,17 @@ static int yaffs_ScanBackwards(yaffs_Dev
9124  
9125                                 }
9126  
9127 +                               if (!in->valid && in->variantType !=
9128 +                                   (oh ? oh->type : tags.extraObjectType))
9129 +                                       T(YAFFS_TRACE_ERROR, (
9130 +                                               TSTR("yaffs tragedy: Bad object type, "
9131 +                                           TCONT("%d != %d, for object %d at chunk ")
9132 +                                           TCONT("%d during scan")
9133 +                                               TENDSTR), oh ?
9134 +                                           oh->type : tags.extraObjectType,
9135 +                                           in->variantType, tags.objectId,
9136 +                                           chunk));
9137 +
9138                                 if (!in->valid &&
9139                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
9140                                      tags.objectId ==
9141 @@ -6340,7 +6365,7 @@ static int yaffs_ScanBackwards(yaffs_Dev
9142                                         /* We only load some info, don't fiddle with directory structure */
9143                                         in->valid = 1;
9144  
9145 -                                       if(oh) {
9146 +                                       if (oh) {
9147                                                 in->variantType = oh->type;
9148  
9149                                                 in->yst_mode = oh->yst_mode;
9150 @@ -6365,15 +6390,15 @@ static int yaffs_ScanBackwards(yaffs_Dev
9151                                                 in->lazyLoaded = 1;
9152                                         }
9153  
9154 -                                       in->chunkId = chunk;
9155 +                                       in->hdrChunk = chunk;
9156  
9157                                 } else if (!in->valid) {
9158                                         /* we need to load this info */
9159  
9160                                         in->valid = 1;
9161 -                                       in->chunkId = chunk;
9162 +                                       in->hdrChunk = chunk;
9163  
9164 -                                       if(oh) {
9165 +                                       if (oh) {
9166                                                 in->variantType = oh->type;
9167  
9168                                                 in->yst_mode = oh->yst_mode;
9169 @@ -6403,20 +6428,19 @@ static int yaffs_ScanBackwards(yaffs_Dev
9170                                                 yaffs_SetObjectName(in, oh->name);
9171                                                 parent =
9172                                                     yaffs_FindOrCreateObjectByNumber
9173 -                                                       (dev, oh->parentObjectId,
9174 -                                                        YAFFS_OBJECT_TYPE_DIRECTORY);
9175 +                                                       (dev, oh->parentObjectId,
9176 +                                                        YAFFS_OBJECT_TYPE_DIRECTORY);
9177  
9178                                                  fileSize = oh->fileSize;
9179 -                                                isShrink = oh->isShrink;
9180 +                                                isShrink = oh->isShrink;
9181                                                  equivalentObjectId = oh->equivalentObjectId;
9182  
9183 -                                       }
9184 -                                       else {
9185 +                                       } else {
9186                                                 in->variantType = tags.extraObjectType;
9187                                                 parent =
9188                                                     yaffs_FindOrCreateObjectByNumber
9189 -                                                       (dev, tags.extraParentObjectId,
9190 -                                                        YAFFS_OBJECT_TYPE_DIRECTORY);
9191 +                                                       (dev, tags.extraParentObjectId,
9192 +                                                        YAFFS_OBJECT_TYPE_DIRECTORY);
9193                                                  fileSize = tags.extraFileLength;
9194                                                  isShrink = tags.extraIsShrinkHeader;
9195                                                  equivalentObjectId = tags.extraEquivalentObjectId;
9196 @@ -6425,29 +6449,30 @@ static int yaffs_ScanBackwards(yaffs_Dev
9197                                         }
9198                                         in->dirty = 0;
9199  
9200 +                                       if (!parent)
9201 +                                               alloc_failed = 1;
9202 +
9203                                         /* directory stuff...
9204                                          * hook up to parent
9205                                          */
9206  
9207 -                                       if (parent->variantType ==
9208 +                                       if (parent && parent->variantType ==
9209                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
9210                                                 /* Set up as a directory */
9211                                                 parent->variantType =
9212 -                                                   YAFFS_OBJECT_TYPE_DIRECTORY;
9213 -                                               INIT_LIST_HEAD(&parent->variant.
9214 -                                                              directoryVariant.
9215 -                                                              children);
9216 -                                       } else if (parent->variantType !=
9217 -                                                  YAFFS_OBJECT_TYPE_DIRECTORY)
9218 -                                       {
9219 +                                                       YAFFS_OBJECT_TYPE_DIRECTORY;
9220 +                                               YINIT_LIST_HEAD(&parent->variant.
9221 +                                                       directoryVariant.
9222 +                                                       children);
9223 +                                       } else if (!parent || parent->variantType !=
9224 +                                                  YAFFS_OBJECT_TYPE_DIRECTORY) {
9225                                                 /* Hoosterman, another problem....
9226                                                  * We're trying to use a non-directory as a directory
9227                                                  */
9228  
9229                                                 T(YAFFS_TRACE_ERROR,
9230                                                   (TSTR
9231 -                                                  ("yaffs tragedy: attempting to use non-directory as"
9232 -                                                   " a directory in scan. Put in lost+found."
9233 +                                                  ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
9234                                                     TENDSTR)));
9235                                                 parent = dev->lostNFoundDir;
9236                                         }
9237 @@ -6494,12 +6519,12 @@ static int yaffs_ScanBackwards(yaffs_Dev
9238  
9239                                                 break;
9240                                         case YAFFS_OBJECT_TYPE_HARDLINK:
9241 -                                               if(!itsUnlinked) {
9242 -                                                 in->variant.hardLinkVariant.equivalentObjectId =
9243 -                                                   equivalentObjectId;
9244 -                                                 in->hardLinks.next =
9245 -                                                   (struct list_head *) hardList;
9246 -                                                 hardList = in;
9247 +                                               if (!itsUnlinked) {
9248 +                                                       in->variant.hardLinkVariant.equivalentObjectId =
9249 +                                                               equivalentObjectId;
9250 +                                                       in->hardLinks.next =
9251 +                                                               (struct ylist_head *) hardList;
9252 +                                                       hardList = in;
9253                                                 }
9254                                                 break;
9255                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
9256 @@ -6509,12 +6534,11 @@ static int yaffs_ScanBackwards(yaffs_Dev
9257                                                 /* Do nothing */
9258                                                 break;
9259                                         case YAFFS_OBJECT_TYPE_SYMLINK:
9260 -                                               if(oh){
9261 -                                                  in->variant.symLinkVariant.alias =
9262 -                                                   yaffs_CloneString(oh->
9263 -                                                                     alias);
9264 -                                                  if(!in->variant.symLinkVariant.alias)
9265 -                                                       alloc_failed = 1;
9266 +                                               if (oh) {
9267 +                                                       in->variant.symLinkVariant.alias =
9268 +                                                               yaffs_CloneString(oh->alias);
9269 +                                                       if (!in->variant.symLinkVariant.alias)
9270 +                                                               alloc_failed = 1;
9271                                                 }
9272                                                 break;
9273                                         }
9274 @@ -6551,75 +6575,129 @@ static int yaffs_ScanBackwards(yaffs_Dev
9275          * We should now have scanned all the objects, now it's time to add these
9276          * hardlinks.
9277          */
9278 -       yaffs_HardlinkFixup(dev,hardList);
9279 +       yaffs_HardlinkFixup(dev, hardList);
9280  
9281  
9282 -       /*
9283 -       *  Sort out state of unlinked and deleted objects.
9284 -       */
9285 -       {
9286 -               struct list_head *i;
9287 -               struct list_head *n;
9288 +       yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
9289  
9290 -               yaffs_Object *l;
9291 +       if (alloc_failed)
9292 +               return YAFFS_FAIL;
9293  
9294 -               /* Soft delete all the unlinked files */
9295 -               list_for_each_safe(i, n,
9296 -                                  &dev->unlinkedDir->variant.directoryVariant.
9297 -                                  children) {
9298 -                       if (i) {
9299 -                               l = list_entry(i, yaffs_Object, siblings);
9300 -                               yaffs_DestroyObject(l);
9301 -                       }
9302 -               }
9303 +       T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
9304  
9305 -               /* Soft delete all the deletedDir files */
9306 -               list_for_each_safe(i, n,
9307 -                                  &dev->deletedDir->variant.directoryVariant.
9308 -                                  children) {
9309 -                       if (i) {
9310 -                               l = list_entry(i, yaffs_Object, siblings);
9311 -                               yaffs_DestroyObject(l);
9312 +       return YAFFS_OK;
9313 +}
9314  
9315 -                       }
9316 +/*------------------------------  Directory Functions ----------------------------- */
9317 +
9318 +static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
9319 +{
9320 +       struct ylist_head *lh;
9321 +       yaffs_Object *listObj;
9322 +
9323 +       int count = 0;
9324 +
9325 +       if (!obj) {
9326 +               T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
9327 +               YBUG();
9328 +               return;
9329 +       }
9330 +
9331 +       if (yaffs_SkipVerification(obj->myDev))
9332 +               return;
9333 +
9334 +       if (!obj->parent) {
9335 +               T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
9336 +               YBUG();
9337 +               return;
9338 +       }
9339 +
9340 +       if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
9341 +               T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
9342 +               YBUG();
9343 +       }
9344 +
9345 +       /* Iterate through the objects in each hash entry */
9346 +
9347 +       ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
9348 +               if (lh) {
9349 +                       listObj = ylist_entry(lh, yaffs_Object, siblings);
9350 +                       yaffs_VerifyObject(listObj);
9351 +                       if (obj == listObj)
9352 +                               count++;
9353                 }
9354 +        }
9355 +
9356 +       if (count != 1) {
9357 +               T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
9358 +               YBUG();
9359         }
9360 +}
9361  
9362 -       yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
9363 +static void yaffs_VerifyDirectory(yaffs_Object *directory)
9364 +{
9365 +       struct ylist_head *lh;
9366 +       yaffs_Object *listObj;
9367  
9368 -       if(alloc_failed){
9369 -               return YAFFS_FAIL;
9370 +       if (!directory) {
9371 +               YBUG();
9372 +               return;
9373         }
9374  
9375 -       T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
9376 +       if (yaffs_SkipFullVerification(directory->myDev))
9377 +               return;
9378  
9379 -       return YAFFS_OK;
9380 +       if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
9381 +               T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
9382 +               YBUG();
9383 +       }
9384 +
9385 +       /* Iterate through the objects in each hash entry */
9386 +
9387 +       ylist_for_each(lh, &directory->variant.directoryVariant.children) {
9388 +               if (lh) {
9389 +                       listObj = ylist_entry(lh, yaffs_Object, siblings);
9390 +                       if (listObj->parent != directory) {
9391 +                               T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
9392 +                               YBUG();
9393 +                       }
9394 +                       yaffs_VerifyObjectInDirectory(listObj);
9395 +               }
9396 +       }
9397  }
9398  
9399 -/*------------------------------  Directory Functions ----------------------------- */
9400  
9401 -static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
9402 +static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
9403  {
9404         yaffs_Device *dev = obj->myDev;
9405 +       yaffs_Object *parent;
9406 +
9407 +       yaffs_VerifyObjectInDirectory(obj);
9408 +       parent = obj->parent;
9409 +
9410 +       yaffs_VerifyDirectory(parent);
9411  
9412 -       if(dev && dev->removeObjectCallback)
9413 +       if (dev && dev->removeObjectCallback)
9414                 dev->removeObjectCallback(obj);
9415  
9416 -       list_del_init(&obj->siblings);
9417 +
9418 +       ylist_del_init(&obj->siblings);
9419         obj->parent = NULL;
9420 +
9421 +       yaffs_VerifyDirectory(parent);
9422  }
9423  
9424  
9425 -static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
9426 -                                      yaffs_Object * obj)
9427 +static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
9428 +                                       yaffs_Object *obj)
9429  {
9430 -
9431         if (!directory) {
9432                 T(YAFFS_TRACE_ALWAYS,
9433                   (TSTR
9434                    ("tragedy: Trying to add an object to a null pointer directory"
9435                     TENDSTR)));
9436                 YBUG();
9437 +               return;
9438         }
9439         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
9440                 T(YAFFS_TRACE_ALWAYS,
9441 @@ -6631,37 +6709,42 @@ static void yaffs_AddObjectToDirectory(y
9442  
9443         if (obj->siblings.prev == NULL) {
9444                 /* Not initialised */
9445 -               INIT_LIST_HEAD(&obj->siblings);
9446 -
9447 -       } else if (!list_empty(&obj->siblings)) {
9448 -               /* If it is holed up somewhere else, un hook it */
9449 -               yaffs_RemoveObjectFromDirectory(obj);
9450 +               YBUG();
9451         }
9452 +
9453 +
9454 +       yaffs_VerifyDirectory(directory);
9455 +
9456 +       yaffs_RemoveObjectFromDirectory(obj);
9457 +
9458 +
9459         /* Now add it */
9460 -       list_add(&obj->siblings, &directory->variant.directoryVariant.children);
9461 +       ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
9462         obj->parent = directory;
9463  
9464         if (directory == obj->myDev->unlinkedDir
9465 -           || directory == obj->myDev->deletedDir) {
9466 +                       || directory == obj->myDev->deletedDir) {
9467                 obj->unlinked = 1;
9468                 obj->myDev->nUnlinkedFiles++;
9469                 obj->renameAllowed = 0;
9470         }
9471 +
9472 +       yaffs_VerifyDirectory(directory);
9473 +       yaffs_VerifyObjectInDirectory(obj);
9474  }
9475  
9476 -yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
9477 -                                    const YCHAR * name)
9478 +yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
9479 +                                    const YCHAR *name)
9480  {
9481         int sum;
9482  
9483 -       struct list_head *i;
9484 +       struct ylist_head *i;
9485         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
9486  
9487         yaffs_Object *l;
9488  
9489 -       if (!name) {
9490 +       if (!name)
9491                 return NULL;
9492 -       }
9493  
9494         if (!directory) {
9495                 T(YAFFS_TRACE_ALWAYS,
9496 @@ -6669,6 +6752,7 @@ yaffs_Object *yaffs_FindObjectByName(yaf
9497                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
9498                     TENDSTR)));
9499                 YBUG();
9500 +               return NULL;
9501         }
9502         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
9503                 T(YAFFS_TRACE_ALWAYS,
9504 @@ -6679,28 +6763,27 @@ yaffs_Object *yaffs_FindObjectByName(yaf
9505  
9506         sum = yaffs_CalcNameSum(name);
9507  
9508 -       list_for_each(i, &directory->variant.directoryVariant.children) {
9509 +       ylist_for_each(i, &directory->variant.directoryVariant.children) {
9510                 if (i) {
9511 -                       l = list_entry(i, yaffs_Object, siblings);
9512 +                       l = ylist_entry(i, yaffs_Object, siblings);
9513 +
9514 +                       if (l->parent != directory)
9515 +                               YBUG();
9516  
9517                         yaffs_CheckObjectDetailsLoaded(l);
9518  
9519                         /* Special case for lost-n-found */
9520                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
9521 -                               if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
9522 +                               if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
9523                                         return l;
9524 -                               }
9525 -                       } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
9526 -                       {
9527 -                               /* LostnFound cunk called Objxxx
9528 +                       } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
9529 +                               /* LostnFound chunk called Objxxx
9530                                  * Do a real check
9531                                  */
9532                                 yaffs_GetObjectName(l, buffer,
9533                                                     YAFFS_MAX_NAME_LENGTH);
9534 -                               if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
9535 +                               if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
9536                                         return l;
9537 -                               }
9538 -
9539                         }
9540                 }
9541         }
9542 @@ -6710,10 +6793,10 @@ yaffs_Object *yaffs_FindObjectByName(yaf
9543  
9544  
9545  #if 0
9546 -int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
9547 -                                  int (*fn) (yaffs_Object *))
9548 +int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
9549 +                                       int (*fn) (yaffs_Object *))
9550  {
9551 -       struct list_head *i;
9552 +       struct ylist_head *i;
9553         yaffs_Object *l;
9554  
9555         if (!theDir) {
9556 @@ -6722,20 +6805,21 @@ int yaffs_ApplyToDirectoryChildren(yaffs
9557                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
9558                     TENDSTR)));
9559                 YBUG();
9560 +               return YAFFS_FAIL;
9561         }
9562         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
9563                 T(YAFFS_TRACE_ALWAYS,
9564                   (TSTR
9565                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
9566                 YBUG();
9567 +               return YAFFS_FAIL;
9568         }
9569  
9570 -       list_for_each(i, &theDir->variant.directoryVariant.children) {
9571 +       ylist_for_each(i, &theDir->variant.directoryVariant.children) {
9572                 if (i) {
9573 -                       l = list_entry(i, yaffs_Object, siblings);
9574 -                       if (l && !fn(l)) {
9575 +                       l = ylist_entry(i, yaffs_Object, siblings);
9576 +                       if (l && !fn(l))
9577                                 return YAFFS_FAIL;
9578 -                       }
9579                 }
9580         }
9581  
9582 @@ -6748,7 +6832,7 @@ int yaffs_ApplyToDirectoryChildren(yaffs
9583   * actual object.
9584   */
9585  
9586 -yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
9587 +yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
9588  {
9589         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
9590                 /* We want the object id of the equivalent object, not this one */
9591 @@ -6756,10 +6840,9 @@ yaffs_Object *yaffs_GetEquivalentObject(
9592                 yaffs_CheckObjectDetailsLoaded(obj);
9593         }
9594         return obj;
9595 -
9596  }
9597  
9598 -int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
9599 +int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
9600  {
9601         memset(name, 0, buffSize * sizeof(YCHAR));
9602  
9603 @@ -6767,18 +6850,26 @@ int yaffs_GetObjectName(yaffs_Object * o
9604  
9605         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
9606                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
9607 -       } else if (obj->chunkId <= 0) {
9608 +       } else if (obj->hdrChunk <= 0) {
9609                 YCHAR locName[20];
9610 +               YCHAR numString[20];
9611 +               YCHAR *x = &numString[19];
9612 +               unsigned v = obj->objectId;
9613 +               numString[19] = 0;
9614 +               while (v > 0) {
9615 +                       x--;
9616 +                       *x = '0' + (v % 10);
9617 +                       v /= 10;
9618 +               }
9619                 /* make up a name */
9620 -               yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
9621 -                             obj->objectId);
9622 +               yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
9623 +               yaffs_strcat(locName, x);
9624                 yaffs_strncpy(name, locName, buffSize - 1);
9625  
9626         }
9627  #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
9628 -       else if (obj->shortName[0]) {
9629 +       else if (obj->shortName[0])
9630                 yaffs_strcpy(name, obj->shortName);
9631 -       }
9632  #endif
9633         else {
9634                 int result;
9635 @@ -6788,9 +6879,9 @@ int yaffs_GetObjectName(yaffs_Object * o
9636  
9637                 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
9638  
9639 -               if (obj->chunkId >= 0) {
9640 +               if (obj->hdrChunk > 0) {
9641                         result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
9642 -                                                       obj->chunkId, buffer,
9643 +                                                       obj->hdrChunk, buffer,
9644                                                         NULL);
9645                 }
9646                 yaffs_strncpy(name, oh->name, buffSize - 1);
9647 @@ -6801,46 +6892,43 @@ int yaffs_GetObjectName(yaffs_Object * o
9648         return yaffs_strlen(name);
9649  }
9650  
9651 -int yaffs_GetObjectFileLength(yaffs_Object * obj)
9652 +int yaffs_GetObjectFileLength(yaffs_Object *obj)
9653  {
9654 -
9655         /* Dereference any hard linking */
9656         obj = yaffs_GetEquivalentObject(obj);
9657  
9658 -       if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
9659 +       if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
9660                 return obj->variant.fileVariant.fileSize;
9661 -       }
9662 -       if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
9663 +       if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
9664                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
9665 -       } else {
9666 +       else {
9667                 /* Only a directory should drop through to here */
9668                 return obj->myDev->nDataBytesPerChunk;
9669         }
9670  }
9671  
9672 -int yaffs_GetObjectLinkCount(yaffs_Object * obj)
9673 +int yaffs_GetObjectLinkCount(yaffs_Object *obj)
9674  {
9675         int count = 0;
9676 -       struct list_head *i;
9677 +       struct ylist_head *i;
9678  
9679 -       if (!obj->unlinked) {
9680 -               count++;        /* the object itself */
9681 -       }
9682 -       list_for_each(i, &obj->hardLinks) {
9683 -               count++;        /* add the hard links; */
9684 -       }
9685 -       return count;
9686 +       if (!obj->unlinked)
9687 +               count++;                /* the object itself */
9688 +
9689 +       ylist_for_each(i, &obj->hardLinks)
9690 +               count++;                /* add the hard links; */
9691  
9692 +       return count;
9693  }
9694  
9695 -int yaffs_GetObjectInode(yaffs_Object * obj)
9696 +int yaffs_GetObjectInode(yaffs_Object *obj)
9697  {
9698         obj = yaffs_GetEquivalentObject(obj);
9699  
9700         return obj->objectId;
9701  }
9702  
9703 -unsigned yaffs_GetObjectType(yaffs_Object * obj)
9704 +unsigned yaffs_GetObjectType(yaffs_Object *obj)
9705  {
9706         obj = yaffs_GetEquivalentObject(obj);
9707  
9708 @@ -6872,19 +6960,18 @@ unsigned yaffs_GetObjectType(yaffs_Objec
9709         }
9710  }
9711  
9712 -YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
9713 +YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
9714  {
9715         obj = yaffs_GetEquivalentObject(obj);
9716 -       if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
9717 +       if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
9718                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
9719 -       } else {
9720 +       else
9721                 return yaffs_CloneString(_Y(""));
9722 -       }
9723  }
9724  
9725  #ifndef CONFIG_YAFFS_WINCE
9726  
9727 -int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
9728 +int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
9729  {
9730         unsigned int valid = attr->ia_valid;
9731  
9732 @@ -6910,7 +6997,7 @@ int yaffs_SetAttributes(yaffs_Object * o
9733         return YAFFS_OK;
9734  
9735  }
9736 -int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
9737 +int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
9738  {
9739         unsigned int valid = 0;
9740  
9741 @@ -6934,13 +7021,12 @@ int yaffs_GetAttributes(yaffs_Object * o
9742         attr->ia_valid = valid;
9743  
9744         return YAFFS_OK;
9745 -
9746  }
9747  
9748  #endif
9749  
9750  #if 0
9751 -int yaffs_DumpObject(yaffs_Object * obj)
9752 +int yaffs_DumpObject(yaffs_Object *obj)
9753  {
9754         YCHAR name[257];
9755  
9756 @@ -6951,7 +7037,7 @@ int yaffs_DumpObject(yaffs_Object * obj)
9757            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
9758             " chunk %d type %d size %d\n"
9759             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
9760 -          obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
9761 +          obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
9762            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
9763  
9764         return YAFFS_OK;
9765 @@ -6960,7 +7046,7 @@ int yaffs_DumpObject(yaffs_Object * obj)
9766  
9767  /*---------------------------- Initialisation code -------------------------------------- */
9768  
9769 -static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
9770 +static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
9771  {
9772  
9773         /* Common functions, gotta have */
9774 @@ -7011,7 +7097,7 @@ static int yaffs_CreateInitialDirectorie
9775             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
9776                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
9777  
9778 -       if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
9779 +       if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
9780                 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
9781                 return YAFFS_OK;
9782         }
9783 @@ -7019,7 +7105,7 @@ static int yaffs_CreateInitialDirectorie
9784         return YAFFS_FAIL;
9785  }
9786  
9787 -int yaffs_GutsInitialise(yaffs_Device * dev)
9788 +int yaffs_GutsInitialise(yaffs_Device *dev)
9789  {
9790         int init_failed = 0;
9791         unsigned x;
9792 @@ -7040,6 +7126,8 @@ int yaffs_GutsInitialise(yaffs_Device *
9793         dev->chunkOffset = 0;
9794         dev->nFreeChunks = 0;
9795  
9796 +       dev->gcBlock = -1;
9797 +
9798         if (dev->startBlock == 0) {
9799                 dev->internalStartBlock = dev->startBlock + 1;
9800                 dev->internalEndBlock = dev->endBlock + 1;
9801 @@ -7049,18 +7137,18 @@ int yaffs_GutsInitialise(yaffs_Device *
9802  
9803         /* Check geometry parameters. */
9804  
9805 -       if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
9806 -           (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
9807 +       if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
9808 +           (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
9809 +           (dev->inbandTags && !dev->isYaffs2) ||
9810              dev->nChunksPerBlock < 2 ||
9811              dev->nReservedBlocks < 2 ||
9812              dev->internalStartBlock <= 0 ||
9813              dev->internalEndBlock <= 0 ||
9814 -            dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)      // otherwise it is too small
9815 -           ) {
9816 +            dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) {   /* otherwise it is too small */
9817                 T(YAFFS_TRACE_ALWAYS,
9818                   (TSTR
9819 -                  ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
9820 -                   TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
9821 +                  ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
9822 +                   TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
9823                 return YAFFS_FAIL;
9824         }
9825  
9826 @@ -7070,6 +7158,12 @@ int yaffs_GutsInitialise(yaffs_Device *
9827                 return YAFFS_FAIL;
9828         }
9829  
9830 +       /* Sort out space for inband tags, if required */
9831 +       if (dev->inbandTags)
9832 +               dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
9833 +       else
9834 +               dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
9835 +
9836         /* Got the right mix of functions? */
9837         if (!yaffs_CheckDevFunctions(dev)) {
9838                 /* Function missing */
9839 @@ -7097,31 +7191,18 @@ int yaffs_GutsInitialise(yaffs_Device *
9840  
9841         dev->isMounted = 1;
9842  
9843 -
9844 -
9845         /* OK now calculate a few things for the device */
9846  
9847         /*
9848          *  Calculate all the chunk size manipulation numbers:
9849          */
9850 -        /* Start off assuming it is a power of 2 */
9851 -        dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
9852 -        dev->chunkMask = (1<<dev->chunkShift) - 1;
9853 -
9854 -        if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
9855 -               /* Yes it is a power of 2, disable crumbs */
9856 -               dev->crumbMask = 0;
9857 -               dev->crumbShift = 0;
9858 -               dev->crumbsPerChunk = 0;
9859 -        } else {
9860 -               /* Not a power of 2, use crumbs instead */
9861 -               dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
9862 -               dev->crumbMask = (1<<dev->crumbShift)-1;
9863 -               dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
9864 -               dev->chunkShift = 0;
9865 -               dev->chunkMask = 0;
9866 -       }
9867 -
9868 +       x = dev->nDataBytesPerChunk;
9869 +       /* We always use dev->chunkShift and dev->chunkDiv */
9870 +       dev->chunkShift = Shifts(x);
9871 +       x >>= dev->chunkShift;
9872 +       dev->chunkDiv = x;
9873 +       /* We only use chunk mask if chunkDiv is 1 */
9874 +       dev->chunkMask = (1<<dev->chunkShift) - 1;
9875  
9876         /*
9877          * Calculate chunkGroupBits.
9878 @@ -7133,16 +7214,15 @@ int yaffs_GutsInitialise(yaffs_Device *
9879         bits = ShiftsGE(x);
9880  
9881         /* Set up tnode width if wide tnodes are enabled. */
9882 -       if(!dev->wideTnodesDisabled){
9883 +       if (!dev->wideTnodesDisabled) {
9884                 /* bits must be even so that we end up with 32-bit words */
9885 -               if(bits & 1)
9886 +               if (bits & 1)
9887                         bits++;
9888 -               if(bits < 16)
9889 +               if (bits < 16)
9890                         dev->tnodeWidth = 16;
9891                 else
9892                         dev->tnodeWidth = bits;
9893 -       }
9894 -       else
9895 +       } else
9896                 dev->tnodeWidth = 16;
9897  
9898         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
9899 @@ -7193,7 +7273,7 @@ int yaffs_GutsInitialise(yaffs_Device *
9900         dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
9901  
9902         /* Initialise temporary buffers and caches. */
9903 -       if(!yaffs_InitialiseTempBuffers(dev))
9904 +       if (!yaffs_InitialiseTempBuffers(dev))
9905                 init_failed = 1;
9906  
9907         dev->srCache = NULL;
9908 @@ -7203,25 +7283,26 @@ int yaffs_GutsInitialise(yaffs_Device *
9909         if (!init_failed &&
9910             dev->nShortOpCaches > 0) {
9911                 int i;
9912 -               __u8 *buf;
9913 +               void *buf;
9914                 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
9915  
9916 -               if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
9917 +               if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
9918                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
9919 -               }
9920  
9921 -               buf = dev->srCache =  YMALLOC(srCacheBytes);
9922 +               dev->srCache =  YMALLOC(srCacheBytes);
9923  
9924 -               if(dev->srCache)
9925 -                       memset(dev->srCache,0,srCacheBytes);
9926 +               buf = (__u8 *) dev->srCache;
9927 +
9928 +               if (dev->srCache)
9929 +                       memset(dev->srCache, 0, srCacheBytes);
9930  
9931                 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
9932                         dev->srCache[i].object = NULL;
9933                         dev->srCache[i].lastUse = 0;
9934                         dev->srCache[i].dirty = 0;
9935 -                       dev->srCache[i].data = buf = YMALLOC_DMA(dev->nDataBytesPerChunk);
9936 +                       dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
9937                 }
9938 -               if(!buf)
9939 +               if (!buf)
9940                         init_failed = 1;
9941  
9942                 dev->srLastUse = 0;
9943 @@ -7229,29 +7310,30 @@ int yaffs_GutsInitialise(yaffs_Device *
9944  
9945         dev->cacheHits = 0;
9946  
9947 -       if(!init_failed){
9948 +       if (!init_failed) {
9949                 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
9950 -               if(!dev->gcCleanupList)
9951 +               if (!dev->gcCleanupList)
9952                         init_failed = 1;
9953         }
9954  
9955 -       if (dev->isYaffs2) {
9956 +       if (dev->isYaffs2)
9957                 dev->useHeaderFileSize = 1;
9958 -       }
9959 -       if(!init_failed && !yaffs_InitialiseBlocks(dev))
9960 +
9961 +       if (!init_failed && !yaffs_InitialiseBlocks(dev))
9962                 init_failed = 1;
9963  
9964         yaffs_InitialiseTnodes(dev);
9965         yaffs_InitialiseObjects(dev);
9966  
9967 -       if(!init_failed && !yaffs_CreateInitialDirectories(dev))
9968 +       if (!init_failed && !yaffs_CreateInitialDirectories(dev))
9969                 init_failed = 1;
9970  
9971  
9972 -       if(!init_failed){
9973 +       if (!init_failed) {
9974                 /* Now scan the flash. */
9975                 if (dev->isYaffs2) {
9976 -                       if(yaffs_CheckpointRestore(dev)) {
9977 +                       if (yaffs_CheckpointRestore(dev)) {
9978 +                               yaffs_CheckObjectDetailsLoaded(dev->rootDir);
9979                                 T(YAFFS_TRACE_ALWAYS,
9980                                   (TSTR("yaffs: restored from checkpoint" TENDSTR)));
9981                         } else {
9982 @@ -7273,24 +7355,25 @@ int yaffs_GutsInitialise(yaffs_Device *
9983                                 dev->nBackgroundDeletions = 0;
9984                                 dev->oldestDirtySequence = 0;
9985  
9986 -                               if(!init_failed && !yaffs_InitialiseBlocks(dev))
9987 +                               if (!init_failed && !yaffs_InitialiseBlocks(dev))
9988                                         init_failed = 1;
9989  
9990                                 yaffs_InitialiseTnodes(dev);
9991                                 yaffs_InitialiseObjects(dev);
9992  
9993 -                               if(!init_failed && !yaffs_CreateInitialDirectories(dev))
9994 +                               if (!init_failed && !yaffs_CreateInitialDirectories(dev))
9995                                         init_failed = 1;
9996  
9997 -                               if(!init_failed && !yaffs_ScanBackwards(dev))
9998 +                               if (!init_failed && !yaffs_ScanBackwards(dev))
9999                                         init_failed = 1;
10000                         }
10001 -               }else
10002 -                       if(!yaffs_Scan(dev))
10003 +               } else if (!yaffs_Scan(dev))
10004                                 init_failed = 1;
10005 +
10006 +               yaffs_StripDeletedObjects(dev);
10007         }
10008  
10009 -       if(init_failed){
10010 +       if (init_failed) {
10011                 /* Clean up the mess */
10012                 T(YAFFS_TRACE_TRACING,
10013                   (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
10014 @@ -7318,7 +7401,7 @@ int yaffs_GutsInitialise(yaffs_Device *
10015  
10016  }
10017  
10018 -void yaffs_Deinitialise(yaffs_Device * dev)
10019 +void yaffs_Deinitialise(yaffs_Device *dev)
10020  {
10021         if (dev->isMounted) {
10022                 int i;
10023 @@ -7330,7 +7413,7 @@ void yaffs_Deinitialise(yaffs_Device * d
10024                     dev->srCache) {
10025  
10026                         for (i = 0; i < dev->nShortOpCaches; i++) {
10027 -                               if(dev->srCache[i].data)
10028 +                               if (dev->srCache[i].data)
10029                                         YFREE(dev->srCache[i].data);
10030                                 dev->srCache[i].data = NULL;
10031                         }
10032 @@ -7341,16 +7424,17 @@ void yaffs_Deinitialise(yaffs_Device * d
10033  
10034                 YFREE(dev->gcCleanupList);
10035  
10036 -               for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
10037 +               for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
10038                         YFREE(dev->tempBuffer[i].buffer);
10039 -               }
10040  
10041                 dev->isMounted = 0;
10042 -       }
10043  
10044 +               if (dev->deinitialiseNAND)
10045 +                       dev->deinitialiseNAND(dev);
10046 +       }
10047  }
10048  
10049 -static int yaffs_CountFreeChunks(yaffs_Device * dev)
10050 +static int yaffs_CountFreeChunks(yaffs_Device *dev)
10051  {
10052         int nFree;
10053         int b;
10054 @@ -7358,7 +7442,7 @@ static int yaffs_CountFreeChunks(yaffs_D
10055         yaffs_BlockInfo *blk;
10056  
10057         for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
10058 -            b++) {
10059 +                       b++) {
10060                 blk = yaffs_GetBlockInfo(dev, b);
10061  
10062                 switch (blk->blockState) {
10063 @@ -7373,19 +7457,19 @@ static int yaffs_CountFreeChunks(yaffs_D
10064                 default:
10065                         break;
10066                 }
10067 -
10068         }
10069  
10070         return nFree;
10071  }
10072  
10073 -int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
10074 +int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
10075  {
10076         /* This is what we report to the outside world */
10077  
10078         int nFree;
10079         int nDirtyCacheChunks;
10080         int blocksForCheckpoint;
10081 +       int i;
10082  
10083  #if 1
10084         nFree = dev->nFreeChunks;
10085 @@ -7397,12 +7481,9 @@ int yaffs_GetNumberOfFreeChunks(yaffs_De
10086  
10087         /* Now count the number of dirty chunks in the cache and subtract those */
10088  
10089 -       {
10090 -               int i;
10091 -               for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
10092 -                       if (dev->srCache[i].dirty)
10093 -                               nDirtyCacheChunks++;
10094 -               }
10095 +       for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
10096 +               if (dev->srCache[i].dirty)
10097 +                       nDirtyCacheChunks++;
10098         }
10099  
10100         nFree -= nDirtyCacheChunks;
10101 @@ -7410,8 +7491,8 @@ int yaffs_GetNumberOfFreeChunks(yaffs_De
10102         nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
10103  
10104         /* Now we figure out how much to reserve for the checkpoint and report that... */
10105 -       blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
10106 -       if(blocksForCheckpoint < 0)
10107 +       blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
10108 +       if (blocksForCheckpoint < 0)
10109                 blocksForCheckpoint = 0;
10110  
10111         nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
10112 @@ -7425,12 +7506,12 @@ int yaffs_GetNumberOfFreeChunks(yaffs_De
10113  
10114  static int yaffs_freeVerificationFailures;
10115  
10116 -static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
10117 +static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
10118  {
10119         int counted;
10120         int difference;
10121  
10122 -       if(yaffs_SkipVerification(dev))
10123 +       if (yaffs_SkipVerification(dev))
10124                 return;
10125  
10126         counted = yaffs_CountFreeChunks(dev);
10127 @@ -7447,23 +7528,25 @@ static void yaffs_VerifyFreeChunks(yaffs
10128  
10129  /*---------------------------------------- YAFFS test code ----------------------*/
10130  
10131 -#define yaffs_CheckStruct(structure,syze, name) \
10132 -           if(sizeof(structure) != syze) \
10133 -              { \
10134 -                T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
10135 -                name,syze,sizeof(structure))); \
10136 -                return YAFFS_FAIL; \
10137 -               }
10138 +#define yaffs_CheckStruct(structure, syze, name) \
10139 +       do { \
10140 +               if (sizeof(structure) != syze) { \
10141 +                       T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
10142 +                               name, syze, sizeof(structure))); \
10143 +                       return YAFFS_FAIL; \
10144 +               } \
10145 +       } while (0)
10146  
10147  static int yaffs_CheckStructures(void)
10148  {
10149 -/*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
10150 -/*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
10151 -/*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
10152 +/*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
10153 +/*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
10154 +/*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
10155  #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
10156 -       yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
10157 +       yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
10158  #endif
10159 -           yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")
10160 -
10161 -           return YAFFS_OK;
10162 +#ifndef CONFIG_YAFFS_WINCE
10163 +       yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");
10164 +#endif
10165 +       return YAFFS_OK;
10166  }
10167 --- a/fs/yaffs2/yaffs_guts.h
10168 +++ b/fs/yaffs2/yaffs_guts.h
10169 @@ -90,7 +90,7 @@
10170  
10171  #define YAFFS_MAX_SHORT_OP_CACHES      20
10172  
10173 -#define YAFFS_N_TEMP_BUFFERS           4
10174 +#define YAFFS_N_TEMP_BUFFERS           6
10175  
10176  /* We limit the number attempts at sucessfully saving a chunk of data.
10177   * Small-page devices have 32 pages per block; large-page devices have 64.
10178 @@ -108,6 +108,9 @@
10179  #define YAFFS_LOWEST_SEQUENCE_NUMBER   0x00001000
10180  #define YAFFS_HIGHEST_SEQUENCE_NUMBER  0xEFFFFF00
10181  
10182 +/* Special sequence number for bad block that failed to be marked bad */
10183 +#define YAFFS_SEQUENCE_BAD_BLOCK       0xFFFF0000
10184 +
10185  /* ChunkCache is used for short read/write operations.*/
10186  typedef struct {
10187         struct yaffs_ObjectStruct *object;
10188 @@ -134,11 +137,10 @@ typedef struct {
10189  typedef struct {
10190         unsigned chunkId:20;
10191         unsigned serialNumber:2;
10192 -       unsigned byteCount:10;
10193 +       unsigned byteCountLSB:10;
10194         unsigned objectId:18;
10195         unsigned ecc:12;
10196 -       unsigned unusedStuff:2;
10197 -
10198 +       unsigned byteCountMSB:2;
10199  } yaffs_Tags;
10200  
10201  typedef union {
10202 @@ -277,13 +279,13 @@ typedef struct {
10203  
10204         int softDeletions:10;   /* number of soft deleted pages */
10205         int pagesInUse:10;      /* number of pages in use */
10206 -       yaffs_BlockState blockState:4;  /* One of the above block states */
10207 +       unsigned blockState:4;  /* One of the above block states. NB use unsigned because enum is sometimes an int */
10208         __u32 needsRetiring:1;  /* Data has failed on this block, need to get valid data off */
10209 -                               /* and retire the block. */
10210 -       __u32 skipErasedCheck: 1; /* If this is set we can skip the erased check on this block */
10211 -       __u32 gcPrioritise: 1;  /* An ECC check or blank check has failed on this block.
10212 +                               /* and retire the block. */
10213 +       __u32 skipErasedCheck:1; /* If this is set we can skip the erased check on this block */
10214 +       __u32 gcPrioritise:1;   /* An ECC check or blank check has failed on this block.
10215                                    It should be prioritised for GC */
10216 -        __u32 chunkErrorStrikes:3; /* How many times we've had ecc etc failures on this block and tried to reuse it */
10217 +       __u32 chunkErrorStrikes:3; /* How many times we've had ecc etc failures on this block and tried to reuse it */
10218  
10219  #ifdef CONFIG_YAFFS_YAFFS2
10220         __u32 hasShrinkHeader:1; /* This block has at least one shrink object header */
10221 @@ -300,11 +302,11 @@ typedef struct {
10222  
10223         /* Apply to everything  */
10224         int parentObjectId;
10225 -       __u16 sum__NoLongerUsed;        /* checksum of name. No longer used */
10226 +       __u16 sum__NoLongerUsed;        /* checksum of name. No longer used */
10227         YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
10228  
10229 -       /* Thes following apply to directories, files, symlinks - not hard links */
10230 -       __u32 yst_mode;         /* protection */
10231 +       /* The following apply to directories, files, symlinks - not hard links */
10232 +       __u32 yst_mode;         /* protection */
10233  
10234  #ifdef CONFIG_YAFFS_WINCE
10235         __u32 notForWinCE[5];
10236 @@ -331,11 +333,14 @@ typedef struct {
10237         __u32 win_ctime[2];
10238         __u32 win_atime[2];
10239         __u32 win_mtime[2];
10240 -       __u32 roomToGrow[4];
10241  #else
10242 -       __u32 roomToGrow[10];
10243 +       __u32 roomToGrow[6];
10244 +
10245  #endif
10246 +       __u32 inbandShadowsObject;
10247 +       __u32 inbandIsShrink;
10248  
10249 +       __u32 reservedSpace[2];
10250         int shadowsObject;      /* This object header shadows the specified object if > 0 */
10251  
10252         /* isShrink applies to object headers written when we shrink the file (ie resize) */
10253 @@ -381,7 +386,7 @@ typedef struct {
10254  } yaffs_FileStructure;
10255  
10256  typedef struct {
10257 -       struct list_head children;      /* list of child links */
10258 +       struct ylist_head children;     /* list of child links */
10259  } yaffs_DirectoryStructure;
10260  
10261  typedef struct {
10262 @@ -418,23 +423,24 @@ struct yaffs_ObjectStruct {
10263                                  * still in the inode cache. Free of object is defered.
10264                                  * until the inode is released.
10265                                  */
10266 +       __u8 beingCreated:1;    /* This object is still being created so skip some checks. */
10267  
10268         __u8 serial;            /* serial number of chunk in NAND. Cached here */
10269         __u16 sum;              /* sum of the name to speed searching */
10270  
10271 -       struct yaffs_DeviceStruct *myDev;       /* The device I'm on */
10272 +       struct yaffs_DeviceStruct *myDev;       /* The device I'm on */
10273  
10274 -       struct list_head hashLink;      /* list of objects in this hash bucket */
10275 +       struct ylist_head hashLink;     /* list of objects in this hash bucket */
10276  
10277 -       struct list_head hardLinks;     /* all the equivalent hard linked objects */
10278 +       struct ylist_head hardLinks;    /* all the equivalent hard linked objects */
10279  
10280         /* directory structure stuff */
10281         /* also used for linking up the free list */
10282         struct yaffs_ObjectStruct *parent;
10283 -       struct list_head siblings;
10284 +       struct ylist_head siblings;
10285  
10286         /* Where's my object header in NAND? */
10287 -       int chunkId;
10288 +       int hdrChunk;
10289  
10290         int nDataChunks;        /* Number of data chunks attached to the file. */
10291  
10292 @@ -485,7 +491,7 @@ struct yaffs_ObjectList_struct {
10293  typedef struct yaffs_ObjectList_struct yaffs_ObjectList;
10294  
10295  typedef struct {
10296 -       struct list_head list;
10297 +       struct ylist_head list;
10298         int count;
10299  } yaffs_ObjectBucket;
10300  
10301 @@ -495,11 +501,10 @@ typedef struct {
10302   */
10303  
10304  typedef struct {
10305 -        int structType;
10306 +       int structType;
10307         __u32 objectId;
10308         __u32 parentId;
10309 -       int chunkId;
10310 -
10311 +       int hdrChunk;
10312         yaffs_ObjectType variantType:3;
10313         __u8 deleted:1;
10314         __u8 softDeleted:1;
10315 @@ -511,8 +516,7 @@ typedef struct {
10316  
10317         int nDataChunks;
10318         __u32 fileSizeOrEquivalentObjectId;
10319 -
10320 -}yaffs_CheckpointObject;
10321 +} yaffs_CheckpointObject;
10322  
10323  /*--------------------- Temporary buffers ----------------
10324   *
10325 @@ -528,13 +532,13 @@ typedef struct {
10326  /*----------------- Device ---------------------------------*/
10327  
10328  struct yaffs_DeviceStruct {
10329 -       struct list_head devList;
10330 +       struct ylist_head devList;
10331         const char *name;
10332  
10333         /* Entry parameters set up way early. Yaffs sets up the rest.*/
10334         int nDataBytesPerChunk; /* Should be a power of 2 >= 512 */
10335         int nChunksPerBlock;    /* does not need to be a power of 2 */
10336 -       int nBytesPerSpare;     /* spare area size */
10337 +       int spareBytesPerChunk; /* spare area size */
10338         int startBlock;         /* Start block we're allowed to use */
10339         int endBlock;           /* End block we're allowed to use */
10340         int nReservedBlocks;    /* We want this tuneable so that we can reduce */
10341 @@ -544,9 +548,7 @@ struct yaffs_DeviceStruct {
10342         /* Stuff used by the shared space checkpointing mechanism */
10343         /* If this value is zero, then this mechanism is disabled */
10344  
10345 -       int nCheckpointReservedBlocks; /* Blocks to reserve for checkpoint data */
10346 -
10347 -
10348 +/*     int nCheckpointReservedBlocks; */ /* Blocks to reserve for checkpoint data */
10349  
10350  
10351         int nShortOpCaches;     /* If <= 0, then short op caching is disabled, else
10352 @@ -560,30 +562,31 @@ struct yaffs_DeviceStruct {
10353         void *genericDevice;    /* Pointer to device context
10354                                  * On an mtd this holds the mtd pointer.
10355                                  */
10356 -        void *superBlock;
10357 +       void *superBlock;
10358  
10359         /* NAND access functions (Must be set before calling YAFFS)*/
10360  
10361 -       int (*writeChunkToNAND) (struct yaffs_DeviceStruct * dev,
10362 -                                int chunkInNAND, const __u8 * data,
10363 -                                const yaffs_Spare * spare);
10364 -       int (*readChunkFromNAND) (struct yaffs_DeviceStruct * dev,
10365 -                                 int chunkInNAND, __u8 * data,
10366 -                                 yaffs_Spare * spare);
10367 -       int (*eraseBlockInNAND) (struct yaffs_DeviceStruct * dev,
10368 -                                int blockInNAND);
10369 -       int (*initialiseNAND) (struct yaffs_DeviceStruct * dev);
10370 +       int (*writeChunkToNAND) (struct yaffs_DeviceStruct *dev,
10371 +                                       int chunkInNAND, const __u8 *data,
10372 +                                       const yaffs_Spare *spare);
10373 +       int (*readChunkFromNAND) (struct yaffs_DeviceStruct *dev,
10374 +                                       int chunkInNAND, __u8 *data,
10375 +                                       yaffs_Spare *spare);
10376 +       int (*eraseBlockInNAND) (struct yaffs_DeviceStruct *dev,
10377 +                                       int blockInNAND);
10378 +       int (*initialiseNAND) (struct yaffs_DeviceStruct *dev);
10379 +       int (*deinitialiseNAND) (struct yaffs_DeviceStruct *dev);
10380  
10381  #ifdef CONFIG_YAFFS_YAFFS2
10382 -       int (*writeChunkWithTagsToNAND) (struct yaffs_DeviceStruct * dev,
10383 -                                        int chunkInNAND, const __u8 * data,
10384 -                                        const yaffs_ExtendedTags * tags);
10385 -       int (*readChunkWithTagsFromNAND) (struct yaffs_DeviceStruct * dev,
10386 -                                         int chunkInNAND, __u8 * data,
10387 -                                         yaffs_ExtendedTags * tags);
10388 -       int (*markNANDBlockBad) (struct yaffs_DeviceStruct * dev, int blockNo);
10389 -       int (*queryNANDBlock) (struct yaffs_DeviceStruct * dev, int blockNo,
10390 -                              yaffs_BlockState * state, int *sequenceNumber);
10391 +       int (*writeChunkWithTagsToNAND) (struct yaffs_DeviceStruct *dev,
10392 +                                        int chunkInNAND, const __u8 *data,
10393 +                                        const yaffs_ExtendedTags *tags);
10394 +       int (*readChunkWithTagsFromNAND) (struct yaffs_DeviceStruct *dev,
10395 +                                         int chunkInNAND, __u8 *data,
10396 +                                         yaffs_ExtendedTags *tags);
10397 +       int (*markNANDBlockBad) (struct yaffs_DeviceStruct *dev, int blockNo);
10398 +       int (*queryNANDBlock) (struct yaffs_DeviceStruct *dev, int blockNo,
10399 +                              yaffs_BlockState *state, __u32 *sequenceNumber);
10400  #endif
10401  
10402         int isYaffs2;
10403 @@ -595,10 +598,12 @@ struct yaffs_DeviceStruct {
10404         void (*removeObjectCallback)(struct yaffs_ObjectStruct *obj);
10405  
10406         /* Callback to mark the superblock dirsty */
10407 -       void (*markSuperBlockDirty)(void * superblock);
10408 +       void (*markSuperBlockDirty)(void *superblock);
10409  
10410         int wideTnodesDisabled; /* Set to disable wide tnodes */
10411  
10412 +       YCHAR *pathDividers;    /* String of legal path dividers */
10413 +
10414  
10415         /* End of stuff that must be set before initialisation. */
10416  
10417 @@ -615,16 +620,14 @@ struct yaffs_DeviceStruct {
10418         __u32 tnodeWidth;
10419         __u32 tnodeMask;
10420  
10421 -       /* Stuff to support various file offses to chunk/offset translations */
10422 -       /* "Crumbs" for nDataBytesPerChunk not being a power of 2 */
10423 -       __u32 crumbMask;
10424 -       __u32 crumbShift;
10425 -       __u32 crumbsPerChunk;
10426 -
10427 -       /* Straight shifting for nDataBytesPerChunk being a power of 2 */
10428 -       __u32 chunkShift;
10429 -       __u32 chunkMask;
10430 -
10431 +       /* Stuff for figuring out file offset to chunk conversions */
10432 +       __u32 chunkShift; /* Shift value */
10433 +       __u32 chunkDiv;   /* Divisor after shifting: 1 for power-of-2 sizes */
10434 +       __u32 chunkMask;  /* Mask to use for power-of-2 case */
10435 +
10436 +       /* Stuff to handle inband tags */
10437 +       int inbandTags;
10438 +       __u32 totalBytesPerChunk;
10439  
10440  #ifdef __KERNEL__
10441  
10442 @@ -633,7 +636,7 @@ struct yaffs_DeviceStruct {
10443         __u8 *spareBuffer;      /* For mtdif2 use. Don't know the size of the buffer
10444                                  * at compile time so we have to allocate it.
10445                                  */
10446 -       void (*putSuperFunc) (struct super_block * sb);
10447 +       void (*putSuperFunc) (struct super_block *sb);
10448  #endif
10449  
10450         int isMounted;
10451 @@ -663,6 +666,8 @@ struct yaffs_DeviceStruct {
10452         __u32 checkpointSum;
10453         __u32 checkpointXor;
10454  
10455 +       int nCheckpointBlocksRequired; /* Number of blocks needed to store current checkpoint set */
10456 +
10457         /* Block Info */
10458         yaffs_BlockInfo *blockInfo;
10459         __u8 *chunkBits;        /* bitmap of chunks in use */
10460 @@ -684,11 +689,15 @@ struct yaffs_DeviceStruct {
10461         yaffs_TnodeList *allocatedTnodeList;
10462  
10463         int isDoingGC;
10464 +       int gcBlock;
10465 +       int gcChunk;
10466  
10467         int nObjectsCreated;
10468         yaffs_Object *freeObjects;
10469         int nFreeObjects;
10470  
10471 +       int nHardLinks;
10472 +
10473         yaffs_ObjectList *allocatedObjectList;
10474  
10475         yaffs_ObjectBucket objectBucket[YAFFS_NOBJECT_BUCKETS];
10476 @@ -745,8 +754,10 @@ struct yaffs_DeviceStruct {
10477         int nBackgroundDeletions;       /* Count of background deletions. */
10478  
10479  
10480 +       /* Temporary buffer management */
10481         yaffs_TempBuffer tempBuffer[YAFFS_N_TEMP_BUFFERS];
10482         int maxTemp;
10483 +       int tempInUse;
10484         int unmanagedTempAllocations;
10485         int unmanagedTempDeallocations;
10486  
10487 @@ -758,9 +769,9 @@ struct yaffs_DeviceStruct {
10488  
10489  typedef struct yaffs_DeviceStruct yaffs_Device;
10490  
10491 -/* The static layout of bllock usage etc is stored in the super block header */
10492 +/* The static layout of block usage etc is stored in the super block header */
10493  typedef struct {
10494 -        int StructType;
10495 +       int StructType;
10496         int version;
10497         int checkpointStartBlock;
10498         int checkpointEndBlock;
10499 @@ -773,7 +784,7 @@ typedef struct {
10500   * must be preserved over unmount/mount cycles.
10501   */
10502  typedef struct {
10503 -        int structType;
10504 +       int structType;
10505         int nErasedBlocks;
10506         int allocationBlock;    /* Current block being allocated off */
10507         __u32 allocationPage;
10508 @@ -791,57 +802,45 @@ typedef struct {
10509  
10510  
10511  typedef struct {
10512 -    int structType;
10513 -    __u32 magic;
10514 -    __u32 version;
10515 -    __u32 head;
10516 +       int structType;
10517 +       __u32 magic;
10518 +       __u32 version;
10519 +       __u32 head;
10520  } yaffs_CheckpointValidity;
10521  
10522 -/* Function to manipulate block info */
10523 -static Y_INLINE yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blk)
10524 -{
10525 -       if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
10526 -               T(YAFFS_TRACE_ERROR,
10527 -                 (TSTR
10528 -                  ("**>> yaffs: getBlockInfo block %d is not valid" TENDSTR),
10529 -                  blk));
10530 -               YBUG();
10531 -       }
10532 -       return &dev->blockInfo[blk - dev->internalStartBlock];
10533 -}
10534  
10535  /*----------------------- YAFFS Functions -----------------------*/
10536  
10537 -int yaffs_GutsInitialise(yaffs_Device * dev);
10538 -void yaffs_Deinitialise(yaffs_Device * dev);
10539 +int yaffs_GutsInitialise(yaffs_Device *dev);
10540 +void yaffs_Deinitialise(yaffs_Device *dev);
10541  
10542 -int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev);
10543 +int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev);
10544  
10545 -int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
10546 -                      yaffs_Object * newDir, const YCHAR * newName);
10547 +int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
10548 +                      yaffs_Object *newDir, const YCHAR *newName);
10549  
10550 -int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name);
10551 -int yaffs_DeleteFile(yaffs_Object * obj);
10552 +int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name);
10553 +int yaffs_DeleteObject(yaffs_Object *obj);
10554  
10555 -int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize);
10556 -int yaffs_GetObjectFileLength(yaffs_Object * obj);
10557 -int yaffs_GetObjectInode(yaffs_Object * obj);
10558 -unsigned yaffs_GetObjectType(yaffs_Object * obj);
10559 -int yaffs_GetObjectLinkCount(yaffs_Object * obj);
10560 +int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize);
10561 +int yaffs_GetObjectFileLength(yaffs_Object *obj);
10562 +int yaffs_GetObjectInode(yaffs_Object *obj);
10563 +unsigned yaffs_GetObjectType(yaffs_Object *obj);
10564 +int yaffs_GetObjectLinkCount(yaffs_Object *obj);
10565  
10566 -int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr);
10567 -int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr);
10568 +int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr);
10569 +int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr);
10570  
10571  /* File operations */
10572 -int yaffs_ReadDataFromFile(yaffs_Object * obj, __u8 * buffer, loff_t offset,
10573 -                          int nBytes);
10574 -int yaffs_WriteDataToFile(yaffs_Object * obj, const __u8 * buffer, loff_t offset,
10575 -                         int nBytes, int writeThrough);
10576 -int yaffs_ResizeFile(yaffs_Object * obj, loff_t newSize);
10577 -
10578 -yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
10579 -                             __u32 mode, __u32 uid, __u32 gid);
10580 -int yaffs_FlushFile(yaffs_Object * obj, int updateTime);
10581 +int yaffs_ReadDataFromFile(yaffs_Object *obj, __u8 *buffer, loff_t offset,
10582 +                               int nBytes);
10583 +int yaffs_WriteDataToFile(yaffs_Object *obj, const __u8 *buffer, loff_t offset,
10584 +                               int nBytes, int writeThrough);
10585 +int yaffs_ResizeFile(yaffs_Object *obj, loff_t newSize);
10586 +
10587 +yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
10588 +                               __u32 mode, __u32 uid, __u32 gid);
10589 +int yaffs_FlushFile(yaffs_Object *obj, int updateTime);
10590  
10591  /* Flushing and checkpointing */
10592  void yaffs_FlushEntireDeviceCache(yaffs_Device *dev);
10593 @@ -850,33 +849,33 @@ int yaffs_CheckpointSave(yaffs_Device *d
10594  int yaffs_CheckpointRestore(yaffs_Device *dev);
10595  
10596  /* Directory operations */
10597 -yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
10598 -                                  __u32 mode, __u32 uid, __u32 gid);
10599 -yaffs_Object *yaffs_FindObjectByName(yaffs_Object * theDir, const YCHAR * name);
10600 -int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
10601 +yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
10602 +                               __u32 mode, __u32 uid, __u32 gid);
10603 +yaffs_Object *yaffs_FindObjectByName(yaffs_Object *theDir, const YCHAR *name);
10604 +int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
10605                                    int (*fn) (yaffs_Object *));
10606  
10607 -yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number);
10608 +yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number);
10609  
10610  /* Link operations */
10611 -yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
10612 -                        yaffs_Object * equivalentObject);
10613 +yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
10614 +                        yaffs_Object *equivalentObject);
10615  
10616 -yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj);
10617 +yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj);
10618  
10619  /* Symlink operations */
10620 -yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
10621 +yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
10622                                  __u32 mode, __u32 uid, __u32 gid,
10623 -                                const YCHAR * alias);
10624 -YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj);
10625 +                                const YCHAR *alias);
10626 +YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj);
10627  
10628  /* Special inodes (fifos, sockets and devices) */
10629 -yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
10630 +yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
10631                                  __u32 mode, __u32 uid, __u32 gid, __u32 rdev);
10632  
10633  /* Special directories */
10634 -yaffs_Object *yaffs_Root(yaffs_Device * dev);
10635 -yaffs_Object *yaffs_LostNFound(yaffs_Device * dev);
10636 +yaffs_Object *yaffs_Root(yaffs_Device *dev);
10637 +yaffs_Object *yaffs_LostNFound(yaffs_Device *dev);
10638  
10639  #ifdef CONFIG_YAFFS_WINCE
10640  /* CONFIG_YAFFS_WINCE special stuff */
10641 @@ -885,18 +884,21 @@ void yfsd_WinFileTimeNow(__u32 target[2]
10642  
10643  #ifdef __KERNEL__
10644  
10645 -void yaffs_HandleDeferedFree(yaffs_Object * obj);
10646 +void yaffs_HandleDeferedFree(yaffs_Object *obj);
10647  #endif
10648  
10649  /* Debug dump  */
10650 -int yaffs_DumpObject(yaffs_Object * obj);
10651 +int yaffs_DumpObject(yaffs_Object *obj);
10652  
10653 -void yaffs_GutsTest(yaffs_Device * dev);
10654 +void yaffs_GutsTest(yaffs_Device *dev);
10655  
10656  /* A few useful functions */
10657 -void yaffs_InitialiseTags(yaffs_ExtendedTags * tags);
10658 -void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn);
10659 -int yaffs_CheckFF(__u8 * buffer, int nBytes);
10660 +void yaffs_InitialiseTags(yaffs_ExtendedTags *tags);
10661 +void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn);
10662 +int yaffs_CheckFF(__u8 *buffer, int nBytes);
10663  void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi);
10664  
10665 +__u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo);
10666 +void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer, int lineNo);
10667 +
10668  #endif
10669 --- a/fs/yaffs2/yaffs_mtdif1.c
10670 +++ b/fs/yaffs2/yaffs_mtdif1.c
10671 @@ -26,7 +26,7 @@
10672  #include "yportenv.h"
10673  #include "yaffs_guts.h"
10674  #include "yaffs_packedtags1.h"
10675 -#include "yaffs_tagscompat.h"  // for yaffs_CalcTagsECC
10676 +#include "yaffs_tagscompat.h"  /* for yaffs_CalcTagsECC */
10677  
10678  #include "linux/kernel.h"
10679  #include "linux/version.h"
10680 @@ -34,9 +34,9 @@
10681  #include "linux/mtd/mtd.h"
10682  
10683  /* Don't compile this module if we don't have MTD's mtd_oob_ops interface */
10684 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
10685 +#if (MTD_VERSION_CODE > MTD_VERSION(2, 6, 17))
10686  
10687 -const char *yaffs_mtdif1_c_version = "$Id: yaffs_mtdif1.c,v 1.3 2007/05/15 20:16:11 ian Exp $";
10688 +const char *yaffs_mtdif1_c_version = "$Id: yaffs_mtdif1.c,v 1.10 2009-03-09 07:41:10 charles Exp $";
10689  
10690  #ifndef CONFIG_YAFFS_9BYTE_TAGS
10691  # define YTAG1_SIZE 8
10692 @@ -89,9 +89,9 @@ static struct nand_ecclayout nand_oob_16
10693   * Returns YAFFS_OK or YAFFS_FAIL.
10694   */
10695  int nandmtd1_WriteChunkWithTagsToNAND(yaffs_Device *dev,
10696 -       int chunkInNAND, const __u8 * data, const yaffs_ExtendedTags * etags)
10697 +       int chunkInNAND, const __u8 *data, const yaffs_ExtendedTags *etags)
10698  {
10699 -       struct mtd_info * mtd = dev->genericDevice;
10700 +       struct mtd_info *mtd = dev->genericDevice;
10701         int chunkBytes = dev->nDataBytesPerChunk;
10702         loff_t addr = ((loff_t)chunkInNAND) * chunkBytes;
10703         struct mtd_oob_ops ops;
10704 @@ -146,7 +146,7 @@ int nandmtd1_WriteChunkWithTagsToNAND(ya
10705  
10706  /* Return with empty ExtendedTags but add eccResult.
10707   */
10708 -static int rettags(yaffs_ExtendedTags * etags, int eccResult, int retval)
10709 +static int rettags(yaffs_ExtendedTags *etags, int eccResult, int retval)
10710  {
10711         if (etags) {
10712                 memset(etags, 0, sizeof(*etags));
10713 @@ -169,9 +169,9 @@ static int rettags(yaffs_ExtendedTags *
10714   * Returns YAFFS_OK or YAFFS_FAIL.
10715   */
10716  int nandmtd1_ReadChunkWithTagsFromNAND(yaffs_Device *dev,
10717 -       int chunkInNAND, __u8 * data, yaffs_ExtendedTags * etags)
10718 +       int chunkInNAND, __u8 *data, yaffs_ExtendedTags *etags)
10719  {
10720 -       struct mtd_info * mtd = dev->genericDevice;
10721 +       struct mtd_info *mtd = dev->genericDevice;
10722         int chunkBytes = dev->nDataBytesPerChunk;
10723         loff_t addr = ((loff_t)chunkInNAND) * chunkBytes;
10724         int eccres = YAFFS_ECC_RESULT_NO_ERROR;
10725 @@ -189,7 +189,7 @@ int nandmtd1_ReadChunkWithTagsFromNAND(y
10726         ops.datbuf = data;
10727         ops.oobbuf = (__u8 *)&pt1;
10728  
10729 -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20))
10730 +#if (MTD_VERSION_CODE < MTD_VERSION(2, 6, 20))
10731         /* In MTD 2.6.18 to 2.6.19 nand_base.c:nand_do_read_oob() has a bug;
10732          * help it out with ops.len = ops.ooblen when ops.datbuf == NULL.
10733          */
10734 @@ -284,11 +284,11 @@ int nandmtd1_ReadChunkWithTagsFromNAND(y
10735   */
10736  int nandmtd1_MarkNANDBlockBad(struct yaffs_DeviceStruct *dev, int blockNo)
10737  {
10738 -       struct mtd_info * mtd = dev->genericDevice;
10739 +       struct mtd_info *mtd = dev->genericDevice;
10740         int blocksize = dev->nChunksPerBlock * dev->nDataBytesPerChunk;
10741         int retval;
10742  
10743 -       yaffs_trace(YAFFS_TRACE_BAD_BLOCKS, "marking block %d bad", blockNo);
10744 +       yaffs_trace(YAFFS_TRACE_BAD_BLOCKS, "marking block %d bad\n", blockNo);
10745  
10746         retval = mtd->block_markbad(mtd, (loff_t)blocksize * blockNo);
10747         return (retval) ? YAFFS_FAIL : YAFFS_OK;
10748 @@ -298,7 +298,7 @@ int nandmtd1_MarkNANDBlockBad(struct yaf
10749   *
10750   * Returns YAFFS_OK or YAFFS_FAIL.
10751   */
10752 -static int nandmtd1_TestPrerequists(struct mtd_info * mtd)
10753 +static int nandmtd1_TestPrerequists(struct mtd_info *mtd)
10754  {
10755         /* 2.6.18 has mtd->ecclayout->oobavail */
10756         /* 2.6.21 has mtd->ecclayout->oobavail and mtd->oobavail */
10757 @@ -323,10 +323,11 @@ static int nandmtd1_TestPrerequists(stru
10758   * Always returns YAFFS_OK.
10759   */
10760  int nandmtd1_QueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo,
10761 -       yaffs_BlockState * pState, int *pSequenceNumber)
10762 +       yaffs_BlockState *pState, __u32 *pSequenceNumber)
10763  {
10764 -       struct mtd_info * mtd = dev->genericDevice;
10765 +       struct mtd_info *mtd = dev->genericDevice;
10766         int chunkNo = blockNo * dev->nChunksPerBlock;
10767 +       loff_t addr = (loff_t)chunkNo * dev->nDataBytesPerChunk;
10768         yaffs_ExtendedTags etags;
10769         int state = YAFFS_BLOCK_STATE_DEAD;
10770         int seqnum = 0;
10771 @@ -335,21 +336,22 @@ int nandmtd1_QueryNANDBlock(struct yaffs
10772         /* We don't yet have a good place to test for MTD config prerequists.
10773          * Do it here as we are called during the initial scan.
10774          */
10775 -       if (nandmtd1_TestPrerequists(mtd) != YAFFS_OK) {
10776 +       if (nandmtd1_TestPrerequists(mtd) != YAFFS_OK)
10777                 return YAFFS_FAIL;
10778 -       }
10779  
10780         retval = nandmtd1_ReadChunkWithTagsFromNAND(dev, chunkNo, NULL, &etags);
10781 +       etags.blockBad = (mtd->block_isbad)(mtd, addr);
10782         if (etags.blockBad) {
10783                 yaffs_trace(YAFFS_TRACE_BAD_BLOCKS,
10784 -                       "block %d is marked bad", blockNo);
10785 +                       "block %d is marked bad\n", blockNo);
10786                 state = YAFFS_BLOCK_STATE_DEAD;
10787 -       }
10788 -       else if (etags.chunkUsed) {
10789 +       } else if (etags.eccResult != YAFFS_ECC_RESULT_NO_ERROR) {
10790 +               /* bad tags, need to look more closely */
10791 +               state = YAFFS_BLOCK_STATE_NEEDS_SCANNING;
10792 +       } else if (etags.chunkUsed) {
10793                 state = YAFFS_BLOCK_STATE_NEEDS_SCANNING;
10794                 seqnum = etags.sequenceNumber;
10795 -       }
10796 -       else {
10797 +       } else {
10798                 state = YAFFS_BLOCK_STATE_EMPTY;
10799         }
10800  
10801 @@ -360,4 +362,4 @@ int nandmtd1_QueryNANDBlock(struct yaffs
10802         return YAFFS_OK;
10803  }
10804  
10805 -#endif /*KERNEL_VERSION*/
10806 +#endif /*MTD_VERSION*/
10807 --- a/fs/yaffs2/yaffs_mtdif1.h
10808 +++ b/fs/yaffs2/yaffs_mtdif1.h
10809 @@ -14,15 +14,15 @@
10810  #ifndef __YAFFS_MTDIF1_H__
10811  #define __YAFFS_MTDIF1_H__
10812  
10813 -int nandmtd1_WriteChunkWithTagsToNAND(yaffs_Device * dev, int chunkInNAND,
10814 -       const __u8 * data, const yaffs_ExtendedTags * tags);
10815 +int nandmtd1_WriteChunkWithTagsToNAND(yaffs_Device *dev, int chunkInNAND,
10816 +       const __u8 *data, const yaffs_ExtendedTags *tags);
10817  
10818 -int nandmtd1_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND,
10819 -       __u8 * data, yaffs_ExtendedTags * tags);
10820 +int nandmtd1_ReadChunkWithTagsFromNAND(yaffs_Device *dev, int chunkInNAND,
10821 +       __u8 *data, yaffs_ExtendedTags *tags);
10822  
10823  int nandmtd1_MarkNANDBlockBad(struct yaffs_DeviceStruct *dev, int blockNo);
10824  
10825  int nandmtd1_QueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo,
10826 -       yaffs_BlockState * state, int *sequenceNumber);
10827 +       yaffs_BlockState *state, __u32 *sequenceNumber);
10828  
10829  #endif
10830 --- a/fs/yaffs2/yaffs_mtdif2.c
10831 +++ b/fs/yaffs2/yaffs_mtdif2.c
10832 @@ -14,7 +14,7 @@
10833  /* mtd interface for YAFFS2 */
10834  
10835  const char *yaffs_mtdif2_c_version =
10836 -    "$Id: yaffs_mtdif2.c,v 1.17 2007-02-14 01:09:06 wookey Exp $";
10837 +       "$Id: yaffs_mtdif2.c,v 1.23 2009-03-06 17:20:53 wookey Exp $";
10838  
10839  #include "yportenv.h"
10840  
10841 @@ -27,19 +27,23 @@ const char *yaffs_mtdif2_c_version =
10842  
10843  #include "yaffs_packedtags2.h"
10844  
10845 -int nandmtd2_WriteChunkWithTagsToNAND(yaffs_Device * dev, int chunkInNAND,
10846 -                                     const __u8 * data,
10847 -                                     const yaffs_ExtendedTags * tags)
10848 +/* NB For use with inband tags....
10849 + * We assume that the data buffer is of size totalBytersPerChunk so that we can also
10850 + * use it to load the tags.
10851 + */
10852 +int nandmtd2_WriteChunkWithTagsToNAND(yaffs_Device *dev, int chunkInNAND,
10853 +                                     const __u8 *data,
10854 +                                     const yaffs_ExtendedTags *tags)
10855  {
10856         struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice);
10857 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
10858 +#if (MTD_VERSION_CODE > MTD_VERSION(2, 6, 17))
10859         struct mtd_oob_ops ops;
10860  #else
10861         size_t dummy;
10862  #endif
10863         int retval = 0;
10864  
10865 -       loff_t addr = ((loff_t) chunkInNAND) * dev->nDataBytesPerChunk;
10866 +       loff_t addr;
10867  
10868         yaffs_PackedTags2 pt;
10869  
10870 @@ -48,46 +52,40 @@ int nandmtd2_WriteChunkWithTagsToNAND(ya
10871            ("nandmtd2_WriteChunkWithTagsToNAND chunk %d data %p tags %p"
10872             TENDSTR), chunkInNAND, data, tags));
10873  
10874 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
10875 -       if (tags)
10876 -               yaffs_PackTags2(&pt, tags);
10877 -       else
10878 -               BUG(); /* both tags and data should always be present */
10879  
10880 -       if (data) {
10881 -               ops.mode = MTD_OOB_AUTO;
10882 -               ops.ooblen = sizeof(pt);
10883 -               ops.len = dev->nDataBytesPerChunk;
10884 -               ops.ooboffs = 0;
10885 -               ops.datbuf = (__u8 *)data;
10886 -               ops.oobbuf = (void *)&pt;
10887 -               retval = mtd->write_oob(mtd, addr, &ops);
10888 +       addr  = ((loff_t) chunkInNAND) * dev->totalBytesPerChunk;
10889 +
10890 +       /* For yaffs2 writing there must be both data and tags.
10891 +        * If we're using inband tags, then the tags are stuffed into
10892 +        * the end of the data buffer.
10893 +        */
10894 +       if (!data || !tags)
10895 +               BUG();
10896 +       else if (dev->inbandTags) {
10897 +               yaffs_PackedTags2TagsPart *pt2tp;
10898 +               pt2tp = (yaffs_PackedTags2TagsPart *)(data + dev->nDataBytesPerChunk);
10899 +               yaffs_PackTags2TagsPart(pt2tp, tags);
10900         } else
10901 -               BUG(); /* both tags and data should always be present */
10902 -#else
10903 -       if (tags) {
10904                 yaffs_PackTags2(&pt, tags);
10905 -       }
10906  
10907 -       if (data && tags) {
10908 -               if (dev->useNANDECC)
10909 -                       retval =
10910 -                           mtd->write_ecc(mtd, addr, dev->nDataBytesPerChunk,
10911 -                                          &dummy, data, (__u8 *) & pt, NULL);
10912 -               else
10913 -                       retval =
10914 -                           mtd->write_ecc(mtd, addr, dev->nDataBytesPerChunk,
10915 -                                          &dummy, data, (__u8 *) & pt, NULL);
10916 -       } else {
10917 -               if (data)
10918 -                       retval =
10919 -                           mtd->write(mtd, addr, dev->nDataBytesPerChunk, &dummy,
10920 -                                      data);
10921 -               if (tags)
10922 -                       retval =
10923 -                           mtd->write_oob(mtd, addr, mtd->oobsize, &dummy,
10924 -                                          (__u8 *) & pt);
10925 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
10926 +       ops.mode = MTD_OOB_AUTO;
10927 +       ops.ooblen = (dev->inbandTags) ? 0 : sizeof(pt);
10928 +       ops.len = dev->totalBytesPerChunk;
10929 +       ops.ooboffs = 0;
10930 +       ops.datbuf = (__u8 *)data;
10931 +       ops.oobbuf = (dev->inbandTags) ? NULL : (void *)&pt;
10932 +       retval = mtd->write_oob(mtd, addr, &ops);
10933  
10934 +#else
10935 +       if (!dev->inbandTags) {
10936 +               retval =
10937 +                   mtd->write_ecc(mtd, addr, dev->nDataBytesPerChunk,
10938 +                                  &dummy, data, (__u8 *) &pt, NULL);
10939 +       } else {
10940 +               retval =
10941 +                   mtd->write(mtd, addr, dev->totalBytesPerChunk, &dummy,
10942 +                              data);
10943         }
10944  #endif
10945  
10946 @@ -97,17 +95,18 @@ int nandmtd2_WriteChunkWithTagsToNAND(ya
10947                 return YAFFS_FAIL;
10948  }
10949  
10950 -int nandmtd2_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND,
10951 -                                      __u8 * data, yaffs_ExtendedTags * tags)
10952 +int nandmtd2_ReadChunkWithTagsFromNAND(yaffs_Device *dev, int chunkInNAND,
10953 +                                      __u8 *data, yaffs_ExtendedTags *tags)
10954  {
10955         struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice);
10956 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
10957 +#if (MTD_VERSION_CODE > MTD_VERSION(2, 6, 17))
10958         struct mtd_oob_ops ops;
10959  #endif
10960         size_t dummy;
10961         int retval = 0;
10962 +       int localData = 0;
10963  
10964 -       loff_t addr = ((loff_t) chunkInNAND) * dev->nDataBytesPerChunk;
10965 +       loff_t addr = ((loff_t) chunkInNAND) * dev->totalBytesPerChunk;
10966  
10967         yaffs_PackedTags2 pt;
10968  
10969 @@ -116,9 +115,20 @@ int nandmtd2_ReadChunkWithTagsFromNAND(y
10970            ("nandmtd2_ReadChunkWithTagsFromNAND chunk %d data %p tags %p"
10971             TENDSTR), chunkInNAND, data, tags));
10972  
10973 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
10974 -       if (data && !tags)
10975 -               retval = mtd->read(mtd, addr, dev->nDataBytesPerChunk,
10976 +       if (dev->inbandTags) {
10977 +
10978 +               if (!data) {
10979 +                       localData = 1;
10980 +                       data = yaffs_GetTempBuffer(dev, __LINE__);
10981 +               }
10982 +
10983 +
10984 +       }
10985 +
10986 +
10987 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
10988 +       if (dev->inbandTags || (data && !tags))
10989 +               retval = mtd->read(mtd, addr, dev->totalBytesPerChunk,
10990                                 &dummy, data);
10991         else if (tags) {
10992                 ops.mode = MTD_OOB_AUTO;
10993 @@ -130,38 +140,42 @@ int nandmtd2_ReadChunkWithTagsFromNAND(y
10994                 retval = mtd->read_oob(mtd, addr, &ops);
10995         }
10996  #else
10997 -       if (data && tags) {
10998 -               if (dev->useNANDECC) {
10999 -                       retval =
11000 -                           mtd->read_ecc(mtd, addr, dev->nDataBytesPerChunk,
11001 -                                         &dummy, data, dev->spareBuffer,
11002 -                                         NULL);
11003 -               } else {
11004 -                       retval =
11005 -                           mtd->read_ecc(mtd, addr, dev->nDataBytesPerChunk,
11006 +       if (!dev->inbandTags && data && tags) {
11007 +
11008 +               retval = mtd->read_ecc(mtd, addr, dev->nDataBytesPerChunk,
11009                                           &dummy, data, dev->spareBuffer,
11010                                           NULL);
11011 -               }
11012         } else {
11013                 if (data)
11014                         retval =
11015                             mtd->read(mtd, addr, dev->nDataBytesPerChunk, &dummy,
11016                                       data);
11017 -               if (tags)
11018 +               if (!dev->inbandTags && tags)
11019                         retval =
11020                             mtd->read_oob(mtd, addr, mtd->oobsize, &dummy,
11021                                           dev->spareBuffer);
11022         }
11023  #endif
11024  
11025 -       memcpy(&pt, dev->spareBuffer, sizeof(pt));
11026  
11027 -       if (tags)
11028 -               yaffs_UnpackTags2(tags, &pt);
11029 +       if (dev->inbandTags) {
11030 +               if (tags) {
11031 +                       yaffs_PackedTags2TagsPart *pt2tp;
11032 +                       pt2tp = (yaffs_PackedTags2TagsPart *)&data[dev->nDataBytesPerChunk];
11033 +                       yaffs_UnpackTags2TagsPart(tags, pt2tp);
11034 +               }
11035 +       } else {
11036 +               if (tags) {
11037 +                       memcpy(&pt, dev->spareBuffer, sizeof(pt));
11038 +                       yaffs_UnpackTags2(tags, &pt);
11039 +               }
11040 +       }
11041 +
11042 +       if (localData)
11043 +               yaffs_ReleaseTempBuffer(dev, data, __LINE__);
11044  
11045 -       if(tags && retval == -EBADMSG && tags->eccResult == YAFFS_ECC_RESULT_NO_ERROR)
11046 +       if (tags && retval == -EBADMSG && tags->eccResult == YAFFS_ECC_RESULT_NO_ERROR)
11047                 tags->eccResult = YAFFS_ECC_RESULT_UNFIXED;
11048 -
11049         if (retval == 0)
11050                 return YAFFS_OK;
11051         else
11052 @@ -178,7 +192,7 @@ int nandmtd2_MarkNANDBlockBad(struct yaf
11053         retval =
11054             mtd->block_markbad(mtd,
11055                                blockNo * dev->nChunksPerBlock *
11056 -                              dev->nDataBytesPerChunk);
11057 +                              dev->totalBytesPerChunk);
11058  
11059         if (retval == 0)
11060                 return YAFFS_OK;
11061 @@ -188,7 +202,7 @@ int nandmtd2_MarkNANDBlockBad(struct yaf
11062  }
11063  
11064  int nandmtd2_QueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo,
11065 -                           yaffs_BlockState * state, int *sequenceNumber)
11066 +                           yaffs_BlockState *state, __u32 *sequenceNumber)
11067  {
11068         struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice);
11069         int retval;
11070 @@ -198,7 +212,7 @@ int nandmtd2_QueryNANDBlock(struct yaffs
11071         retval =
11072             mtd->block_isbad(mtd,
11073                              blockNo * dev->nChunksPerBlock *
11074 -                            dev->nDataBytesPerChunk);
11075 +                            dev->totalBytesPerChunk);
11076  
11077         if (retval) {
11078                 T(YAFFS_TRACE_MTD, (TSTR("block is bad" TENDSTR)));
11079 --- a/fs/yaffs2/yaffs_mtdif2.h
11080 +++ b/fs/yaffs2/yaffs_mtdif2.h
11081 @@ -17,13 +17,13 @@
11082  #define __YAFFS_MTDIF2_H__
11083  
11084  #include "yaffs_guts.h"
11085 -int nandmtd2_WriteChunkWithTagsToNAND(yaffs_Device * dev, int chunkInNAND,
11086 -                                     const __u8 * data,
11087 -                                     const yaffs_ExtendedTags * tags);
11088 -int nandmtd2_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND,
11089 -                                      __u8 * data, yaffs_ExtendedTags * tags);
11090 +int nandmtd2_WriteChunkWithTagsToNAND(yaffs_Device *dev, int chunkInNAND,
11091 +                               const __u8 *data,
11092 +                               const yaffs_ExtendedTags *tags);
11093 +int nandmtd2_ReadChunkWithTagsFromNAND(yaffs_Device *dev, int chunkInNAND,
11094 +                               __u8 *data, yaffs_ExtendedTags *tags);
11095  int nandmtd2_MarkNANDBlockBad(struct yaffs_DeviceStruct *dev, int blockNo);
11096  int nandmtd2_QueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo,
11097 -                           yaffs_BlockState * state, int *sequenceNumber);
11098 +                       yaffs_BlockState *state, __u32 *sequenceNumber);
11099  
11100  #endif
11101 --- a/fs/yaffs2/yaffs_mtdif.c
11102 +++ b/fs/yaffs2/yaffs_mtdif.c
11103 @@ -12,7 +12,7 @@
11104   */
11105  
11106  const char *yaffs_mtdif_c_version =
11107 -    "$Id: yaffs_mtdif.c,v 1.19 2007-02-14 01:09:06 wookey Exp $";
11108 +       "$Id: yaffs_mtdif.c,v 1.22 2009-03-06 17:20:51 wookey Exp $";
11109  
11110  #include "yportenv.h"
11111  
11112 @@ -24,7 +24,7 @@ const char *yaffs_mtdif_c_version =
11113  #include "linux/time.h"
11114  #include "linux/mtd/nand.h"
11115  
11116 -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,18))
11117 +#if (MTD_VERSION_CODE < MTD_VERSION(2, 6, 18))
11118  static struct nand_oobinfo yaffs_oobinfo = {
11119         .useecc = 1,
11120         .eccbytes = 6,
11121 @@ -36,7 +36,7 @@ static struct nand_oobinfo yaffs_noeccin
11122  };
11123  #endif
11124  
11125 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
11126 +#if (MTD_VERSION_CODE > MTD_VERSION(2, 6, 17))
11127  static inline void translate_spare2oob(const yaffs_Spare *spare, __u8 *oob)
11128  {
11129         oob[0] = spare->tagByte0;
11130 @@ -45,8 +45,8 @@ static inline void translate_spare2oob(c
11131         oob[3] = spare->tagByte3;
11132         oob[4] = spare->tagByte4;
11133         oob[5] = spare->tagByte5 & 0x3f;
11134 -       oob[5] |= spare->blockStatus == 'Y' ? 0: 0x80;
11135 -       oob[5] |= spare->pageStatus == 0 ? 0: 0x40;
11136 +       oob[5] |= spare->blockStatus == 'Y' ? 0 : 0x80;
11137 +       oob[5] |= spare->pageStatus == 0 ? 0 : 0x40;
11138         oob[6] = spare->tagByte6;
11139         oob[7] = spare->tagByte7;
11140  }
11141 @@ -71,18 +71,18 @@ static inline void translate_oob2spare(y
11142  }
11143  #endif
11144  
11145 -int nandmtd_WriteChunkToNAND(yaffs_Device * dev, int chunkInNAND,
11146 -                            const __u8 * data, const yaffs_Spare * spare)
11147 +int nandmtd_WriteChunkToNAND(yaffs_Device *dev, int chunkInNAND,
11148 +                            const __u8 *data, const yaffs_Spare *spare)
11149  {
11150         struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice);
11151 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
11152 +#if (MTD_VERSION_CODE > MTD_VERSION(2, 6, 17))
11153         struct mtd_oob_ops ops;
11154  #endif
11155         size_t dummy;
11156         int retval = 0;
11157  
11158         loff_t addr = ((loff_t) chunkInNAND) * dev->nDataBytesPerChunk;
11159 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
11160 +#if (MTD_VERSION_CODE > MTD_VERSION(2, 6, 17))
11161         __u8 spareAsBytes[8]; /* OOB */
11162  
11163         if (data && !spare)
11164 @@ -135,18 +135,18 @@ int nandmtd_WriteChunkToNAND(yaffs_Devic
11165                 return YAFFS_FAIL;
11166  }
11167  
11168 -int nandmtd_ReadChunkFromNAND(yaffs_Device * dev, int chunkInNAND, __u8 * data,
11169 -                             yaffs_Spare * spare)
11170 +int nandmtd_ReadChunkFromNAND(yaffs_Device *dev, int chunkInNAND, __u8 *data,
11171 +                             yaffs_Spare *spare)
11172  {
11173         struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice);
11174 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
11175 +#if (MTD_VERSION_CODE > MTD_VERSION(2, 6, 17))
11176         struct mtd_oob_ops ops;
11177  #endif
11178         size_t dummy;
11179         int retval = 0;
11180  
11181         loff_t addr = ((loff_t) chunkInNAND) * dev->nDataBytesPerChunk;
11182 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17))
11183 +#if (MTD_VERSION_CODE > MTD_VERSION(2, 6, 17))
11184         __u8 spareAsBytes[8]; /* OOB */
11185  
11186         if (data && !spare)
11187 @@ -205,7 +205,7 @@ int nandmtd_ReadChunkFromNAND(yaffs_Devi
11188                 return YAFFS_FAIL;
11189  }
11190  
11191 -int nandmtd_EraseBlockInNAND(yaffs_Device * dev, int blockNumber)
11192 +int nandmtd_EraseBlockInNAND(yaffs_Device *dev, int blockNumber)
11193  {
11194         struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice);
11195         __u32 addr =
11196 @@ -234,7 +234,7 @@ int nandmtd_EraseBlockInNAND(yaffs_Devic
11197                 return YAFFS_FAIL;
11198  }
11199  
11200 -int nandmtd_InitialiseNAND(yaffs_Device * dev)
11201 +int nandmtd_InitialiseNAND(yaffs_Device *dev)
11202  {
11203         return YAFFS_OK;
11204  }
11205 --- a/fs/yaffs2/yaffs_mtdif.h
11206 +++ b/fs/yaffs2/yaffs_mtdif.h
11207 @@ -18,10 +18,15 @@
11208  
11209  #include "yaffs_guts.h"
11210  
11211 -int nandmtd_WriteChunkToNAND(yaffs_Device * dev, int chunkInNAND,
11212 -                            const __u8 * data, const yaffs_Spare * spare);
11213 -int nandmtd_ReadChunkFromNAND(yaffs_Device * dev, int chunkInNAND, __u8 * data,
11214 -                             yaffs_Spare * spare);
11215 -int nandmtd_EraseBlockInNAND(yaffs_Device * dev, int blockNumber);
11216 -int nandmtd_InitialiseNAND(yaffs_Device * dev);
11217 +#if (MTD_VERSION_CODE < MTD_VERSION(2, 6, 18))
11218 +extern struct nand_oobinfo yaffs_oobinfo;
11219 +extern struct nand_oobinfo yaffs_noeccinfo;
11220 +#endif
11221 +
11222 +int nandmtd_WriteChunkToNAND(yaffs_Device *dev, int chunkInNAND,
11223 +                       const __u8 *data, const yaffs_Spare *spare);
11224 +int nandmtd_ReadChunkFromNAND(yaffs_Device *dev, int chunkInNAND, __u8 *data,
11225 +                       yaffs_Spare *spare);
11226 +int nandmtd_EraseBlockInNAND(yaffs_Device *dev, int blockNumber);
11227 +int nandmtd_InitialiseNAND(yaffs_Device *dev);
11228  #endif
11229 --- a/fs/yaffs2/yaffs_nand.c
11230 +++ b/fs/yaffs2/yaffs_nand.c
11231 @@ -12,16 +12,17 @@
11232   */
11233  
11234  const char *yaffs_nand_c_version =
11235 -    "$Id: yaffs_nand.c,v 1.7 2007-02-14 01:09:06 wookey Exp $";
11236 +       "$Id: yaffs_nand.c,v 1.10 2009-03-06 17:20:54 wookey Exp $";
11237  
11238  #include "yaffs_nand.h"
11239  #include "yaffs_tagscompat.h"
11240  #include "yaffs_tagsvalidity.h"
11241  
11242 +#include "yaffs_getblockinfo.h"
11243  
11244 -int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND,
11245 -                                          __u8 * buffer,
11246 -                                          yaffs_ExtendedTags * tags)
11247 +int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device *dev, int chunkInNAND,
11248 +                                          __u8 *buffer,
11249 +                                          yaffs_ExtendedTags *tags)
11250  {
11251         int result;
11252         yaffs_ExtendedTags localTags;
11253 @@ -29,7 +30,7 @@ int yaffs_ReadChunkWithTagsFromNAND(yaff
11254         int realignedChunkInNAND = chunkInNAND - dev->chunkOffset;
11255  
11256         /* If there are no tags provided, use local tags to get prioritised gc working */
11257 -       if(!tags)
11258 +       if (!tags)
11259                 tags = &localTags;
11260  
11261         if (dev->readChunkWithTagsFromNAND)
11262 @@ -40,20 +41,20 @@ int yaffs_ReadChunkWithTagsFromNAND(yaff
11263                                                                         realignedChunkInNAND,
11264                                                                         buffer,
11265                                                                         tags);
11266 -       if(tags &&
11267 -          tags->eccResult > YAFFS_ECC_RESULT_NO_ERROR){
11268 +       if (tags &&
11269 +          tags->eccResult > YAFFS_ECC_RESULT_NO_ERROR) {
11270  
11271                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, chunkInNAND/dev->nChunksPerBlock);
11272 -                yaffs_HandleChunkError(dev,bi);
11273 +               yaffs_HandleChunkError(dev, bi);
11274         }
11275  
11276         return result;
11277  }
11278  
11279 -int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
11280 +int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,
11281                                                    int chunkInNAND,
11282 -                                                  const __u8 * buffer,
11283 -                                                  yaffs_ExtendedTags * tags)
11284 +                                                  const __u8 *buffer,
11285 +                                                  yaffs_ExtendedTags *tags)
11286  {
11287         chunkInNAND -= dev->chunkOffset;
11288  
11289 @@ -84,7 +85,7 @@ int yaffs_WriteChunkWithTagsToNAND(yaffs
11290                                                                        tags);
11291  }
11292  
11293 -int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo)
11294 +int yaffs_MarkBlockBad(yaffs_Device *dev, int blockNo)
11295  {
11296         blockNo -= dev->blockOffset;
11297  
11298 @@ -95,10 +96,10 @@ int yaffs_MarkBlockBad(yaffs_Device * de
11299                 return yaffs_TagsCompatabilityMarkNANDBlockBad(dev, blockNo);
11300  }
11301  
11302 -int yaffs_QueryInitialBlockState(yaffs_Device * dev,
11303 +int yaffs_QueryInitialBlockState(yaffs_Device *dev,
11304                                                  int blockNo,
11305 -                                                yaffs_BlockState * state,
11306 -                                                unsigned *sequenceNumber)
11307 +                                                yaffs_BlockState *state,
11308 +                                                __u32 *sequenceNumber)
11309  {
11310         blockNo -= dev->blockOffset;
11311  
11312 --- a/fs/yaffs2/yaffs_nandemul2k.h
11313 +++ b/fs/yaffs2/yaffs_nandemul2k.h
11314 @@ -21,14 +21,14 @@
11315  #include "yaffs_guts.h"
11316  
11317  int nandemul2k_WriteChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
11318 -                                       int chunkInNAND, const __u8 * data,
11319 -                                       yaffs_ExtendedTags * tags);
11320 +                                       int chunkInNAND, const __u8 *data,
11321 +                                       const yaffs_ExtendedTags *tags);
11322  int nandemul2k_ReadChunkWithTagsFromNAND(struct yaffs_DeviceStruct *dev,
11323 -                                        int chunkInNAND, __u8 * data,
11324 -                                        yaffs_ExtendedTags * tags);
11325 +                                        int chunkInNAND, __u8 *data,
11326 +                                        yaffs_ExtendedTags *tags);
11327  int nandemul2k_MarkNANDBlockBad(struct yaffs_DeviceStruct *dev, int blockNo);
11328  int nandemul2k_QueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo,
11329 -                             yaffs_BlockState * state, int *sequenceNumber);
11330 +                             yaffs_BlockState *state, __u32 *sequenceNumber);
11331  int nandemul2k_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,
11332                                 int blockInNAND);
11333  int nandemul2k_InitialiseNAND(struct yaffs_DeviceStruct *dev);
11334 --- a/fs/yaffs2/yaffs_nand.h
11335 +++ b/fs/yaffs2/yaffs_nand.h
11336 @@ -19,21 +19,21 @@
11337  
11338  
11339  
11340 -int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND,
11341 -                                          __u8 * buffer,
11342 -                                          yaffs_ExtendedTags * tags);
11343 -
11344 -int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
11345 -                                                  int chunkInNAND,
11346 -                                                  const __u8 * buffer,
11347 -                                                  yaffs_ExtendedTags * tags);
11348 -
11349 -int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo);
11350 -
11351 -int yaffs_QueryInitialBlockState(yaffs_Device * dev,
11352 -                                                int blockNo,
11353 -                                                yaffs_BlockState * state,
11354 -                                                unsigned *sequenceNumber);
11355 +int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device *dev, int chunkInNAND,
11356 +                                       __u8 *buffer,
11357 +                                       yaffs_ExtendedTags *tags);
11358 +
11359 +int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,
11360 +                                               int chunkInNAND,
11361 +                                               const __u8 *buffer,
11362 +                                               yaffs_ExtendedTags *tags);
11363 +
11364 +int yaffs_MarkBlockBad(yaffs_Device *dev, int blockNo);
11365 +
11366 +int yaffs_QueryInitialBlockState(yaffs_Device *dev,
11367 +                                               int blockNo,
11368 +                                               yaffs_BlockState *state,
11369 +                                               unsigned *sequenceNumber);
11370  
11371  int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,
11372                                   int blockInNAND);
11373 --- a/fs/yaffs2/yaffs_packedtags1.c
11374 +++ b/fs/yaffs2/yaffs_packedtags1.c
11375 @@ -14,7 +14,7 @@
11376  #include "yaffs_packedtags1.h"
11377  #include "yportenv.h"
11378  
11379 -void yaffs_PackTags1(yaffs_PackedTags1 * pt, const yaffs_ExtendedTags * t)
11380 +void yaffs_PackTags1(yaffs_PackedTags1 *pt, const yaffs_ExtendedTags *t)
11381  {
11382         pt->chunkId = t->chunkId;
11383         pt->serialNumber = t->serialNumber;
11384 @@ -27,7 +27,7 @@ void yaffs_PackTags1(yaffs_PackedTags1 *
11385  
11386  }
11387  
11388 -void yaffs_UnpackTags1(yaffs_ExtendedTags * t, const yaffs_PackedTags1 * pt)
11389 +void yaffs_UnpackTags1(yaffs_ExtendedTags *t, const yaffs_PackedTags1 *pt)
11390  {
11391         static const __u8 allFF[] =
11392             { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
11393 @@ -35,9 +35,8 @@ void yaffs_UnpackTags1(yaffs_ExtendedTag
11394  
11395         if (memcmp(allFF, pt, sizeof(yaffs_PackedTags1))) {
11396                 t->blockBad = 0;
11397 -               if (pt->shouldBeFF != 0xFFFFFFFF) {
11398 +               if (pt->shouldBeFF != 0xFFFFFFFF)
11399                         t->blockBad = 1;
11400 -               }
11401                 t->chunkUsed = 1;
11402                 t->objectId = pt->objectId;
11403                 t->chunkId = pt->chunkId;
11404 @@ -47,6 +46,5 @@ void yaffs_UnpackTags1(yaffs_ExtendedTag
11405                 t->serialNumber = pt->serialNumber;
11406         } else {
11407                 memset(t, 0, sizeof(yaffs_ExtendedTags));
11408 -
11409         }
11410  }
11411 --- a/fs/yaffs2/yaffs_packedtags1.h
11412 +++ b/fs/yaffs2/yaffs_packedtags1.h
11413 @@ -32,6 +32,6 @@ typedef struct {
11414  
11415  } yaffs_PackedTags1;
11416  
11417 -void yaffs_PackTags1(yaffs_PackedTags1 * pt, const yaffs_ExtendedTags * t);
11418 -void yaffs_UnpackTags1(yaffs_ExtendedTags * t, const yaffs_PackedTags1 * pt);
11419 +void yaffs_PackTags1(yaffs_PackedTags1 *pt, const yaffs_ExtendedTags *t);
11420 +void yaffs_UnpackTags1(yaffs_ExtendedTags *t, const yaffs_PackedTags1 *pt);
11421  #endif
11422 --- a/fs/yaffs2/yaffs_packedtags2.c
11423 +++ b/fs/yaffs2/yaffs_packedtags2.c
11424 @@ -37,60 +37,68 @@
11425  #define EXTRA_OBJECT_TYPE_SHIFT (28)
11426  #define EXTRA_OBJECT_TYPE_MASK  ((0x0F) << EXTRA_OBJECT_TYPE_SHIFT)
11427  
11428 -static void yaffs_DumpPackedTags2(const yaffs_PackedTags2 * pt)
11429 +
11430 +static void yaffs_DumpPackedTags2TagsPart(const yaffs_PackedTags2TagsPart *ptt)
11431  {
11432         T(YAFFS_TRACE_MTD,
11433           (TSTR("packed tags obj %d chunk %d byte %d seq %d" TENDSTR),
11434 -          pt->t.objectId, pt->t.chunkId, pt->t.byteCount,
11435 -          pt->t.sequenceNumber));
11436 +          ptt->objectId, ptt->chunkId, ptt->byteCount,
11437 +          ptt->sequenceNumber));
11438 +}
11439 +static void yaffs_DumpPackedTags2(const yaffs_PackedTags2 *pt)
11440 +{
11441 +       yaffs_DumpPackedTags2TagsPart(&pt->t);
11442  }
11443  
11444 -static void yaffs_DumpTags2(const yaffs_ExtendedTags * t)
11445 +static void yaffs_DumpTags2(const yaffs_ExtendedTags *t)
11446  {
11447         T(YAFFS_TRACE_MTD,
11448           (TSTR
11449 -          ("ext.tags eccres %d blkbad %d chused %d obj %d chunk%d byte "
11450 -           "%d del %d ser %d seq %d"
11451 +          ("ext.tags eccres %d blkbad %d chused %d obj %d chunk%d byte %d del %d ser %d seq %d"
11452             TENDSTR), t->eccResult, t->blockBad, t->chunkUsed, t->objectId,
11453            t->chunkId, t->byteCount, t->chunkDeleted, t->serialNumber,
11454            t->sequenceNumber));
11455  
11456  }
11457  
11458 -void yaffs_PackTags2(yaffs_PackedTags2 * pt, const yaffs_ExtendedTags * t)
11459 +void yaffs_PackTags2TagsPart(yaffs_PackedTags2TagsPart *ptt,
11460 +               const yaffs_ExtendedTags *t)
11461  {
11462 -       pt->t.chunkId = t->chunkId;
11463 -       pt->t.sequenceNumber = t->sequenceNumber;
11464 -       pt->t.byteCount = t->byteCount;
11465 -       pt->t.objectId = t->objectId;
11466 +       ptt->chunkId = t->chunkId;
11467 +       ptt->sequenceNumber = t->sequenceNumber;
11468 +       ptt->byteCount = t->byteCount;
11469 +       ptt->objectId = t->objectId;
11470  
11471         if (t->chunkId == 0 && t->extraHeaderInfoAvailable) {
11472                 /* Store the extra header info instead */
11473                 /* We save the parent object in the chunkId */
11474 -               pt->t.chunkId = EXTRA_HEADER_INFO_FLAG
11475 +               ptt->chunkId = EXTRA_HEADER_INFO_FLAG
11476                         | t->extraParentObjectId;
11477 -               if (t->extraIsShrinkHeader) {
11478 -                       pt->t.chunkId |= EXTRA_SHRINK_FLAG;
11479 -               }
11480 -               if (t->extraShadows) {
11481 -                       pt->t.chunkId |= EXTRA_SHADOWS_FLAG;
11482 -               }
11483 +               if (t->extraIsShrinkHeader)
11484 +                       ptt->chunkId |= EXTRA_SHRINK_FLAG;
11485 +               if (t->extraShadows)
11486 +                       ptt->chunkId |= EXTRA_SHADOWS_FLAG;
11487  
11488 -               pt->t.objectId &= ~EXTRA_OBJECT_TYPE_MASK;
11489 -               pt->t.objectId |=
11490 +               ptt->objectId &= ~EXTRA_OBJECT_TYPE_MASK;
11491 +               ptt->objectId |=
11492                     (t->extraObjectType << EXTRA_OBJECT_TYPE_SHIFT);
11493  
11494 -               if (t->extraObjectType == YAFFS_OBJECT_TYPE_HARDLINK) {
11495 -                       pt->t.byteCount = t->extraEquivalentObjectId;
11496 -               } else if (t->extraObjectType == YAFFS_OBJECT_TYPE_FILE) {
11497 -                       pt->t.byteCount = t->extraFileLength;
11498 -               } else {
11499 -                       pt->t.byteCount = 0;
11500 -               }
11501 +               if (t->extraObjectType == YAFFS_OBJECT_TYPE_HARDLINK)
11502 +                       ptt->byteCount = t->extraEquivalentObjectId;
11503 +               else if (t->extraObjectType == YAFFS_OBJECT_TYPE_FILE)
11504 +                       ptt->byteCount = t->extraFileLength;
11505 +               else
11506 +                       ptt->byteCount = 0;
11507         }
11508  
11509 -       yaffs_DumpPackedTags2(pt);
11510 +       yaffs_DumpPackedTags2TagsPart(ptt);
11511         yaffs_DumpTags2(t);
11512 +}
11513 +
11514 +
11515 +void yaffs_PackTags2(yaffs_PackedTags2 *pt, const yaffs_ExtendedTags *t)
11516 +{
11517 +       yaffs_PackTags2TagsPart(&pt->t, t);
11518  
11519  #ifndef YAFFS_IGNORE_TAGS_ECC
11520         {
11521 @@ -101,82 +109,98 @@ void yaffs_PackTags2(yaffs_PackedTags2 *
11522  #endif
11523  }
11524  
11525 -void yaffs_UnpackTags2(yaffs_ExtendedTags * t, yaffs_PackedTags2 * pt)
11526 +
11527 +void yaffs_UnpackTags2TagsPart(yaffs_ExtendedTags *t,
11528 +               yaffs_PackedTags2TagsPart *ptt)
11529  {
11530  
11531         memset(t, 0, sizeof(yaffs_ExtendedTags));
11532  
11533         yaffs_InitialiseTags(t);
11534  
11535 -       if (pt->t.sequenceNumber != 0xFFFFFFFF) {
11536 -               /* Page is in use */
11537 -#ifdef YAFFS_IGNORE_TAGS_ECC
11538 -               {
11539 -                       t->eccResult = YAFFS_ECC_RESULT_NO_ERROR;
11540 -               }
11541 -#else
11542 -               {
11543 -                       yaffs_ECCOther ecc;
11544 -                       int result;
11545 -                       yaffs_ECCCalculateOther((unsigned char *)&pt->t,
11546 -                                               sizeof
11547 -                                               (yaffs_PackedTags2TagsPart),
11548 -                                               &ecc);
11549 -                       result =
11550 -                           yaffs_ECCCorrectOther((unsigned char *)&pt->t,
11551 -                                                 sizeof
11552 -                                                 (yaffs_PackedTags2TagsPart),
11553 -                                                 &pt->ecc, &ecc);
11554 -                       switch(result){
11555 -                               case 0:
11556 -                                       t->eccResult = YAFFS_ECC_RESULT_NO_ERROR;
11557 -                                       break;
11558 -                               case 1:
11559 -                                       t->eccResult = YAFFS_ECC_RESULT_FIXED;
11560 -                                       break;
11561 -                               case -1:
11562 -                                       t->eccResult = YAFFS_ECC_RESULT_UNFIXED;
11563 -                                       break;
11564 -                               default:
11565 -                                       t->eccResult = YAFFS_ECC_RESULT_UNKNOWN;
11566 -                       }
11567 -               }
11568 -#endif
11569 +       if (ptt->sequenceNumber != 0xFFFFFFFF) {
11570                 t->blockBad = 0;
11571                 t->chunkUsed = 1;
11572 -               t->objectId = pt->t.objectId;
11573 -               t->chunkId = pt->t.chunkId;
11574 -               t->byteCount = pt->t.byteCount;
11575 +               t->objectId = ptt->objectId;
11576 +               t->chunkId = ptt->chunkId;
11577 +               t->byteCount = ptt->byteCount;
11578                 t->chunkDeleted = 0;
11579                 t->serialNumber = 0;
11580 -               t->sequenceNumber = pt->t.sequenceNumber;
11581 +               t->sequenceNumber = ptt->sequenceNumber;
11582  
11583                 /* Do extra header info stuff */
11584  
11585 -               if (pt->t.chunkId & EXTRA_HEADER_INFO_FLAG) {
11586 +               if (ptt->chunkId & EXTRA_HEADER_INFO_FLAG) {
11587                         t->chunkId = 0;
11588                         t->byteCount = 0;
11589  
11590                         t->extraHeaderInfoAvailable = 1;
11591                         t->extraParentObjectId =
11592 -                           pt->t.chunkId & (~(ALL_EXTRA_FLAGS));
11593 +                           ptt->chunkId & (~(ALL_EXTRA_FLAGS));
11594                         t->extraIsShrinkHeader =
11595 -                           (pt->t.chunkId & EXTRA_SHRINK_FLAG) ? 1 : 0;
11596 +                           (ptt->chunkId & EXTRA_SHRINK_FLAG) ? 1 : 0;
11597                         t->extraShadows =
11598 -                           (pt->t.chunkId & EXTRA_SHADOWS_FLAG) ? 1 : 0;
11599 +                           (ptt->chunkId & EXTRA_SHADOWS_FLAG) ? 1 : 0;
11600                         t->extraObjectType =
11601 -                           pt->t.objectId >> EXTRA_OBJECT_TYPE_SHIFT;
11602 +                           ptt->objectId >> EXTRA_OBJECT_TYPE_SHIFT;
11603                         t->objectId &= ~EXTRA_OBJECT_TYPE_MASK;
11604  
11605 -                       if (t->extraObjectType == YAFFS_OBJECT_TYPE_HARDLINK) {
11606 -                               t->extraEquivalentObjectId = pt->t.byteCount;
11607 -                       } else {
11608 -                               t->extraFileLength = pt->t.byteCount;
11609 +                       if (t->extraObjectType == YAFFS_OBJECT_TYPE_HARDLINK)
11610 +                               t->extraEquivalentObjectId = ptt->byteCount;
11611 +                       else
11612 +                               t->extraFileLength = ptt->byteCount;
11613 +               }
11614 +       }
11615 +
11616 +       yaffs_DumpPackedTags2TagsPart(ptt);
11617 +       yaffs_DumpTags2(t);
11618 +
11619 +}
11620 +
11621 +
11622 +void yaffs_UnpackTags2(yaffs_ExtendedTags *t, yaffs_PackedTags2 *pt)
11623 +{
11624 +
11625 +       yaffs_ECCResult eccResult = YAFFS_ECC_RESULT_NO_ERROR;
11626 +
11627 +       if (pt->t.sequenceNumber != 0xFFFFFFFF) {
11628 +               /* Page is in use */
11629 +#ifndef YAFFS_IGNORE_TAGS_ECC
11630 +               {
11631 +                       yaffs_ECCOther ecc;
11632 +                       int result;
11633 +                       yaffs_ECCCalculateOther((unsigned char *)&pt->t,
11634 +                                               sizeof
11635 +                                               (yaffs_PackedTags2TagsPart),
11636 +                                               &ecc);
11637 +                       result =
11638 +                           yaffs_ECCCorrectOther((unsigned char *)&pt->t,
11639 +                                                 sizeof
11640 +                                                 (yaffs_PackedTags2TagsPart),
11641 +                                                 &pt->ecc, &ecc);
11642 +                       switch (result) {
11643 +                       case 0:
11644 +                               eccResult = YAFFS_ECC_RESULT_NO_ERROR;
11645 +                               break;
11646 +                       case 1:
11647 +                               eccResult = YAFFS_ECC_RESULT_FIXED;
11648 +                               break;
11649 +                       case -1:
11650 +                               eccResult = YAFFS_ECC_RESULT_UNFIXED;
11651 +                               break;
11652 +                       default:
11653 +                               eccResult = YAFFS_ECC_RESULT_UNKNOWN;
11654                         }
11655                 }
11656 +#endif
11657         }
11658  
11659 +       yaffs_UnpackTags2TagsPart(t, &pt->t);
11660 +
11661 +       t->eccResult = eccResult;
11662 +
11663         yaffs_DumpPackedTags2(pt);
11664         yaffs_DumpTags2(t);
11665  
11666  }
11667 +
11668 --- a/fs/yaffs2/yaffs_packedtags2.h
11669 +++ b/fs/yaffs2/yaffs_packedtags2.h
11670 @@ -33,6 +33,11 @@ typedef struct {
11671         yaffs_ECCOther ecc;
11672  } yaffs_PackedTags2;
11673  
11674 -void yaffs_PackTags2(yaffs_PackedTags2 * pt, const yaffs_ExtendedTags * t);
11675 -void yaffs_UnpackTags2(yaffs_ExtendedTags * t, yaffs_PackedTags2 * pt);
11676 +/* Full packed tags with ECC, used for oob tags */
11677 +void yaffs_PackTags2(yaffs_PackedTags2 *pt, const yaffs_ExtendedTags *t);
11678 +void yaffs_UnpackTags2(yaffs_ExtendedTags *t, yaffs_PackedTags2 *pt);
11679 +
11680 +/* Only the tags part (no ECC for use with inband tags */
11681 +void yaffs_PackTags2TagsPart(yaffs_PackedTags2TagsPart *pt, const yaffs_ExtendedTags *t);
11682 +void yaffs_UnpackTags2TagsPart(yaffs_ExtendedTags *t, yaffs_PackedTags2TagsPart *pt);
11683  #endif
11684 --- a/fs/yaffs2/yaffs_qsort.c
11685 +++ b/fs/yaffs2/yaffs_qsort.c
11686 @@ -28,12 +28,12 @@
11687   */
11688  
11689  #include "yportenv.h"
11690 -//#include <linux/string.h>
11691 +/* #include <linux/string.h> */
11692  
11693  /*
11694   * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
11695   */
11696 -#define swapcode(TYPE, parmi, parmj, n) {              \
11697 +#define swapcode(TYPE, parmi, parmj, n) do {           \
11698         long i = (n) / sizeof (TYPE);                   \
11699         register TYPE *pi = (TYPE *) (parmi);           \
11700         register TYPE *pj = (TYPE *) (parmj);           \
11701 @@ -41,28 +41,29 @@
11702                 register TYPE   t = *pi;                \
11703                 *pi++ = *pj;                            \
11704                 *pj++ = t;                              \
11705 -        } while (--i > 0);                             \
11706 -}
11707 +       } while (--i > 0);                              \
11708 +} while (0)
11709  
11710  #define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \
11711 -       es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;
11712 +       es % sizeof(long) ? 2 : es == sizeof(long) ? 0 : 1;
11713  
11714  static __inline void
11715  swapfunc(char *a, char *b, int n, int swaptype)
11716  {
11717         if (swaptype <= 1)
11718 -               swapcode(long, a, b, n)
11719 +               swapcode(long, a, b, n);
11720         else
11721 -               swapcode(char, a, b, n)
11722 +               swapcode(char, a, b, n);
11723  }
11724  
11725 -#define swap(a, b)                                     \
11726 +#define yswap(a, b) do {                                       \
11727         if (swaptype == 0) {                            \
11728                 long t = *(long *)(a);                  \
11729                 *(long *)(a) = *(long *)(b);            \
11730                 *(long *)(b) = t;                       \
11731         } else                                          \
11732 -               swapfunc(a, b, es, swaptype)
11733 +               swapfunc(a, b, es, swaptype);           \
11734 +} while (0)
11735  
11736  #define vecswap(a, b, n)       if ((n) > 0) swapfunc(a, b, n, swaptype)
11737  
11738 @@ -70,12 +71,12 @@ static __inline char *
11739  med3(char *a, char *b, char *c, int (*cmp)(const void *, const void *))
11740  {
11741         return cmp(a, b) < 0 ?
11742 -              (cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a ))
11743 -              :(cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c ));
11744 +               (cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a))
11745 +               : (cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c));
11746  }
11747  
11748  #ifndef min
11749 -#define min(a,b) (((a) < (b)) ? (a) : (b))
11750 +#define min(a, b) (((a) < (b)) ? (a) : (b))
11751  #endif
11752  
11753  void
11754 @@ -92,7 +93,7 @@ loop: SWAPINIT(a, es);
11755                 for (pm = (char *)a + es; pm < (char *) a + n * es; pm += es)
11756                         for (pl = pm; pl > (char *) a && cmp(pl - es, pl) > 0;
11757                              pl -= es)
11758 -                               swap(pl, pl - es);
11759 +                               yswap(pl, pl - es);
11760                 return;
11761         }
11762         pm = (char *)a + (n / 2) * es;
11763 @@ -107,7 +108,7 @@ loop:       SWAPINIT(a, es);
11764                 }
11765                 pm = med3(pl, pm, pn, cmp);
11766         }
11767 -       swap(a, pm);
11768 +       yswap(a, pm);
11769         pa = pb = (char *)a + es;
11770  
11771         pc = pd = (char *)a + (n - 1) * es;
11772 @@ -115,7 +116,7 @@ loop:       SWAPINIT(a, es);
11773                 while (pb <= pc && (r = cmp(pb, a)) <= 0) {
11774                         if (r == 0) {
11775                                 swap_cnt = 1;
11776 -                               swap(pa, pb);
11777 +                               yswap(pa, pb);
11778                                 pa += es;
11779                         }
11780                         pb += es;
11781 @@ -123,14 +124,14 @@ loop:     SWAPINIT(a, es);
11782                 while (pb <= pc && (r = cmp(pc, a)) >= 0) {
11783                         if (r == 0) {
11784                                 swap_cnt = 1;
11785 -                               swap(pc, pd);
11786 +                               yswap(pc, pd);
11787                                 pd -= es;
11788                         }
11789                         pc -= es;
11790                 }
11791                 if (pb > pc)
11792                         break;
11793 -               swap(pb, pc);
11794 +               yswap(pb, pc);
11795                 swap_cnt = 1;
11796                 pb += es;
11797                 pc -= es;
11798 @@ -139,7 +140,7 @@ loop:       SWAPINIT(a, es);
11799                 for (pm = (char *) a + es; pm < (char *) a + n * es; pm += es)
11800                         for (pl = pm; pl > (char *) a && cmp(pl - es, pl) > 0;
11801                              pl -= es)
11802 -                               swap(pl, pl - es);
11803 +                               yswap(pl, pl - es);
11804                 return;
11805         }
11806  
11807 @@ -148,9 +149,11 @@ loop:      SWAPINIT(a, es);
11808         vecswap(a, pb - r, r);
11809         r = min((long)(pd - pc), (long)(pn - pd - es));
11810         vecswap(pb, pn - r, r);
11811 -       if ((r = pb - pa) > es)
11812 +       r = pb - pa;
11813 +       if (r > es)
11814                 yaffs_qsort(a, r / es, es, cmp);
11815 -       if ((r = pd - pc) > es) {
11816 +       r = pd - pc;
11817 +       if (r > es) {
11818                 /* Iterate rather than recurse to save stack space */
11819                 a = pn - r;
11820                 n = r / es;
11821 --- a/fs/yaffs2/yaffs_qsort.h
11822 +++ b/fs/yaffs2/yaffs_qsort.h
11823 @@ -17,7 +17,7 @@
11824  #ifndef __YAFFS_QSORT_H__
11825  #define __YAFFS_QSORT_H__
11826  
11827 -extern void yaffs_qsort (void *const base, size_t total_elems, size_t size,
11828 -                   int (*cmp)(const void *, const void *));
11829 +extern void yaffs_qsort(void *const base, size_t total_elems, size_t size,
11830 +                       int (*cmp)(const void *, const void *));
11831  
11832  #endif
11833 --- a/fs/yaffs2/yaffs_tagscompat.c
11834 +++ b/fs/yaffs2/yaffs_tagscompat.c
11835 @@ -14,16 +14,17 @@
11836  #include "yaffs_guts.h"
11837  #include "yaffs_tagscompat.h"
11838  #include "yaffs_ecc.h"
11839 +#include "yaffs_getblockinfo.h"
11840  
11841 -static void yaffs_HandleReadDataError(yaffs_Device * dev, int chunkInNAND);
11842 +static void yaffs_HandleReadDataError(yaffs_Device *dev, int chunkInNAND);
11843  #ifdef NOTYET
11844 -static void yaffs_CheckWrittenBlock(yaffs_Device * dev, int chunkInNAND);
11845 -static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
11846 -                                    const __u8 * data,
11847 -                                    const yaffs_Spare * spare);
11848 -static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
11849 -                                   const yaffs_Spare * spare);
11850 -static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND);
11851 +static void yaffs_CheckWrittenBlock(yaffs_Device *dev, int chunkInNAND);
11852 +static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
11853 +                                    const __u8 *data,
11854 +                                    const yaffs_Spare *spare);
11855 +static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
11856 +                                   const yaffs_Spare *spare);
11857 +static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND);
11858  #endif
11859  
11860  static const char yaffs_countBitsTable[256] = {
11861 @@ -54,13 +55,13 @@ int yaffs_CountBits(__u8 x)
11862  
11863  /********** Tags ECC calculations  *********/
11864  
11865 -void yaffs_CalcECC(const __u8 * data, yaffs_Spare * spare)
11866 +void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
11867  {
11868         yaffs_ECCCalculate(data, spare->ecc1);
11869         yaffs_ECCCalculate(&data[256], spare->ecc2);
11870  }
11871  
11872 -void yaffs_CalcTagsECC(yaffs_Tags * tags)
11873 +void yaffs_CalcTagsECC(yaffs_Tags *tags)
11874  {
11875         /* Calculate an ecc */
11876  
11877 @@ -74,9 +75,8 @@ void yaffs_CalcTagsECC(yaffs_Tags * tags
11878         for (i = 0; i < 8; i++) {
11879                 for (j = 1; j & 0xff; j <<= 1) {
11880                         bit++;
11881 -                       if (b[i] & j) {
11882 +                       if (b[i] & j)
11883                                 ecc ^= bit;
11884 -                       }
11885                 }
11886         }
11887  
11888 @@ -84,7 +84,7 @@ void yaffs_CalcTagsECC(yaffs_Tags * tags
11889  
11890  }
11891  
11892 -int yaffs_CheckECCOnTags(yaffs_Tags * tags)
11893 +int yaffs_CheckECCOnTags(yaffs_Tags *tags)
11894  {
11895         unsigned ecc = tags->ecc;
11896  
11897 @@ -115,8 +115,8 @@ int yaffs_CheckECCOnTags(yaffs_Tags * ta
11898  
11899  /********** Tags **********/
11900  
11901 -static void yaffs_LoadTagsIntoSpare(yaffs_Spare * sparePtr,
11902 -                                   yaffs_Tags * tagsPtr)
11903 +static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr,
11904 +                               yaffs_Tags *tagsPtr)
11905  {
11906         yaffs_TagsUnion *tu = (yaffs_TagsUnion *) tagsPtr;
11907  
11908 @@ -132,8 +132,8 @@ static void yaffs_LoadTagsIntoSpare(yaff
11909         sparePtr->tagByte7 = tu->asBytes[7];
11910  }
11911  
11912 -static void yaffs_GetTagsFromSpare(yaffs_Device * dev, yaffs_Spare * sparePtr,
11913 -                                  yaffs_Tags * tagsPtr)
11914 +static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,
11915 +                               yaffs_Tags *tagsPtr)
11916  {
11917         yaffs_TagsUnion *tu = (yaffs_TagsUnion *) tagsPtr;
11918         int result;
11919 @@ -148,21 +148,20 @@ static void yaffs_GetTagsFromSpare(yaffs
11920         tu->asBytes[7] = sparePtr->tagByte7;
11921  
11922         result = yaffs_CheckECCOnTags(tagsPtr);
11923 -       if (result > 0) {
11924 +       if (result > 0)
11925                 dev->tagsEccFixed++;
11926 -       } else if (result < 0) {
11927 +       else if (result < 0)
11928                 dev->tagsEccUnfixed++;
11929 -       }
11930  }
11931  
11932 -static void yaffs_SpareInitialise(yaffs_Spare * spare)
11933 +static void yaffs_SpareInitialise(yaffs_Spare *spare)
11934  {
11935         memset(spare, 0xFF, sizeof(yaffs_Spare));
11936  }
11937  
11938  static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,
11939 -                                 int chunkInNAND, const __u8 * data,
11940 -                                 yaffs_Spare * spare)
11941 +                               int chunkInNAND, const __u8 *data,
11942 +                               yaffs_Spare *spare)
11943  {
11944         if (chunkInNAND < dev->startBlock * dev->nChunksPerBlock) {
11945                 T(YAFFS_TRACE_ERROR,
11946 @@ -177,9 +176,9 @@ static int yaffs_WriteChunkToNAND(struct
11947  
11948  static int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,
11949                                    int chunkInNAND,
11950 -                                  __u8 * data,
11951 -                                  yaffs_Spare * spare,
11952 -                                  yaffs_ECCResult * eccResult,
11953 +                                  __u8 *data,
11954 +                                  yaffs_Spare *spare,
11955 +                                  yaffs_ECCResult *eccResult,
11956                                    int doErrorCorrection)
11957  {
11958         int retVal;
11959 @@ -252,9 +251,11 @@ static int yaffs_ReadChunkFromNAND(struc
11960                 /* Must allocate enough memory for spare+2*sizeof(int) */
11961                 /* for ecc results from device. */
11962                 struct yaffs_NANDSpare nspare;
11963 -               retVal =
11964 -                   dev->readChunkFromNAND(dev, chunkInNAND, data,
11965 -                                          (yaffs_Spare *) & nspare);
11966 +
11967 +               memset(&nspare, 0, sizeof(nspare));
11968 +
11969 +               retVal = dev->readChunkFromNAND(dev, chunkInNAND, data,
11970 +                                       (yaffs_Spare *) &nspare);
11971                 memcpy(spare, &nspare, sizeof(yaffs_Spare));
11972                 if (data && doErrorCorrection) {
11973                         if (nspare.eccres1 > 0) {
11974 @@ -302,8 +303,7 @@ static int yaffs_ReadChunkFromNAND(struc
11975  static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
11976                                   int chunkInNAND)
11977  {
11978 -
11979 -       static int init = 0;
11980 +       static int init;
11981         static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK];
11982         static __u8 data[YAFFS_BYTES_PER_CHUNK];
11983         /* Might as well always allocate the larger size for */
11984 @@ -331,12 +331,12 @@ static int yaffs_CheckChunkErased(struct
11985   * Functions for robustisizing
11986   */
11987  
11988 -static void yaffs_HandleReadDataError(yaffs_Device * dev, int chunkInNAND)
11989 +static void yaffs_HandleReadDataError(yaffs_Device *dev, int chunkInNAND)
11990  {
11991         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
11992  
11993         /* Mark the block for retirement */
11994 -       yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1;
11995 +       yaffs_GetBlockInfo(dev, blockInNAND + dev->blockOffset)->needsRetiring = 1;
11996         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
11997           (TSTR("**>>Block %d marked for retirement" TENDSTR), blockInNAND));
11998  
11999 @@ -348,22 +348,22 @@ static void yaffs_HandleReadDataError(ya
12000  }
12001  
12002  #ifdef NOTYET
12003 -static void yaffs_CheckWrittenBlock(yaffs_Device * dev, int chunkInNAND)
12004 +static void yaffs_CheckWrittenBlock(yaffs_Device *dev, int chunkInNAND)
12005  {
12006  }
12007  
12008 -static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
12009 -                                    const __u8 * data,
12010 -                                    const yaffs_Spare * spare)
12011 +static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
12012 +                                    const __u8 *data,
12013 +                                    const yaffs_Spare *spare)
12014  {
12015  }
12016  
12017 -static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
12018 -                                   const yaffs_Spare * spare)
12019 +static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
12020 +                                   const yaffs_Spare *spare)
12021  {
12022  }
12023  
12024 -static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND)
12025 +static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND)
12026  {
12027         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
12028  
12029 @@ -373,8 +373,8 @@ static void yaffs_HandleWriteChunkError(
12030         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
12031  }
12032  
12033 -static int yaffs_VerifyCompare(const __u8 * d0, const __u8 * d1,
12034 -                              const yaffs_Spare * s0, const yaffs_Spare * s1)
12035 +static int yaffs_VerifyCompare(const __u8 *d0, const __u8 *d1,
12036 +                              const yaffs_Spare *s0, const yaffs_Spare *s1)
12037  {
12038  
12039         if (memcmp(d0, d1, YAFFS_BYTES_PER_CHUNK) != 0 ||
12040 @@ -398,28 +398,35 @@ static int yaffs_VerifyCompare(const __u
12041  }
12042  #endif                         /* NOTYET */
12043  
12044 -int yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(yaffs_Device * dev,
12045 -                                                   int chunkInNAND,
12046 -                                                   const __u8 * data,
12047 -                                                   const yaffs_ExtendedTags *
12048 -                                                   eTags)
12049 +int yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(yaffs_Device *dev,
12050 +                                               int chunkInNAND,
12051 +                                               const __u8 *data,
12052 +                                               const yaffs_ExtendedTags *eTags)
12053  {
12054         yaffs_Spare spare;
12055         yaffs_Tags tags;
12056  
12057         yaffs_SpareInitialise(&spare);
12058  
12059 -       if (eTags->chunkDeleted) {
12060 +       if (eTags->chunkDeleted)
12061                 spare.pageStatus = 0;
12062 -       } else {
12063 +       else {
12064                 tags.objectId = eTags->objectId;
12065                 tags.chunkId = eTags->chunkId;
12066 -               tags.byteCount = eTags->byteCount;
12067 +
12068 +               tags.byteCountLSB = eTags->byteCount & 0x3ff;
12069 +
12070 +               if (dev->nDataBytesPerChunk >= 1024)
12071 +                       tags.byteCountMSB = (eTags->byteCount >> 10) & 3;
12072 +               else
12073 +                       tags.byteCountMSB = 3;
12074 +
12075 +
12076                 tags.serialNumber = eTags->serialNumber;
12077  
12078 -               if (!dev->useNANDECC && data) {
12079 +               if (!dev->useNANDECC && data)
12080                         yaffs_CalcECC(data, &spare);
12081 -               }
12082 +
12083                 yaffs_LoadTagsIntoSpare(&spare, &tags);
12084  
12085         }
12086 @@ -427,15 +434,15 @@ int yaffs_TagsCompatabilityWriteChunkWit
12087         return yaffs_WriteChunkToNAND(dev, chunkInNAND, data, &spare);
12088  }
12089  
12090 -int yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(yaffs_Device * dev,
12091 +int yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(yaffs_Device *dev,
12092                                                      int chunkInNAND,
12093 -                                                    __u8 * data,
12094 -                                                    yaffs_ExtendedTags * eTags)
12095 +                                                    __u8 *data,
12096 +                                                    yaffs_ExtendedTags *eTags)
12097  {
12098  
12099         yaffs_Spare spare;
12100         yaffs_Tags tags;
12101 -       yaffs_ECCResult eccResult;
12102 +       yaffs_ECCResult eccResult = YAFFS_ECC_RESULT_UNKNOWN;
12103  
12104         static yaffs_Spare spareFF;
12105         static int init;
12106 @@ -466,7 +473,11 @@ int yaffs_TagsCompatabilityReadChunkWith
12107  
12108                                 eTags->objectId = tags.objectId;
12109                                 eTags->chunkId = tags.chunkId;
12110 -                               eTags->byteCount = tags.byteCount;
12111 +                               eTags->byteCount = tags.byteCountLSB;
12112 +
12113 +                               if (dev->nDataBytesPerChunk >= 1024)
12114 +                                       eTags->byteCount |= (((unsigned) tags.byteCountMSB) << 10);
12115 +
12116                                 eTags->serialNumber = tags.serialNumber;
12117                         }
12118                 }
12119 @@ -497,9 +508,9 @@ int yaffs_TagsCompatabilityMarkNANDBlock
12120  }
12121  
12122  int yaffs_TagsCompatabilityQueryNANDBlock(struct yaffs_DeviceStruct *dev,
12123 -                                         int blockNo, yaffs_BlockState *
12124 -                                         state,
12125 -                                         int *sequenceNumber)
12126 +                                         int blockNo,
12127 +                                         yaffs_BlockState *state,
12128 +                                         __u32 *sequenceNumber)
12129  {
12130  
12131         yaffs_Spare spare0, spare1;
12132 --- a/fs/yaffs2/yaffs_tagscompat.h
12133 +++ b/fs/yaffs2/yaffs_tagscompat.h
12134 @@ -17,24 +17,23 @@
12135  #define __YAFFS_TAGSCOMPAT_H__
12136  
12137  #include "yaffs_guts.h"
12138 -int yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(yaffs_Device * dev,
12139 -                                                   int chunkInNAND,
12140 -                                                   const __u8 * data,
12141 -                                                   const yaffs_ExtendedTags *
12142 -                                                   tags);
12143 -int yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(yaffs_Device * dev,
12144 -                                                    int chunkInNAND,
12145 -                                                    __u8 * data,
12146 -                                                    yaffs_ExtendedTags *
12147 -                                                    tags);
12148 +int yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(yaffs_Device *dev,
12149 +                                               int chunkInNAND,
12150 +                                               const __u8 *data,
12151 +                                               const yaffs_ExtendedTags *tags);
12152 +int yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(yaffs_Device *dev,
12153 +                                               int chunkInNAND,
12154 +                                               __u8 *data,
12155 +                                               yaffs_ExtendedTags *tags);
12156  int yaffs_TagsCompatabilityMarkNANDBlockBad(struct yaffs_DeviceStruct *dev,
12157                                             int blockNo);
12158  int yaffs_TagsCompatabilityQueryNANDBlock(struct yaffs_DeviceStruct *dev,
12159 -                                         int blockNo, yaffs_BlockState *
12160 -                                         state, int *sequenceNumber);
12161 +                                         int blockNo,
12162 +                                         yaffs_BlockState *state,
12163 +                                         __u32 *sequenceNumber);
12164  
12165 -void yaffs_CalcTagsECC(yaffs_Tags * tags);
12166 -int yaffs_CheckECCOnTags(yaffs_Tags * tags);
12167 +void yaffs_CalcTagsECC(yaffs_Tags *tags);
12168 +int yaffs_CheckECCOnTags(yaffs_Tags *tags);
12169  int yaffs_CountBits(__u8 byte);
12170  
12171  #endif
12172 --- a/fs/yaffs2/yaffs_tagsvalidity.c
12173 +++ b/fs/yaffs2/yaffs_tagsvalidity.c
12174 @@ -13,14 +13,14 @@
12175  
12176  #include "yaffs_tagsvalidity.h"
12177  
12178 -void yaffs_InitialiseTags(yaffs_ExtendedTags * tags)
12179 +void yaffs_InitialiseTags(yaffs_ExtendedTags *tags)
12180  {
12181         memset(tags, 0, sizeof(yaffs_ExtendedTags));
12182         tags->validMarker0 = 0xAAAAAAAA;
12183         tags->validMarker1 = 0x55555555;
12184  }
12185  
12186 -int yaffs_ValidateTags(yaffs_ExtendedTags * tags)
12187 +int yaffs_ValidateTags(yaffs_ExtendedTags *tags)
12188  {
12189         return (tags->validMarker0 == 0xAAAAAAAA &&
12190                 tags->validMarker1 == 0x55555555);
12191 --- a/fs/yaffs2/yaffs_tagsvalidity.h
12192 +++ b/fs/yaffs2/yaffs_tagsvalidity.h
12193 @@ -19,6 +19,6 @@
12194  
12195  #include "yaffs_guts.h"
12196  
12197 -void yaffs_InitialiseTags(yaffs_ExtendedTags * tags);
12198 -int yaffs_ValidateTags(yaffs_ExtendedTags * tags);
12199 +void yaffs_InitialiseTags(yaffs_ExtendedTags *tags);
12200 +int yaffs_ValidateTags(yaffs_ExtendedTags *tags);
12201  #endif
12202 --- a/fs/yaffs2/yportenv.h
12203 +++ b/fs/yaffs2/yportenv.h
12204 @@ -17,17 +17,28 @@
12205  #ifndef __YPORTENV_H__
12206  #define __YPORTENV_H__
12207  
12208 +/*
12209 + * Define the MTD version in terms of Linux Kernel versions
12210 + * This allows yaffs to be used independantly of the kernel
12211 + * as well as with it.
12212 + */
12213 +
12214 +#define MTD_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + (c))
12215 +
12216  #if defined CONFIG_YAFFS_WINCE
12217  
12218  #include "ywinceenv.h"
12219  
12220 -#elif  defined __KERNEL__
12221 +#elif defined __KERNEL__
12222  
12223  #include "moduleconfig.h"
12224  
12225  /* Linux kernel */
12226 +
12227  #include <linux/version.h>
12228 -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19))
12229 +#define MTD_VERSION_CODE LINUX_VERSION_CODE
12230 +
12231 +#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 19))
12232  #include <linux/config.h>
12233  #endif
12234  #include <linux/kernel.h>
12235 @@ -40,12 +51,13 @@
12236  #define YCHAR char
12237  #define YUCHAR unsigned char
12238  #define _Y(x)     x
12239 -#define yaffs_strcpy(a,b)    strcpy(a,b)
12240 -#define yaffs_strncpy(a,b,c) strncpy(a,b,c)
12241 -#define yaffs_strncmp(a,b,c) strncmp(a,b,c)
12242 -#define yaffs_strlen(s)             strlen(s)
12243 -#define yaffs_sprintf       sprintf
12244 -#define yaffs_toupper(a)     toupper(a)
12245 +#define yaffs_strcat(a, b)     strcat(a, b)
12246 +#define yaffs_strcpy(a, b)     strcpy(a, b)
12247 +#define yaffs_strncpy(a, b, c) strncpy(a, b, c)
12248 +#define yaffs_strncmp(a, b, c) strncmp(a, b, c)
12249 +#define yaffs_strlen(s)               strlen(s)
12250 +#define yaffs_sprintf         sprintf
12251 +#define yaffs_toupper(a)       toupper(a)
12252  
12253  #define Y_INLINE inline
12254  
12255 @@ -53,19 +65,19 @@
12256  #define YAFFS_LOSTNFOUND_PREFIX                "obj"
12257  
12258  /* #define YPRINTF(x) printk x */
12259 -#define YMALLOC(x) kmalloc(x,GFP_KERNEL)
12260 +#define YMALLOC(x) kmalloc(x, GFP_NOFS)
12261  #define YFREE(x)   kfree(x)
12262  #define YMALLOC_ALT(x) vmalloc(x)
12263  #define YFREE_ALT(x)   vfree(x)
12264  #define YMALLOC_DMA(x) YMALLOC(x)
12265  
12266 -// KR - added for use in scan so processes aren't blocked indefinitely.
12267 +/* KR - added for use in scan so processes aren't blocked indefinitely. */
12268  #define YYIELD() schedule()
12269  
12270  #define YAFFS_ROOT_MODE                        0666
12271  #define YAFFS_LOSTNFOUND_MODE          0666
12272  
12273 -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
12274 +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
12275  #define Y_CURRENT_TIME CURRENT_TIME.tv_sec
12276  #define Y_TIME_CONVERT(x) (x).tv_sec
12277  #else
12278 @@ -73,11 +85,12 @@
12279  #define Y_TIME_CONVERT(x) (x)
12280  #endif
12281  
12282 -#define yaffs_SumCompare(x,y) ((x) == (y))
12283 -#define yaffs_strcmp(a,b) strcmp(a,b)
12284 +#define yaffs_SumCompare(x, y) ((x) == (y))
12285 +#define yaffs_strcmp(a, b) strcmp(a, b)
12286  
12287  #define TENDSTR "\n"
12288  #define TSTR(x) KERN_WARNING x
12289 +#define TCONT(x) x
12290  #define TOUT(p) printk p
12291  
12292  #define yaffs_trace(mask, fmt, args...) \
12293 @@ -90,6 +103,8 @@
12294  
12295  #elif defined CONFIG_YAFFS_DIRECT
12296  
12297 +#define MTD_VERSION_CODE MTD_VERSION(2, 6, 22)
12298 +
12299  /* Direct interface */
12300  #include "ydirectenv.h"
12301  
12302 @@ -111,11 +126,12 @@
12303  #define YCHAR char
12304  #define YUCHAR unsigned char
12305  #define _Y(x)     x
12306 -#define yaffs_strcpy(a,b)    strcpy(a,b)
12307 -#define yaffs_strncpy(a,b,c) strncpy(a,b,c)
12308 -#define yaffs_strlen(s)             strlen(s)
12309 -#define yaffs_sprintf       sprintf
12310 -#define yaffs_toupper(a)     toupper(a)
12311 +#define yaffs_strcat(a, b)     strcat(a, b)
12312 +#define yaffs_strcpy(a, b)     strcpy(a, b)
12313 +#define yaffs_strncpy(a, b, c) strncpy(a, b, c)
12314 +#define yaffs_strlen(s)               strlen(s)
12315 +#define yaffs_sprintf         sprintf
12316 +#define yaffs_toupper(a)       toupper(a)
12317  
12318  #define Y_INLINE inline
12319  
12320 @@ -133,8 +149,8 @@
12321  #define YAFFS_ROOT_MODE                                0666
12322  #define YAFFS_LOSTNFOUND_MODE          0666
12323  
12324 -#define yaffs_SumCompare(x,y) ((x) == (y))
12325 -#define yaffs_strcmp(a,b) strcmp(a,b)
12326 +#define yaffs_SumCompare(x, y) ((x) == (y))
12327 +#define yaffs_strcmp(a, b) strcmp(a, b)
12328  
12329  #else
12330  /* Should have specified a configuration type */
12331 @@ -178,10 +194,10 @@ extern unsigned int yaffs_wr_attempts;
12332  #define YAFFS_TRACE_ALWAYS             0xF0000000
12333  
12334  
12335 -#define T(mask,p) do{ if((mask) & (yaffs_traceMask | YAFFS_TRACE_ALWAYS)) TOUT(p);} while(0)
12336 +#define T(mask, p) do { if ((mask) & (yaffs_traceMask | YAFFS_TRACE_ALWAYS)) TOUT(p); } while (0)
12337  
12338 -#ifndef CONFIG_YAFFS_WINCE
12339 -#define YBUG() T(YAFFS_TRACE_BUG,(TSTR("==>> yaffs bug: " __FILE__ " %d" TENDSTR),__LINE__))
12340 +#ifndef YBUG
12341 +#define YBUG() do {T(YAFFS_TRACE_BUG, (TSTR("==>> yaffs bug: " __FILE__ " %d" TENDSTR), __LINE__)); } while (0)
12342  #endif
12343  
12344  #endif