Merge git://git.kernel.org/pub/scm/linux/kernel/git/brodo/pcmcia-2.6/
[safe/jmp/linux-2.6] / fs / jffs / intrep.c
1 /*
2  * JFFS -- Journaling Flash File System, Linux implementation.
3  *
4  * Copyright (C) 1999, 2000  Axis Communications, Inc.
5  *
6  * Created by Finn Hakansson <finn@axis.com>.
7  *
8  * This is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * $Id: intrep.c,v 1.102 2001/09/23 23:28:36 dwmw2 Exp $
14  *
15  * Ported to Linux 2.3.x and MTD:
16  * Copyright (C) 2000  Alexander Larsson (alex@cendio.se), Cendio Systems AB
17  *
18  */
19
20 /* This file contains the code for the internal structure of the
21    Journaling Flash File System, JFFS.  */
22
23 /*
24  * Todo list:
25  *
26  * memcpy_to_flash() and memcpy_from_flash() functions.
27  *
28  * Implementation of hard links.
29  *
30  * Organize the source code in a better way. Against the VFS we could
31  * have jffs_ext.c, and against the block device jffs_int.c.
32  * A better file-internal organization too.
33  *
34  * A better checksum algorithm.
35  *
36  * Consider endianness stuff. ntohl() etc.
37  *
38  * Are we handling the atime, mtime, ctime members of the inode right?
39  *
40  * Remove some duplicated code. Take a look at jffs_write_node() and
41  * jffs_rewrite_data() for instance.
42  *
43  * Implement more meaning of the nlink member in various data structures.
44  * nlink could be used in conjunction with hard links for instance.
45  *
46  * Better memory management. Allocate data structures in larger chunks
47  * if possible.
48  *
49  * If too much meta data is stored, a garbage collect should be issued.
50  * We have experienced problems with too much meta data with for instance
51  * log files.
52  *
53  * Improve the calls to jffs_ioctl(). We would like to retrieve more
54  * information to be able to debug (or to supervise) JFFS during run-time.
55  *
56  */
57
58 #include <linux/config.h>
59 #include <linux/types.h>
60 #include <linux/slab.h>
61 #include <linux/jffs.h>
62 #include <linux/fs.h>
63 #include <linux/stat.h>
64 #include <linux/pagemap.h>
65 #include <linux/mutex.h>
66 #include <asm/byteorder.h>
67 #include <linux/smp_lock.h>
68 #include <linux/time.h>
69 #include <linux/ctype.h>
70
71 #include "intrep.h"
72 #include "jffs_fm.h"
73
74 long no_jffs_node = 0;
75 static long no_jffs_file = 0;
76 #if defined(JFFS_MEMORY_DEBUG) && JFFS_MEMORY_DEBUG
77 long no_jffs_control = 0;
78 long no_jffs_raw_inode = 0;
79 long no_jffs_node_ref = 0;
80 long no_jffs_fm = 0;
81 long no_jffs_fmcontrol = 0;
82 long no_hash = 0;
83 long no_name = 0;
84 #endif
85
86 static int jffs_scan_flash(struct jffs_control *c);
87 static int jffs_update_file(struct jffs_file *f, struct jffs_node *node);
88 static int jffs_build_file(struct jffs_file *f);
89 static int jffs_free_file(struct jffs_file *f);
90 static int jffs_free_node_list(struct jffs_file *f);
91 static int jffs_garbage_collect_now(struct jffs_control *c);
92 static int jffs_insert_file_into_hash(struct jffs_file *f);
93 static int jffs_remove_redundant_nodes(struct jffs_file *f);
94
95 /* Is there enough space on the flash?  */
96 static inline int JFFS_ENOUGH_SPACE(struct jffs_control *c, __u32 space)
97 {
98         struct jffs_fmcontrol *fmc = c->fmc;
99
100         while (1) {
101                 if ((fmc->flash_size - (fmc->used_size + fmc->dirty_size))
102                         >= fmc->min_free_size + space) {
103                         return 1;
104                 }
105                 if (fmc->dirty_size < fmc->sector_size)
106                         return 0;
107
108                 if (jffs_garbage_collect_now(c)) {
109                   D1(printk("JFFS_ENOUGH_SPACE: jffs_garbage_collect_now() failed.\n"));
110                   return 0;
111                 }
112         }
113 }
114
115 #if CONFIG_JFFS_FS_VERBOSE > 0
116 static __u8
117 flash_read_u8(struct mtd_info *mtd, loff_t from)
118 {
119         size_t retlen;
120         __u8 ret;
121         int res;
122
123         res = MTD_READ(mtd, from, 1, &retlen, &ret);
124         if (retlen != 1) {
125                 printk("Didn't read a byte in flash_read_u8(). Returned %d\n", res);
126                 return 0;
127         }
128
129         return ret;
130 }
131
132 static void
133 jffs_hexdump(struct mtd_info *mtd, loff_t pos, int size)
134 {
135         char line[16];
136         int j = 0;
137
138         while (size > 0) {
139                 int i;
140
141                 printk("%ld:", (long) pos);
142                 for (j = 0; j < 16; j++) {
143                         line[j] = flash_read_u8(mtd, pos++);
144                 }
145                 for (i = 0; i < j; i++) {
146                         if (!(i & 1)) {
147                                 printk(" %.2x", line[i] & 0xff);
148                         }
149                         else {
150                                 printk("%.2x", line[i] & 0xff);
151                         }
152                 }
153
154                 /* Print empty space */
155                 for (; i < 16; i++) {
156                         if (!(i & 1)) {
157                                 printk("   ");
158                         }
159                         else {
160                                 printk("  ");
161                         }
162                 }
163                 printk("  ");
164
165                 for (i = 0; i < j; i++) {
166                         if (isgraph(line[i])) {
167                                 printk("%c", line[i]);
168                         }
169                         else {
170                                 printk(".");
171                         }
172                 }
173                 printk("\n");
174                 size -= 16;
175         }
176 }
177
178 /* Print the contents of a node.  */
179 static void
180 jffs_print_node(struct jffs_node *n)
181 {
182         D(printk("jffs_node: 0x%p\n", n));
183         D(printk("{\n"));
184         D(printk("        0x%08x, /* version  */\n", n->version));
185         D(printk("        0x%08x, /* data_offset  */\n", n->data_offset));
186         D(printk("        0x%08x, /* data_size  */\n", n->data_size));
187         D(printk("        0x%08x, /* removed_size  */\n", n->removed_size));
188         D(printk("        0x%08x, /* fm_offset  */\n", n->fm_offset));
189         D(printk("        0x%02x,       /* name_size  */\n", n->name_size));
190         D(printk("        0x%p, /* fm,  fm->offset: %u  */\n",
191                  n->fm, (n->fm ? n->fm->offset : 0)));
192         D(printk("        0x%p, /* version_prev  */\n", n->version_prev));
193         D(printk("        0x%p, /* version_next  */\n", n->version_next));
194         D(printk("        0x%p, /* range_prev  */\n", n->range_prev));
195         D(printk("        0x%p, /* range_next  */\n", n->range_next));
196         D(printk("}\n"));
197 }
198
199 #endif
200
201 /* Print the contents of a raw inode.  */
202 static void
203 jffs_print_raw_inode(struct jffs_raw_inode *raw_inode)
204 {
205         D(printk("jffs_raw_inode: inode number: %u\n", raw_inode->ino));
206         D(printk("{\n"));
207         D(printk("        0x%08x, /* magic  */\n", raw_inode->magic));
208         D(printk("        0x%08x, /* ino  */\n", raw_inode->ino));
209         D(printk("        0x%08x, /* pino  */\n", raw_inode->pino));
210         D(printk("        0x%08x, /* version  */\n", raw_inode->version));
211         D(printk("        0x%08x, /* mode  */\n", raw_inode->mode));
212         D(printk("        0x%04x,     /* uid  */\n", raw_inode->uid));
213         D(printk("        0x%04x,     /* gid  */\n", raw_inode->gid));
214         D(printk("        0x%08x, /* atime  */\n", raw_inode->atime));
215         D(printk("        0x%08x, /* mtime  */\n", raw_inode->mtime));
216         D(printk("        0x%08x, /* ctime  */\n", raw_inode->ctime));
217         D(printk("        0x%08x, /* offset  */\n", raw_inode->offset));
218         D(printk("        0x%08x, /* dsize  */\n", raw_inode->dsize));
219         D(printk("        0x%08x, /* rsize  */\n", raw_inode->rsize));
220         D(printk("        0x%02x,       /* nsize  */\n", raw_inode->nsize));
221         D(printk("        0x%02x,       /* nlink  */\n", raw_inode->nlink));
222         D(printk("        0x%02x,       /* spare  */\n",
223                  raw_inode->spare));
224         D(printk("        %u,          /* rename  */\n",
225                  raw_inode->rename));
226         D(printk("        %u,          /* deleted  */\n",
227                  raw_inode->deleted));
228         D(printk("        0x%02x,       /* accurate  */\n",
229                  raw_inode->accurate));
230         D(printk("        0x%08x, /* dchksum  */\n", raw_inode->dchksum));
231         D(printk("        0x%04x,     /* nchksum  */\n", raw_inode->nchksum));
232         D(printk("        0x%04x,     /* chksum  */\n", raw_inode->chksum));
233         D(printk("}\n"));
234 }
235
236 #define flash_safe_acquire(arg)
237 #define flash_safe_release(arg)
238
239
240 static int
241 flash_safe_read(struct mtd_info *mtd, loff_t from,
242                 u_char *buf, size_t count)
243 {
244         size_t retlen;
245         int res;
246
247         D3(printk(KERN_NOTICE "flash_safe_read(%p, %08x, %p, %08x)\n",
248                   mtd, (unsigned int) from, buf, count));
249
250         res = mtd->read(mtd, from, count, &retlen, buf);
251         if (retlen != count) {
252                 panic("Didn't read all bytes in flash_safe_read(). Returned %d\n", res);
253         }
254         return res?res:retlen;
255 }
256
257
258 static __u32
259 flash_read_u32(struct mtd_info *mtd, loff_t from)
260 {
261         size_t retlen;
262         __u32 ret;
263         int res;
264
265         res = mtd->read(mtd, from, 4, &retlen, (unsigned char *)&ret);
266         if (retlen != 4) {
267                 printk("Didn't read all bytes in flash_read_u32(). Returned %d\n", res);
268                 return 0;
269         }
270
271         return ret;
272 }
273
274
275 static int
276 flash_safe_write(struct mtd_info *mtd, loff_t to,
277                  const u_char *buf, size_t count)
278 {
279         size_t retlen;
280         int res;
281
282         D3(printk(KERN_NOTICE "flash_safe_write(%p, %08x, %p, %08x)\n",
283                   mtd, (unsigned int) to, buf, count));
284
285         res = mtd->write(mtd, to, count, &retlen, buf);
286         if (retlen != count) {
287                 printk("Didn't write all bytes in flash_safe_write(). Returned %d\n", res);
288         }
289         return res?res:retlen;
290 }
291
292
293 static int
294 flash_safe_writev(struct mtd_info *mtd, const struct kvec *vecs,
295                         unsigned long iovec_cnt, loff_t to)
296 {
297         size_t retlen, retlen_a;
298         int i;
299         int res;
300
301         D3(printk(KERN_NOTICE "flash_safe_writev(%p, %08x, %p)\n",
302                   mtd, (unsigned int) to, vecs));
303
304         if (mtd->writev) {
305                 res = mtd->writev(mtd, vecs, iovec_cnt, to, &retlen);
306                 return res ? res : retlen;
307         }
308         /* Not implemented writev. Repeatedly use write - on the not so
309            unreasonable assumption that the mtd driver doesn't care how
310            many write cycles we use. */
311         res=0;
312         retlen=0;
313
314         for (i=0; !res && i<iovec_cnt; i++) {
315                 res = mtd->write(mtd, to, vecs[i].iov_len, &retlen_a,
316                                  vecs[i].iov_base);
317                 if (retlen_a != vecs[i].iov_len) {
318                         printk("Didn't write all bytes in flash_safe_writev(). Returned %d\n", res);
319                         if (i != iovec_cnt-1)
320                                 return -EIO;
321                 }
322                 /* If res is non-zero, retlen_a is undefined, but we don't
323                    care because in that case it's not going to be 
324                    returned anyway.
325                 */
326                 to += retlen_a;
327                 retlen += retlen_a;
328         }
329         return res?res:retlen;
330 }
331
332
333 static int
334 flash_memset(struct mtd_info *mtd, loff_t to,
335              const u_char c, size_t size)
336 {
337         static unsigned char pattern[64];
338         int i;
339
340         /* fill up pattern */
341
342         for(i = 0; i < 64; i++)
343                 pattern[i] = c;
344
345         /* write as many 64-byte chunks as we can */
346
347         while (size >= 64) {
348                 flash_safe_write(mtd, to, pattern, 64);
349                 size -= 64;
350                 to += 64;
351         }
352
353         /* and the rest */
354
355         if(size)
356                 flash_safe_write(mtd, to, pattern, size);
357
358         return size;
359 }
360
361
362 static void
363 intrep_erase_callback(struct erase_info *done)
364 {
365         wait_queue_head_t *wait_q;
366
367         wait_q = (wait_queue_head_t *)done->priv;
368
369         wake_up(wait_q);
370 }
371
372
373 static int
374 flash_erase_region(struct mtd_info *mtd, loff_t start,
375                    size_t size)
376 {
377         struct erase_info *erase;
378         DECLARE_WAITQUEUE(wait, current);
379         wait_queue_head_t wait_q;
380
381         erase = kmalloc(sizeof(struct erase_info), GFP_KERNEL);
382         if (!erase)
383                 return -ENOMEM;
384
385         init_waitqueue_head(&wait_q);
386
387         erase->mtd = mtd;
388         erase->callback = intrep_erase_callback;
389         erase->addr = start;
390         erase->len = size;
391         erase->priv = (u_long)&wait_q;
392
393         /* FIXME: Use TASK_INTERRUPTIBLE and deal with being interrupted */
394         set_current_state(TASK_UNINTERRUPTIBLE);
395         add_wait_queue(&wait_q, &wait);
396
397         if (mtd->erase(mtd, erase) < 0) {
398                 set_current_state(TASK_RUNNING);
399                 remove_wait_queue(&wait_q, &wait);
400                 kfree(erase);
401
402                 printk(KERN_WARNING "flash: erase of region [0x%lx, 0x%lx] "
403                        "totally failed\n", (long)start, (long)start + size);
404
405                 return -1;
406         }
407
408         schedule(); /* Wait for flash to finish. */
409         remove_wait_queue(&wait_q, &wait);
410
411         kfree(erase);
412
413         return 0;
414 }
415
416 /* This routine calculates checksums in JFFS.  */
417 static __u32
418 jffs_checksum(const void *data, int size)
419 {
420         __u32 sum = 0;
421         __u8 *ptr = (__u8 *)data;
422         while (size-- > 0) {
423                 sum += *ptr++;
424         }
425         D3(printk(", result: 0x%08x\n", sum));
426         return sum;
427 }
428
429
430 static int
431 jffs_checksum_flash(struct mtd_info *mtd, loff_t start, int size, __u32 *result)
432 {
433         __u32 sum = 0;
434         loff_t ptr = start;
435         __u8 *read_buf;
436         int i, length;
437
438         /* Allocate read buffer */
439         read_buf = (__u8 *) kmalloc (sizeof(__u8) * 4096, GFP_KERNEL);
440         if (!read_buf) {
441                 printk(KERN_NOTICE "kmalloc failed in jffs_checksum_flash()\n");
442                 return -ENOMEM;
443         }
444         /* Loop until checksum done */
445         while (size) {
446                 /* Get amount of data to read */
447                 if (size < 4096)
448                         length = size;
449                 else
450                         length = 4096;
451
452                 /* Perform flash read */
453                 D3(printk(KERN_NOTICE "jffs_checksum_flash\n"));
454                 flash_safe_read(mtd, ptr, &read_buf[0], length);
455
456                 /* Compute checksum */
457                 for (i=0; i < length ; i++)
458                         sum += read_buf[i];
459
460                 /* Update pointer and size */
461                 size -= length;
462                 ptr += length;
463         }
464
465         /* Free read buffer */
466         kfree(read_buf);
467
468         /* Return result */
469         D3(printk("checksum result: 0x%08x\n", sum));
470         *result = sum;
471         return 0;
472 }
473
474 static __inline__ void jffs_fm_write_lock(struct jffs_fmcontrol *fmc)
475 {
476   //    down(&fmc->wlock);
477 }
478
479 static __inline__ void jffs_fm_write_unlock(struct jffs_fmcontrol *fmc)
480 {
481   //    up(&fmc->wlock);
482 }
483
484
485 /* Create and initialize a new struct jffs_file.  */
486 static struct jffs_file *
487 jffs_create_file(struct jffs_control *c,
488                  const struct jffs_raw_inode *raw_inode)
489 {
490         struct jffs_file *f;
491
492         if (!(f = (struct jffs_file *)kmalloc(sizeof(struct jffs_file),
493                                               GFP_KERNEL))) {
494                 D(printk("jffs_create_file(): Failed!\n"));
495                 return NULL;
496         }
497         no_jffs_file++;
498         memset(f, 0, sizeof(struct jffs_file));
499         f->ino = raw_inode->ino;
500         f->pino = raw_inode->pino;
501         f->nlink = raw_inode->nlink;
502         f->deleted = raw_inode->deleted;
503         f->c = c;
504
505         return f;
506 }
507
508
509 /* Build a control block for the file system.  */
510 static struct jffs_control *
511 jffs_create_control(struct super_block *sb)
512 {
513         struct jffs_control *c;
514         register int s = sizeof(struct jffs_control);
515         int i;
516         D(char *t = 0);
517
518         D2(printk("jffs_create_control()\n"));
519
520         if (!(c = (struct jffs_control *)kmalloc(s, GFP_KERNEL))) {
521                 goto fail_control;
522         }
523         DJM(no_jffs_control++);
524         c->root = NULL;
525         c->gc_task = NULL;
526         c->hash_len = JFFS_HASH_SIZE;
527         s = sizeof(struct list_head) * c->hash_len;
528         if (!(c->hash = (struct list_head *)kmalloc(s, GFP_KERNEL))) {
529                 goto fail_hash;
530         }
531         DJM(no_hash++);
532         for (i = 0; i < c->hash_len; i++)
533                 INIT_LIST_HEAD(&c->hash[i]);
534         if (!(c->fmc = jffs_build_begin(c, MINOR(sb->s_dev)))) {
535                 goto fail_fminit;
536         }
537         c->next_ino = JFFS_MIN_INO + 1;
538         c->delete_list = (struct jffs_delete_list *) 0;
539         return c;
540
541 fail_fminit:
542         D(t = "c->fmc");
543 fail_hash:
544         kfree(c);
545         DJM(no_jffs_control--);
546         D(t = t ? t : "c->hash");
547 fail_control:
548         D(t = t ? t : "control");
549         D(printk("jffs_create_control(): Allocation failed: (%s)\n", t));
550         return (struct jffs_control *)0;
551 }
552
553
554 /* Clean up all data structures associated with the file system.  */
555 void
556 jffs_cleanup_control(struct jffs_control *c)
557 {
558         D2(printk("jffs_cleanup_control()\n"));
559
560         if (!c) {
561                 D(printk("jffs_cleanup_control(): c == NULL !!!\n"));
562                 return;
563         }
564
565         while (c->delete_list) {
566                 struct jffs_delete_list *delete_list_element;
567                 delete_list_element = c->delete_list;
568                 c->delete_list = c->delete_list->next;
569                 kfree(delete_list_element);
570         }
571
572         /* Free all files and nodes.  */
573         if (c->hash) {
574                 jffs_foreach_file(c, jffs_free_node_list);
575                 jffs_foreach_file(c, jffs_free_file);
576                 kfree(c->hash);
577                 DJM(no_hash--);
578         }
579         jffs_cleanup_fmcontrol(c->fmc);
580         kfree(c);
581         DJM(no_jffs_control--);
582         D3(printk("jffs_cleanup_control(): Leaving...\n"));
583 }
584
585
586 /* This function adds a virtual root node to the in-RAM representation.
587    Called by jffs_build_fs().  */
588 static int
589 jffs_add_virtual_root(struct jffs_control *c)
590 {
591         struct jffs_file *root;
592         struct jffs_node *node;
593
594         D2(printk("jffs_add_virtual_root(): "
595                   "Creating a virtual root directory.\n"));
596
597         if (!(root = (struct jffs_file *)kmalloc(sizeof(struct jffs_file),
598                                                  GFP_KERNEL))) {
599                 return -ENOMEM;
600         }
601         no_jffs_file++;
602         if (!(node = jffs_alloc_node())) {
603                 kfree(root);
604                 no_jffs_file--;
605                 return -ENOMEM;
606         }
607         DJM(no_jffs_node++);
608         memset(node, 0, sizeof(struct jffs_node));
609         node->ino = JFFS_MIN_INO;
610         memset(root, 0, sizeof(struct jffs_file));
611         root->ino = JFFS_MIN_INO;
612         root->mode = S_IFDIR | S_IRWXU | S_IRGRP
613                      | S_IXGRP | S_IROTH | S_IXOTH;
614         root->atime = root->mtime = root->ctime = get_seconds();
615         root->nlink = 1;
616         root->c = c;
617         root->version_head = root->version_tail = node;
618         jffs_insert_file_into_hash(root);
619         return 0;
620 }
621
622
623 /* This is where the file system is built and initialized.  */
624 int
625 jffs_build_fs(struct super_block *sb)
626 {
627         struct jffs_control *c;
628         int err = 0;
629
630         D2(printk("jffs_build_fs()\n"));
631
632         if (!(c = jffs_create_control(sb))) {
633                 return -ENOMEM;
634         }
635         c->building_fs = 1;
636         c->sb = sb;
637         if ((err = jffs_scan_flash(c)) < 0) {
638                 if(err == -EAGAIN){
639                         /* scan_flash() wants us to try once more. A flipping 
640                            bits sector was detect in the middle of the scan flash.
641                            Clean up old allocated memory before going in.
642                         */
643                         D1(printk("jffs_build_fs: Cleaning up all control structures,"
644                                   " reallocating them and trying mount again.\n"));
645                         jffs_cleanup_control(c);
646                         if (!(c = jffs_create_control(sb))) {
647                                 return -ENOMEM;
648                         }
649                         c->building_fs = 1;
650                         c->sb = sb;
651
652                         if ((err = jffs_scan_flash(c)) < 0) {
653                                 goto jffs_build_fs_fail;
654                         }                       
655                 }else{
656                         goto jffs_build_fs_fail;
657                 }
658         }
659
660         /* Add a virtual root node if no one exists.  */
661         if (!jffs_find_file(c, JFFS_MIN_INO)) {
662                 if ((err = jffs_add_virtual_root(c)) < 0) {
663                         goto jffs_build_fs_fail;
664                 }
665         }
666
667         while (c->delete_list) {
668                 struct jffs_file *f;
669                 struct jffs_delete_list *delete_list_element;
670
671                 if ((f = jffs_find_file(c, c->delete_list->ino))) {
672                         f->deleted = 1;
673                 }
674                 delete_list_element = c->delete_list;
675                 c->delete_list = c->delete_list->next;
676                 kfree(delete_list_element);
677         }
678
679         /* Remove deleted nodes.  */
680         if ((err = jffs_foreach_file(c, jffs_possibly_delete_file)) < 0) {
681                 printk(KERN_ERR "JFFS: Failed to remove deleted nodes.\n");
682                 goto jffs_build_fs_fail;
683         }
684         /* Remove redundant nodes.  (We are not interested in the
685            return value in this case.)  */
686         jffs_foreach_file(c, jffs_remove_redundant_nodes);
687         /* Try to build a tree from all the nodes.  */
688         if ((err = jffs_foreach_file(c, jffs_insert_file_into_tree)) < 0) {
689                 printk("JFFS: Failed to build tree.\n");
690                 goto jffs_build_fs_fail;
691         }
692         /* Compute the sizes of all files in the filesystem.  Adjust if
693            necessary.  */
694         if ((err = jffs_foreach_file(c, jffs_build_file)) < 0) {
695                 printk("JFFS: Failed to build file system.\n");
696                 goto jffs_build_fs_fail;
697         }
698         sb->s_fs_info = (void *)c;
699         c->building_fs = 0;
700
701         D1(jffs_print_hash_table(c));
702         D1(jffs_print_tree(c->root, 0));
703
704         return 0;
705
706 jffs_build_fs_fail:
707         jffs_cleanup_control(c);
708         return err;
709 } /* jffs_build_fs()  */
710
711
712 /*
713   This checks for sectors that were being erased in their previous 
714   lifetimes and for some reason or the other (power fail etc.), 
715   the erase cycles never completed.
716   As the flash array would have reverted back to read status, 
717   these sectors are detected by the symptom of the "flipping bits",
718   i.e. bits being read back differently from the same location in
719   flash if read multiple times.
720   The only solution to this is to re-erase the entire
721   sector.
722   Unfortunately detecting "flipping bits" is not a simple exercise
723   as a bit may be read back at 1 or 0 depending on the alignment 
724   of the stars in the universe.
725   The level of confidence is in direct proportion to the number of 
726   scans done. By power fail testing I (Vipin) have been able to 
727   proove that reading twice is not enough.
728   Maybe 4 times? Change NUM_REREADS to a higher number if you want
729   a (even) higher degree of confidence in your mount process. 
730   A higher number would of course slow down your mount.
731 */
732 static int check_partly_erased_sectors(struct jffs_fmcontrol *fmc){
733
734 #define NUM_REREADS             4 /* see note above */
735 #define READ_AHEAD_BYTES        4096 /* must be a multiple of 4, 
736                                         usually set to kernel page size */
737
738         __u8 *read_buf1;
739         __u8 *read_buf2;
740
741         int err = 0;
742         int retlen;
743         int i;
744         int cnt;
745         __u32 offset;
746         loff_t pos = 0;
747         loff_t end = fmc->flash_size;
748
749
750         /* Allocate read buffers */
751         read_buf1 = (__u8 *) kmalloc (sizeof(__u8) * READ_AHEAD_BYTES, GFP_KERNEL);
752         if (!read_buf1)
753                 return -ENOMEM;
754
755         read_buf2 = (__u8 *) kmalloc (sizeof(__u8) * READ_AHEAD_BYTES, GFP_KERNEL);
756         if (!read_buf2) {
757                 kfree(read_buf1);
758                 return -ENOMEM;
759         }
760
761  CHECK_NEXT:
762         while(pos < end){
763                 
764                 D1(printk("check_partly_erased_sector():checking sector which contains"
765                           " offset 0x%x for flipping bits..\n", (__u32)pos));
766                 
767                 retlen = flash_safe_read(fmc->mtd, pos,
768                                          &read_buf1[0], READ_AHEAD_BYTES);
769                 retlen &= ~3;
770                 
771                 for(cnt = 0; cnt < NUM_REREADS; cnt++){
772                         (void)flash_safe_read(fmc->mtd, pos,
773                                               &read_buf2[0], READ_AHEAD_BYTES);
774                         
775                         for (i=0 ; i < retlen ; i+=4) {
776                                 /* buffers MUST match, double word for word! */
777                                 if(*((__u32 *) &read_buf1[i]) !=
778                                    *((__u32 *) &read_buf2[i])
779                                    ){
780                                         /* flipping bits detected, time to erase sector */
781                                         /* This will help us log some statistics etc. */
782                                         D1(printk("Flipping bits detected in re-read round:%i of %i\n",
783                                                cnt, NUM_REREADS));
784                                         D1(printk("check_partly_erased_sectors:flipping bits detected"
785                                                   " @offset:0x%x(0x%x!=0x%x)\n",
786                                                   (__u32)pos+i, *((__u32 *) &read_buf1[i]), 
787                                                   *((__u32 *) &read_buf2[i])));
788                                         
789                                         /* calculate start of present sector */
790                                         offset = (((__u32)pos+i)/(__u32)fmc->sector_size) * (__u32)fmc->sector_size;
791                                         
792                                         D1(printk("check_partly_erased_sector():erasing sector starting 0x%x.\n",
793                                                   offset));
794                                         
795                                         if (flash_erase_region(fmc->mtd,
796                                                                offset, fmc->sector_size) < 0) {
797                                                 printk(KERN_ERR "JFFS: Erase of flash failed. "
798                                                        "offset = %u, erase_size = %d\n",
799                                                        offset , fmc->sector_size);
800                                                 
801                                                 err = -EIO;
802                                                 goto returnBack;
803
804                                         }else{
805                                                 D1(printk("JFFS: Erase of flash sector @0x%x successful.\n",
806                                                        offset));
807                                                 /* skip ahead to the next sector */
808                                                 pos = (((__u32)pos+i)/(__u32)fmc->sector_size) * (__u32)fmc->sector_size;
809                                                 pos += fmc->sector_size;
810                                                 goto CHECK_NEXT;
811                                         }
812                                 }
813                         }
814                 }
815                 pos += READ_AHEAD_BYTES;
816         }
817
818  returnBack:
819         kfree(read_buf1);
820         kfree(read_buf2);
821
822         D2(printk("check_partly_erased_sector():Done checking all sectors till offset 0x%x for flipping bits.\n",
823                   (__u32)pos));
824
825         return err;
826
827 }/* end check_partly_erased_sectors() */
828
829
830
831 /* Scan the whole flash memory in order to find all nodes in the
832    file systems.  */
833 static int
834 jffs_scan_flash(struct jffs_control *c)
835 {
836         char name[JFFS_MAX_NAME_LEN + 2];
837         struct jffs_raw_inode raw_inode;
838         struct jffs_node *node = NULL;
839         struct jffs_fmcontrol *fmc = c->fmc;
840         __u32 checksum;
841         __u8 tmp_accurate;
842         __u16 tmp_chksum;
843         __u32 deleted_file;
844         loff_t pos = 0;
845         loff_t start;
846         loff_t test_start;
847         loff_t end = fmc->flash_size;
848         __u8 *read_buf;
849         int i, len, retlen;
850         __u32 offset;
851
852         __u32 free_chunk_size1;
853         __u32 free_chunk_size2;
854
855         
856 #define NUMFREEALLOWED     2        /* 2 chunks of at least erase size space allowed */
857         int num_free_space = 0;       /* Flag err if more than TWO
858                                        free blocks found. This is NOT allowed
859                                        by the current jffs design.
860                                     */
861         int num_free_spc_not_accp = 0; /* For debugging purposed keep count 
862                                         of how much free space was rejected and
863                                         marked dirty
864                                      */
865
866         D1(printk("jffs_scan_flash(): start pos = 0x%lx, end = 0x%lx\n",
867                   (long)pos, (long)end));
868
869         flash_safe_acquire(fmc->mtd);
870
871         /*
872           check and make sure that any sector does not suffer
873           from the "partly erased, bit flipping syndrome" (TM Vipin :)
874           If so, offending sectors will be erased.
875         */
876         if(check_partly_erased_sectors(fmc) < 0){
877
878                 flash_safe_release(fmc->mtd);
879                 return -EIO; /* bad, bad, bad error. Cannot continue.*/
880         }
881
882         /* Allocate read buffer */
883         read_buf = (__u8 *) kmalloc (sizeof(__u8) * 4096, GFP_KERNEL);
884         if (!read_buf) {
885                 flash_safe_release(fmc->mtd);
886                 return -ENOMEM;
887         }
888                               
889         /* Start the scan.  */
890         while (pos < end) {
891                 deleted_file = 0;
892
893                 /* Remember the position from where we started this scan.  */
894                 start = pos;
895
896                 switch (flash_read_u32(fmc->mtd, pos)) {
897                 case JFFS_EMPTY_BITMASK:
898                         /* We have found 0xffffffff at this position.  We have to
899                            scan the rest of the flash till the end or till
900                            something else than 0xffffffff is found.
901                            Keep going till we do not find JFFS_EMPTY_BITMASK 
902                            anymore */
903
904                         D1(printk("jffs_scan_flash(): 0xffffffff at pos 0x%lx.\n",
905                                   (long)pos));
906
907                         while(pos < end){
908
909                               len = end - pos < 4096 ? end - pos : 4096;
910                               
911                               retlen = flash_safe_read(fmc->mtd, pos,
912                                                  &read_buf[0], len);
913
914                               retlen &= ~3;
915                               
916                               for (i=0 ; i < retlen ; i+=4, pos += 4) {
917                                       if(*((__u32 *) &read_buf[i]) !=
918                                          JFFS_EMPTY_BITMASK)
919                                         break;
920                               }
921                               if (i == retlen)
922                                     continue;
923                               else
924                                     break;
925                         }
926
927                         D1(printk("jffs_scan_flash():0xffffffff ended at pos 0x%lx.\n",
928                                   (long)pos));
929                         
930                         /* If some free space ends in the middle of a sector,
931                            treat it as dirty rather than clean.
932                            This is to handle the case where one thread 
933                            allocated space for a node, but didn't get to
934                            actually _write_ it before power was lost, leaving
935                            a gap in the log. Shifting all node writes into
936                            a single kernel thread will fix the original problem.
937                         */
938                         if ((__u32) pos % fmc->sector_size) {
939                                 /* If there was free space in previous 
940                                    sectors, don't mark that dirty too - 
941                                    only from the beginning of this sector
942                                    (or from start) 
943                                 */
944
945                                 test_start = pos & ~(fmc->sector_size-1); /* end of last sector */
946
947                                 if (start < test_start) {
948
949                                         /* free space started in the previous sector! */
950
951                                         if((num_free_space < NUMFREEALLOWED) && 
952                                            ((unsigned int)(test_start - start) >= fmc->sector_size)){
953
954                                                 /*
955                                                   Count it in if we are still under NUMFREEALLOWED *and* it is 
956                                                   at least 1 erase sector in length. This will keep us from 
957                                                   picking any little ole' space as "free".
958                                                 */
959                                           
960                                                 D1(printk("Reducing end of free space to 0x%x from 0x%x\n",
961                                                           (unsigned int)test_start, (unsigned int)pos));
962
963                                                 D1(printk("Free space accepted: Starting 0x%x for 0x%x bytes\n",
964                                                           (unsigned int) start,
965                                                           (unsigned int)(test_start - start)));
966
967                                                 /* below, space from "start" to "pos" will be marked dirty. */
968                                                 start = test_start; 
969                                                 
970                                                 /* Being in here means that we have found at least an entire 
971                                                    erase sector size of free space ending on a sector boundary.
972                                                    Keep track of free spaces accepted.
973                                                 */
974                                                 num_free_space++;
975                                         }else{
976                                                 num_free_spc_not_accp++;
977                                                 D1(printk("Free space (#%i) found but *Not* accepted: Starting"
978                                                           " 0x%x for 0x%x bytes\n",
979                                                           num_free_spc_not_accp, (unsigned int)start, 
980                                                           (unsigned int)((unsigned int)(pos & ~(fmc->sector_size-1)) - (unsigned int)start)));
981                                                 
982                                         }
983                                         
984                                 }
985                                 if((((__u32)(pos - start)) != 0)){
986
987                                         D1(printk("Dirty space: Starting 0x%x for 0x%x bytes\n",
988                                                   (unsigned int) start, (unsigned int) (pos - start)));
989                                         jffs_fmalloced(fmc, (__u32) start,
990                                                        (__u32) (pos - start), NULL);
991                                 }else{
992                                         /* "Flipping bits" detected. This means that our scan for them
993                                            did not catch this offset. See check_partly_erased_sectors() for
994                                            more info.
995                                         */
996                                         
997                                         D1(printk("jffs_scan_flash():wants to allocate dirty flash "
998                                                   "space for 0 bytes.\n"));
999                                         D1(printk("jffs_scan_flash(): Flipping bits! We will free "
1000                                                   "all allocated memory, erase this sector and remount\n"));
1001
1002                                         /* calculate start of present sector */
1003                                         offset = (((__u32)pos)/(__u32)fmc->sector_size) * (__u32)fmc->sector_size;
1004                                         
1005                                         D1(printk("jffs_scan_flash():erasing sector starting 0x%x.\n",
1006                                                   offset));
1007                                         
1008                                         if (flash_erase_region(fmc->mtd,
1009                                                                offset, fmc->sector_size) < 0) {
1010                                                 printk(KERN_ERR "JFFS: Erase of flash failed. "
1011                                                        "offset = %u, erase_size = %d\n",
1012                                                        offset , fmc->sector_size);
1013
1014                                                 flash_safe_release(fmc->mtd);
1015                                                 kfree(read_buf);
1016                                                 return -1; /* bad, bad, bad! */
1017
1018                                         }
1019                                         flash_safe_release(fmc->mtd);
1020                                         kfree(read_buf);
1021
1022                                         return -EAGAIN; /* erased offending sector. Try mount one more time please. */
1023                                 }
1024                         }else{
1025                                 /* Being in here means that we have found free space that ends on an erase sector
1026                                    boundary.
1027                                    Count it in if we are still under NUMFREEALLOWED *and* it is at least 1 erase 
1028                                    sector in length. This will keep us from picking any little ole' space as "free".
1029                                  */
1030                                  if((num_free_space < NUMFREEALLOWED) && 
1031                                     ((unsigned int)(pos - start) >= fmc->sector_size)){
1032                                            /* We really don't do anything to mark space as free, except *not* 
1033                                               mark it dirty and just advance the "pos" location pointer. 
1034                                               It will automatically be picked up as free space.
1035                                             */ 
1036                                            num_free_space++;
1037                                            D1(printk("Free space accepted: Starting 0x%x for 0x%x bytes\n",
1038                                                      (unsigned int) start, (unsigned int) (pos - start)));
1039                                  }else{
1040                                          num_free_spc_not_accp++;
1041                                          D1(printk("Free space (#%i) found but *Not* accepted: Starting "
1042                                                    "0x%x for 0x%x bytes\n", num_free_spc_not_accp, 
1043                                                    (unsigned int) start, 
1044                                                    (unsigned int) (pos - start)));
1045                                          
1046                                          /* Mark this space as dirty. We already have our free space. */
1047                                          D1(printk("Dirty space: Starting 0x%x for 0x%x bytes\n",
1048                                                    (unsigned int) start, (unsigned int) (pos - start)));
1049                                          jffs_fmalloced(fmc, (__u32) start,
1050                                                         (__u32) (pos - start), NULL);                                      
1051                                  }
1052                                  
1053                         }
1054                         if(num_free_space > NUMFREEALLOWED){
1055                                  printk(KERN_WARNING "jffs_scan_flash(): Found free space "
1056                                         "number %i. Only %i free space is allowed.\n",
1057                                         num_free_space, NUMFREEALLOWED);                              
1058                         }
1059                         continue;
1060
1061                 case JFFS_DIRTY_BITMASK:
1062                         /* We have found 0x00000000 at this position.  Scan as far
1063                            as possible to find out how much is dirty.  */
1064                         D1(printk("jffs_scan_flash(): 0x00000000 at pos 0x%lx.\n",
1065                                   (long)pos));
1066                         for (; pos < end
1067                                && JFFS_DIRTY_BITMASK == flash_read_u32(fmc->mtd, pos);
1068                              pos += 4);
1069                         D1(printk("jffs_scan_flash(): 0x00 ended at "
1070                                   "pos 0x%lx.\n", (long)pos));
1071                         jffs_fmalloced(fmc, (__u32) start,
1072                                        (__u32) (pos - start), NULL);
1073                         continue;
1074
1075                 case JFFS_MAGIC_BITMASK:
1076                         /* We have probably found a new raw inode.  */
1077                         break;
1078
1079                 default:
1080                 bad_inode:
1081                         /* We're f*cked.  This is not solved yet.  We have
1082                            to scan for the magic pattern.  */
1083                         D1(printk("*************** Dirty flash memory or "
1084                                   "bad inode: "
1085                                   "hexdump(pos = 0x%lx, len = 128):\n",
1086                                   (long)pos));
1087                         D1(jffs_hexdump(fmc->mtd, pos, 128));
1088
1089                         for (pos += 4; pos < end; pos += 4) {
1090                                 switch (flash_read_u32(fmc->mtd, pos)) {
1091                                 case JFFS_MAGIC_BITMASK:
1092                                 case JFFS_EMPTY_BITMASK:
1093                                         /* handle these in the main switch() loop */
1094                                         goto cont_scan;
1095
1096                                 default:
1097                                         break;
1098                                 }
1099                         }
1100
1101                         cont_scan:
1102                         /* First, mark as dirty the region
1103                            which really does contain crap. */
1104                         jffs_fmalloced(fmc, (__u32) start,
1105                                        (__u32) (pos - start),
1106                                        NULL);
1107                         
1108                         continue;
1109                 }/* switch */
1110
1111                 /* We have found the beginning of an inode.  Create a
1112                    node for it unless there already is one available.  */
1113                 if (!node) {
1114                         if (!(node = jffs_alloc_node())) {
1115                                 /* Free read buffer */
1116                                 kfree(read_buf);
1117
1118                                 /* Release the flash device */
1119                                 flash_safe_release(fmc->mtd);
1120         
1121                                 return -ENOMEM;
1122                         }
1123                         DJM(no_jffs_node++);
1124                 }
1125
1126                 /* Read the next raw inode.  */
1127
1128                 flash_safe_read(fmc->mtd, pos, (u_char *) &raw_inode,
1129                                 sizeof(struct jffs_raw_inode));
1130
1131                 /* When we compute the checksum for the inode, we never
1132                    count the 'accurate' or the 'checksum' fields.  */
1133                 tmp_accurate = raw_inode.accurate;
1134                 tmp_chksum = raw_inode.chksum;
1135                 raw_inode.accurate = 0;
1136                 raw_inode.chksum = 0;
1137                 checksum = jffs_checksum(&raw_inode,
1138                                          sizeof(struct jffs_raw_inode));
1139                 raw_inode.accurate = tmp_accurate;
1140                 raw_inode.chksum = tmp_chksum;
1141
1142                 D3(printk("*** We have found this raw inode at pos 0x%lx "
1143                           "on the flash:\n", (long)pos));
1144                 D3(jffs_print_raw_inode(&raw_inode));
1145
1146                 if (checksum != raw_inode.chksum) {
1147                         D1(printk("jffs_scan_flash(): Bad checksum: "
1148                                   "checksum = %u, "
1149                                   "raw_inode.chksum = %u\n",
1150                                   checksum, raw_inode.chksum));
1151                         pos += sizeof(struct jffs_raw_inode);
1152                         jffs_fmalloced(fmc, (__u32) start,
1153                                        (__u32) (pos - start), NULL);
1154                         /* Reuse this unused struct jffs_node.  */
1155                         continue;
1156                 }
1157
1158                 /* Check the raw inode read so far.  Start with the
1159                    maximum length of the filename.  */
1160                 if (raw_inode.nsize > JFFS_MAX_NAME_LEN) {
1161                         printk(KERN_WARNING "jffs_scan_flash: Found a "
1162                                "JFFS node with name too large\n");
1163                         goto bad_inode;
1164                 }
1165
1166                 if (raw_inode.rename && raw_inode.dsize != sizeof(__u32)) {
1167                         printk(KERN_WARNING "jffs_scan_flash: Found a "
1168                                "rename node with dsize %u.\n",
1169                                raw_inode.dsize);
1170                         jffs_print_raw_inode(&raw_inode);
1171                         goto bad_inode;
1172                 }
1173
1174                 /* The node's data segment should not exceed a
1175                    certain length.  */
1176                 if (raw_inode.dsize > fmc->max_chunk_size) {
1177                         printk(KERN_WARNING "jffs_scan_flash: Found a "
1178                                "JFFS node with dsize (0x%x) > max_chunk_size (0x%x)\n",
1179                                raw_inode.dsize, fmc->max_chunk_size);
1180                         goto bad_inode;
1181                 }
1182
1183                 pos += sizeof(struct jffs_raw_inode);
1184
1185                 /* This shouldn't be necessary because a node that
1186                    violates the flash boundaries shouldn't be written
1187                    in the first place. */
1188                 if (pos >= end) {
1189                         goto check_node;
1190                 }
1191
1192                 /* Read the name.  */
1193                 *name = 0;
1194                 if (raw_inode.nsize) {
1195                         flash_safe_read(fmc->mtd, pos, name, raw_inode.nsize);
1196                         name[raw_inode.nsize] = '\0';
1197                         pos += raw_inode.nsize
1198                                + JFFS_GET_PAD_BYTES(raw_inode.nsize);
1199                         D3(printk("name == \"%s\"\n", name));
1200                         checksum = jffs_checksum(name, raw_inode.nsize);
1201                         if (checksum != raw_inode.nchksum) {
1202                                 D1(printk("jffs_scan_flash(): Bad checksum: "
1203                                           "checksum = %u, "
1204                                           "raw_inode.nchksum = %u\n",
1205                                           checksum, raw_inode.nchksum));
1206                                 jffs_fmalloced(fmc, (__u32) start,
1207                                                (__u32) (pos - start), NULL);
1208                                 /* Reuse this unused struct jffs_node.  */
1209                                 continue;
1210                         }
1211                         if (pos >= end) {
1212                                 goto check_node;
1213                         }
1214                 }
1215
1216                 /* Read the data, if it exists, in order to be sure it
1217                    matches the checksum.  */
1218                 if (raw_inode.dsize) {
1219                         if (raw_inode.rename) {
1220                                 deleted_file = flash_read_u32(fmc->mtd, pos);
1221                         }
1222                         if (jffs_checksum_flash(fmc->mtd, pos, raw_inode.dsize, &checksum)) {
1223                                 printk("jffs_checksum_flash() failed to calculate a checksum\n");
1224                                 jffs_fmalloced(fmc, (__u32) start,
1225                                                (__u32) (pos - start), NULL);
1226                                 /* Reuse this unused struct jffs_node.  */
1227                                 continue;
1228                         }                               
1229                         pos += raw_inode.dsize
1230                                + JFFS_GET_PAD_BYTES(raw_inode.dsize);
1231
1232                         if (checksum != raw_inode.dchksum) {
1233                                 D1(printk("jffs_scan_flash(): Bad checksum: "
1234                                           "checksum = %u, "
1235                                           "raw_inode.dchksum = %u\n",
1236                                           checksum, raw_inode.dchksum));
1237                                 jffs_fmalloced(fmc, (__u32) start,
1238                                                (__u32) (pos - start), NULL);
1239                                 /* Reuse this unused struct jffs_node.  */
1240                                 continue;
1241                         }
1242                 }
1243
1244                 check_node:
1245
1246                 /* Remember the highest inode number in the whole file
1247                    system.  This information will be used when assigning
1248                    new files new inode numbers.  */
1249                 if (c->next_ino <= raw_inode.ino) {
1250                         c->next_ino = raw_inode.ino + 1;
1251                 }
1252
1253                 if (raw_inode.accurate) {
1254                         int err;
1255                         node->data_offset = raw_inode.offset;
1256                         node->data_size = raw_inode.dsize;
1257                         node->removed_size = raw_inode.rsize;
1258                         /* Compute the offset to the actual data in the
1259                            on-flash node.  */
1260                         node->fm_offset
1261                         = sizeof(struct jffs_raw_inode)
1262                           + raw_inode.nsize
1263                           + JFFS_GET_PAD_BYTES(raw_inode.nsize);
1264                         node->fm = jffs_fmalloced(fmc, (__u32) start,
1265                                                   (__u32) (pos - start),
1266                                                   node);
1267                         if (!node->fm) {
1268                                 D(printk("jffs_scan_flash(): !node->fm\n"));
1269                                 jffs_free_node(node);
1270                                 DJM(no_jffs_node--);
1271
1272                                 /* Free read buffer */
1273                                 kfree(read_buf);
1274
1275                                 /* Release the flash device */
1276                                 flash_safe_release(fmc->mtd);
1277
1278                                 return -ENOMEM;
1279                         }
1280                         if ((err = jffs_insert_node(c, NULL, &raw_inode,
1281                                                     name, node)) < 0) {
1282                                 printk("JFFS: Failed to handle raw inode. "
1283                                        "(err = %d)\n", err);
1284                                 break;
1285                         }
1286                         if (raw_inode.rename) {
1287                                 struct jffs_delete_list *dl
1288                                 = (struct jffs_delete_list *)
1289                                   kmalloc(sizeof(struct jffs_delete_list),
1290                                           GFP_KERNEL);
1291                                 if (!dl) {
1292                                         D(printk("jffs_scan_flash: !dl\n"));
1293                                         jffs_free_node(node);
1294                                         DJM(no_jffs_node--);
1295
1296                                         /* Release the flash device */
1297                                         flash_safe_release(fmc->flash_part);
1298
1299                                         /* Free read buffer */
1300                                         kfree(read_buf);
1301
1302                                         return -ENOMEM;
1303                                 }
1304                                 dl->ino = deleted_file;
1305                                 dl->next = c->delete_list;
1306                                 c->delete_list = dl;
1307                                 node->data_size = 0;
1308                         }
1309                         D3(jffs_print_node(node));
1310                         node = NULL; /* Don't free the node!  */
1311                 }
1312                 else {
1313                         jffs_fmalloced(fmc, (__u32) start,
1314                                        (__u32) (pos - start), NULL);
1315                         D3(printk("jffs_scan_flash(): Just found an obsolete "
1316                                   "raw_inode. Continuing the scan...\n"));
1317                         /* Reuse this unused struct jffs_node.  */
1318                 }
1319         }
1320
1321         if (node) {
1322                 jffs_free_node(node);
1323                 DJM(no_jffs_node--);
1324         }
1325         jffs_build_end(fmc);
1326
1327         /* Free read buffer */
1328         kfree(read_buf);
1329
1330         if(!num_free_space){
1331                 printk(KERN_WARNING "jffs_scan_flash(): Did not find even a single "
1332                        "chunk of free space. This is BAD!\n");
1333         }
1334
1335         /* Return happy */
1336         D3(printk("jffs_scan_flash(): Leaving...\n"));
1337         flash_safe_release(fmc->mtd);
1338
1339         /* This is to trap the "free size accounting screwed error. */
1340         free_chunk_size1 = jffs_free_size1(fmc);
1341         free_chunk_size2 = jffs_free_size2(fmc);
1342
1343         if (free_chunk_size1 + free_chunk_size2 != fmc->free_size) {
1344
1345                 printk(KERN_WARNING "jffs_scan_falsh():Free size accounting screwed\n");
1346                 printk(KERN_WARNING "jfffs_scan_flash():free_chunk_size1 == 0x%x, "
1347                        "free_chunk_size2 == 0x%x, fmc->free_size == 0x%x\n", 
1348                        free_chunk_size1, free_chunk_size2, fmc->free_size);
1349
1350                 return -1; /* Do NOT mount f/s so that we can inspect what happened.
1351                               Mounting this  screwed up f/s will screw us up anyway.
1352                             */
1353         }       
1354
1355         return 0; /* as far as we are concerned, we are happy! */
1356 } /* jffs_scan_flash()  */
1357
1358
1359 /* Insert any kind of node into the file system.  Take care of data
1360    insertions and deletions.  Also remove redundant information. The
1361    memory allocated for the `name' is regarded as "given away" in the
1362    caller's perspective.  */
1363 int
1364 jffs_insert_node(struct jffs_control *c, struct jffs_file *f,
1365                  const struct jffs_raw_inode *raw_inode,
1366                  const char *name, struct jffs_node *node)
1367 {
1368         int update_name = 0;
1369         int insert_into_tree = 0;
1370
1371         D2(printk("jffs_insert_node(): ino = %u, version = %u, "
1372                   "name = \"%s\", deleted = %d\n",
1373                   raw_inode->ino, raw_inode->version,
1374                   ((name && *name) ? name : ""), raw_inode->deleted));
1375
1376         /* If there doesn't exist an associated jffs_file, then
1377            create, initialize and insert one into the file system.  */
1378         if (!f && !(f = jffs_find_file(c, raw_inode->ino))) {
1379                 if (!(f = jffs_create_file(c, raw_inode))) {
1380                         return -ENOMEM;
1381                 }
1382                 jffs_insert_file_into_hash(f);
1383                 insert_into_tree = 1;
1384         }
1385         node->ino = raw_inode->ino;
1386         node->version = raw_inode->version;
1387         node->data_size = raw_inode->dsize;
1388         node->fm_offset = sizeof(struct jffs_raw_inode) + raw_inode->nsize
1389                           + JFFS_GET_PAD_BYTES(raw_inode->nsize);
1390         node->name_size = raw_inode->nsize;
1391
1392         /* Now insert the node at the correct position into the file's
1393            version list.  */
1394         if (!f->version_head) {
1395                 /* This is the first node.  */
1396                 f->version_head = node;
1397                 f->version_tail = node;
1398                 node->version_prev = NULL;
1399                 node->version_next = NULL;
1400                 f->highest_version = node->version;
1401                 update_name = 1;
1402                 f->mode = raw_inode->mode;
1403                 f->uid = raw_inode->uid;
1404                 f->gid = raw_inode->gid;
1405                 f->atime = raw_inode->atime;
1406                 f->mtime = raw_inode->mtime;
1407                 f->ctime = raw_inode->ctime;
1408         }
1409         else if ((f->highest_version < node->version)
1410                  || (node->version == 0)) {
1411                 /* Insert at the end of the list.  I.e. this node is the
1412                    newest one so far.  */
1413                 node->version_prev = f->version_tail;
1414                 node->version_next = NULL;
1415                 f->version_tail->version_next = node;
1416                 f->version_tail = node;
1417                 f->highest_version = node->version;
1418                 update_name = 1;
1419                 f->pino = raw_inode->pino;
1420                 f->mode = raw_inode->mode;
1421                 f->uid = raw_inode->uid;
1422                 f->gid = raw_inode->gid;
1423                 f->atime = raw_inode->atime;
1424                 f->mtime = raw_inode->mtime;
1425                 f->ctime = raw_inode->ctime;
1426         }
1427         else if (f->version_head->version > node->version) {
1428                 /* Insert at the bottom of the list.  */
1429                 node->version_prev = NULL;
1430                 node->version_next = f->version_head;
1431                 f->version_head->version_prev = node;
1432                 f->version_head = node;
1433                 if (!f->name) {
1434                         update_name = 1;
1435                 }
1436         }
1437         else {
1438                 struct jffs_node *n;
1439                 int newer_name = 0;
1440                 /* Search for the insertion position starting from
1441                    the tail (newest node).  */
1442                 for (n = f->version_tail; n; n = n->version_prev) {
1443                         if (n->version < node->version) {
1444                                 node->version_prev = n;
1445                                 node->version_next = n->version_next;
1446                                 node->version_next->version_prev = node;
1447                                 n->version_next = node;
1448                                 if (!newer_name) {
1449                                         update_name = 1;
1450                                 }
1451                                 break;
1452                         }
1453                         if (n->name_size) {
1454                                 newer_name = 1;
1455                         }
1456                 }
1457         }
1458
1459         /* Deletion is irreversible. If any 'deleted' node is ever
1460            written, the file is deleted */
1461         if (raw_inode->deleted)
1462                 f->deleted = raw_inode->deleted;
1463
1464         /* Perhaps update the name.  */
1465         if (raw_inode->nsize && update_name && name && *name && (name != f->name)) {
1466                 if (f->name) {
1467                         kfree(f->name);
1468                         DJM(no_name--);
1469                 }
1470                 if (!(f->name = (char *) kmalloc(raw_inode->nsize + 1,
1471                                                  GFP_KERNEL))) {
1472                         return -ENOMEM;
1473                 }
1474                 DJM(no_name++);
1475                 memcpy(f->name, name, raw_inode->nsize);
1476                 f->name[raw_inode->nsize] = '\0';
1477                 f->nsize = raw_inode->nsize;
1478                 D3(printk("jffs_insert_node(): Updated the name of "
1479                           "the file to \"%s\".\n", name));
1480         }
1481
1482         if (!c->building_fs) {
1483                 D3(printk("jffs_insert_node(): ---------------------------"
1484                           "------------------------------------------- 1\n"));
1485                 if (insert_into_tree) {
1486                         jffs_insert_file_into_tree(f);
1487                 }
1488                 /* Once upon a time, we would call jffs_possibly_delete_file()
1489                    here. That causes an oops if someone's still got the file
1490                    open, so now we only do it in jffs_delete_inode()
1491                    -- dwmw2
1492                 */
1493                 if (node->data_size || node->removed_size) {
1494                         jffs_update_file(f, node);
1495                 }
1496                 jffs_remove_redundant_nodes(f);
1497
1498                 jffs_garbage_collect_trigger(c);
1499
1500                 D3(printk("jffs_insert_node(): ---------------------------"
1501                           "------------------------------------------- 2\n"));
1502         }
1503
1504         return 0;
1505 } /* jffs_insert_node()  */
1506
1507
1508 /* Unlink a jffs_node from the version list it is in.  */
1509 static inline void
1510 jffs_unlink_node_from_version_list(struct jffs_file *f,
1511                                    struct jffs_node *node)
1512 {
1513         if (node->version_prev) {
1514                 node->version_prev->version_next = node->version_next;
1515         } else {
1516                 f->version_head = node->version_next;
1517         }
1518         if (node->version_next) {
1519                 node->version_next->version_prev = node->version_prev;
1520         } else {
1521                 f->version_tail = node->version_prev;
1522         }
1523 }
1524
1525
1526 /* Unlink a jffs_node from the range list it is in.  */
1527 static inline void
1528 jffs_unlink_node_from_range_list(struct jffs_file *f, struct jffs_node *node)
1529 {
1530         if (node->range_prev) {
1531                 node->range_prev->range_next = node->range_next;
1532         }
1533         else {
1534                 f->range_head = node->range_next;
1535         }
1536         if (node->range_next) {
1537                 node->range_next->range_prev = node->range_prev;
1538         }
1539         else {
1540                 f->range_tail = node->range_prev;
1541         }
1542 }
1543
1544
1545 /* Function used by jffs_remove_redundant_nodes() below.  This function
1546    classifies what kind of information a node adds to a file.  */
1547 static inline __u8
1548 jffs_classify_node(struct jffs_node *node)
1549 {
1550         __u8 mod_type = JFFS_MODIFY_INODE;
1551
1552         if (node->name_size) {
1553                 mod_type |= JFFS_MODIFY_NAME;
1554         }
1555         if (node->data_size || node->removed_size) {
1556                 mod_type |= JFFS_MODIFY_DATA;
1557         }
1558         return mod_type;
1559 }
1560
1561
1562 /* Remove redundant nodes from a file.  Mark the on-flash memory
1563    as dirty.  */
1564 static int
1565 jffs_remove_redundant_nodes(struct jffs_file *f)
1566 {
1567         struct jffs_node *newest_node;
1568         struct jffs_node *cur;
1569         struct jffs_node *prev;
1570         __u8 newest_type;
1571         __u8 mod_type;
1572         __u8 node_with_name_later = 0;
1573
1574         if (!(newest_node = f->version_tail)) {
1575                 return 0;
1576         }
1577
1578         /* What does the `newest_node' modify?  */
1579         newest_type = jffs_classify_node(newest_node);
1580         node_with_name_later = newest_type & JFFS_MODIFY_NAME;
1581
1582         D3(printk("jffs_remove_redundant_nodes(): ino: %u, name: \"%s\", "
1583                   "newest_type: %u\n", f->ino, (f->name ? f->name : ""),
1584                   newest_type));
1585
1586         /* Traverse the file's nodes and determine which of them that are
1587            superfluous.  Yeah, this might look very complex at first
1588            glance but it is actually very simple.  */
1589         for (cur = newest_node->version_prev; cur; cur = prev) {
1590                 prev = cur->version_prev;
1591                 mod_type = jffs_classify_node(cur);
1592                 if ((mod_type <= JFFS_MODIFY_INODE)
1593                     || ((newest_type & JFFS_MODIFY_NAME)
1594                         && (mod_type
1595                             <= (JFFS_MODIFY_INODE + JFFS_MODIFY_NAME)))
1596                     || (cur->data_size == 0 && cur->removed_size
1597                         && !cur->version_prev && node_with_name_later)) {
1598                         /* Yes, this node is redundant. Remove it.  */
1599                         D2(printk("jffs_remove_redundant_nodes(): "
1600                                   "Removing node: ino: %u, version: %u, "
1601                                   "mod_type: %u\n", cur->ino, cur->version,
1602                                   mod_type));
1603                         jffs_unlink_node_from_version_list(f, cur);
1604                         jffs_fmfree(f->c->fmc, cur->fm, cur);
1605                         jffs_free_node(cur);
1606                         DJM(no_jffs_node--);
1607                 }
1608                 else {
1609                         node_with_name_later |= (mod_type & JFFS_MODIFY_NAME);
1610                 }
1611         }
1612
1613         return 0;
1614 }
1615
1616
1617 /* Insert a file into the hash table.  */
1618 static int
1619 jffs_insert_file_into_hash(struct jffs_file *f)
1620 {
1621         int i = f->ino % f->c->hash_len;
1622
1623         D3(printk("jffs_insert_file_into_hash(): f->ino: %u\n", f->ino));
1624
1625         list_add(&f->hash, &f->c->hash[i]);
1626         return 0;
1627 }
1628
1629
1630 /* Insert a file into the file system tree.  */
1631 int
1632 jffs_insert_file_into_tree(struct jffs_file *f)
1633 {
1634         struct jffs_file *parent;
1635
1636         D3(printk("jffs_insert_file_into_tree(): name: \"%s\"\n",
1637                   (f->name ? f->name : "")));
1638
1639         if (!(parent = jffs_find_file(f->c, f->pino))) {
1640                 if (f->pino == 0) {
1641                         f->c->root = f;
1642                         f->parent = NULL;
1643                         f->sibling_prev = NULL;
1644                         f->sibling_next = NULL;
1645                         return 0;
1646                 }
1647                 else {
1648                         D1(printk("jffs_insert_file_into_tree(): Found "
1649                                   "inode with no parent and pino == %u\n",
1650                                   f->pino));
1651                         return -1;
1652                 }
1653         }
1654         f->parent = parent;
1655         f->sibling_next = parent->children;
1656         if (f->sibling_next) {
1657                 f->sibling_next->sibling_prev = f;
1658         }
1659         f->sibling_prev = NULL;
1660         parent->children = f;
1661         return 0;
1662 }
1663
1664
1665 /* Remove a file from the hash table.  */
1666 static int
1667 jffs_unlink_file_from_hash(struct jffs_file *f)
1668 {
1669         D3(printk("jffs_unlink_file_from_hash(): f: 0x%p, "
1670                   "ino %u\n", f, f->ino));
1671
1672         list_del(&f->hash);
1673         return 0;
1674 }
1675
1676
1677 /* Just remove the file from the parent's children.  Don't free
1678    any memory.  */
1679 int
1680 jffs_unlink_file_from_tree(struct jffs_file *f)
1681 {
1682         D3(printk("jffs_unlink_file_from_tree(): ino: %d, pino: %d, name: "
1683                   "\"%s\"\n", f->ino, f->pino, (f->name ? f->name : "")));
1684
1685         if (f->sibling_prev) {
1686                 f->sibling_prev->sibling_next = f->sibling_next;
1687         }
1688         else if (f->parent) {
1689                 D3(printk("f->parent=%p\n", f->parent));
1690                 f->parent->children = f->sibling_next;
1691         }
1692         if (f->sibling_next) {
1693                 f->sibling_next->sibling_prev = f->sibling_prev;
1694         }
1695         return 0;
1696 }
1697
1698
1699 /* Find a file with its inode number.  */
1700 struct jffs_file *
1701 jffs_find_file(struct jffs_control *c, __u32 ino)
1702 {
1703         struct jffs_file *f;
1704         int i = ino % c->hash_len;
1705
1706         D3(printk("jffs_find_file(): ino: %u\n", ino));
1707
1708         list_for_each_entry(f, &c->hash[i], hash) {
1709                 if (ino != f->ino)
1710                         continue;
1711                 D3(printk("jffs_find_file(): Found file with ino "
1712                                "%u. (name: \"%s\")\n",
1713                                ino, (f->name ? f->name : ""));
1714                 );
1715                 return f;
1716         }
1717         D3(printk("jffs_find_file(): Didn't find file "
1718                          "with ino %u.\n", ino);
1719         );
1720         return NULL;
1721 }
1722
1723
1724 /* Find a file in a directory.  We are comparing the names.  */
1725 struct jffs_file *
1726 jffs_find_child(struct jffs_file *dir, const char *name, int len)
1727 {
1728         struct jffs_file *f;
1729
1730         D3(printk("jffs_find_child()\n"));
1731
1732         for (f = dir->children; f; f = f->sibling_next) {
1733                 if (!f->deleted && f->name
1734                     && !strncmp(f->name, name, len)
1735                     && f->name[len] == '\0') {
1736                         break;
1737                 }
1738         }
1739
1740         D3(if (f) {
1741                 printk("jffs_find_child(): Found \"%s\".\n", f->name);
1742         }
1743         else {
1744                 char *copy = (char *) kmalloc(len + 1, GFP_KERNEL);
1745                 if (copy) {
1746                         memcpy(copy, name, len);
1747                         copy[len] = '\0';
1748                 }
1749                 printk("jffs_find_child(): Didn't find the file \"%s\".\n",
1750                        (copy ? copy : ""));
1751                 kfree(copy);
1752         });
1753
1754         return f;
1755 }
1756
1757
1758 /* Write a raw inode that takes up a certain amount of space in the flash
1759    memory.  At the end of the flash device, there is often space that is
1760    impossible to use.  At these times we want to mark this space as not
1761    used.  In the cases when the amount of space is greater or equal than
1762    a struct jffs_raw_inode, we write a "dummy node" that takes up this
1763    space.  The space after the raw inode, if it exists, is left as it is.
1764    Since this space after the raw inode contains JFFS_EMPTY_BITMASK bytes,
1765    we can compute the checksum of it; we don't have to manipulate it any
1766    further.
1767
1768    If the space left on the device is less than the size of a struct
1769    jffs_raw_inode, this space is filled with JFFS_DIRTY_BITMASK bytes.
1770    No raw inode is written this time.  */
1771 static int
1772 jffs_write_dummy_node(struct jffs_control *c, struct jffs_fm *dirty_fm)
1773 {
1774         struct jffs_fmcontrol *fmc = c->fmc;
1775         int err;
1776
1777         D1(printk("jffs_write_dummy_node(): dirty_fm->offset = 0x%08x, "
1778                   "dirty_fm->size = %u\n",
1779                   dirty_fm->offset, dirty_fm->size));
1780
1781         if (dirty_fm->size >= sizeof(struct jffs_raw_inode)) {
1782                 struct jffs_raw_inode raw_inode;
1783                 memset(&raw_inode, 0, sizeof(struct jffs_raw_inode));
1784                 raw_inode.magic = JFFS_MAGIC_BITMASK;
1785                 raw_inode.dsize = dirty_fm->size
1786                                   - sizeof(struct jffs_raw_inode);
1787                 raw_inode.dchksum = raw_inode.dsize * 0xff;
1788                 raw_inode.chksum
1789                 = jffs_checksum(&raw_inode, sizeof(struct jffs_raw_inode));
1790
1791                 if ((err = flash_safe_write(fmc->mtd,
1792                                             dirty_fm->offset,
1793                                             (u_char *)&raw_inode,
1794                                             sizeof(struct jffs_raw_inode)))
1795                     < 0) {
1796                         printk(KERN_ERR "JFFS: jffs_write_dummy_node: "
1797                                "flash_safe_write failed!\n");
1798                         return err;
1799                 }
1800         }
1801         else {
1802                 flash_safe_acquire(fmc->mtd);
1803                 flash_memset(fmc->mtd, dirty_fm->offset, 0, dirty_fm->size);
1804                 flash_safe_release(fmc->mtd);
1805         }
1806
1807         D3(printk("jffs_write_dummy_node(): Leaving...\n"));
1808         return 0;
1809 }
1810
1811
1812 /* Write a raw inode, possibly its name and possibly some data.  */
1813 int
1814 jffs_write_node(struct jffs_control *c, struct jffs_node *node,
1815                 struct jffs_raw_inode *raw_inode,
1816                 const char *name, const unsigned char *data,
1817                 int recoverable,
1818                 struct jffs_file *f)
1819 {
1820         struct jffs_fmcontrol *fmc = c->fmc;
1821         struct jffs_fm *fm;
1822         struct kvec node_iovec[4];
1823         unsigned long iovec_cnt;
1824
1825         __u32 pos;
1826         int err;
1827         __u32 slack = 0;
1828
1829         __u32 total_name_size = raw_inode->nsize
1830                                 + JFFS_GET_PAD_BYTES(raw_inode->nsize);
1831         __u32 total_data_size = raw_inode->dsize
1832                                 + JFFS_GET_PAD_BYTES(raw_inode->dsize);
1833         __u32 total_size = sizeof(struct jffs_raw_inode)
1834                            + total_name_size + total_data_size;
1835         
1836         /* If this node isn't something that will eventually let
1837            GC free even more space, then don't allow it unless
1838            there's at least max_chunk_size space still available
1839         */
1840         if (!recoverable)
1841                 slack = fmc->max_chunk_size;
1842                 
1843
1844         /* Fire the retrorockets and shoot the fruiton torpedoes, sir!  */
1845
1846         ASSERT(if (!node) {
1847                 printk("jffs_write_node(): node == NULL\n");
1848                 return -EINVAL;
1849         });
1850         ASSERT(if (raw_inode && raw_inode->nsize && !name) {
1851                 printk("*** jffs_write_node(): nsize = %u but name == NULL\n",
1852                        raw_inode->nsize);
1853                 return -EINVAL;
1854         });
1855
1856         D1(printk("jffs_write_node(): filename = \"%s\", ino = %u, "
1857                   "total_size = %u\n",
1858                   (name ? name : ""), raw_inode->ino,
1859                   total_size));
1860
1861         jffs_fm_write_lock(fmc);
1862
1863 retry:
1864         fm = NULL;
1865         err = 0;
1866         while (!fm) {
1867
1868                 /* Deadlocks suck. */
1869                 while(fmc->free_size < fmc->min_free_size + total_size + slack) {
1870                         jffs_fm_write_unlock(fmc);
1871                         if (!JFFS_ENOUGH_SPACE(c, total_size + slack))
1872                                 return -ENOSPC;
1873                         jffs_fm_write_lock(fmc);
1874                 }
1875
1876                 /* First try to allocate some flash memory.  */
1877                 err = jffs_fmalloc(fmc, total_size, node, &fm);
1878                 
1879                 if (err == -ENOSPC) {
1880                         /* Just out of space. GC and try again */
1881                         if (fmc->dirty_size < fmc->sector_size) {
1882                                 D(printk("jffs_write_node(): jffs_fmalloc(0x%p, %u) "
1883                                          "failed, no dirty space to GC\n", fmc,
1884                                          total_size));
1885                                 return err;
1886                         }
1887                         
1888                         D1(printk(KERN_INFO "jffs_write_node(): Calling jffs_garbage_collect_now()\n"));
1889                         jffs_fm_write_unlock(fmc);
1890                         if ((err = jffs_garbage_collect_now(c))) {
1891                                 D(printk("jffs_write_node(): jffs_garbage_collect_now() failed\n"));
1892                                 return err;
1893                         }
1894                         jffs_fm_write_lock(fmc);
1895                         continue;
1896                 } 
1897
1898                 if (err < 0) {
1899                         jffs_fm_write_unlock(fmc);
1900
1901                         D(printk("jffs_write_node(): jffs_fmalloc(0x%p, %u) "
1902                                  "failed!\n", fmc, total_size));
1903                         return err;
1904                 }
1905
1906                 if (!fm->nodes) {
1907                         /* The jffs_fm struct that we got is not good enough.
1908                            Make that space dirty and try again  */
1909                         if ((err = jffs_write_dummy_node(c, fm)) < 0) {
1910                                 kfree(fm);
1911                                 DJM(no_jffs_fm--);
1912                                 jffs_fm_write_unlock(fmc);
1913                                 D(printk("jffs_write_node(): "
1914                                          "jffs_write_dummy_node(): Failed!\n"));
1915                                 return err;
1916                         }
1917                         fm = NULL;
1918                 }
1919         } /* while(!fm) */
1920         node->fm = fm;
1921
1922         ASSERT(if (fm->nodes == 0) {
1923                 printk(KERN_ERR "jffs_write_node(): fm->nodes == 0\n");
1924         });
1925
1926         pos = node->fm->offset;
1927
1928         /* Increment the version number here. We can't let the caller
1929            set it beforehand, because we might have had to do GC on a node
1930            of this file - and we'd end up reusing version numbers.
1931         */
1932         if (f) {
1933                 raw_inode->version = f->highest_version + 1;
1934                 D1(printk (KERN_NOTICE "jffs_write_node(): setting version of %s to %d\n", f->name, raw_inode->version));
1935
1936                 /* if the file was deleted, set the deleted bit in the raw inode */
1937                 if (f->deleted)
1938                         raw_inode->deleted = 1;
1939         }
1940
1941         /* Compute the checksum for the data and name chunks.  */
1942         raw_inode->dchksum = jffs_checksum(data, raw_inode->dsize);
1943         raw_inode->nchksum = jffs_checksum(name, raw_inode->nsize);
1944
1945         /* The checksum is calculated without the chksum and accurate
1946            fields so set them to zero first.  */
1947         raw_inode->accurate = 0;
1948         raw_inode->chksum = 0;
1949         raw_inode->chksum = jffs_checksum(raw_inode,
1950                                           sizeof(struct jffs_raw_inode));
1951         raw_inode->accurate = 0xff;
1952
1953         D3(printk("jffs_write_node(): About to write this raw inode to the "
1954                   "flash at pos 0x%lx:\n", (long)pos));
1955         D3(jffs_print_raw_inode(raw_inode));
1956
1957         /* The actual raw JFFS node */
1958         node_iovec[0].iov_base = (void *) raw_inode;
1959         node_iovec[0].iov_len = (size_t) sizeof(struct jffs_raw_inode);
1960         iovec_cnt = 1;
1961
1962         /* Get name and size if there is one */
1963         if (raw_inode->nsize) {
1964                 node_iovec[iovec_cnt].iov_base = (void *) name;
1965                 node_iovec[iovec_cnt].iov_len = (size_t) raw_inode->nsize;
1966                 iovec_cnt++;
1967
1968                 if (JFFS_GET_PAD_BYTES(raw_inode->nsize)) {
1969                         static unsigned char allff[3]={255,255,255};
1970                         /* Add some extra padding if necessary */
1971                         node_iovec[iovec_cnt].iov_base = allff;
1972                         node_iovec[iovec_cnt].iov_len =
1973                                 JFFS_GET_PAD_BYTES(raw_inode->nsize);
1974                         iovec_cnt++;
1975                 }
1976         }
1977
1978         /* Get data and size if there is any */
1979         if (raw_inode->dsize) {
1980                 node_iovec[iovec_cnt].iov_base = (void *) data;
1981                 node_iovec[iovec_cnt].iov_len = (size_t) raw_inode->dsize;
1982                 iovec_cnt++;
1983                 /* No need to pad this because we're not actually putting
1984                    anything after it.
1985                 */
1986         }
1987
1988         if ((err = flash_safe_writev(fmc->mtd, node_iovec, iovec_cnt,
1989                                     pos)) < 0) {
1990                 jffs_fmfree_partly(fmc, fm, 0);
1991                 jffs_fm_write_unlock(fmc);
1992                 printk(KERN_ERR "JFFS: jffs_write_node: Failed to write, "
1993                        "requested %i, wrote %i\n", total_size, err);
1994                 goto retry;
1995         }
1996         if (raw_inode->deleted)
1997                 f->deleted = 1;
1998
1999         jffs_fm_write_unlock(fmc);
2000         D3(printk("jffs_write_node(): Leaving...\n"));
2001         return raw_inode->dsize;
2002 } /* jffs_write_node()  */
2003
2004
2005 /* Read data from the node and write it to the buffer.  'node_offset'
2006    is how much we have read from this particular node before and which
2007    shouldn't be read again.  'max_size' is how much space there is in
2008    the buffer.  */
2009 static int
2010 jffs_get_node_data(struct jffs_file *f, struct jffs_node *node, 
2011                    unsigned char *buf,__u32 node_offset, __u32 max_size)
2012 {
2013         struct jffs_fmcontrol *fmc = f->c->fmc;
2014         __u32 pos = node->fm->offset + node->fm_offset + node_offset;
2015         __u32 avail = node->data_size - node_offset;
2016         __u32 r;
2017
2018         D2(printk("  jffs_get_node_data(): file: \"%s\", ino: %u, "
2019                   "version: %u, node_offset: %u\n",
2020                   f->name, node->ino, node->version, node_offset));
2021
2022         r = min(avail, max_size);
2023         D3(printk(KERN_NOTICE "jffs_get_node_data\n"));
2024         flash_safe_read(fmc->mtd, pos, buf, r);
2025
2026         D3(printk("  jffs_get_node_data(): Read %u byte%s.\n",
2027                   r, (r == 1 ? "" : "s")));
2028
2029         return r;
2030 }
2031
2032
2033 /* Read data from the file's nodes.  Write the data to the buffer
2034    'buf'.  'read_offset' tells how much data we should skip.  */
2035 int
2036 jffs_read_data(struct jffs_file *f, unsigned char *buf, __u32 read_offset,
2037                __u32 size)
2038 {
2039         struct jffs_node *node;
2040         __u32 read_data = 0; /* Total amount of read data.  */
2041         __u32 node_offset = 0;
2042         __u32 pos = 0; /* Number of bytes traversed.  */
2043
2044         D2(printk("jffs_read_data(): file = \"%s\", read_offset = %d, "
2045                   "size = %u\n",
2046                   (f->name ? f->name : ""), read_offset, size));
2047
2048         if (read_offset >= f->size) {
2049                 D(printk("  f->size: %d\n", f->size));
2050                 return 0;
2051         }
2052
2053         /* First find the node to read data from.  */
2054         node = f->range_head;
2055         while (pos <= read_offset) {
2056                 node_offset = read_offset - pos;
2057                 if (node_offset >= node->data_size) {
2058                         pos += node->data_size;
2059                         node = node->range_next;
2060                 }
2061                 else {
2062                         break;
2063                 }
2064         }
2065
2066         /* "Cats are living proof that not everything in nature
2067            has to be useful."
2068            - Garrison Keilor ('97)  */
2069
2070         /* Fill the buffer.  */
2071         while (node && (read_data < size)) {
2072                 int r;
2073                 if (!node->fm) {
2074                         /* This node does not refer to real data.  */
2075                         r = min(size - read_data,
2076                                      node->data_size - node_offset);
2077                         memset(&buf[read_data], 0, r);
2078                 }
2079                 else if ((r = jffs_get_node_data(f, node, &buf[read_data],
2080                                                  node_offset,
2081                                                  size - read_data)) < 0) {
2082                         return r;
2083                 }
2084                 read_data += r;
2085                 node_offset = 0;
2086                 node = node->range_next;
2087         }
2088         D3(printk("  jffs_read_data(): Read %u bytes.\n", read_data));
2089         return read_data;
2090 }
2091
2092
2093 /* Used for traversing all nodes in the hash table.  */
2094 int
2095 jffs_foreach_file(struct jffs_control *c, int (*func)(struct jffs_file *))
2096 {
2097         int pos;
2098         int r;
2099         int result = 0;
2100
2101         for (pos = 0; pos < c->hash_len; pos++) {
2102                 struct jffs_file *f, *next;
2103
2104                 /* We must do _safe, because 'func' might remove the
2105                    current file 'f' from the list.  */
2106                 list_for_each_entry_safe(f, next, &c->hash[pos], hash) {
2107                         r = func(f);
2108                         if (r < 0)
2109                                 return r;
2110                         result += r;
2111                 }
2112         }
2113
2114         return result;
2115 }
2116
2117
2118 /* Free all nodes associated with a file.  */
2119 static int
2120 jffs_free_node_list(struct jffs_file *f)
2121 {
2122         struct jffs_node *node;
2123         struct jffs_node *p;
2124
2125         D3(printk("jffs_free_node_list(): f #%u, \"%s\"\n",
2126                   f->ino, (f->name ? f->name : "")));
2127         node = f->version_head;
2128         while (node) {
2129                 p = node;
2130                 node = node->version_next;
2131                 jffs_free_node(p);
2132                 DJM(no_jffs_node--);
2133         }
2134         return 0;
2135 }
2136
2137
2138 /* Free a file and its name.  */
2139 static int
2140 jffs_free_file(struct jffs_file *f)
2141 {
2142         D3(printk("jffs_free_file: f #%u, \"%s\"\n",
2143                   f->ino, (f->name ? f->name : "")));
2144
2145         if (f->name) {
2146                 kfree(f->name);
2147                 DJM(no_name--);
2148         }
2149         kfree(f);
2150         no_jffs_file--;
2151         return 0;
2152 }
2153
2154 static long
2155 jffs_get_file_count(void)
2156 {
2157         return no_jffs_file;
2158 }
2159
2160 /* See if a file is deleted. If so, mark that file's nodes as obsolete.  */
2161 int
2162 jffs_possibly_delete_file(struct jffs_file *f)
2163 {
2164         struct jffs_node *n;
2165
2166         D3(printk("jffs_possibly_delete_file(): ino: %u\n",
2167                   f->ino));
2168
2169         ASSERT(if (!f) {
2170                 printk(KERN_ERR "jffs_possibly_delete_file(): f == NULL\n");
2171                 return -1;
2172         });
2173
2174         if (f->deleted) {
2175                 /* First try to remove all older versions.  Commence with
2176                    the oldest node.  */
2177                 for (n = f->version_head; n; n = n->version_next) {
2178                         if (!n->fm) {
2179                                 continue;
2180                         }
2181                         if (jffs_fmfree(f->c->fmc, n->fm, n) < 0) {
2182                                 break;
2183                         }
2184                 }
2185                 /* Unlink the file from the filesystem.  */
2186                 if (!f->c->building_fs) {
2187                         jffs_unlink_file_from_tree(f);
2188                 }
2189                 jffs_unlink_file_from_hash(f);
2190                 jffs_free_node_list(f);
2191                 jffs_free_file(f);
2192         }
2193         return 0;
2194 }
2195
2196
2197 /* Used in conjunction with jffs_foreach_file() to count the number
2198    of files in the file system.  */
2199 int
2200 jffs_file_count(struct jffs_file *f)
2201 {
2202         return 1;
2203 }
2204
2205
2206 /* Build up a file's range list from scratch by going through the
2207    version list.  */
2208 static int
2209 jffs_build_file(struct jffs_file *f)
2210 {
2211         struct jffs_node *n;
2212
2213         D3(printk("jffs_build_file(): ino: %u, name: \"%s\"\n",
2214                   f->ino, (f->name ? f->name : "")));
2215
2216         for (n = f->version_head; n; n = n->version_next) {
2217                 jffs_update_file(f, n);
2218         }
2219         return 0;
2220 }
2221
2222
2223 /* Remove an amount of data from a file. If this amount of data is
2224    zero, that could mean that a node should be split in two parts.
2225    We remove or change the appropriate nodes in the lists.
2226
2227    Starting offset of area to be removed is node->data_offset,
2228    and the length of the area is in node->removed_size.   */
2229 static int
2230 jffs_delete_data(struct jffs_file *f, struct jffs_node *node)
2231 {
2232         struct jffs_node *n;
2233         __u32 offset = node->data_offset;
2234         __u32 remove_size = node->removed_size;
2235
2236         D3(printk("jffs_delete_data(): offset = %u, remove_size = %u\n",
2237                   offset, remove_size));
2238
2239         if (remove_size == 0
2240             && f->range_tail
2241             && f->range_tail->data_offset + f->range_tail->data_size
2242                == offset) {
2243                 /* A simple append; nothing to remove or no node to split.  */
2244                 return 0;
2245         }
2246
2247         /* Find the node where we should begin the removal.  */
2248         for (n = f->range_head; n; n = n->range_next) {
2249                 if (n->data_offset + n->data_size > offset) {
2250                         break;
2251                 }
2252         }
2253         if (!n) {
2254                 /* If there's no data in the file there's no data to
2255                    remove either.  */
2256                 return 0;
2257         }
2258
2259         if (n->data_offset > offset) {
2260                 /* XXX: Not implemented yet.  */
2261                 printk(KERN_WARNING "JFFS: An unexpected situation "
2262                        "occurred in jffs_delete_data.\n");
2263         }
2264         else if (n->data_offset < offset) {
2265                 /* See if the node has to be split into two parts.  */
2266                 if (n->data_offset + n->data_size > offset + remove_size) {
2267                         /* Do the split.  */
2268                         struct jffs_node *new_node;
2269                         D3(printk("jffs_delete_data(): Split node with "
2270                                   "version number %u.\n", n->version));
2271
2272                         if (!(new_node = jffs_alloc_node())) {
2273                                 D(printk("jffs_delete_data(): -ENOMEM\n"));
2274                                 return -ENOMEM;
2275                         }
2276                         DJM(no_jffs_node++);
2277
2278                         new_node->ino = n->ino;
2279                         new_node->version = n->version;
2280                         new_node->data_offset = offset;
2281                         new_node->data_size = n->data_size - (remove_size + (offset - n->data_offset));
2282                         new_node->fm_offset = n->fm_offset + (remove_size + (offset - n->data_offset));
2283                         new_node->name_size = n->name_size;
2284                         new_node->fm = n->fm;
2285                         new_node->version_prev = n;
2286                         new_node->version_next = n->version_next;
2287                         if (new_node->version_next) {
2288                                 new_node->version_next->version_prev
2289                                 = new_node;
2290                         }
2291                         else {
2292                                 f->version_tail = new_node;
2293                         }
2294                         n->version_next = new_node;
2295                         new_node->range_prev = n;
2296                         new_node->range_next = n->range_next;
2297                         if (new_node->range_next) {
2298                                 new_node->range_next->range_prev = new_node;
2299                         }
2300                         else {
2301                                 f->range_tail = new_node;
2302                         }
2303                         /* A very interesting can of worms.  */
2304                         n->range_next = new_node;
2305                         n->data_size = offset - n->data_offset;
2306                         if (new_node->fm)
2307                                 jffs_add_node(new_node);
2308                         else {
2309                                 D1(printk(KERN_WARNING "jffs_delete_data(): Splitting an empty node (file hold).\n!"));
2310                                 D1(printk(KERN_WARNING "FIXME: Did dwmw2 do the right thing here?\n"));
2311                         }
2312                         n = new_node->range_next;
2313                         remove_size = 0;
2314                 }
2315                 else {
2316                         /* No.  No need to split the node.  Just remove
2317                            the end of the node.  */
2318                         int r = min(n->data_offset + n->data_size
2319                                          - offset, remove_size);
2320                         n->data_size -= r;
2321                         remove_size -= r;
2322                         n = n->range_next;
2323                 }
2324         }
2325
2326         /* Remove as many nodes as necessary.  */
2327         while (n && remove_size) {
2328                 if (n->data_size <= remove_size) {
2329                         struct jffs_node *p = n;
2330                         remove_size -= n->data_size;
2331                         n = n->range_next;
2332                         D3(printk("jffs_delete_data(): Removing node: "
2333                                   "ino: %u, version: %u%s\n",
2334                                   p->ino, p->version,
2335                                   (p->fm ? "" : " (virtual)")));
2336                         if (p->fm) {
2337                                 jffs_fmfree(f->c->fmc, p->fm, p);
2338                         }
2339                         jffs_unlink_node_from_range_list(f, p);
2340                         jffs_unlink_node_from_version_list(f, p);
2341                         jffs_free_node(p);
2342                         DJM(no_jffs_node--);
2343                 }
2344                 else {
2345                         n->data_size -= remove_size;
2346                         n->fm_offset += remove_size;
2347                         n->data_offset -= (node->removed_size - remove_size);
2348                         n = n->range_next;
2349                         break;
2350                 }
2351         }
2352
2353         /* Adjust the following nodes' information about offsets etc.  */
2354         while (n && node->removed_size) {
2355                 n->data_offset -= node->removed_size;
2356                 n = n->range_next;
2357         }
2358
2359         if (node->removed_size > (f->size - node->data_offset)) {
2360                 /* It's possible that the removed_size is in fact
2361                  * greater than the amount of data we actually thought
2362                  * were present in the first place - some of the nodes 
2363                  * which this node originally obsoleted may already have
2364                  * been deleted from the flash by subsequent garbage 
2365                  * collection.
2366                  *
2367                  * If this is the case, don't let f->size go negative.
2368                  * Bad things would happen :)
2369                  */
2370                 f->size = node->data_offset;
2371         } else {
2372                 f->size -= node->removed_size;
2373         }
2374         D3(printk("jffs_delete_data(): f->size = %d\n", f->size));
2375         return 0;
2376 } /* jffs_delete_data()  */
2377
2378
2379 /* Insert some data into a file.  Prior to the call to this function,
2380    jffs_delete_data should be called.  */
2381 static int
2382 jffs_insert_data(struct jffs_file *f, struct jffs_node *node)
2383 {
2384         D3(printk("jffs_insert_data(): node->data_offset = %u, "
2385                   "node->data_size = %u, f->size = %u\n",
2386                   node->data_offset, node->data_size, f->size));
2387
2388         /* Find the position where we should insert data.  */
2389         retry:
2390         if (node->data_offset == f->size) {
2391                 /* A simple append.  This is the most common operation.  */
2392                 node->range_next = NULL;
2393                 node->range_prev = f->range_tail;
2394                 if (node->range_prev) {
2395                         node->range_prev->range_next = node;
2396                 }
2397                 f->range_tail = node;
2398                 f->size += node->data_size;
2399                 if (!f->range_head) {
2400                         f->range_head = node;
2401                 }
2402         }
2403         else if (node->data_offset < f->size) {
2404                 /* Trying to insert data into the middle of the file.  This
2405                    means no problem because jffs_delete_data() has already
2406                    prepared the range list for us.  */
2407                 struct jffs_node *n;
2408
2409                 /* Find the correct place for the insertion and then insert
2410                    the node.  */
2411                 for (n = f->range_head; n; n = n->range_next) {
2412                         D2(printk("Cool stuff's happening!\n"));
2413
2414                         if (n->data_offset == node->data_offset) {
2415                                 node->range_prev = n->range_prev;
2416                                 if (node->range_prev) {
2417                                         node->range_prev->range_next = node;
2418                                 }
2419                                 else {
2420                                         f->range_head = node;
2421                                 }
2422                                 node->range_next = n;
2423                                 n->range_prev = node;
2424                                 break;
2425                         }
2426                         ASSERT(else if (n->data_offset + n->data_size >
2427                                         node->data_offset) {
2428                                 printk(KERN_ERR "jffs_insert_data(): "
2429                                        "Couldn't find a place to insert "
2430                                        "the data!\n");
2431                                 return -1;
2432                         });
2433                 }
2434
2435                 /* Adjust later nodes' offsets etc.  */
2436                 n = node->range_next;
2437                 while (n) {
2438                         n->data_offset += node->data_size;
2439                         n = n->range_next;
2440                 }
2441                 f->size += node->data_size;
2442         }
2443         else if (node->data_offset > f->size) {
2444                 /* Okay.  This is tricky.  This means that we want to insert
2445                    data at a place that is beyond the limits of the file as
2446                    it is constructed right now.  This is actually a common
2447                    event that for instance could occur during the mounting
2448                    of the file system if a large file have been truncated,
2449                    rewritten and then only partially garbage collected.  */
2450
2451                 struct jffs_node *n;
2452
2453                 /* We need a place holder for the data that is missing in
2454                    front of this insertion.  This "virtual node" will not
2455                    be associated with any space on the flash device.  */
2456                 struct jffs_node *virtual_node;
2457                 if (!(virtual_node = jffs_alloc_node())) {
2458                         return -ENOMEM;
2459                 }
2460
2461                 D(printk("jffs_insert_data: Inserting a virtual node.\n"));
2462                 D(printk("  node->data_offset = %u\n", node->data_offset));
2463                 D(printk("  f->size = %u\n", f->size));
2464
2465                 virtual_node->ino = node->ino;
2466                 virtual_node->version = node->version;
2467                 virtual_node->removed_size = 0;
2468                 virtual_node->fm_offset = 0;
2469                 virtual_node->name_size = 0;
2470                 virtual_node->fm = NULL; /* This is a virtual data holder.  */
2471                 virtual_node->version_prev = NULL;
2472                 virtual_node->version_next = NULL;
2473                 virtual_node->range_next = NULL;
2474
2475                 /* Are there any data at all in the file yet?  */
2476                 if (f->range_head) {
2477                         virtual_node->data_offset
2478                         = f->range_tail->data_offset
2479                           + f->range_tail->data_size;
2480                         virtual_node->data_size
2481                         = node->data_offset - virtual_node->data_offset;
2482                         virtual_node->range_prev = f->range_tail;
2483                         f->range_tail->range_next = virtual_node;
2484                 }
2485                 else {
2486                         virtual_node->data_offset = 0;
2487                         virtual_node->data_size = node->data_offset;
2488                         virtual_node->range_prev = NULL;
2489                         f->range_head = virtual_node;
2490                 }
2491
2492                 f->range_tail = virtual_node;
2493                 f->size += virtual_node->data_size;
2494
2495                 /* Insert this virtual node in the version list as well.  */
2496                 for (n = f->version_head; n ; n = n->version_next) {
2497                         if (n->version == virtual_node->version) {
2498                                 virtual_node->version_prev = n->version_prev;
2499                                 n->version_prev = virtual_node;
2500                                 if (virtual_node->version_prev) {
2501                                         virtual_node->version_prev
2502                                         ->version_next = virtual_node;
2503                                 }
2504                                 else {
2505                                         f->version_head = virtual_node;
2506                                 }
2507                                 virtual_node->version_next = n;
2508                                 break;
2509                         }
2510                 }
2511
2512                 D(jffs_print_node(virtual_node));
2513
2514                 /* Make a new try to insert the node.  */
2515                 goto retry;
2516         }
2517
2518         D3(printk("jffs_insert_data(): f->size = %d\n", f->size));
2519         return 0;
2520 }
2521
2522
2523 /* A new node (with data) has been added to the file and now the range
2524    list has to be modified.  */
2525 static int
2526 jffs_update_file(struct jffs_file *f, struct jffs_node *node)
2527 {
2528         int err;
2529
2530         D3(printk("jffs_update_file(): ino: %u, version: %u\n",
2531                   f->ino, node->version));
2532
2533         if (node->data_size == 0) {
2534                 if (node->removed_size == 0) {
2535                         /* data_offset == X  */
2536                         /* data_size == 0  */
2537                         /* remove_size == 0  */
2538                 }
2539                 else {
2540                         /* data_offset == X  */
2541                         /* data_size == 0  */
2542                         /* remove_size != 0  */
2543                         if ((err = jffs_delete_data(f, node)) < 0) {
2544                                 return err;
2545                         }
2546                 }
2547         }
2548         else {
2549                 /* data_offset == X  */
2550                 /* data_size != 0  */
2551                 /* remove_size == Y  */
2552                 if ((err = jffs_delete_data(f, node)) < 0) {
2553                         return err;
2554                 }
2555                 if ((err = jffs_insert_data(f, node)) < 0) {
2556                         return err;
2557                 }
2558         }
2559         return 0;
2560 }
2561
2562 /* Print the contents of a file.  */
2563 #if 0
2564 int
2565 jffs_print_file(struct jffs_file *f)
2566 {
2567         D(int i);
2568         D(printk("jffs_file: 0x%p\n", f));
2569         D(printk("{\n"));
2570         D(printk("        0x%08x, /* ino  */\n", f->ino));
2571         D(printk("        0x%08x, /* pino  */\n", f->pino));
2572         D(printk("        0x%08x, /* mode  */\n", f->mode));
2573         D(printk("        0x%04x,     /* uid  */\n", f->uid));
2574         D(printk("        0x%04x,     /* gid  */\n", f->gid));
2575         D(printk("        0x%08x, /* atime  */\n", f->atime));
2576         D(printk("        0x%08x, /* mtime  */\n", f->mtime));
2577         D(printk("        0x%08x, /* ctime  */\n", f->ctime));
2578         D(printk("        0x%02x,       /* nsize  */\n", f->nsize));
2579         D(printk("        0x%02x,       /* nlink  */\n", f->nlink));
2580         D(printk("        0x%02x,       /* deleted  */\n", f->deleted));
2581         D(printk("        \"%s\", ", (f->name ? f->name : "")));
2582         D(for (i = strlen(f->name ? f->name : ""); i < 8; ++i) {
2583                 printk(" ");
2584         });
2585         D(printk("/* name  */\n"));
2586         D(printk("        0x%08x, /* size  */\n", f->size));
2587         D(printk("        0x%08x, /* highest_version  */\n",
2588                  f->highest_version));
2589         D(printk("        0x%p, /* c  */\n", f->c));
2590         D(printk("        0x%p, /* parent  */\n", f->parent));
2591         D(printk("        0x%p, /* children  */\n", f->children));
2592         D(printk("        0x%p, /* sibling_prev  */\n", f->sibling_prev));
2593         D(printk("        0x%p, /* sibling_next  */\n", f->sibling_next));
2594         D(printk("        0x%p, /* hash_prev  */\n", f->hash.prev));
2595         D(printk("        0x%p, /* hash_next  */\n", f->hash.next));
2596         D(printk("        0x%p, /* range_head  */\n", f->range_head));
2597         D(printk("        0x%p, /* range_tail  */\n", f->range_tail));
2598         D(printk("        0x%p, /* version_head  */\n", f->version_head));
2599         D(printk("        0x%p, /* version_tail  */\n", f->version_tail));
2600         D(printk("}\n"));
2601         return 0;
2602 }
2603 #endif  /*  0  */
2604
2605 void
2606 jffs_print_hash_table(struct jffs_control *c)
2607 {
2608         int i;
2609
2610         printk("JFFS: Dumping the file system's hash table...\n");
2611         for (i = 0; i < c->hash_len; i++) {
2612                 struct jffs_file *f;
2613                 list_for_each_entry(f, &c->hash[i], hash) {
2614                         printk("*** c->hash[%u]: \"%s\" "
2615                                "(ino: %u, pino: %u)\n",
2616                                i, (f->name ? f->name : ""),
2617                                f->ino, f->pino);
2618                 }
2619         }
2620 }
2621
2622
2623 void
2624 jffs_print_tree(struct jffs_file *first_file, int indent)
2625 {
2626         struct jffs_file *f;
2627         char *space;
2628         int dir;
2629
2630         if (!first_file) {
2631                 return;
2632         }
2633
2634         if (!(space = (char *) kmalloc(indent + 1, GFP_KERNEL))) {
2635                 printk("jffs_print_tree(): Out of memory!\n");
2636                 return;
2637         }
2638
2639         memset(space, ' ', indent);
2640         space[indent] = '\0';
2641
2642         for (f = first_file; f; f = f->sibling_next) {
2643                 dir = S_ISDIR(f->mode);
2644                 printk("%s%s%s (ino: %u, highest_version: %u, size: %u)\n",
2645                        space, (f->name ? f->name : ""), (dir ? "/" : ""),
2646                        f->ino, f->highest_version, f->size);
2647                 if (dir) {
2648                         jffs_print_tree(f->children, indent + 2);
2649                 }
2650         }
2651
2652         kfree(space);
2653 }
2654
2655
2656 #if defined(JFFS_MEMORY_DEBUG) && JFFS_MEMORY_DEBUG
2657 void
2658 jffs_print_memory_allocation_statistics(void)
2659 {
2660         static long printout;
2661         printk("________ Memory printout #%ld ________\n", ++printout);
2662         printk("no_jffs_file = %ld\n", no_jffs_file);
2663         printk("no_jffs_node = %ld\n", no_jffs_node);
2664         printk("no_jffs_control = %ld\n", no_jffs_control);
2665         printk("no_jffs_raw_inode = %ld\n", no_jffs_raw_inode);
2666         printk("no_jffs_node_ref = %ld\n", no_jffs_node_ref);
2667         printk("no_jffs_fm = %ld\n", no_jffs_fm);
2668         printk("no_jffs_fmcontrol = %ld\n", no_jffs_fmcontrol);
2669         printk("no_hash = %ld\n", no_hash);
2670         printk("no_name = %ld\n", no_name);
2671         printk("\n");
2672 }
2673 #endif
2674
2675
2676 /* Rewrite `size' bytes, and begin at `node'.  */
2677 static int
2678 jffs_rewrite_data(struct jffs_file *f, struct jffs_node *node, __u32 size)
2679 {
2680         struct jffs_control *c = f->c;
2681         struct jffs_fmcontrol *fmc = c->fmc;
2682         struct jffs_raw_inode raw_inode;
2683         struct jffs_node *new_node;
2684         struct jffs_fm *fm;
2685         __u32 pos;
2686         __u32 pos_dchksum;
2687         __u32 total_name_size;
2688         __u32 total_data_size;
2689         __u32 total_size;
2690         int err;
2691
2692         D1(printk("***jffs_rewrite_data(): node: %u, name: \"%s\", size: %u\n",
2693                   f->ino, (f->name ? f->name : "(null)"), size));
2694
2695         /* Create and initialize the new node.  */
2696         if (!(new_node = jffs_alloc_node())) {
2697                 D(printk("jffs_rewrite_data(): "
2698                          "Failed to allocate node.\n"));
2699                 return -ENOMEM;
2700         }
2701         DJM(no_jffs_node++);
2702         new_node->data_offset = node->data_offset;
2703         new_node->removed_size = size;
2704         total_name_size = JFFS_PAD(f->nsize);
2705         total_data_size = JFFS_PAD(size);
2706         total_size = sizeof(struct jffs_raw_inode)
2707                      + total_name_size + total_data_size;
2708         new_node->fm_offset = sizeof(struct jffs_raw_inode)
2709                               + total_name_size;
2710
2711 retry:
2712         jffs_fm_write_lock(fmc);
2713         err = 0;
2714
2715         if ((err = jffs_fmalloc(fmc, total_size, new_node, &fm)) < 0) {
2716                 DJM(no_jffs_node--);
2717                 jffs_fm_write_unlock(fmc);
2718                 D(printk("jffs_rewrite_data(): Failed to allocate fm.\n"));
2719                 jffs_free_node(new_node);
2720                 return err;
2721         }
2722         else if (!fm->nodes) {
2723                 /* The jffs_fm struct that we got is not big enough.  */
2724                 /* This should never happen, because we deal with this case
2725                    in jffs_garbage_collect_next().*/
2726                 printk(KERN_WARNING "jffs_rewrite_data(): Allocated node is too small (%d bytes of %d)\n", fm->size, total_size);
2727                 if ((err = jffs_write_dummy_node(c, fm)) < 0) {
2728                         D(printk("jffs_rewrite_data(): "
2729                                  "jffs_write_dummy_node() Failed!\n"));
2730                 } else {
2731                         err = -ENOSPC;
2732                 }
2733                 DJM(no_jffs_fm--);
2734                 jffs_fm_write_unlock(fmc);
2735                 kfree(fm);
2736                 
2737                 return err;
2738         }
2739         new_node->fm = fm;
2740
2741         /* Initialize the raw inode.  */
2742         raw_inode.magic = JFFS_MAGIC_BITMASK;
2743         raw_inode.ino = f->ino;
2744         raw_inode.pino = f->pino;
2745         raw_inode.version = f->highest_version + 1;
2746         raw_inode.mode = f->mode;
2747         raw_inode.uid = f->uid;
2748         raw_inode.gid = f->gid;
2749         raw_inode.atime = f->atime;
2750         raw_inode.mtime = f->mtime;
2751         raw_inode.ctime = f->ctime;
2752         raw_inode.offset = node->data_offset;
2753         raw_inode.dsize = size;
2754         raw_inode.rsize = size;
2755         raw_inode.nsize = f->nsize;
2756         raw_inode.nlink = f->nlink;
2757         raw_inode.spare = 0;
2758         raw_inode.rename = 0;
2759         raw_inode.deleted = f->deleted;
2760         raw_inode.accurate = 0xff;
2761         raw_inode.dchksum = 0;
2762         raw_inode.nchksum = 0;
2763
2764         pos = new_node->fm->offset;
2765         pos_dchksum = pos +JFFS_RAW_INODE_DCHKSUM_OFFSET;
2766
2767         D3(printk("jffs_rewrite_data(): Writing this raw inode "
2768                   "to pos 0x%ul.\n", pos));
2769         D3(jffs_print_raw_inode(&raw_inode));
2770
2771         if ((err = flash_safe_write(fmc->mtd, pos,
2772                                     (u_char *) &raw_inode,
2773                                     sizeof(struct jffs_raw_inode)
2774                                     - sizeof(__u32)
2775                                     - sizeof(__u16) - sizeof(__u16))) < 0) {
2776                 jffs_fmfree_partly(fmc, fm,
2777                                    total_name_size + total_data_size);
2778                 jffs_fm_write_unlock(fmc);
2779                 printk(KERN_ERR "JFFS: jffs_rewrite_data: Write error during "
2780                         "rewrite. (raw inode)\n");
2781                 printk(KERN_ERR "JFFS: jffs_rewrite_data: Now retrying "
2782                         "rewrite. (raw inode)\n");
2783                 goto retry;
2784         }
2785         pos += sizeof(struct jffs_raw_inode);
2786
2787         /* Write the name to the flash memory.  */
2788         if (f->nsize) {
2789                 D3(printk("jffs_rewrite_data(): Writing name \"%s\" to "
2790                           "pos 0x%ul.\n", f->name, (unsigned int) pos));
2791                 if ((err = flash_safe_write(fmc->mtd, pos,
2792                                             (u_char *)f->name,
2793                                             f->nsize)) < 0) {
2794                         jffs_fmfree_partly(fmc, fm, total_data_size);
2795                         jffs_fm_write_unlock(fmc);
2796                         printk(KERN_ERR "JFFS: jffs_rewrite_data: Write "
2797                                 "error during rewrite. (name)\n");
2798                         printk(KERN_ERR "JFFS: jffs_rewrite_data: Now retrying "
2799                                 "rewrite. (name)\n");
2800                         goto retry;
2801                 }
2802                 pos += total_name_size;
2803                 raw_inode.nchksum = jffs_checksum(f->name, f->nsize);
2804         }
2805
2806         /* Write the data.  */
2807         if (size) {
2808                 int r;
2809                 unsigned char *page;
2810                 __u32 offset = node->data_offset;
2811
2812                 if (!(page = (unsigned char *)__get_free_page(GFP_KERNEL))) {
2813                         jffs_fmfree_partly(fmc, fm, 0);
2814                         return -1;
2815                 }
2816
2817                 while (size) {
2818                         __u32 s = min(size, (__u32)PAGE_SIZE);
2819                         if ((r = jffs_read_data(f, (char *)page,
2820                                                 offset, s)) < s) {
2821                                 free_page((unsigned long)page);
2822                                 jffs_fmfree_partly(fmc, fm, 0);
2823                                 jffs_fm_write_unlock(fmc);
2824                                 printk(KERN_ERR "JFFS: jffs_rewrite_data: "
2825                                          "jffs_read_data() "
2826                                          "failed! (r = %d)\n", r);
2827                                 return -1;
2828                         }
2829                         if ((err = flash_safe_write(fmc->mtd,
2830                                                     pos, page, r)) < 0) {
2831                                 free_page((unsigned long)page);
2832                                 jffs_fmfree_partly(fmc, fm, 0);
2833                                 jffs_fm_write_unlock(fmc);
2834                                 printk(KERN_ERR "JFFS: jffs_rewrite_data: "
2835                                        "Write error during rewrite. "
2836                                        "(data)\n");
2837                                 goto retry;
2838                         }
2839                         pos += r;
2840                         size -= r;
2841                         offset += r;
2842                         raw_inode.dchksum += jffs_checksum(page, r);
2843                 }
2844
2845                 free_page((unsigned long)page);
2846         }
2847
2848         raw_inode.accurate = 0;
2849         raw_inode.chksum = jffs_checksum(&raw_inode,
2850                                          sizeof(struct jffs_raw_inode)
2851                                          - sizeof(__u16));
2852
2853         /* Add the checksum.  */
2854         if ((err
2855              = flash_safe_write(fmc->mtd, pos_dchksum,
2856                                 &((u_char *)
2857                                 &raw_inode)[JFFS_RAW_INODE_DCHKSUM_OFFSET],
2858                                 sizeof(__u32) + sizeof(__u16)
2859                                 + sizeof(__u16))) < 0) {
2860                 jffs_fmfree_partly(fmc, fm, 0);
2861                 jffs_fm_write_unlock(fmc);
2862                 printk(KERN_ERR "JFFS: jffs_rewrite_data: Write error during "
2863                        "rewrite. (checksum)\n");
2864                 goto retry;
2865         }
2866
2867         /* Now make the file system aware of the newly written node.  */
2868         jffs_insert_node(c, f, &raw_inode, f->name, new_node);
2869         jffs_fm_write_unlock(fmc);
2870
2871         D3(printk("jffs_rewrite_data(): Leaving...\n"));
2872         return 0;
2873 } /* jffs_rewrite_data()  */
2874
2875
2876 /* jffs_garbage_collect_next implements one step in the garbage collect
2877    process and is often called multiple times at each occasion of a
2878    garbage collect.  */
2879
2880 static int
2881 jffs_garbage_collect_next(struct jffs_control *c)
2882 {
2883         struct jffs_fmcontrol *fmc = c->fmc;
2884         struct jffs_node *node;
2885         struct jffs_file *f;
2886         int err = 0;
2887         __u32 size;
2888         __u32 data_size;
2889         __u32 total_name_size;
2890         __u32 extra_available;
2891         __u32 space_needed;
2892         __u32 free_chunk_size1 = jffs_free_size1(fmc);
2893         D2(__u32 free_chunk_size2 = jffs_free_size2(fmc));
2894
2895         /* Get the oldest node in the flash.  */
2896         node = jffs_get_oldest_node(fmc);
2897         ASSERT(if (!node) {
2898                 printk(KERN_ERR "JFFS: jffs_garbage_collect_next: "
2899                        "No oldest node found!\n");
2900                 err = -1;
2901                 goto jffs_garbage_collect_next_end;
2902                 
2903
2904         });
2905
2906         /* Find its corresponding file too.  */
2907         f = jffs_find_file(c, node->ino);
2908
2909         if (!f) {
2910           printk (KERN_ERR "JFFS: jffs_garbage_collect_next: "
2911                   "No file to garbage collect! "
2912                   "(ino = 0x%08x)\n", node->ino);
2913           /* FIXME: Free the offending node and recover. */
2914           err = -1;
2915           goto jffs_garbage_collect_next_end;
2916         }
2917
2918         /* We always write out the name. Theoretically, we don't need
2919            to, but for now it's easier - because otherwise we'd have
2920            to keep track of how many times the current name exists on
2921            the flash and make sure it never reaches zero.
2922
2923            The current approach means that would be possible to cause
2924            the GC to end up eating its tail by writing lots of nodes
2925            with no name for it to garbage-collect. Hence the change in
2926            inode.c to write names with _every_ node.
2927
2928            It sucks, but it _should_ work.
2929         */
2930         total_name_size = JFFS_PAD(f->nsize);
2931
2932         D1(printk("jffs_garbage_collect_next(): \"%s\", "
2933                   "ino: %u, version: %u, location 0x%x, dsize %u\n",
2934                   (f->name ? f->name : ""), node->ino, node->version, 
2935                   node->fm->offset, node->data_size));
2936
2937         /* Compute how many data it's possible to rewrite at the moment.  */
2938         data_size = f->size - node->data_offset;
2939
2940         /* And from that, the total size of the chunk we want to write */
2941         size = sizeof(struct jffs_raw_inode) + total_name_size
2942                + data_size + JFFS_GET_PAD_BYTES(data_size);
2943
2944         /* If that's more than max_chunk_size, reduce it accordingly */
2945         if (size > fmc->max_chunk_size) {
2946                 size = fmc->max_chunk_size;
2947                 data_size = size - sizeof(struct jffs_raw_inode)
2948                             - total_name_size;
2949         }
2950
2951         /* If we're asking to take up more space than free_chunk_size1
2952            but we _could_ fit in it, shrink accordingly.
2953         */
2954         if (size > free_chunk_size1) {
2955
2956                 if (free_chunk_size1 <
2957                     (sizeof(struct jffs_raw_inode) + total_name_size + BLOCK_SIZE)){
2958                         /* The space left is too small to be of any
2959                            use really.  */
2960                         struct jffs_fm *dirty_fm
2961                         = jffs_fmalloced(fmc,
2962                                          fmc->tail->offset + fmc->tail->size,
2963                                          free_chunk_size1, NULL);
2964                         if (!dirty_fm) {
2965                                 printk(KERN_ERR "JFFS: "
2966                                        "jffs_garbage_collect_next: "
2967                                        "Failed to allocate `dirty' "
2968                                        "flash memory!\n");
2969                                 err = -1;
2970                                 goto jffs_garbage_collect_next_end;
2971                         }
2972                         D1(printk("Dirtying end of flash - too small\n"));
2973                         jffs_write_dummy_node(c, dirty_fm);
2974                         err = 0;
2975                         goto jffs_garbage_collect_next_end;
2976                 }
2977                 D1(printk("Reducing size of new node from %d to %d to avoid "
2978                           " exceeding free_chunk_size1\n",
2979                           size, free_chunk_size1));
2980
2981                 size = free_chunk_size1;
2982                 data_size = size - sizeof(struct jffs_raw_inode)
2983                             - total_name_size;
2984         }
2985
2986
2987         /* Calculate the amount of space needed to hold the nodes
2988            which are remaining in the tail */
2989         space_needed = fmc->min_free_size - (node->fm->offset % fmc->sector_size);
2990
2991         /* From that, calculate how much 'extra' space we can use to
2992            increase the size of the node we're writing from the size
2993            of the node we're obsoleting
2994         */
2995         if (space_needed > fmc->free_size) {
2996                 /* If we've gone below min_free_size for some reason,
2997                    don't fuck up. This is why we have 
2998                    min_free_size > sector_size. Whinge about it though,
2999                    just so I can convince myself my maths is right.
3000                 */
3001                 D1(printk(KERN_WARNING "jffs_garbage_collect_next(): "
3002                           "space_needed %d exceeded free_size %d\n",
3003                           space_needed, fmc->free_size));
3004                 extra_available = 0;
3005         } else {
3006                 extra_available = fmc->free_size - space_needed;
3007         }
3008
3009         /* Check that we don't use up any more 'extra' space than
3010            what's available */
3011         if (size > JFFS_PAD(node->data_size) + total_name_size + 
3012             sizeof(struct jffs_raw_inode) + extra_available) {
3013                 D1(printk("Reducing size of new node from %d to %ld to avoid "
3014                        "catching our tail\n", size, 
3015                           (long) (JFFS_PAD(node->data_size) + JFFS_PAD(node->name_size) + 
3016                           sizeof(struct jffs_raw_inode) + extra_available)));
3017                 D1(printk("space_needed = %d, extra_available = %d\n", 
3018                           space_needed, extra_available));
3019
3020                 size = JFFS_PAD(node->data_size) + total_name_size + 
3021                   sizeof(struct jffs_raw_inode) + extra_available;
3022                 data_size = size - sizeof(struct jffs_raw_inode)
3023                         - total_name_size;
3024         };
3025
3026         D2(printk("  total_name_size: %u\n", total_name_size));
3027         D2(printk("  data_size: %u\n", data_size));
3028         D2(printk("  size: %u\n", size));
3029         D2(printk("  f->nsize: %u\n", f->nsize));
3030         D2(printk("  f->size: %u\n", f->size));
3031         D2(printk("  node->data_offset: %u\n", node->data_offset));
3032         D2(printk("  free_chunk_size1: %u\n", free_chunk_size1));
3033         D2(printk("  free_chunk_size2: %u\n", free_chunk_size2));
3034         D2(printk("  node->fm->offset: 0x%08x\n", node->fm->offset));
3035
3036         if ((err = jffs_rewrite_data(f, node, data_size))) {
3037                 printk(KERN_WARNING "jffs_rewrite_data() failed: %d\n", err);
3038                 return err;
3039         }
3040           
3041 jffs_garbage_collect_next_end:
3042         D3(printk("jffs_garbage_collect_next: Leaving...\n"));
3043         return err;
3044 } /* jffs_garbage_collect_next */
3045
3046
3047 /* If an obsolete node is partly going to be erased due to garbage
3048    collection, the part that isn't going to be erased must be filled
3049    with zeroes so that the scan of the flash will work smoothly next
3050    time.  (The data in the file could for instance be a JFFS image
3051    which could cause enormous confusion during a scan of the flash
3052    device if we didn't do this.)
3053      There are two phases in this procedure: First, the clearing of
3054    the name and data parts of the node. Second, possibly also clearing
3055    a part of the raw inode as well.  If the box is power cycled during
3056    the first phase, only the checksum of this node-to-be-cleared-at-
3057    the-end will be wrong.  If the box is power cycled during, or after,
3058    the clearing of the raw inode, the information like the length of
3059    the name and data parts are zeroed.  The next time the box is
3060    powered up, the scanning algorithm manages this faulty data too
3061    because:
3062
3063    - The checksum is invalid and thus the raw inode must be discarded
3064      in any case.
3065    - If the lengths of the data part or the name part are zeroed, the
3066      scanning just continues after the raw inode.  But after the inode
3067      the scanning procedure just finds zeroes which is the same as
3068      dirt.
3069
3070    So, in the end, this could never fail. :-)  Even if it does fail,
3071    the scanning algorithm should manage that too.  */
3072
3073 static int
3074 jffs_clear_end_of_node(struct jffs_control *c, __u32 erase_size)
3075 {
3076         struct jffs_fm *fm;
3077         struct jffs_fmcontrol *fmc = c->fmc;
3078         __u32 zero_offset;
3079         __u32 zero_size;
3080         __u32 zero_offset_data;
3081         __u32 zero_size_data;
3082         __u32 cutting_raw_inode = 0;
3083
3084         if (!(fm = jffs_cut_node(fmc, erase_size))) {
3085                 D3(printk("jffs_clear_end_of_node(): fm == NULL\n"));
3086                 return 0;
3087         }
3088
3089         /* Where and how much shall we clear?  */
3090         zero_offset = fmc->head->offset + erase_size;
3091         zero_size = fm->offset + fm->size - zero_offset;
3092
3093         /* Do we have to clear the raw_inode explicitly?  */
3094         if (fm->size - zero_size < sizeof(struct jffs_raw_inode)) {
3095                 cutting_raw_inode = sizeof(struct jffs_raw_inode)
3096                                     - (fm->size - zero_size);
3097         }
3098
3099         /* First, clear the name and data fields.  */
3100         zero_offset_data = zero_offset + cutting_raw_inode;
3101         zero_size_data = zero_size - cutting_raw_inode;
3102         flash_safe_acquire(fmc->mtd);
3103         flash_memset(fmc->mtd, zero_offset_data, 0, zero_size_data);
3104         flash_safe_release(fmc->mtd);
3105
3106         /* Should we clear a part of the raw inode?  */
3107         if (cutting_raw_inode) {
3108                 /* I guess it is ok to clear the raw inode in this order.  */
3109                 flash_safe_acquire(fmc->mtd);
3110                 flash_memset(fmc->mtd, zero_offset, 0,
3111                              cutting_raw_inode);
3112                 flash_safe_release(fmc->mtd);
3113         }
3114
3115         return 0;
3116 } /* jffs_clear_end_of_node()  */
3117
3118 /* Try to erase as much as possible of the dirt in the flash memory.  */
3119 static long
3120 jffs_try_to_erase(struct jffs_control *c)
3121 {
3122         struct jffs_fmcontrol *fmc = c->fmc;
3123         long erase_size;
3124         int err;
3125         __u32 offset;
3126
3127         D3(printk("jffs_try_to_erase()\n"));
3128
3129         erase_size = jffs_erasable_size(fmc);
3130
3131         D2(printk("jffs_try_to_erase(): erase_size = %ld\n", erase_size));
3132
3133         if (erase_size == 0) {
3134                 return 0;
3135         }
3136         else if (erase_size < 0) {
3137                 printk(KERN_ERR "JFFS: jffs_try_to_erase: "
3138                        "jffs_erasable_size returned %ld.\n", erase_size);
3139                 return erase_size;
3140         }
3141
3142         if ((err = jffs_clear_end_of_node(c, erase_size)) < 0) {
3143                 printk(KERN_ERR "JFFS: jffs_try_to_erase: "
3144                        "Clearing of node failed.\n");
3145                 return err;
3146         }
3147
3148         offset = fmc->head->offset;
3149
3150         /* Now, let's try to do the erase.  */
3151         if ((err = flash_erase_region(fmc->mtd,
3152                                       offset, erase_size)) < 0) {
3153                 printk(KERN_ERR "JFFS: Erase of flash failed. "
3154                        "offset = %u, erase_size = %ld\n",
3155                        offset, erase_size);
3156                 /* XXX: Here we should allocate this area as dirty
3157                    with jffs_fmalloced or something similar.  Now
3158                    we just report the error.  */
3159                 return err;
3160         }
3161
3162 #if 0
3163         /* Check if the erased sectors really got erased.  */
3164         {
3165                 __u32 pos;
3166                 __u32 end;
3167
3168                 pos = (__u32)flash_get_direct_pointer(to_kdev_t(c->sb->s_dev), offset);
3169                 end = pos + erase_size;
3170
3171                 D2(printk("JFFS: Checking erased sector(s)...\n"));
3172
3173                 flash_safe_acquire(fmc->mtd);
3174
3175                 for (; pos < end; pos += 4) {
3176                         if (*(__u32 *)pos != JFFS_EMPTY_BITMASK) {
3177                                 printk("JFFS: Erase failed! pos = 0x%lx\n",
3178                                        (long)pos);
3179                                 jffs_hexdump(fmc->mtd, pos,
3180                                              jffs_min(256, end - pos));
3181                                 err = -1;
3182                                 break;
3183                         }
3184                 }
3185
3186                 flash_safe_release(fmc->mtd);
3187
3188                 if (!err) {
3189                         D2(printk("JFFS: Erase succeeded.\n"));
3190                 }
3191                 else {
3192                         /* XXX: Here we should allocate the memory
3193                            with jffs_fmalloced() in order to prevent
3194                            JFFS from using this area accidentally.  */
3195                         return err;
3196                 }
3197         }
3198 #endif
3199
3200         /* Update the flash memory data structures.  */
3201         jffs_sync_erase(fmc, erase_size);
3202
3203         return erase_size;
3204 }
3205
3206
3207 /* There are different criteria that should trigger a garbage collect:
3208
3209    1. There is too much dirt in the memory.
3210    2. The free space is becoming small.
3211    3. There are many versions of a node.
3212
3213    The garbage collect should always be done in a manner that guarantees
3214    that future garbage collects cannot be locked.  E.g. Rewritten chunks
3215    should not be too large (span more than one sector in the flash memory
3216    for exemple).  Of course there is a limit on how intelligent this garbage
3217    collection can be.  */
3218
3219
3220 static int
3221 jffs_garbage_collect_now(struct jffs_control *c)
3222 {
3223         struct jffs_fmcontrol *fmc = c->fmc;
3224         long erased = 0;
3225         int result = 0;
3226         D1(int i = 1);
3227         D2(printk("***jffs_garbage_collect_now(): fmc->dirty_size = %u, fmc->free_size = 0x%x\n, fcs1=0x%x, fcs2=0x%x",
3228                   fmc->dirty_size, fmc->free_size, jffs_free_size1(fmc), jffs_free_size2(fmc)));
3229         D2(jffs_print_fmcontrol(fmc));
3230
3231         //      down(&fmc->gclock);
3232
3233         /* If it is possible to garbage collect, do so.  */
3234         
3235         while (erased == 0) {
3236                 D1(printk("***jffs_garbage_collect_now(): round #%u, "
3237                           "fmc->dirty_size = %u\n", i++, fmc->dirty_size));
3238                 D2(jffs_print_fmcontrol(fmc));
3239
3240                 if ((erased = jffs_try_to_erase(c)) < 0) {
3241                         printk(KERN_WARNING "JFFS: Error in "
3242                                "garbage collector.\n");
3243                         result = erased;
3244                         goto gc_end;
3245                 }
3246                 if (erased)
3247                         break;
3248                 
3249                 if (fmc->free_size == 0) {
3250                         /* Argh */
3251                         printk(KERN_ERR "jffs_garbage_collect_now(): free_size == 0. This is BAD.\n");
3252                         result = -ENOSPC;
3253                         break;
3254                 }
3255
3256                 if (fmc->dirty_size < fmc->sector_size) {
3257                         /* Actually, we _may_ have been able to free some, 
3258                          * if there are many overlapping nodes which aren't
3259                          * actually marked dirty because they still have
3260                          * some valid data in each.
3261                          */
3262                         result = -ENOSPC;
3263                         break;
3264                 }
3265
3266                 /* Let's dare to make a garbage collect.  */
3267                 if ((result = jffs_garbage_collect_next(c)) < 0) {
3268                         printk(KERN_ERR "JFFS: Something "
3269                                "has gone seriously wrong "
3270                                "with a garbage collect.\n");
3271                         goto gc_end;
3272                 }
3273
3274                 D1(printk("   jffs_garbage_collect_now(): erased: %ld\n", erased));
3275                 DJM(jffs_print_memory_allocation_statistics());
3276         }
3277         
3278 gc_end:
3279         //      up(&fmc->gclock);
3280
3281         D3(printk("   jffs_garbage_collect_now(): Leaving...\n"));
3282         D1(if (erased) {
3283                 printk("jffs_g_c_now(): erased = %ld\n", erased);
3284                 jffs_print_fmcontrol(fmc);
3285         });
3286
3287         if (!erased && !result)
3288                 return -ENOSPC;
3289
3290         return result;
3291 } /* jffs_garbage_collect_now() */
3292
3293
3294 /* Determine if it is reasonable to start garbage collection.
3295    We start a gc pass if either:
3296    - The number of free bytes < MIN_FREE_BYTES && at least one
3297      block is dirty, OR
3298    - The number of dirty bytes > MAX_DIRTY_BYTES
3299 */
3300 static inline int thread_should_wake (struct jffs_control *c)
3301 {
3302         D1(printk (KERN_NOTICE "thread_should_wake(): free=%d, dirty=%d, blocksize=%d.\n",
3303                    c->fmc->free_size, c->fmc->dirty_size, c->fmc->sector_size));
3304
3305         /* If there's not enough dirty space to free a block, there's no point. */
3306         if (c->fmc->dirty_size < c->fmc->sector_size) {
3307                 D2(printk(KERN_NOTICE "thread_should_wake(): Not waking. Insufficient dirty space\n"));
3308                 return 0;
3309         }
3310 #if 1
3311         /* If there is too much RAM used by the various structures, GC */
3312         if (jffs_get_node_inuse() > (c->fmc->used_size/c->fmc->max_chunk_size * 5 + jffs_get_file_count() * 2 + 50)) {
3313                 /* FIXME: Provide proof that this test can be satisfied. We
3314                    don't want a filesystem doing endless GC just because this
3315                    condition cannot ever be false.
3316                 */
3317                 D2(printk(KERN_NOTICE "thread_should_wake(): Waking due to number of nodes\n"));
3318                 return 1;
3319         }
3320 #endif
3321         /* If there are fewer free bytes than the threshold, GC */
3322         if (c->fmc->free_size < c->gc_minfree_threshold) {
3323                 D2(printk(KERN_NOTICE "thread_should_wake(): Waking due to insufficent free space\n"));
3324                 return 1;
3325         }
3326         /* If there are more dirty bytes than the threshold, GC */
3327         if (c->fmc->dirty_size > c->gc_maxdirty_threshold) {
3328                 D2(printk(KERN_NOTICE "thread_should_wake(): Waking due to excessive dirty space\n"));
3329                 return 1;
3330         }       
3331         /* FIXME: What about the "There are many versions of a node" condition? */
3332
3333         return 0;
3334 }
3335
3336
3337 void jffs_garbage_collect_trigger(struct jffs_control *c)
3338 {
3339         /* NOTE: We rely on the fact that we have the BKL here.
3340          * Otherwise, the gc_task could go away between the check
3341          * and the wake_up_process()
3342          */
3343         if (c->gc_task && thread_should_wake(c))
3344                 send_sig(SIGHUP, c->gc_task, 1);
3345 }
3346   
3347
3348 /* Kernel threads  take (void *) as arguments.   Thus we pass
3349    the jffs_control data as a (void *) and then cast it. */
3350 int
3351 jffs_garbage_collect_thread(void *ptr)
3352 {
3353         struct jffs_control *c = (struct jffs_control *) ptr;
3354         struct jffs_fmcontrol *fmc = c->fmc;
3355         long erased;
3356         int result = 0;
3357         D1(int i = 1);
3358
3359         daemonize("jffs_gcd");
3360
3361         c->gc_task = current;
3362
3363         lock_kernel();
3364         init_completion(&c->gc_thread_comp); /* barrier */ 
3365         spin_lock_irq(&current->sighand->siglock);
3366         siginitsetinv (&current->blocked, sigmask(SIGHUP) | sigmask(SIGKILL) | sigmask(SIGSTOP) | sigmask(SIGCONT));
3367         recalc_sigpending();
3368         spin_unlock_irq(&current->sighand->siglock);
3369
3370         D1(printk (KERN_NOTICE "jffs_garbage_collect_thread(): Starting infinite loop.\n"));
3371
3372         for (;;) {
3373
3374                 /* See if we need to start gc.  If we don't, go to sleep.
3375                    
3376                    Current implementation is a BAD THING(tm).  If we try 
3377                    to unmount the FS, the unmount operation will sleep waiting
3378                    for this thread to exit.  We need to arrange to send it a
3379                    sig before the umount process sleeps.
3380                 */
3381
3382                 if (!thread_should_wake(c))
3383                         set_current_state (TASK_INTERRUPTIBLE);
3384                 
3385                 schedule(); /* Yes, we do this even if we want to go
3386                                        on immediately - we're a low priority 
3387                                        background task. */
3388
3389                 /* Put_super will send a SIGKILL and then wait on the sem. 
3390                  */
3391                 while (signal_pending(current)) {
3392                         siginfo_t info;
3393                         unsigned long signr = 0;
3394
3395                         if (try_to_freeze())
3396                                 continue;
3397
3398                         spin_lock_irq(&current->sighand->siglock);
3399                         signr = dequeue_signal(current, &current->blocked, &info);
3400                         spin_unlock_irq(&current->sighand->siglock);
3401
3402                         switch(signr) {
3403                         case SIGSTOP:
3404                                 D1(printk("jffs_garbage_collect_thread(): SIGSTOP received.\n"));
3405                                 set_current_state(TASK_STOPPED);
3406                                 schedule();
3407                                 break;
3408
3409                         case SIGKILL:
3410                                 D1(printk("jffs_garbage_collect_thread(): SIGKILL received.\n"));
3411                                 c->gc_task = NULL;
3412                                 complete_and_exit(&c->gc_thread_comp, 0);
3413                         }
3414                 }
3415
3416
3417                 D1(printk (KERN_NOTICE "jffs_garbage_collect_thread(): collecting.\n"));
3418
3419                 D3(printk (KERN_NOTICE "g_c_thread(): down biglock\n"));
3420                 mutex_lock(&fmc->biglock);
3421                 
3422                 D1(printk("***jffs_garbage_collect_thread(): round #%u, "
3423                           "fmc->dirty_size = %u\n", i++, fmc->dirty_size));
3424                 D2(jffs_print_fmcontrol(fmc));
3425
3426                 if ((erased = jffs_try_to_erase(c)) < 0) {
3427                         printk(KERN_WARNING "JFFS: Error in "
3428                                "garbage collector: %ld.\n", erased);
3429                 }
3430
3431                 if (erased)
3432                         goto gc_end;
3433
3434                 if (fmc->free_size == 0) {
3435                         /* Argh. Might as well commit suicide. */
3436                         printk(KERN_ERR "jffs_garbage_collect_thread(): free_size == 0. This is BAD.\n");
3437                         send_sig(SIGQUIT, c->gc_task, 1);
3438                         // panic()
3439                         goto gc_end;
3440                 }
3441                 
3442                 /* Let's dare to make a garbage collect.  */
3443                 if ((result = jffs_garbage_collect_next(c)) < 0) {
3444                         printk(KERN_ERR "JFFS: Something "
3445                                "has gone seriously wrong "
3446                                "with a garbage collect: %d\n", result);
3447                 }
3448                 
3449         gc_end:
3450                 D3(printk (KERN_NOTICE "g_c_thread(): up biglock\n"));
3451                 mutex_unlock(&fmc->biglock);
3452         } /* for (;;) */
3453 } /* jffs_garbage_collect_thread() */