v2.4.8 -> v2.4.8.1
[opensuse:kernel.git] / 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  * - Based on Id: intrep.c,v 1.71 2000/10/27 16:51:29 dwmw2 Exp
14  * - With the ctype() changes from v1.77.
15  *
16  * Ported to Linux 2.3.x and MTD:
17  * Copyright (C) 2000  Alexander Larsson (alex@cendio.se), Cendio Systems AB
18  *
19  */
20
21 /* This file contains the code for the internal structure of the
22    Journaling Flash File System, JFFS.  */
23
24 /*
25  * Todo list:
26  *
27  * memcpy_to_flash() and memcpy_from_flash() functions.
28  *
29  * Implementation of hard links.
30  *
31  * Organize the source code in a better way. Against the VFS we could
32  * have jffs_ext.c, and against the block device jffs_int.c.
33  * A better file-internal organization too.
34  *
35  * A better checksum algorithm.
36  *
37  * Consider endianness stuff. ntohl() etc.
38  *
39  * Are we handling the atime, mtime, ctime members of the inode right?
40  *
41  * Remove some duplicated code. Take a look at jffs_write_node() and
42  * jffs_rewrite_data() for instance.
43  *
44  * Implement more meaning of the nlink member in various data structures.
45  * nlink could be used in conjunction with hard links for instance.
46  *
47  * Better memory management. Allocate data structures in larger chunks
48  * if possible.
49  *
50  * If too much meta data is stored, a garbage collect should be issued.
51  * We have experienced problems with too much meta data with for instance
52  * log files.
53  *
54  * Improve the calls to jffs_ioctl(). We would like to retrieve more
55  * information to be able to debug (or to supervise) JFFS during run-time.
56  *
57  */
58
59 #define __NO_VERSION__
60 #include <linux/types.h>
61 #include <linux/slab.h>
62 #include <linux/jffs.h>
63 #include <linux/fs.h>
64 #include <linux/stat.h>
65 #include <linux/pagemap.h>
66 #include <linux/locks.h>
67 #include <asm/semaphore.h>
68 #include <asm/byteorder.h>
69 #include <linux/version.h>
70 #include <linux/smp_lock.h>
71 #include <linux/sched.h>
72 #include <linux/ctype.h>
73
74 #include "intrep.h"
75 #include "jffs_fm.h"
76
77 #if defined(JFFS_MEMORY_DEBUG) && JFFS_MEMORY_DEBUG
78 long no_jffs_file = 0;
79 long no_jffs_node = 0;
80 long no_jffs_control = 0;
81 long no_jffs_raw_inode = 0;
82 long no_jffs_node_ref = 0;
83 long no_jffs_fm = 0;
84 long no_jffs_fmcontrol = 0;
85 long no_hash = 0;
86 long no_name = 0;
87 #endif
88
89 static int jffs_scan_flash(struct jffs_control *c);
90 static int jffs_update_file(struct jffs_file *f, struct jffs_node *node);
91 static __u8 flash_read_u8(struct mtd_info *mtd, loff_t from);
92
93 #if 1
94 static void
95 jffs_hexdump(struct mtd_info *mtd, loff_t pos, int size)
96 {
97         char line[16];
98         int j = 0;
99
100         while (size > 0) {
101                 int i;
102
103                 printk("%ld:", (long) pos);
104                 for (j = 0; j < 16; j++) {
105                         line[j] = flash_read_u8(mtd, pos++);
106                 }
107                 for (i = 0; i < j; i++) {
108                         if (!(i & 1)) {
109                                 printk(" %.2x", line[i] & 0xff);
110                         }
111                         else {
112                                 printk("%.2x", line[i] & 0xff);
113                         }
114                 }
115
116                 /* Print empty space */
117                 for (; i < 16; i++) {
118                         if (!(i & 1)) {
119                                 printk("   ");
120                         }
121                         else {
122                                 printk("  ");
123                         }
124                 }
125                 printk("  ");
126
127                 for (i = 0; i < j; i++) {
128                         if (isgraph(line[i])) {
129                                 printk("%c", line[i]);
130                         }
131                         else {
132                                 printk(".");
133                         }
134                 }
135                 printk("\n");
136                 size -= 16;
137         }
138 }
139 #endif
140
141 #define flash_safe_acquire(arg)
142 #define flash_safe_release(arg)
143
144
145 static int
146 flash_safe_read(struct mtd_info *mtd, loff_t from,
147                 u_char *buf, size_t count)
148 {
149         size_t retlen;
150         int res;
151
152         D3(printk(KERN_NOTICE "flash_safe_read(%p, %08x, %p, %08x)\n",
153                   mtd, from, buf, count));
154
155         res = MTD_READ(mtd, from, count, &retlen, buf);
156         if (retlen != count) {
157                 panic("Didn't read all bytes in flash_safe_read(). Returned %d\n", res);
158         }
159         return res?res:retlen;
160 }
161
162
163 static __u32
164 flash_read_u32(struct mtd_info *mtd, loff_t from)
165 {
166         size_t retlen;
167         __u32 ret;
168         int res;
169
170         res = MTD_READ(mtd, from, 4, &retlen, (unsigned char *)&ret);
171         if (retlen != 4) {
172                 printk("Didn't read all bytes in flash_read_u32(). Returned %d\n", res);
173                 return 0;
174         }
175
176         return ret;
177 }
178
179
180 static __u8
181 flash_read_u8(struct mtd_info *mtd, loff_t from)
182 {
183         size_t retlen;
184         __u8 ret;
185         int res;
186
187         res = MTD_READ(mtd, from, 1, &retlen, &ret);
188         if (retlen != 1) {
189                 printk("Didn't read a byte in flash_read_u8(). Returned %d\n", res);
190                 return 0;
191         }
192
193         return ret;
194 }
195
196
197 static int
198 flash_safe_write(struct mtd_info *mtd, loff_t to,
199                  const u_char *buf, size_t count)
200 {
201         size_t retlen;
202         int res;
203
204         res = MTD_WRITE(mtd, to, count, &retlen, buf);
205         if (retlen != count) {
206                 printk("Didn't write all bytes in flash_safe_write(). Returned %d\n", res);
207         }
208         return res?res:retlen;
209 }
210
211
212 static int
213 flash_memset(struct mtd_info *mtd, loff_t to,
214              const u_char c, size_t size)
215 {
216         static unsigned char pattern[16];
217         int i;
218
219         /* fill up pattern */
220
221         for(i = 0; i < 16; i++)
222                 pattern[i] = c;
223
224         /* write as many 16-byte chunks as we can */
225
226         while (size >= 16) {
227                 flash_safe_write(mtd, to, pattern, 16);
228                 size -= 16;
229                 to += 16;
230         }
231
232         /* and the rest */
233
234         if(size)
235                 flash_safe_write(mtd, to, pattern, size);
236
237         return size;
238 }
239
240
241 static void
242 intrep_erase_callback(struct erase_info *done)
243 {
244         wait_queue_head_t *wait_q;
245
246         wait_q = (wait_queue_head_t *)done->priv;
247
248         wake_up(wait_q);
249 }
250
251
252 static int
253 flash_erase_region(struct mtd_info *mtd, loff_t start,
254                    size_t size)
255 {
256         struct erase_info *erase;
257         DECLARE_WAITQUEUE(wait, current);
258         wait_queue_head_t wait_q;
259
260         erase = kmalloc(sizeof(struct erase_info), GFP_KERNEL);
261         if (!erase)
262                 return -ENOMEM;
263
264         init_waitqueue_head(&wait_q);
265
266         erase->mtd = mtd;
267         erase->callback = intrep_erase_callback;
268         erase->addr = start;
269         erase->len = size;
270         erase->priv = (u_long)&wait_q;
271
272         /* FIXME: Use TASK_INTERRUPTIBLE and deal with being interrupted */
273         set_current_state(TASK_UNINTERRUPTIBLE);
274         add_wait_queue(&wait_q, &wait);
275
276         if (MTD_ERASE(mtd, erase) < 0) {
277                 set_current_state(TASK_RUNNING);
278                 remove_wait_queue(&wait_q, &wait);
279                 kfree(erase);
280
281                 printk(KERN_WARNING "flash: erase of region [0x%lx, 0x%lx] "
282                        "totally failed\n", (long)start, (long)start + size);
283
284                 return -1;
285         }
286
287         schedule(); /* Wait for flash to finish. */
288         remove_wait_queue(&wait_q, &wait);
289
290         kfree(erase);
291
292         return 0;
293 }
294
295
296 inline int
297 jffs_min(int a, int b)
298 {
299         return (a < b ? a : b);
300 }
301
302
303 inline int
304 jffs_max(int a, int b)
305 {
306         return (a > b ? a : b);
307 }
308
309
310 /* This routine calculates checksums in JFFS.  */
311 __u32
312 jffs_checksum(const void *data, int size)
313 {
314         __u32 sum = 0;
315         __u8 *ptr = (__u8 *)data;
316         while (size-- > 0) {
317                 sum += *ptr++;
318         }
319         D3(printk(", result: 0x%08x\n", sum));
320         return sum;
321 }
322
323
324 __u32
325 jffs_checksum_flash(struct mtd_info *mtd, loff_t start, int size)
326 {
327         __u32 sum = 0;
328         loff_t ptr = start;
329         __u8 *read_buf;
330         int i, length;
331
332         /* Allocate read buffer */
333         read_buf = (__u8 *) kmalloc (sizeof(__u8) * 4096, GFP_KERNEL);
334
335         /* Loop until checksum done */
336         while (size) {
337                 /* Get amount of data to read */
338                 if (size < 4096)
339                         length = size;
340                 else
341                         length = 4096;
342
343                 /* Perform flash read */
344                 D3(printk(KERN_NOTICE "jffs_checksum_flash\n"));
345                 flash_safe_read(mtd, ptr, &read_buf[0], length);
346
347                 /* Compute checksum */
348                 for (i=0; i < length ; i++)
349                         sum += read_buf[i];
350
351                 /* Update pointer and size */
352                 size -= length;
353                 ptr += length;
354         }
355
356         /* Free read buffer */
357         kfree (read_buf);
358
359         /* Return result */
360         D3(printk("checksum result: 0x%08x\n", sum));
361         return sum;
362 }
363 static __inline__ void jffs_fm_write_lock(struct jffs_fmcontrol *fmc)
364 {
365   //    down(&fmc->wlock);
366 }
367
368 static __inline__ void jffs_fm_write_unlock(struct jffs_fmcontrol *fmc)
369 {
370   //    up(&fmc->wlock);
371 }
372
373
374 /* Create and initialize a new struct jffs_file.  */
375 static struct jffs_file *
376 jffs_create_file(struct jffs_control *c,
377                  const struct jffs_raw_inode *raw_inode)
378 {
379         struct jffs_file *f;
380
381         if (!(f = (struct jffs_file *)kmalloc(sizeof(struct jffs_file),
382                                               GFP_KERNEL))) {
383                 D(printk("jffs_create_file(): Failed!\n"));
384                 return 0;
385         }
386         DJM(no_jffs_file++);
387         memset(f, 0, sizeof(struct jffs_file));
388         f->ino = raw_inode->ino;
389         f->pino = raw_inode->pino;
390         f->nlink = raw_inode->nlink;
391         f->deleted = raw_inode->deleted;
392         f->c = c;
393
394         return f;
395 }
396
397
398 /* Build a control block for the file system.  */
399 static struct jffs_control *
400 jffs_create_control(kdev_t dev)
401 {
402         struct jffs_control *c;
403         register int s = sizeof(struct jffs_control);
404         int i;
405         D(char *t = 0);
406
407         D2(printk("jffs_create_control()\n"));
408
409         if (!(c = (struct jffs_control *)kmalloc(s, GFP_KERNEL))) {
410                 goto fail_control;
411         }
412         DJM(no_jffs_control++);
413         c->root = 0;
414         c->gc_task = 0;
415         c->hash_len = JFFS_HASH_SIZE;
416         s = sizeof(struct list_head) * c->hash_len;
417         if (!(c->hash = (struct list_head *)kmalloc(s, GFP_KERNEL))) {
418                 goto fail_hash;
419         }
420         DJM(no_hash++);
421         for (i = 0; i < c->hash_len; i++)
422                 INIT_LIST_HEAD(&c->hash[i]);
423         if (!(c->fmc = jffs_build_begin(c, dev))) {
424                 goto fail_fminit;
425         }
426         c->next_ino = JFFS_MIN_INO + 1;
427         c->delete_list = (struct jffs_delete_list *) 0;
428         return c;
429
430 fail_fminit:
431         D(t = "c->fmc");
432 fail_hash:
433         kfree(c);
434         DJM(no_jffs_control--);
435         D(t = t ? t : "c->hash");
436 fail_control:
437         D(t = t ? t : "control");
438         D(printk("jffs_create_control(): Allocation failed: (%s)\n", t));
439         return (struct jffs_control *)0;
440 }
441
442
443 /* Clean up all data structures associated with the file system.  */
444 void
445 jffs_cleanup_control(struct jffs_control *c)
446 {
447         D2(printk("jffs_cleanup_control()\n"));
448
449         if (!c) {
450                 D(printk("jffs_cleanup_control(): c == NULL !!!\n"));
451                 return;
452         }
453
454         while (c->delete_list) {
455                 struct jffs_delete_list *delete_list_element;
456                 delete_list_element = c->delete_list;
457                 c->delete_list = c->delete_list->next;
458                 kfree(delete_list_element);
459         }
460
461         /* Free all files and nodes.  */
462         if (c->hash) {
463                 jffs_foreach_file(c, jffs_free_node_list);
464                 jffs_foreach_file(c, jffs_free_file);
465                 kfree(c->hash);
466                 DJM(no_hash--);
467         }
468         jffs_cleanup_fmcontrol(c->fmc);
469         kfree(c);
470         DJM(no_jffs_control--);
471         D3(printk("jffs_cleanup_control(): Leaving...\n"));
472 }
473
474
475 /* This function adds a virtual root node to the in-RAM representation.
476    Called by jffs_build_fs().  */
477 static int
478 jffs_add_virtual_root(struct jffs_control *c)
479 {
480         struct jffs_file *root;
481         struct jffs_node *node;
482
483         D2(printk("jffs_add_virtual_root(): "
484                   "Creating a virtual root directory.\n"));
485
486         if (!(root = (struct jffs_file *)kmalloc(sizeof(struct jffs_file),
487                                                  GFP_KERNEL))) {
488                 return -ENOMEM;
489         }
490         DJM(no_jffs_file++);
491         if (!(node = (struct jffs_node *)kmalloc(sizeof(struct jffs_node),
492                                                  GFP_KERNEL))) {
493                 kfree(root);
494                 DJM(no_jffs_file--);
495                 return -ENOMEM;
496         }
497         DJM(no_jffs_node++);
498         memset(node, 0, sizeof(struct jffs_node));
499         node->ino = JFFS_MIN_INO;
500         memset(root, 0, sizeof(struct jffs_file));
501         root->ino = JFFS_MIN_INO;
502         root->mode = S_IFDIR | S_IRWXU | S_IRGRP
503                      | S_IXGRP | S_IROTH | S_IXOTH;
504         root->atime = root->mtime = root->ctime = CURRENT_TIME;
505         root->nlink = 1;
506         root->c = c;
507         root->version_head = root->version_tail = node;
508         jffs_insert_file_into_hash(root);
509         return 0;
510 }
511
512
513 /* This is where the file system is built and initialized.  */
514 int
515 jffs_build_fs(struct super_block *sb)
516 {
517         struct jffs_control *c;
518         int err = 0;
519
520         D2(printk("jffs_build_fs()\n"));
521
522         if (!(c = jffs_create_control(sb->s_dev))) {
523                 return -ENOMEM;
524         }
525         c->building_fs = 1;
526         c->sb = sb;
527         if ((err = jffs_scan_flash(c)) < 0) {
528                 goto jffs_build_fs_fail;
529         }
530
531         /* Add a virtual root node if no one exists.  */
532         if (!jffs_find_file(c, JFFS_MIN_INO)) {
533                 if ((err = jffs_add_virtual_root(c)) < 0) {
534                         goto jffs_build_fs_fail;
535                 }
536         }
537
538         while (c->delete_list) {
539                 struct jffs_file *f;
540                 struct jffs_delete_list *delete_list_element;
541
542                 if ((f = jffs_find_file(c, c->delete_list->ino))) {
543                         f->deleted = 1;
544                 }
545                 delete_list_element = c->delete_list;
546                 c->delete_list = c->delete_list->next;
547                 kfree(delete_list_element);
548         }
549
550         /* Remove deleted nodes.  */
551         if ((err = jffs_foreach_file(c, jffs_possibly_delete_file)) < 0) {
552                 printk(KERN_ERR "JFFS: Failed to remove deleted nodes.\n");
553                 goto jffs_build_fs_fail;
554         }
555         /* Remove redundant nodes.  (We are not interested in the
556            return value in this case.)  */
557         jffs_foreach_file(c, jffs_remove_redundant_nodes);
558         /* Try to build a tree from all the nodes.  */
559         if ((err = jffs_foreach_file(c, jffs_insert_file_into_tree)) < 0) {
560                 printk("JFFS: Failed to build tree.\n");
561                 goto jffs_build_fs_fail;
562         }
563         /* Compute the sizes of all files in the filesystem.  Adjust if
564            necessary.  */
565         if ((err = jffs_foreach_file(c, jffs_build_file)) < 0) {
566                 printk("JFFS: Failed to build file system.\n");
567                 goto jffs_build_fs_fail;
568         }
569         sb->u.generic_sbp = (void *)c;
570         c->building_fs = 0;
571
572         D1(jffs_print_hash_table(c));
573         D1(jffs_print_tree(c->root, 0));
574
575         return 0;
576
577 jffs_build_fs_fail:
578         jffs_cleanup_control(c);
579         return err;
580 } /* jffs_build_fs()  */
581
582
583 /* Scan the whole flash memory in order to find all nodes in the
584    file systems.  */
585 static int
586 jffs_scan_flash(struct jffs_control *c)
587 {
588         char name[JFFS_MAX_NAME_LEN + 2];
589         struct jffs_raw_inode raw_inode;
590         struct jffs_node *node = 0;
591         struct jffs_fmcontrol *fmc = c->fmc;
592         __u32 checksum;
593         __u8 tmp_accurate;
594         __u16 tmp_chksum;
595         __u32 deleted_file;
596         loff_t pos = fmc->flash_start;
597         loff_t start;
598         loff_t end = fmc->flash_start + fmc->flash_size;
599         __u8 *read_buf;
600         int i, len, retlen;
601
602         D1(printk("jffs_scan_flash(): start pos = 0x%lx, end = 0x%lx\n",
603                   (long)pos, (long)end));
604
605         flash_safe_acquire(fmc->mtd);
606
607         /* Allocate read buffer */
608         read_buf = (__u8 *) kmalloc (sizeof(__u8) * 4096, GFP_KERNEL);
609
610         /* Start the scan.  */
611         while (pos < end) {
612                 deleted_file = 0;
613
614                 /* Remember the position from where we started this scan.  */
615                 start = pos;
616
617                 switch (flash_read_u32(fmc->mtd, pos)) {
618                 case JFFS_EMPTY_BITMASK:
619                         /* We have found 0xff at this position.  We have to
620                            scan the rest of the flash till the end or till
621                            something else than 0xff is found.  */
622                         D1(printk("jffs_scan_flash(): 0xff at pos 0x%lx.\n",
623                                   (long)pos));
624
625                         len = end - pos < 4096 ? end - pos : 4096;
626
627                         retlen = flash_safe_read(fmc->mtd, pos,
628                                                  &read_buf[0], len);
629
630                         retlen &= ~3;
631
632                         for (i=0 ; i < retlen ; i+=4, pos += 4) {
633                                 if(*((__u32 *) &read_buf[i]) !=
634                                                 JFFS_EMPTY_BITMASK)
635                                         break;
636                         }
637                         if (i == retlen)
638                                 continue;
639
640                         D1(printk("jffs_scan_flash(): 0xff ended at "
641                                   "pos 0x%lx.\n", (long)pos));
642
643                         /* If some free space ends in the middle of a sector,
644                                 treat it as dirty rather than clean.
645                            This is to handle the case where one thread 
646                            allocated space for a node, but didn't get to
647                            actually _write_ it before power was lost, leaving
648                            a gap in the log. Shifting all node writes into
649                            a single kernel thread will fix the original problem.
650                         */
651                         if ((__u32) pos % fmc->sector_size) {
652                                 /* If there was free space in previous 
653                                    sectors, don't mark that dirty too - 
654                                    only from the beginning of this sector
655                                    (or from start) 
656                                 */
657                                 if (start < (pos & ~(fmc->sector_size-1))) {
658                                         D1(printk("Reducing start to 0x%x from 0x%x\n", pos & ~(fmc->sector_size-1), start));
659                                         start = pos & ~(fmc->sector_size-1);
660                                 }
661                                 D1(printk("Dirty space: 0x%x for 0x%x bytes\n", start, (pos - start)));
662                                 jffs_fmalloced(fmc, (__u32) start,
663                                                (__u32) (pos - start), 0);
664                         }
665                         continue;
666
667                 case JFFS_DIRTY_BITMASK:
668                         /* We have found 0x00 at this position.  Scan as far
669                            as possible to find out how much is dirty.  */
670                         D1(printk("jffs_scan_flash(): 0x00 at pos 0x%lx.\n",
671                                   (long)pos));
672                         for (; pos < end
673                                && JFFS_DIRTY_BITMASK == flash_read_u32(fmc->mtd, pos);
674                              pos += 4);
675                         D1(printk("jffs_scan_flash(): 0x00 ended at "
676                                   "pos 0x%lx.\n", (long)pos));
677                         jffs_fmalloced(fmc, (__u32) start,
678                                        (__u32) (pos - start), 0);
679                         continue;
680
681                 case JFFS_MAGIC_BITMASK:
682                         /* We have probably found a new raw inode.  */
683                         break;
684
685                 default:
686                 bad_inode:
687                         /* We're f*cked.  This is not solved yet.  We have
688                            to scan for the magic pattern.  */
689                         D1(printk("*************** Dirty flash memory or "
690                                   "bad inode: "
691                                   "hexdump(pos = 0x%lx, len = 128):\n",
692                                   (long)pos));
693                         D1(jffs_hexdump(fmc->mtd, pos, 128));
694                 cont_dirty:
695                         for (pos += 4; pos < end; pos += 4) {
696                                 switch (flash_read_u32(fmc->mtd, pos)) {
697                                 case JFFS_MAGIC_BITMASK:
698                                         jffs_fmalloced(fmc, (__u32) start,
699                                                        (__u32) (pos - start),
700                                                        0);
701                                         goto cont_scan;
702                                 case JFFS_EMPTY_BITMASK:
703                                         /* First, mark as dirty the region
704                                            which really does contain crap. */
705                                         jffs_fmalloced(fmc, (__u32) start,
706                                                        (__u32) (pos - start),
707                                                        0);
708
709                                         /* Then, scan the region which looks free.
710                                            Depending on how large it is, we may
711                                            mark it dirty too.
712                                         */
713                                         start = pos;
714                                         for (; pos < end ; pos += 4) {
715                                                 switch (flash_read_u32(fmc->mtd, pos)) {
716                                                 case JFFS_MAGIC_BITMASK:
717                                                         if (pos - start < fmc->max_chunk_size) {
718                                                                 /* Not much free space. Mark it dirty. */
719                                                                 jffs_fmalloced(fmc, (__u32)start,
720                                                                                (__u32)pos-start, 0);
721                                                         }
722                                                         goto cont_scan;
723
724                                                 case JFFS_EMPTY_BITMASK:
725                                                         /* More empty space */
726                                                         continue;
727                                 
728                                                 default: 
729                                                         /* i.e. more dirt */
730                                                         if (pos - start < fmc->max_chunk_size) {
731                                                                 /* There wasn't much before the dirt
732                                                                    started again. Just mark it all dirty
733                                                                 */
734                                                                 goto cont_dirty;
735                                                         }
736                                                         /* There was quite a lot of free space. Leave it
737                                                            free.
738                                                         */
739                                                         goto cont_scan;
740                                                 }
741                                         }
742                                 default:
743                                         break;
744                                 }
745                         }
746                         cont_scan:
747                         continue;
748                 }
749
750                 /* We have found the beginning of an inode.  Create a
751                    node for it unless there already is one available.  */
752                 if (!node) {
753                         if (!(node = (struct jffs_node *)
754                                      kmalloc(sizeof(struct jffs_node),
755                                              GFP_KERNEL))) {
756                                 /* Free read buffer */
757                                 kfree (read_buf);
758
759                                 /* Release the flash device */
760                                 flash_safe_release(fmc->mtd);
761         
762                                 return -ENOMEM;
763                         }
764                         DJM(no_jffs_node++);
765                 }
766
767                 /* Read the next raw inode.  */
768
769                 flash_safe_read(fmc->mtd, pos, (u_char *) &raw_inode,
770                                 sizeof(struct jffs_raw_inode));
771
772                 /* When we compute the checksum for the inode, we never
773                    count the 'accurate' or the 'checksum' fields.  */
774                 tmp_accurate = raw_inode.accurate;
775                 tmp_chksum = raw_inode.chksum;
776                 raw_inode.accurate = 0;
777                 raw_inode.chksum = 0;
778                 checksum = jffs_checksum(&raw_inode,
779                                          sizeof(struct jffs_raw_inode));
780                 raw_inode.accurate = tmp_accurate;
781                 raw_inode.chksum = tmp_chksum;
782
783                 D3(printk("*** We have found this raw inode at pos 0x%lx "
784                           "on the flash:\n", (long)pos));
785                 D3(jffs_print_raw_inode(&raw_inode));
786
787                 if (checksum != raw_inode.chksum) {
788                         D1(printk("jffs_scan_flash(): Bad checksum: "
789                                   "checksum = %u, "
790                                   "raw_inode.chksum = %u\n",
791                                   checksum, raw_inode.chksum));
792                         pos += sizeof(struct jffs_raw_inode);
793                         jffs_fmalloced(fmc, (__u32) start,
794                                        (__u32) (pos - start), 0);
795                         /* Reuse this unused struct jffs_node.  */
796                         continue;
797                 }
798
799                 /* Check the raw inode read so far.  Start with the
800                    maximum length of the filename.  */
801                 if (raw_inode.nsize > JFFS_MAX_NAME_LEN) {
802                         printk(KERN_WARNING "jffs_scan_flash: Found a "
803                                "JFFS node with name too large\n");
804                         goto bad_inode;
805                 }
806
807                 if (raw_inode.rename && raw_inode.dsize != sizeof(__u32)) {
808                         printk(KERN_WARNING "jffs_scan_flash: Found a "
809                                "rename node with dsize %u.\n",
810                                raw_inode.dsize);
811                         jffs_print_raw_inode(&raw_inode);
812                         goto bad_inode;
813                 }
814
815                 /* The node's data segment should not exceed a
816                    certain length.  */
817                 if (raw_inode.dsize > fmc->max_chunk_size) {
818                         printk(KERN_WARNING "jffs_scan_flash: Found a "
819                                "JFFS node with dsize (0x%x) > max_chunk_size (0x%x)\n",
820                                raw_inode.dsize, fmc->max_chunk_size);
821                         goto bad_inode;
822                 }
823
824                 pos += sizeof(struct jffs_raw_inode);
825
826                 /* This shouldn't be necessary because a node that
827                    violates the flash boundaries shouldn't be written
828                    in the first place. */
829                 if (pos >= end) {
830                         goto check_node;
831                 }
832
833                 /* Read the name.  */
834                 *name = 0;
835                 if (raw_inode.nsize) {
836                         flash_safe_read(fmc->mtd, pos, name, raw_inode.nsize);
837                         name[raw_inode.nsize] = '\0';
838                         pos += raw_inode.nsize
839                                + JFFS_GET_PAD_BYTES(raw_inode.nsize);
840                         D3(printk("name == \"%s\"\n", name));
841                         checksum = jffs_checksum(name, raw_inode.nsize);
842                         if (checksum != raw_inode.nchksum) {
843                                 D1(printk("jffs_scan_flash(): Bad checksum: "
844                                           "checksum = %u, "
845                                           "raw_inode.nchksum = %u\n",
846                                           checksum, raw_inode.nchksum));
847                                 jffs_fmalloced(fmc, (__u32) start,
848                                                (__u32) (pos - start), 0);
849                                 /* Reuse this unused struct jffs_node.  */
850                                 continue;
851                         }
852                         if (pos >= end) {
853                                 goto check_node;
854                         }
855                 }
856
857                 /* Read the data, if it exists, in order to be sure it
858                    matches the checksum.  */
859                 if (raw_inode.dsize) {
860                         if (raw_inode.rename) {
861                                 deleted_file = flash_read_u32(fmc->mtd, pos);
862                         }
863                         checksum = jffs_checksum_flash(fmc->mtd, pos, raw_inode.dsize);
864                         pos += raw_inode.dsize
865                                + JFFS_GET_PAD_BYTES(raw_inode.dsize);
866
867                         if (checksum != raw_inode.dchksum) {
868                                 D1(printk("jffs_scan_flash(): Bad checksum: "
869                                           "checksum = %u, "
870                                           "raw_inode.dchksum = %u\n",
871                                           checksum, raw_inode.dchksum));
872                                 jffs_fmalloced(fmc, (__u32) start,
873                                                (__u32) (pos - start), 0);
874                                 /* Reuse this unused struct jffs_node.  */
875                                 continue;
876                         }
877                 }
878
879                 check_node:
880
881                 /* Remember the highest inode number in the whole file
882                    system.  This information will be used when assigning
883                    new files new inode numbers.  */
884                 if (c->next_ino <= raw_inode.ino) {
885                         c->next_ino = raw_inode.ino + 1;
886                 }
887
888                 if (raw_inode.accurate) {
889                         int err;
890                         node->data_offset = raw_inode.offset;
891                         node->data_size = raw_inode.dsize;
892                         node->removed_size = raw_inode.rsize;
893                         /* Compute the offset to the actual data in the
894                            on-flash node.  */
895                         node->fm_offset
896                         = sizeof(struct jffs_raw_inode)
897                           + raw_inode.nsize
898                           + JFFS_GET_PAD_BYTES(raw_inode.nsize);
899                         node->fm = jffs_fmalloced(fmc, (__u32) start,
900                                                   (__u32) (pos - start),
901                                                   node);
902                         if (!node->fm) {
903                                 D(printk("jffs_scan_flash(): !node->fm\n"));
904                                 kfree(node);
905                                 DJM(no_jffs_node--);
906
907                                 /* Free read buffer */
908                                 kfree (read_buf);
909
910                                 /* Release the flash device */
911                                 flash_safe_release(fmc->mtd);
912
913                                 return -ENOMEM;
914                         }
915                         if ((err = jffs_insert_node(c, 0, &raw_inode,
916                                                     name, node)) < 0) {
917                                 printk("JFFS: Failed to handle raw inode. "
918                                        "(err = %d)\n", err);
919                                 break;
920                         }
921                         if (raw_inode.rename) {
922                                 struct jffs_delete_list *dl
923                                 = (struct jffs_delete_list *)
924                                   kmalloc(sizeof(struct jffs_delete_list),
925                                           GFP_KERNEL);
926                                 if (!dl) {
927                                         D(printk("jffs_scan_flash: !dl\n"));
928                                         kfree(node);
929                                         DJM(no_jffs_node--);
930
931                                         /* Release the flash device */
932                                         flash_safe_release(fmc->flash_part);
933
934                                         /* Free read buffer */
935                                         kfree (read_buf);
936
937                                         return -ENOMEM;
938                                 }
939                                 dl->ino = deleted_file;
940                                 dl->next = c->delete_list;
941                                 c->delete_list = dl;
942                                 node->data_size = 0;
943                         }
944                         D3(jffs_print_node(node));
945                         node = 0; /* Don't free the node!  */
946                 }
947                 else {
948                         jffs_fmalloced(fmc, (__u32) start,
949                                        (__u32) (pos - start), 0);
950                         D3(printk("jffs_scan_flash(): Just found an obsolete "
951                                   "raw_inode. Continuing the scan...\n"));
952                         /* Reuse this unused struct jffs_node.  */
953                 }
954         }
955
956         if (node) {
957                 kfree(node);
958                 DJM(no_jffs_node--);
959         }
960         jffs_build_end(fmc);
961
962         /* Free read buffer */
963         kfree (read_buf);
964
965         /* Return happy */
966         D3(printk("jffs_scan_flash(): Leaving...\n"));
967         flash_safe_release(fmc->mtd);
968         return 0;
969 } /* jffs_scan_flash()  */
970
971
972 /* Insert any kind of node into the file system.  Take care of data
973    insertions and deletions.  Also remove redundant information. The
974    memory allocated for the `name' is regarded as "given away" in the
975    caller's perspective.  */
976 int
977 jffs_insert_node(struct jffs_control *c, struct jffs_file *f,
978                  const struct jffs_raw_inode *raw_inode,
979                  const char *name, struct jffs_node *node)
980 {
981         int update_name = 0;
982         int insert_into_tree = 0;
983
984         D2(printk("jffs_insert_node(): ino = %u, version = %u, "
985                   "name = \"%s\", deleted = %d\n",
986                   raw_inode->ino, raw_inode->version,
987                   ((name && *name) ? name : ""), raw_inode->deleted));
988
989         /* If there doesn't exist an associated jffs_file, then
990            create, initialize and insert one into the file system.  */
991         if (!f && !(f = jffs_find_file(c, raw_inode->ino))) {
992                 if (!(f = jffs_create_file(c, raw_inode))) {
993                         return -ENOMEM;
994                 }
995                 jffs_insert_file_into_hash(f);
996                 insert_into_tree = 1;
997         }
998         node->ino = raw_inode->ino;
999         node->version = raw_inode->version;
1000         node->data_size = raw_inode->dsize;
1001         node->fm_offset = sizeof(struct jffs_raw_inode) + raw_inode->nsize
1002                           + JFFS_GET_PAD_BYTES(raw_inode->nsize);
1003         node->name_size = raw_inode->nsize;
1004
1005         /* Now insert the node at the correct position into the file's
1006            version list.  */
1007         if (!f->version_head) {
1008                 /* This is the first node.  */
1009                 f->version_head = node;
1010                 f->version_tail = node;
1011                 node->version_prev = 0;
1012                 node->version_next = 0;
1013                 f->highest_version = node->version;
1014                 update_name = 1;
1015                 f->mode = raw_inode->mode;
1016                 f->uid = raw_inode->uid;
1017                 f->gid = raw_inode->gid;
1018                 f->atime = raw_inode->atime;
1019                 f->mtime = raw_inode->mtime;
1020                 f->ctime = raw_inode->ctime;
1021                 f->deleted = raw_inode->deleted;
1022         }
1023         else if ((f->highest_version < node->version)
1024                  || (node->version == 0)) {
1025                 /* Insert at the end of the list.  I.e. this node is the
1026                    oldest one so far.  */
1027                 node->version_prev = f->version_tail;
1028                 node->version_next = 0;
1029                 f->version_tail->version_next = node;
1030                 f->version_tail = node;
1031                 f->highest_version = node->version;
1032                 update_name = 1;
1033                 f->pino = raw_inode->pino;
1034                 f->mode = raw_inode->mode;
1035                 f->uid = raw_inode->uid;
1036                 f->gid = raw_inode->gid;
1037                 f->atime = raw_inode->atime;
1038                 f->mtime = raw_inode->mtime;
1039                 f->ctime = raw_inode->ctime;
1040                 f->deleted = raw_inode->deleted;
1041         }
1042         else if (f->version_head->version > node->version) {
1043                 /* Insert at the bottom of the list.  */
1044                 node->version_prev = 0;
1045                 node->version_next = f->version_head;
1046                 f->version_head->version_prev = node;
1047                 f->version_head = node;
1048                 if (!f->name) {
1049                         update_name = 1;
1050                 }
1051                 if (raw_inode->deleted) {
1052                         f->deleted = raw_inode->deleted;
1053                 }
1054         }
1055         else {
1056                 struct jffs_node *n;
1057                 int newer_name = 0;
1058                 /* Search for the insertion position starting from
1059                    the tail (newest node).  */
1060                 for (n = f->version_tail; n; n = n->version_prev) {
1061                         if (n->version < node->version) {
1062                                 node->version_prev = n;
1063                                 node->version_next = n->version_next;
1064                                 node->version_next->version_prev = node;
1065                                 n->version_next = node;
1066                                 if (!newer_name) {
1067                                         update_name = 1;
1068                                 }
1069                                 break;
1070                         }
1071                         if (n->name_size) {
1072                                 newer_name = 1;
1073                         }
1074                 }
1075         }
1076
1077         /* Perhaps update the name.  */
1078         if (raw_inode->nsize && update_name && name && *name && (name != f->name)) {
1079                 if (f->name) {
1080                         kfree(f->name);
1081                         DJM(no_name--);
1082                 }
1083                 if (!(f->name = (char *) kmalloc(raw_inode->nsize + 1,
1084                                                  GFP_KERNEL))) {
1085                         return -ENOMEM;
1086                 }
1087                 DJM(no_name++);
1088                 memcpy(f->name, name, raw_inode->nsize);
1089                 f->name[raw_inode->nsize] = '\0';
1090                 f->nsize = raw_inode->nsize;
1091                 D3(printk("jffs_insert_node(): Updated the name of "
1092                           "the file to \"%s\".\n", name));
1093         }
1094
1095         if (!c->building_fs) {
1096                 D3(printk("jffs_insert_node(): ---------------------------"
1097                           "------------------------------------------- 1\n"));
1098                 if (insert_into_tree) {
1099                         jffs_insert_file_into_tree(f);
1100                 }
1101                 if (f->deleted) {
1102                         /* Mark all versions of the node as obsolete.  */
1103                         jffs_possibly_delete_file(f);
1104                 }
1105                 else {
1106                         if (node->data_size || node->removed_size) {
1107                                 jffs_update_file(f, node);
1108                         }
1109                         jffs_remove_redundant_nodes(f);
1110                 }
1111
1112                 jffs_garbage_collect_trigger(c);
1113
1114                 D3(printk("jffs_insert_node(): ---------------------------"
1115                           "------------------------------------------- 2\n"));
1116         }
1117
1118         return 0;
1119 } /* jffs_insert_node()  */
1120
1121
1122 /* Unlink a jffs_node from the version list it is in.  */
1123 static inline void
1124 jffs_unlink_node_from_version_list(struct jffs_file *f,
1125                                    struct jffs_node *node)
1126 {
1127         if (node->version_prev) {
1128                 node->version_prev->version_next = node->version_next;
1129         } else {
1130                 f->version_head = node->version_next;
1131         }
1132         if (node->version_next) {
1133                 node->version_next->version_prev = node->version_prev;
1134         } else {
1135                 f->version_tail = node->version_prev;
1136         }
1137 }
1138
1139
1140 /* Unlink a jffs_node from the range list it is in.  */
1141 static inline void
1142 jffs_unlink_node_from_range_list(struct jffs_file *f, struct jffs_node *node)
1143 {
1144         if (node->range_prev) {
1145                 node->range_prev->range_next = node->range_next;
1146         }
1147         else {
1148                 f->range_head = node->range_next;
1149         }
1150         if (node->range_next) {
1151                 node->range_next->range_prev = node->range_prev;
1152         }
1153         else {
1154                 f->range_tail = node->range_prev;
1155         }
1156 }
1157
1158
1159 /* Function used by jffs_remove_redundant_nodes() below.  This function
1160    classifies what kind of information a node adds to a file.  */
1161 static inline __u8
1162 jffs_classify_node(struct jffs_node *node)
1163 {
1164         __u8 mod_type = JFFS_MODIFY_INODE;
1165
1166         if (node->name_size) {
1167                 mod_type |= JFFS_MODIFY_NAME;
1168         }
1169         if (node->data_size || node->removed_size) {
1170                 mod_type |= JFFS_MODIFY_DATA;
1171         }
1172         return mod_type;
1173 }
1174
1175
1176 /* Remove redundant nodes from a file.  Mark the on-flash memory
1177    as dirty.  */
1178 int
1179 jffs_remove_redundant_nodes(struct jffs_file *f)
1180 {
1181         struct jffs_node *newest_node;
1182         struct jffs_node *cur;
1183         struct jffs_node *prev;
1184         __u8 newest_type;
1185         __u8 mod_type;
1186         __u8 node_with_name_later = 0;
1187
1188         if (!(newest_node = f->version_tail)) {
1189                 return 0;
1190         }
1191
1192         /* What does the `newest_node' modify?  */
1193         newest_type = jffs_classify_node(newest_node);
1194         node_with_name_later = newest_type & JFFS_MODIFY_NAME;
1195
1196         D3(printk("jffs_remove_redundant_nodes(): ino: %u, name: \"%s\", "
1197                   "newest_type: %u\n", f->ino, (f->name ? f->name : ""),
1198                   newest_type));
1199
1200         /* Traverse the file's nodes and determine which of them that are
1201            superfluous.  Yeah, this might look very complex at first
1202            glance but it is actually very simple.  */
1203         for (cur = newest_node->version_prev; cur; cur = prev) {
1204                 prev = cur->version_prev;
1205                 mod_type = jffs_classify_node(cur);
1206                 if ((mod_type <= JFFS_MODIFY_INODE)
1207                     || ((newest_type & JFFS_MODIFY_NAME)
1208                         && (mod_type
1209                             <= (JFFS_MODIFY_INODE + JFFS_MODIFY_NAME)))
1210                     || (cur->data_size == 0 && cur->removed_size
1211                         && !cur->version_prev && node_with_name_later)) {
1212                         /* Yes, this node is redundant. Remove it.  */
1213                         D2(printk("jffs_remove_redundant_nodes(): "
1214                                   "Removing node: ino: %u, version: %u, "
1215                                   "mod_type: %u\n", cur->ino, cur->version,
1216                                   mod_type));
1217                         jffs_unlink_node_from_version_list(f, cur);
1218                         jffs_fmfree(f->c->fmc, cur->fm, cur);
1219                         kfree(cur);
1220                         DJM(no_jffs_node--);
1221                 }
1222                 else {
1223                         node_with_name_later |= (mod_type & JFFS_MODIFY_NAME);
1224                 }
1225         }
1226
1227         return 0;
1228 }
1229
1230
1231 /* Insert a file into the hash table.  */
1232 int
1233 jffs_insert_file_into_hash(struct jffs_file *f)
1234 {
1235         int i = f->ino % f->c->hash_len;
1236
1237         D3(printk("jffs_insert_file_into_hash(): f->ino: %u\n", f->ino));
1238
1239         list_add(&f->hash, &f->c->hash[i]);
1240         return 0;
1241 }
1242
1243
1244 /* Insert a file into the file system tree.  */
1245 int
1246 jffs_insert_file_into_tree(struct jffs_file *f)
1247 {
1248         struct jffs_file *parent;
1249
1250         D3(printk("jffs_insert_file_into_tree(): name: \"%s\"\n",
1251                   (f->name ? f->name : "")));
1252
1253         if (!(parent = jffs_find_file(f->c, f->pino))) {
1254                 if (f->pino == 0) {
1255                         f->c->root = f;
1256                         f->parent = 0;
1257                         f->sibling_prev = 0;
1258                         f->sibling_next = 0;
1259                         return 0;
1260                 }
1261                 else {
1262                         D1(printk("jffs_insert_file_into_tree(): Found "
1263                                   "inode with no parent and pino == %u\n",
1264                                   f->pino));
1265                         return -1;
1266                 }
1267         }
1268         f->parent = parent;
1269         f->sibling_next = parent->children;
1270         if (f->sibling_next) {
1271                 f->sibling_next->sibling_prev = f;
1272         }
1273         f->sibling_prev = 0;
1274         parent->children = f;
1275         return 0;
1276 }
1277
1278
1279 /* Remove a file from the hash table.  */
1280 int
1281 jffs_unlink_file_from_hash(struct jffs_file *f)
1282 {
1283         D3(printk("jffs_unlink_file_from_hash(): f: 0x%p, "
1284                   "ino %u\n", f, f->ino));
1285
1286         list_del(&f->hash);
1287         return 0;
1288 }
1289
1290
1291 /* Just remove the file from the parent's children.  Don't free
1292    any memory.  */
1293 int
1294 jffs_unlink_file_from_tree(struct jffs_file *f)
1295 {
1296         D3(printk("jffs_unlink_file_from_tree(): ino: %d, pino: %d, name: "
1297                   "\"%s\"\n", f->ino, f->pino, (f->name ? f->name : "")));
1298
1299         if (f->sibling_prev) {
1300                 f->sibling_prev->sibling_next = f->sibling_next;
1301         }
1302         else if (f->parent) {
1303                 D3(printk("f->parent=%p\n", f->parent));
1304                 f->parent->children = f->sibling_next;
1305         }
1306         if (f->sibling_next) {
1307                 f->sibling_next->sibling_prev = f->sibling_prev;
1308         }
1309         return 0;
1310 }
1311
1312
1313 /* Find a file with its inode number.  */
1314 struct jffs_file *
1315 jffs_find_file(struct jffs_control *c, __u32 ino)
1316 {
1317         struct jffs_file *f;
1318         int i = ino % c->hash_len;
1319         struct list_head *tmp;
1320
1321         D3(printk("jffs_find_file(): ino: %u\n", ino));
1322
1323         for (tmp = c->hash[i].next; tmp != &c->hash[i]; tmp = tmp->next) {
1324                 f = list_entry(tmp, struct jffs_file, hash);
1325                 if (ino != f->ino)
1326                         continue;
1327                 D3(printk("jffs_find_file(): Found file with ino "
1328                                "%u. (name: \"%s\")\n",
1329                                ino, (f->name ? f->name : ""));
1330                 );
1331                 return f;
1332         }
1333         D3(printk("jffs_find_file(): Didn't find file "
1334                          "with ino %u.\n", ino);
1335         );
1336         return NULL;
1337 }
1338
1339
1340 /* Find a file in a directory.  We are comparing the names.  */
1341 struct jffs_file *
1342 jffs_find_child(struct jffs_file *dir, const char *name, int len)
1343 {
1344         struct jffs_file *f;
1345
1346         D3(printk("jffs_find_child()\n"));
1347
1348         for (f = dir->children; f; f = f->sibling_next) {
1349                 if (f->name
1350                     && !strncmp(f->name, name, len)
1351                     && f->name[len] == '\0') {
1352                         break;
1353                 }
1354         }
1355
1356         D3(if (f) {
1357                 printk("jffs_find_child(): Found \"%s\".\n", f->name);
1358         }
1359         else {
1360                 char *copy = (char *) kmalloc(len + 1, GFP_KERNEL);
1361                 if (copy) {
1362                         memcpy(copy, name, len);
1363                         copy[len] = '\0';
1364                 }
1365                 printk("jffs_find_child(): Didn't find the file \"%s\".\n",
1366                        (copy ? copy : ""));
1367                 if (copy) {
1368                         kfree(copy);
1369                 }
1370         });
1371
1372         return f;
1373 }
1374
1375
1376 /* Write a raw inode that takes up a certain amount of space in the flash
1377    memory.  At the end of the flash device, there is often space that is
1378    impossible to use.  At these times we want to mark this space as not
1379    used.  In the cases when the amount of space is greater or equal than
1380    a struct jffs_raw_inode, we write a "dummy node" that takes up this
1381    space.  The space after the raw inode, if it exists, is left as it is.
1382    Since this space after the raw inode contains JFFS_EMPTY_BITMASK bytes,
1383    we can compute the checksum of it; we don't have to manipulate it any
1384    further.
1385
1386    If the space left on the device is less than the size of a struct
1387    jffs_raw_inode, this space is filled with JFFS_DIRTY_BITMASK bytes.
1388    No raw inode is written this time.  */
1389 static int
1390 jffs_write_dummy_node(struct jffs_control *c, struct jffs_fm *dirty_fm)
1391 {
1392         struct jffs_fmcontrol *fmc = c->fmc;
1393         int err;
1394
1395         D1(printk("jffs_write_dummy_node(): dirty_fm->offset = 0x%08x, "
1396                   "dirty_fm->size = %u\n",
1397                   dirty_fm->offset, dirty_fm->size));
1398
1399         if (dirty_fm->size >= sizeof(struct jffs_raw_inode)) {
1400                 struct jffs_raw_inode raw_inode;
1401                 memset(&raw_inode, 0, sizeof(struct jffs_raw_inode));
1402                 raw_inode.magic = JFFS_MAGIC_BITMASK;
1403                 raw_inode.dsize = dirty_fm->size
1404                                   - sizeof(struct jffs_raw_inode);
1405                 raw_inode.dchksum = raw_inode.dsize * 0xff;
1406                 raw_inode.chksum
1407                 = jffs_checksum(&raw_inode, sizeof(struct jffs_raw_inode));
1408
1409                 if ((err = flash_safe_write(fmc->mtd,
1410                                             dirty_fm->offset,
1411                                             (u_char *)&raw_inode,
1412                                             sizeof(struct jffs_raw_inode)))
1413                     < 0) {
1414                         printk(KERN_ERR "JFFS: jffs_write_dummy_node: "
1415                                "flash_safe_write failed!\n");
1416                         return err;
1417                 }
1418         }
1419         else {
1420                 flash_safe_acquire(fmc->mtd);
1421                 flash_memset(fmc->mtd, dirty_fm->offset, 0, dirty_fm->size);
1422                 flash_safe_release(fmc->mtd);
1423         }
1424
1425         D3(printk("jffs_write_dummy_node(): Leaving...\n"));
1426         return 0;
1427 }
1428
1429
1430 /* Write a raw inode, possibly its name and possibly some data.  */
1431 int
1432 jffs_write_node(struct jffs_control *c, struct jffs_node *node,
1433                 struct jffs_raw_inode *raw_inode,
1434                 const char *name, const unsigned char *data,
1435                 int recoverable,
1436                 struct jffs_file *f)
1437 {
1438         struct jffs_fmcontrol *fmc = c->fmc;
1439         struct jffs_fm *fm = NULL;
1440         __u32 pos;
1441         int err;
1442         __u32 slack = 0;
1443
1444         __u32 total_name_size = raw_inode->nsize
1445                                 + JFFS_GET_PAD_BYTES(raw_inode->nsize);
1446         __u32 total_data_size = raw_inode->dsize
1447                                 + JFFS_GET_PAD_BYTES(raw_inode->dsize);
1448         __u32 total_size = sizeof(struct jffs_raw_inode)
1449                            + total_name_size + total_data_size;
1450         
1451         /* If this node isn't something that will eventually let
1452            GC free even more space, then don't allow it unless
1453            there's at least max_chunk_size space still available
1454         */
1455         if (!recoverable)
1456                 slack = fmc->max_chunk_size;
1457                 
1458
1459         /* Fire the retrorockets and shoot the fruiton torpedoes, sir!  */
1460
1461         ASSERT(if (!node) {
1462                 printk("jffs_write_node(): node == NULL\n");
1463                 return -EINVAL;
1464         });
1465         ASSERT(if (raw_inode && raw_inode->nsize && !name) {
1466                 printk("*** jffs_write_node(): nsize = %u but name == NULL\n",
1467                        raw_inode->nsize);
1468                 return -EINVAL;
1469         });
1470
1471         D1(printk("jffs_write_node(): filename = \"%s\", ino = %u, "
1472                   "total_size = %u\n",
1473                   (name ? name : ""), raw_inode->ino,
1474                   total_size));
1475
1476         jffs_fm_write_lock(fmc);
1477
1478         while (!fm) {
1479
1480                 /* Deadlocks suck. */
1481                 while(fmc->free_size < fmc->min_free_size + total_size + slack) {
1482                         jffs_fm_write_unlock(fmc);
1483                         if (!JFFS_ENOUGH_SPACE(c, total_size + slack))
1484                                 return -ENOSPC;
1485                         jffs_fm_write_lock(fmc);
1486                 }
1487
1488                 /* First try to allocate some flash memory.  */
1489                 err = jffs_fmalloc(fmc, total_size, node, &fm);
1490                 
1491                 if (err == -ENOSPC) {
1492                         /* Just out of space. GC and try again */
1493                         if (fmc->dirty_size < fmc->sector_size) {
1494                                 D(printk("jffs_write_node(): jffs_fmalloc(0x%p, %u) "
1495                                          "failed, no dirty space to GC\n", fmc,
1496                                          total_size));
1497                                 return err;
1498                         }
1499                         
1500                         D1(printk(KERN_INFO "jffs_write_node(): Calling jffs_garbage_collect_now()\n"));
1501                         jffs_fm_write_unlock(fmc);
1502                         if ((err = jffs_garbage_collect_now(c))) {
1503                                 D(printk("jffs_write_node(): jffs_garbage_collect_now() failed\n"));
1504                                 return err;
1505                         }
1506                         jffs_fm_write_lock(fmc);
1507                         continue;
1508                 } 
1509
1510                 if (err < 0) {
1511                         jffs_fm_write_unlock(fmc);
1512
1513                         D(printk("jffs_write_node(): jffs_fmalloc(0x%p, %u) "
1514                                  "failed!\n", fmc, total_size));
1515                         return err;
1516                 }
1517
1518                 if (!fm->nodes) {
1519                         /* The jffs_fm struct that we got is not good enough.
1520                            Make that space dirty and try again  */
1521                         if ((err = jffs_write_dummy_node(c, fm)) < 0) {
1522                                 kfree(fm);
1523                                 DJM(no_jffs_fm--);
1524                                 jffs_fm_write_unlock(fmc);
1525                                 D(printk("jffs_write_node(): "
1526                                          "jffs_write_dummy_node(): Failed!\n"));
1527                                 return err;
1528                         }
1529                         fm = NULL;
1530                 }
1531         } /* while(!fm) */
1532         node->fm = fm;
1533
1534         ASSERT(if (fm->nodes == 0) {
1535                 printk(KERN_ERR "jffs_write_node(): fm->nodes == 0\n");
1536         });
1537
1538         pos = node->fm->offset;
1539
1540         /* Increment the version number here. We can't let the caller
1541            set it beforehand, because we might have had to do GC on a node
1542            of this file - and we'd end up reusing version numbers.
1543         */
1544         if (f) {
1545                 raw_inode->version = f->highest_version + 1;
1546                 D1(printk (KERN_NOTICE "jffs_write_node(): setting version of %s to %d\n", f->name, raw_inode->version));
1547         }
1548
1549         /* Compute the checksum for the data and name chunks.  */
1550         raw_inode->dchksum = jffs_checksum(data, raw_inode->dsize);
1551         raw_inode->nchksum = jffs_checksum(name, raw_inode->nsize);
1552
1553         /* The checksum is calculated without the chksum and accurate
1554            fields so set them to zero first.  */
1555         raw_inode->accurate = 0;
1556         raw_inode->chksum = 0;
1557         raw_inode->chksum = jffs_checksum(raw_inode,
1558                                           sizeof(struct jffs_raw_inode));
1559         raw_inode->accurate = 0xff;
1560
1561         D3(printk("jffs_write_node(): About to write this raw inode to the "
1562                   "flash at pos 0x%lx:\n", (long)pos));
1563         D3(jffs_print_raw_inode(raw_inode));
1564
1565         /* Step 1: Write the raw jffs inode to the flash.  */
1566         if ((err = flash_safe_write(fmc->mtd, pos,
1567                                     (u_char *)raw_inode,
1568                                     sizeof(struct jffs_raw_inode))) < 0) {
1569                 jffs_fmfree_partly(fmc, fm,
1570                                    total_name_size + total_data_size);
1571                 jffs_fm_write_unlock(fmc);
1572                 printk(KERN_ERR "JFFS: jffs_write_node: Failed to write "
1573                        "raw_inode.\n");
1574                 return err;
1575         }
1576         pos += sizeof(struct jffs_raw_inode);
1577
1578         /* Step 2: Write the name, if there is any.  */
1579         if (raw_inode->nsize) {
1580                 if ((err = flash_safe_write(fmc->mtd, pos,
1581                                             (u_char *)name,
1582                                             raw_inode->nsize)) < 0) {
1583                         jffs_fmfree_partly(fmc, fm, total_data_size);
1584                         jffs_fm_write_unlock(fmc);
1585                         printk(KERN_ERR "JFFS: jffs_write_node: Failed to "
1586                               "write the name.\n");
1587                         return err;
1588                 }
1589                 pos += total_name_size;
1590         }
1591
1592         /* Step 3: Append the actual data, if any.  */
1593         if (raw_inode->dsize) {
1594                 if ((err = flash_safe_write(fmc->mtd, pos, data,
1595                                             raw_inode->dsize)) < 0) {
1596                         jffs_fmfree_partly(fmc, fm, 0);
1597                         jffs_fm_write_unlock(fmc);
1598                         printk(KERN_ERR "JFFS: jffs_write_node: Failed to "
1599                                "write the data.\n");
1600                         return err;
1601                 }
1602         }
1603         jffs_fm_write_unlock(fmc);
1604         D3(printk("jffs_write_node(): Leaving...\n"));
1605         return raw_inode->dsize;
1606 } /* jffs_write_node()  */
1607
1608
1609 /* Read data from the node and write it to the buffer.  'node_offset'
1610    is how much we have read from this particular node before and which
1611    shouldn't be read again.  'max_size' is how much space there is in
1612    the buffer.  */
1613 static int
1614 jffs_get_node_data(struct jffs_file *f, struct jffs_node *node, 
1615                    unsigned char *buf,__u32 node_offset, __u32 max_size,
1616                    kdev_t dev)
1617 {
1618         struct jffs_fmcontrol *fmc = f->c->fmc;
1619         __u32 pos = node->fm->offset + node->fm_offset + node_offset;
1620         __u32 avail = node->data_size - node_offset;
1621         __u32 r;
1622
1623         D2(printk("  jffs_get_node_data(): file: \"%s\", ino: %u, "
1624                   "version: %u, node_offset: %u\n",
1625                   f->name, node->ino, node->version, node_offset));
1626
1627         r = jffs_min(avail, max_size);
1628         D3(printk(KERN_NOTICE "jffs_get_node_data\n"));
1629         flash_safe_read(fmc->mtd, pos, buf, r);
1630
1631         D3(printk("  jffs_get_node_data(): Read %u byte%s.\n",
1632                   r, (r == 1 ? "" : "s")));
1633
1634         return r;
1635 }
1636
1637
1638 /* Read data from the file's nodes.  Write the data to the buffer
1639    'buf'.  'read_offset' tells how much data we should skip.  */
1640 int
1641 jffs_read_data(struct jffs_file *f, unsigned char *buf, __u32 read_offset,
1642                __u32 size)
1643 {
1644         struct jffs_node *node;
1645         __u32 read_data = 0; /* Total amount of read data.  */
1646         __u32 node_offset = 0;
1647         __u32 pos = 0; /* Number of bytes traversed.  */
1648
1649         D2(printk("jffs_read_data(): file = \"%s\", read_offset = %d, "
1650                   "size = %u\n",
1651                   (f->name ? f->name : ""), read_offset, size));
1652
1653         if (read_offset >= f->size) {
1654                 D(printk("  f->size: %d\n", f->size));
1655                 return 0;
1656         }
1657
1658         /* First find the node to read data from.  */
1659         node = f->range_head;
1660         while (pos <= read_offset) {
1661                 node_offset = read_offset - pos;
1662                 if (node_offset >= node->data_size) {
1663                         pos += node->data_size;
1664                         node = node->range_next;
1665                 }
1666                 else {
1667                         break;
1668                 }
1669         }
1670
1671         /* "Cats are living proof that not everything in nature
1672            has to be useful."
1673            - Garrison Keilor ('97)  */
1674
1675         /* Fill the buffer.  */
1676         while (node && (read_data < size)) {
1677                 int r;
1678                 if (!node->fm) {
1679                         /* This node does not refer to real data.  */
1680                         r = jffs_min(size - read_data,
1681                                      node->data_size - node_offset);
1682                         memset(&buf[read_data], 0, r);
1683                 }
1684                 else if ((r = jffs_get_node_data(f, node, &buf[read_data],
1685                                                  node_offset,
1686                                                  size - read_data,
1687                                                  f->c->sb->s_dev)) < 0) {
1688                         return r;
1689                 }
1690                 read_data += r;
1691                 node_offset = 0;
1692                 node = node->range_next;
1693         }
1694         D3(printk("  jffs_read_data(): Read %u bytes.\n", read_data));
1695         return read_data;
1696 }
1697
1698
1699 /* Used for traversing all nodes in the hash table.  */
1700 int
1701 jffs_foreach_file(struct jffs_control *c, int (*func)(struct jffs_file *))
1702 {
1703         int pos;
1704         int r;
1705         int result = 0;
1706
1707         for (pos = 0; pos < c->hash_len; pos++) {
1708                 struct list_head *p, *next;
1709                 for (p = c->hash[pos].next; p != &c->hash[pos]; p = next) {
1710                         /* We need a reference to the next file in the
1711                            list because `func' might remove the current
1712                            file `f'.  */
1713                         next = p->next;
1714                         r = func(list_entry(p, struct jffs_file, hash));
1715                         if (r < 0)
1716                                 return r;
1717                         result += r;
1718                 }
1719         }
1720
1721         return result;
1722 }
1723
1724
1725 /* Free all nodes associated with a file.  */
1726 int
1727 jffs_free_node_list(struct jffs_file *f)
1728 {
1729         struct jffs_node *node;
1730         struct jffs_node *p;
1731
1732         D3(printk("jffs_free_node_list(): f #%u, \"%s\"\n",
1733                   f->ino, (f->name ? f->name : "")));
1734         node = f->version_head;
1735         while (node) {
1736                 p = node;
1737                 node = node->version_next;
1738                 kfree(p);
1739                 DJM(no_jffs_node--);
1740         }
1741         return 0;
1742 }
1743
1744
1745 /* Free a file and its name.  */
1746 int
1747 jffs_free_file(struct jffs_file *f)
1748 {
1749         D3(printk("jffs_free_file: f #%u, \"%s\"\n",
1750                   f->ino, (f->name ? f->name : "")));
1751
1752         if (f->name) {
1753                 kfree(f->name);
1754                 DJM(no_name--);
1755         }
1756         kfree(f);
1757         DJM(no_jffs_file--);
1758         return 0;
1759 }
1760
1761
1762 /* See if a file is deleted. If so, mark that file's nodes as obsolete.  */
1763 int
1764 jffs_possibly_delete_file(struct jffs_file *f)
1765 {
1766         struct jffs_node *n;
1767
1768         D3(printk("jffs_possibly_delete_file(): ino: %u\n",
1769                   f->ino));
1770
1771         ASSERT(if (!f) {
1772                 printk(KERN_ERR "jffs_possibly_delete_file(): f == NULL\n");
1773                 return -1;
1774         });
1775
1776         if (f->deleted) {
1777                 /* First try to remove all older versions.  Commence with
1778                    the oldest node.  */
1779                 for (n = f->version_head; n; n = n->version_next) {
1780                         if (!n->fm) {
1781                                 continue;
1782                         }
1783                         if (jffs_fmfree(f->c->fmc, n->fm, n) < 0) {
1784                                 break;
1785                         }
1786                 }
1787                 /* Unlink the file from the filesystem.  */
1788                 if (!f->c->building_fs) {
1789                         jffs_unlink_file_from_tree(f);
1790                 }
1791                 jffs_unlink_file_from_hash(f);
1792                 jffs_free_node_list(f);
1793                 jffs_free_file(f);
1794         }
1795         return 0;
1796 }
1797
1798
1799 /* Used in conjunction with jffs_foreach_file() to count the number
1800    of files in the file system.  */
1801 int
1802 jffs_file_count(struct jffs_file *f)
1803 {
1804         return 1;
1805 }
1806
1807
1808 /* Build up a file's range list from scratch by going through the
1809    version list.  */
1810 int
1811 jffs_build_file(struct jffs_file *f)
1812 {
1813         struct jffs_node *n;
1814
1815         D3(printk("jffs_build_file(): ino: %u, name: \"%s\"\n",
1816                   f->ino, (f->name ? f->name : "")));
1817
1818         for (n = f->version_head; n; n = n->version_next) {
1819                 jffs_update_file(f, n);
1820         }
1821         return 0;
1822 }
1823
1824
1825 /* Remove an amount of data from a file. If this amount of data is
1826    zero, that could mean that a node should be split in two parts.
1827    We remove or change the appropriate nodes in the lists.
1828
1829    Starting offset of area to be removed is node->data_offset,
1830    and the length of the area is in node->removed_size.   */
1831 static int
1832 jffs_delete_data(struct jffs_file *f, struct jffs_node *node)
1833 {
1834         struct jffs_node *n;
1835         __u32 offset = node->data_offset;
1836         __u32 remove_size = node->removed_size;
1837
1838         D3(printk("jffs_delete_data(): offset = %u, remove_size = %u\n",
1839                   offset, remove_size));
1840
1841         if (remove_size == 0
1842             && f->range_tail
1843             && f->range_tail->data_offset + f->range_tail->data_size
1844                == offset) {
1845                 /* A simple append; nothing to remove or no node to split.  */
1846                 return 0;
1847         }
1848
1849         /* Find the node where we should begin the removal.  */
1850         for (n = f->range_head; n; n = n->range_next) {
1851                 if (n->data_offset + n->data_size > offset) {
1852                         break;
1853                 }
1854         }
1855         if (!n) {
1856                 /* If there's no data in the file there's no data to
1857                    remove either.  */
1858                 return 0;
1859         }
1860
1861         if (n->data_offset > offset) {
1862                 /* XXX: Not implemented yet.  */
1863                 printk(KERN_WARNING "JFFS: An unexpected situation "
1864                        "occurred in jffs_delete_data.\n");
1865         }
1866         else if (n->data_offset < offset) {
1867                 /* See if the node has to be split into two parts.  */
1868                 if (n->data_offset + n->data_size > offset + remove_size) {
1869                         /* Do the split.  */
1870                         struct jffs_node *new_node;
1871                         D3(printk("jffs_delete_data(): Split node with "
1872                                   "version number %u.\n", n->version));
1873
1874                         if (!(new_node = (struct jffs_node *)
1875                                          kmalloc(sizeof(struct jffs_node),
1876                                                  GFP_KERNEL))) {
1877                                 D(printk("jffs_delete_data(): -ENOMEM\n"));
1878                                 return -ENOMEM;
1879                         }
1880                         DJM(no_jffs_node++);
1881
1882                         new_node->ino = n->ino;
1883                         new_node->version = n->version;
1884                         new_node->data_offset = offset;
1885                         new_node->data_size = n->data_size - (remove_size + (offset - n->data_offset));
1886                         new_node->fm_offset = n->fm_offset + (remove_size + (offset - n->data_offset));
1887                         new_node->name_size = n->name_size;
1888                         new_node->fm = n->fm;
1889                         new_node->version_prev = n;
1890                         new_node->version_next = n->version_next;
1891                         if (new_node->version_next) {
1892                                 new_node->version_next->version_prev
1893                                 = new_node;
1894                         }
1895                         else {
1896                                 f->version_tail = new_node;
1897                         }
1898                         n->version_next = new_node;
1899                         new_node->range_prev = n;
1900                         new_node->range_next = n->range_next;
1901                         if (new_node->range_next) {
1902                                 new_node->range_next->range_prev = new_node;
1903                         }
1904                         else {
1905                                 f->range_tail = new_node;
1906                         }
1907                         /* A very interesting can of worms.  */
1908                         n->range_next = new_node;
1909                         n->data_size = offset - n->data_offset;
1910                         if (new_node->fm)
1911                                 jffs_add_node(new_node);
1912                         else {
1913                                 D1(printk(KERN_WARNING "jffs_delete_data(): Splitting an empty node (file hold).\n!"));
1914                                 D1(printk(KERN_WARNING "FIXME: Did dwmw2 do the right thing here?\n"));
1915                         }
1916                         n = new_node->range_next;
1917                         remove_size = 0;
1918                 }
1919                 else {
1920                         /* No.  No need to split the node.  Just remove
1921                            the end of the node.  */
1922                         int r = jffs_min(n->data_offset + n->data_size
1923                                          - offset, remove_size);
1924                         n->data_size -= r;
1925                         remove_size -= r;
1926                         n = n->range_next;
1927                 }
1928         }
1929
1930         /* Remove as many nodes as necessary.  */
1931         while (n && remove_size) {
1932                 if (n->data_size <= remove_size) {
1933                         struct jffs_node *p = n;
1934                         remove_size -= n->data_size;
1935                         n = n->range_next;
1936                         D3(printk("jffs_delete_data(): Removing node: "
1937                                   "ino: %u, version: %u%s\n",
1938                                   p->ino, p->version,
1939                                   (p->fm ? "" : " (virtual)")));
1940                         if (p->fm) {
1941                                 jffs_fmfree(f->c->fmc, p->fm, p);
1942                         }
1943                         jffs_unlink_node_from_range_list(f, p);
1944                         jffs_unlink_node_from_version_list(f, p);
1945                         kfree(p);
1946                         DJM(no_jffs_node--);
1947                 }
1948                 else {
1949                         n->data_size -= remove_size;
1950                         n->fm_offset += remove_size;
1951                         n->data_offset -= (node->removed_size - remove_size);
1952                         n = n->range_next;
1953                         break;
1954                 }
1955         }
1956
1957         /* Adjust the following nodes' information about offsets etc.  */
1958         while (n && node->removed_size) {
1959                 n->data_offset -= node->removed_size;
1960                 n = n->range_next;
1961         }
1962
1963         if (node->removed_size > (f->size - node->data_offset)) {
1964                 /* It's possible that the removed_size is in fact
1965                  * greater than the amount of data we actually thought
1966                  * were present in the first place - some of the nodes 
1967                  * which this node originally obsoleted may already have
1968                  * been deleted from the flash by subsequent garbage 
1969                  * collection.
1970                  *
1971                  * If this is the case, don't let f->size go negative.
1972                  * Bad things would happen :)
1973                  */
1974                 f->size = node->data_offset;
1975         } else {
1976                 f->size -= node->removed_size;
1977         }
1978         D3(printk("jffs_delete_data(): f->size = %d\n", f->size));
1979         return 0;
1980 } /* jffs_delete_data()  */
1981
1982
1983 /* Insert some data into a file.  Prior to the call to this function,
1984    jffs_delete_data should be called.  */
1985 static int
1986 jffs_insert_data(struct jffs_file *f, struct jffs_node *node)
1987 {
1988         D3(printk("jffs_insert_data(): node->data_offset = %u, "
1989                   "node->data_size = %u, f->size = %u\n",
1990                   node->data_offset, node->data_size, f->size));
1991
1992         /* Find the position where we should insert data.  */
1993         retry:
1994         if (node->data_offset == f->size) {
1995                 /* A simple append.  This is the most common operation.  */
1996                 node->range_next = 0;
1997                 node->range_prev = f->range_tail;
1998                 if (node->range_prev) {
1999                         node->range_prev->range_next = node;
2000                 }
2001                 f->range_tail = node;
2002                 f->size += node->data_size;
2003                 if (!f->range_head) {
2004                         f->range_head = node;
2005                 }
2006         }
2007         else if (node->data_offset < f->size) {
2008                 /* Trying to insert data into the middle of the file.  This
2009                    means no problem because jffs_delete_data() has already
2010                    prepared the range list for us.  */
2011                 struct jffs_node *n;
2012
2013                 /* Find the correct place for the insertion and then insert
2014                    the node.  */
2015                 for (n = f->range_head; n; n = n->range_next) {
2016                         D2(printk("Cool stuff's happening!\n"));
2017
2018                         if (n->data_offset == node->data_offset) {
2019                                 node->range_prev = n->range_prev;
2020                                 if (node->range_prev) {
2021                                         node->range_prev->range_next = node;
2022                                 }
2023                                 else {
2024                                         f->range_head = node;
2025                                 }
2026                                 node->range_next = n;
2027                                 n->range_prev = node;
2028                                 break;
2029                         }
2030                         ASSERT(else if (n->data_offset + n->data_size >
2031                                         node->data_offset) {
2032                                 printk(KERN_ERR "jffs_insert_data(): "
2033                                        "Couldn't find a place to insert "
2034                                        "the data!\n");
2035                                 return -1;
2036                         });
2037                 }
2038
2039                 /* Adjust later nodes' offsets etc.  */
2040                 n = node->range_next;
2041                 while (n) {
2042                         n->data_offset += node->data_size;
2043                         n = n->range_next;
2044                 }
2045                 f->size += node->data_size;
2046         }
2047         else if (node->data_offset > f->size) {
2048                 /* Okay.  This is tricky.  This means that we want to insert
2049                    data at a place that is beyond the limits of the file as
2050                    it is constructed right now.  This is actually a common
2051                    event that for instance could occur during the mounting
2052                    of the file system if a large file have been truncated,
2053                    rewritten and then only partially garbage collected.  */
2054
2055                 struct jffs_node *n;
2056
2057                 /* We need a place holder for the data that is missing in
2058                    front of this insertion.  This "virtual node" will not
2059                    be associated with any space on the flash device.  */
2060                 struct jffs_node *virtual_node;
2061                 if (!(virtual_node = (struct jffs_node *)
2062                                      kmalloc(sizeof(struct jffs_node),
2063                                              GFP_KERNEL))) {
2064                         return -ENOMEM;
2065                 }
2066
2067                 D(printk("jffs_insert_data: Inserting a virtual node.\n"));
2068                 D(printk("  node->data_offset = %u\n", node->data_offset));
2069                 D(printk("  f->size = %u\n", f->size));
2070
2071                 virtual_node->ino = node->ino;
2072                 virtual_node->version = node->version;
2073                 virtual_node->removed_size = 0;
2074                 virtual_node->fm_offset = 0;
2075                 virtual_node->name_size = 0;
2076                 virtual_node->fm = 0; /* This is a virtual data holder.  */
2077                 virtual_node->version_prev = 0;
2078                 virtual_node->version_next = 0;
2079                 virtual_node->range_next = 0;
2080
2081                 /* Are there any data at all in the file yet?  */
2082                 if (f->range_head) {
2083                         virtual_node->data_offset
2084                         = f->range_tail->data_offset
2085                           + f->range_tail->data_size;
2086                         virtual_node->data_size
2087                         = node->data_offset - virtual_node->data_offset;
2088                         virtual_node->range_prev = f->range_tail;
2089                         f->range_tail->range_next = virtual_node;
2090                 }
2091                 else {
2092                         virtual_node->data_offset = 0;
2093                         virtual_node->data_size = node->data_offset;
2094                         virtual_node->range_prev = 0;
2095                         f->range_head = virtual_node;
2096                 }
2097
2098                 f->range_tail = virtual_node;
2099                 f->size += virtual_node->data_size;
2100
2101                 /* Insert this virtual node in the version list as well.  */
2102                 for (n = f->version_head; n ; n = n->version_next) {
2103                         if (n->version == virtual_node->version) {
2104                                 virtual_node->version_prev = n->version_prev;
2105                                 n->version_prev = virtual_node;
2106                                 if (virtual_node->version_prev) {
2107                                         virtual_node->version_prev
2108                                         ->version_next = virtual_node;
2109                                 }
2110                                 else {
2111                                         f->version_head = virtual_node;
2112                                 }
2113                                 virtual_node->version_next = n;
2114                                 break;
2115                         }
2116                 }
2117
2118                 D(jffs_print_node(virtual_node));
2119
2120                 /* Make a new try to insert the node.  */
2121                 goto retry;
2122         }
2123
2124         D3(printk("jffs_insert_data(): f->size = %d\n", f->size));
2125         return 0;
2126 }
2127
2128
2129 /* A new node (with data) has been added to the file and now the range
2130    list has to be modified.  */
2131 static int
2132 jffs_update_file(struct jffs_file *f, struct jffs_node *node)
2133 {
2134         int err;
2135
2136         D3(printk("jffs_update_file(): ino: %u, version: %u\n",
2137                   f->ino, node->version));
2138
2139         if (node->data_size == 0) {
2140                 if (node->removed_size == 0) {
2141                         /* data_offset == X  */
2142                         /* data_size == 0  */
2143                         /* remove_size == 0  */
2144                 }
2145                 else {
2146                         /* data_offset == X  */
2147                         /* data_size == 0  */
2148                         /* remove_size != 0  */
2149                         if ((err = jffs_delete_data(f, node)) < 0) {
2150                                 return err;
2151                         }
2152                 }
2153         }
2154         else {
2155                 /* data_offset == X  */
2156                 /* data_size != 0  */
2157                 /* remove_size == Y  */
2158                 if ((err = jffs_delete_data(f, node)) < 0) {
2159                         return err;
2160                 }
2161                 if ((err = jffs_insert_data(f, node)) < 0) {
2162                         return err;
2163                 }
2164         }
2165         return 0;
2166 }
2167
2168
2169 /* Print the contents of a node.  */
2170 void
2171 jffs_print_node(struct jffs_node *n)
2172 {
2173         D(printk("jffs_node: 0x%p\n", n));
2174         D(printk("{\n"));
2175         D(printk("        0x%08x, /* version  */\n", n->version));
2176         D(printk("        0x%08x, /* data_offset  */\n", n->data_offset));
2177         D(printk("        0x%08x, /* data_size  */\n", n->data_size));
2178         D(printk("        0x%08x, /* removed_size  */\n", n->removed_size));
2179         D(printk("        0x%08x, /* fm_offset  */\n", n->fm_offset));
2180         D(printk("        0x%02x,       /* name_size  */\n", n->name_size));
2181         D(printk("        0x%p, /* fm,  fm->offset: %u  */\n",
2182                  n->fm, (n->fm ? n->fm->offset : 0)));
2183         D(printk("        0x%p, /* version_prev  */\n", n->version_prev));
2184         D(printk("        0x%p, /* version_next  */\n", n->version_next));
2185         D(printk("        0x%p, /* range_prev  */\n", n->range_prev));
2186         D(printk("        0x%p, /* range_next  */\n", n->range_next));
2187         D(printk("}\n"));
2188 }
2189
2190
2191 /* Print the contents of a raw inode.  */
2192 void
2193 jffs_print_raw_inode(struct jffs_raw_inode *raw_inode)
2194 {
2195         D(printk("jffs_raw_inode: inode number: %u\n", raw_inode->ino));
2196         D(printk("{\n"));
2197         D(printk("        0x%08x, /* magic  */\n", raw_inode->magic));
2198         D(printk("        0x%08x, /* ino  */\n", raw_inode->ino));
2199         D(printk("        0x%08x, /* pino  */\n", raw_inode->pino));
2200         D(printk("        0x%08x, /* version  */\n", raw_inode->version));
2201         D(printk("        0x%08x, /* mode  */\n", raw_inode->mode));
2202         D(printk("        0x%04x,     /* uid  */\n", raw_inode->uid));
2203         D(printk("        0x%04x,     /* gid  */\n", raw_inode->gid));
2204         D(printk("        0x%08x, /* atime  */\n", raw_inode->atime));
2205         D(printk("        0x%08x, /* mtime  */\n", raw_inode->mtime));
2206         D(printk("        0x%08x, /* ctime  */\n", raw_inode->ctime));
2207         D(printk("        0x%08x, /* offset  */\n", raw_inode->offset));
2208         D(printk("        0x%08x, /* dsize  */\n", raw_inode->dsize));
2209         D(printk("        0x%08x, /* rsize  */\n", raw_inode->rsize));
2210         D(printk("        0x%02x,       /* nsize  */\n", raw_inode->nsize));
2211         D(printk("        0x%02x,       /* nlink  */\n", raw_inode->nlink));
2212         D(printk("        0x%02x,       /* spare  */\n",
2213                  raw_inode->spare));
2214         D(printk("        %u,          /* rename  */\n",
2215                  raw_inode->rename));
2216         D(printk("        %u,          /* deleted  */\n",
2217                  raw_inode->deleted));
2218         D(printk("        0x%02x,       /* accurate  */\n",
2219                  raw_inode->accurate));
2220         D(printk("        0x%08x, /* dchksum  */\n", raw_inode->dchksum));
2221         D(printk("        0x%04x,     /* nchksum  */\n", raw_inode->nchksum));
2222         D(printk("        0x%04x,     /* chksum  */\n", raw_inode->chksum));
2223         D(printk("}\n"));
2224 }
2225
2226
2227 /* Print the contents of a file.  */
2228 int
2229 jffs_print_file(struct jffs_file *f)
2230 {
2231         D(int i);
2232         D(printk("jffs_file: 0x%p\n", f));
2233         D(printk("{\n"));
2234         D(printk("        0x%08x, /* ino  */\n", f->ino));
2235         D(printk("        0x%08x, /* pino  */\n", f->pino));
2236         D(printk("        0x%08x, /* mode  */\n", f->mode));
2237         D(printk("        0x%04x,     /* uid  */\n", f->uid));
2238         D(printk("        0x%04x,     /* gid  */\n", f->gid));
2239         D(printk("        0x%08x, /* atime  */\n", f->atime));
2240         D(printk("        0x%08x, /* mtime  */\n", f->mtime));
2241         D(printk("        0x%08x, /* ctime  */\n", f->ctime));
2242         D(printk("        0x%02x,       /* nsize  */\n", f->nsize));
2243         D(printk("        0x%02x,       /* nlink  */\n", f->nlink));
2244         D(printk("        0x%02x,       /* deleted  */\n", f->deleted));
2245         D(printk("        \"%s\", ", (f->name ? f->name : "")));
2246         D(for (i = strlen(f->name ? f->name : ""); i < 8; ++i) {
2247                 printk(" ");
2248         });
2249         D(printk("/* name  */\n"));
2250         D(printk("        0x%08x, /* size  */\n", f->size));
2251         D(printk("        0x%08x, /* highest_version  */\n",
2252                  f->highest_version));
2253         D(printk("        0x%p, /* c  */\n", f->c));
2254         D(printk("        0x%p, /* parent  */\n", f->parent));
2255         D(printk("        0x%p, /* children  */\n", f->children));
2256         D(printk("        0x%p, /* sibling_prev  */\n", f->sibling_prev));
2257         D(printk("        0x%p, /* sibling_next  */\n", f->sibling_next));
2258         D(printk("        0x%p, /* hash_prev  */\n", f->hash.prev));
2259         D(printk("        0x%p, /* hash_next  */\n", f->hash.next));
2260         D(printk("        0x%p, /* range_head  */\n", f->range_head));
2261         D(printk("        0x%p, /* range_tail  */\n", f->range_tail));
2262         D(printk("        0x%p, /* version_head  */\n", f->version_head));
2263         D(printk("        0x%p, /* version_tail  */\n", f->version_tail));
2264         D(printk("}\n"));
2265         return 0;
2266 }
2267
2268
2269 void
2270 jffs_print_hash_table(struct jffs_control *c)
2271 {
2272         int i;
2273
2274         printk("JFFS: Dumping the file system's hash table...\n");
2275         for (i = 0; i < c->hash_len; i++) {
2276                 struct list_head *p;
2277                 for (p = c->hash[i].next; p != &c->hash[i]; p = p->next) {
2278                         struct jffs_file *f=list_entry(p,struct jffs_file,hash);
2279                         printk("*** c->hash[%u]: \"%s\" "
2280                                "(ino: %u, pino: %u)\n",
2281                                i, (f->name ? f->name : ""),
2282                                f->ino, f->pino);
2283                 }
2284         }
2285 }
2286
2287
2288 void
2289 jffs_print_tree(struct jffs_file *first_file, int indent)
2290 {
2291         struct jffs_file *f;
2292         char *space;
2293         int dir;
2294
2295         if (!first_file) {
2296                 return;
2297         }
2298
2299         if (!(space = (char *) kmalloc(indent + 1, GFP_KERNEL))) {
2300                 printk("jffs_print_tree(): Out of memory!\n");
2301                 return;
2302         }
2303
2304         memset(space, ' ', indent);
2305         space[indent] = '\0';
2306
2307         for (f = first_file; f; f = f->sibling_next) {
2308                 dir = S_ISDIR(f->mode);
2309                 printk("%s%s%s (ino: %u, highest_version: %u, size: %u)\n",
2310                        space, (f->name ? f->name : ""), (dir ? "/" : ""),
2311                        f->ino, f->highest_version, f->size);
2312                 if (dir) {
2313                         jffs_print_tree(f->children, indent + 2);
2314                 }
2315         }
2316
2317         kfree(space);
2318 }
2319
2320
2321 #if defined(JFFS_MEMORY_DEBUG) && JFFS_MEMORY_DEBUG
2322 void
2323 jffs_print_memory_allocation_statistics(void)
2324 {
2325         static long printout = 0;
2326         printk("________ Memory printout #%ld ________\n", ++printout);
2327         printk("no_jffs_file = %ld\n", no_jffs_file);
2328         printk("no_jffs_node = %ld\n", no_jffs_node);
2329         printk("no_jffs_control = %ld\n", no_jffs_control);
2330         printk("no_jffs_raw_inode = %ld\n", no_jffs_raw_inode);
2331         printk("no_jffs_node_ref = %ld\n", no_jffs_node_ref);
2332         printk("no_jffs_fm = %ld\n", no_jffs_fm);
2333         printk("no_jffs_fmcontrol = %ld\n", no_jffs_fmcontrol);
2334         printk("no_hash = %ld\n", no_hash);
2335         printk("no_name = %ld\n", no_name);
2336         printk("\n");
2337 }
2338 #endif
2339
2340
2341 /* Rewrite `size' bytes, and begin at `node'.  */
2342 int
2343 jffs_rewrite_data(struct jffs_file *f, struct jffs_node *node, int size)
2344 {
2345         struct jffs_control *c = f->c;
2346         struct jffs_fmcontrol *fmc = c->fmc;
2347         struct jffs_raw_inode raw_inode;
2348         struct jffs_node *new_node;
2349         struct jffs_fm *fm;
2350         __u32 pos;
2351         __u32 pos_dchksum;
2352         __u32 total_name_size;
2353         __u32 total_data_size;
2354         __u32 total_size;
2355         int err;
2356
2357         D1(printk("***jffs_rewrite_data(): node: %u, name: \"%s\", size: %u\n",
2358                   f->ino, (f->name ? f->name : "(null)"), size));
2359
2360         /* Create and initialize the new node.  */
2361         if (!(new_node = (struct jffs_node *)
2362                          kmalloc(sizeof(struct jffs_node), GFP_KERNEL))) {
2363                 D(printk("jffs_rewrite_data(): "
2364                          "Failed to allocate node.\n"));
2365                 return -ENOMEM;
2366         }
2367         DJM(no_jffs_node++);
2368         new_node->data_offset = node->data_offset;
2369         new_node->removed_size = size;
2370         total_name_size = JFFS_PAD(f->nsize);
2371         total_data_size = JFFS_PAD(size);
2372         total_size = sizeof(struct jffs_raw_inode)
2373                      + total_name_size + total_data_size;
2374         new_node->fm_offset = sizeof(struct jffs_raw_inode)
2375                               + total_name_size;
2376
2377         jffs_fm_write_lock(fmc);
2378
2379         if ((err = jffs_fmalloc(fmc, total_size, new_node, &fm)) < 0) {
2380                 DJM(no_jffs_node--);
2381                 jffs_fm_write_unlock(fmc);
2382                 D(printk("jffs_rewrite_data(): Failed to allocate fm.\n"));
2383                 kfree(new_node);
2384                 return err;
2385         }
2386         else if (!fm->nodes) {
2387                 /* The jffs_fm struct that we got is not big enough.  */
2388                 /* This should never happen, because we deal with this case
2389                    in jffs_garbage_collect_next().*/
2390                 printk(KERN_WARNING "jffs_rewrite_data(): Allocated node is too small (%d bytes of %d)\n", fm->size, total_size);
2391                 if ((err = jffs_write_dummy_node(c, fm)) < 0) {
2392                         D(printk("jffs_rewrite_data(): "
2393                                  "jffs_write_dummy_node() Failed!\n"));
2394                 } else {
2395                         err = -ENOSPC;
2396                 }
2397                 DJM(no_jffs_fm--);
2398                 jffs_fm_write_unlock(fmc);
2399                 kfree(fm);
2400                 
2401                 return err;
2402         }
2403         new_node->fm = fm;
2404
2405         /* Initialize the raw inode.  */
2406         raw_inode.magic = JFFS_MAGIC_BITMASK;
2407         raw_inode.ino = f->ino;
2408         raw_inode.pino = f->pino;
2409         raw_inode.version = f->highest_version + 1;
2410         raw_inode.mode = f->mode;
2411         raw_inode.uid = f->uid;
2412         raw_inode.gid = f->gid;
2413         raw_inode.atime = f->atime;
2414         raw_inode.mtime = f->mtime;
2415         raw_inode.ctime = f->ctime;
2416         raw_inode.offset = node->data_offset;
2417         raw_inode.dsize = size;
2418         raw_inode.rsize = size;
2419         raw_inode.nsize = f->nsize;
2420         raw_inode.nlink = f->nlink;
2421         raw_inode.spare = 0;
2422         raw_inode.rename = 0;
2423         raw_inode.deleted = 0;
2424         raw_inode.accurate = 0xff;
2425         raw_inode.dchksum = 0;
2426         raw_inode.nchksum = 0;
2427
2428         pos = new_node->fm->offset;
2429         pos_dchksum = pos +JFFS_RAW_INODE_DCHKSUM_OFFSET;
2430
2431         D3(printk("jffs_rewrite_data(): Writing this raw inode "
2432                   "to pos 0x%ul.\n", pos));
2433         D3(jffs_print_raw_inode(&raw_inode));
2434
2435         if ((err = flash_safe_write(fmc->mtd, pos,
2436                                     (u_char *) &raw_inode,
2437                                     sizeof(struct jffs_raw_inode)
2438                                     - sizeof(__u32)
2439                                     - sizeof(__u16) - sizeof(__u16))) < 0) {
2440                 jffs_fmfree_partly(fmc, fm,
2441                                    total_name_size + total_data_size);
2442                 jffs_fm_write_unlock(fmc);
2443                 printk(KERN_ERR "JFFS: jffs_rewrite_data: Write error during "
2444                        "rewrite. (raw inode)\n");
2445                 return err;
2446         }
2447         pos += sizeof(struct jffs_raw_inode);
2448
2449         /* Write the name to the flash memory.  */
2450         if (f->nsize) {
2451                 D3(printk("jffs_rewrite_data(): Writing name \"%s\" to "
2452                           "pos 0x%ul.\n", f->name, (long)pos));
2453                 if ((err = flash_safe_write(fmc->mtd, pos,
2454                                             (u_char *)f->name,
2455                                             f->nsize)) < 0) {
2456                         jffs_fmfree_partly(fmc, fm, total_data_size);
2457                         jffs_fm_write_unlock(fmc);
2458                         printk(KERN_ERR "JFFS: jffs_rewrite_data: Write "
2459                                "error during rewrite. (name)\n");
2460                         return err;
2461                 }
2462                 pos += total_name_size;
2463                 raw_inode.nchksum = jffs_checksum(f->name, f->nsize);
2464         }
2465
2466         /* Write the data.  */
2467         if (size) {
2468                 int r;
2469                 unsigned char *page;
2470                 __u32 offset = node->data_offset;
2471
2472                 if (!(page = (unsigned char *)__get_free_page(GFP_KERNEL))) {
2473                         jffs_fmfree_partly(fmc, fm, 0);
2474                         return -1;
2475                 }
2476
2477                 while (size) {
2478                         __u32 s = jffs_min(size, PAGE_SIZE);
2479                         if ((r = jffs_read_data(f, (char *)page,
2480                                                 offset, s)) < s) {
2481                                 free_page((unsigned long)page);
2482                                 jffs_fmfree_partly(fmc, fm, 0);
2483                                 jffs_fm_write_unlock(fmc);
2484                                 printk(KERN_ERR "JFFS: jffs_rewrite_data: "
2485                                          "jffs_read_data() "
2486                                          "failed! (r = %d)\n", r);
2487                                 return -1;
2488                         }
2489                         if ((err = flash_safe_write(fmc->mtd,
2490                                                     pos, page, r)) < 0) {
2491                                 free_page((unsigned long)page);
2492                                 jffs_fmfree_partly(fmc, fm, 0);
2493                                 jffs_fm_write_unlock(fmc);
2494                                 printk(KERN_ERR "JFFS: jffs_rewrite_data: "
2495                                        "Write error during rewrite. "
2496                                        "(data)\n");
2497                                 return err;
2498                         }
2499                         pos += r;
2500                         size -= r;
2501                         offset += r;
2502                         raw_inode.dchksum += jffs_checksum(page, r);
2503                 }
2504
2505                 free_page((unsigned long)page);
2506         }
2507
2508         raw_inode.accurate = 0;
2509         raw_inode.chksum = jffs_checksum(&raw_inode,
2510                                          sizeof(struct jffs_raw_inode)
2511                                          - sizeof(__u16));
2512
2513         /* Add the checksum.  */
2514         if ((err
2515              = flash_safe_write(fmc->mtd, pos_dchksum,
2516                                 &((u_char *)
2517                                 &raw_inode)[JFFS_RAW_INODE_DCHKSUM_OFFSET],
2518                                 sizeof(__u32) + sizeof(__u16)
2519                                 + sizeof(__u16))) < 0) {
2520                 jffs_fmfree_partly(fmc, fm, 0);
2521                 jffs_fm_write_unlock(fmc);
2522                 printk(KERN_ERR "JFFS: jffs_rewrite_data: Write error during "
2523                        "rewrite. (checksum)\n");
2524                 return err;
2525         }
2526
2527         /* Now make the file system aware of the newly written node.  */
2528         jffs_insert_node(c, f, &raw_inode, f->name, new_node);
2529         jffs_fm_write_unlock(fmc);
2530
2531         D3(printk("jffs_rewrite_data(): Leaving...\n"));
2532         return 0;
2533 } /* jffs_rewrite_data()  */
2534
2535
2536 /* jffs_garbage_collect_next implements one step in the garbage collect
2537    process and is often called multiple times at each occasion of a
2538    garbage collect.  */
2539
2540 int
2541 jffs_garbage_collect_next(struct jffs_control *c)
2542 {
2543         struct jffs_fmcontrol *fmc = c->fmc;
2544         struct jffs_node *node;
2545         struct jffs_file *f;
2546         int size, err = 0;
2547         int data_size;
2548         int total_name_size;
2549         __u32 extra_available;
2550         __u32 space_needed;
2551         __u32 free_chunk_size1 = jffs_free_size1(fmc);
2552         D2(__u32 free_chunk_size2 = jffs_free_size2(fmc));
2553
2554         /* Get the oldest node in the flash.  */
2555         node = jffs_get_oldest_node(fmc);
2556         ASSERT(if (!node) {
2557                 printk(KERN_ERR "JFFS: jffs_garbage_collect_next: "
2558                        "No oldest node found!\n");
2559                 err = -1;
2560                 goto jffs_garbage_collect_next_end;
2561                 
2562
2563         });
2564
2565         /* Find its corresponding file too.  */
2566         f = jffs_find_file(c, node->ino);
2567
2568         if (!f) {
2569           printk (KERN_ERR "JFFS: jffs_garbage_collect_next: "
2570                   "No file to garbage collect! "
2571                   "(ino = 0x%08x)\n", node->ino);
2572           /* FIXME: Free the offending node and recover. */
2573           err = -1;
2574           goto jffs_garbage_collect_next_end;
2575         }
2576
2577         /* We always write out the name. Theoretically, we don't need
2578            to, but for now it's easier - because otherwise we'd have
2579            to keep track of how many times the current name exists on
2580            the flash and make sure it never reaches zero.
2581
2582            The current approach means that would be possible to cause
2583            the GC to end up eating its tail by writing lots of nodes
2584            with no name for it to garbage-collect. Hence the change in
2585            inode.c to write names with _every_ node.
2586
2587            It sucks, but it _should_ work.
2588         */
2589         total_name_size = JFFS_PAD(f->nsize);
2590
2591         D1(printk("jffs_garbage_collect_next(): \"%s\", "
2592                   "ino: %u, version: %u, location 0x%x, dsize %u\n",
2593                   (f->name ? f->name : ""), node->ino, node->version, 
2594                   node->fm->offset, node->data_size));
2595
2596         /* Compute how many data it's possible to rewrite at the moment.  */
2597         data_size = f->size - node->data_offset;
2598
2599         /* And from that, the total size of the chunk we want to write */
2600         size = sizeof(struct jffs_raw_inode) + total_name_size
2601                + data_size + JFFS_GET_PAD_BYTES(data_size);
2602
2603         /* If that's more than max_chunk_size, reduce it accordingly */
2604         if (size > fmc->max_chunk_size) {
2605                 size = fmc->max_chunk_size;
2606                 data_size = size - sizeof(struct jffs_raw_inode)
2607                             - total_name_size;
2608         }
2609
2610         /* If we're asking to take up more space than free_chunk_size1
2611            but we _could_ fit in it, shrink accordingly.
2612         */
2613         if (size > free_chunk_size1) {
2614
2615                 if (free_chunk_size1 <
2616                     (sizeof(struct jffs_raw_inode) + total_name_size + BLOCK_SIZE)){
2617                         /* The space left is too small to be of any
2618                            use really.  */
2619                         struct jffs_fm *dirty_fm
2620                         = jffs_fmalloced(fmc,
2621                                          fmc->tail->offset + fmc->tail->size,
2622                                          free_chunk_size1, NULL);
2623                         if (!dirty_fm) {
2624                                 printk(KERN_ERR "JFFS: "
2625                                        "jffs_garbage_collect_next: "
2626                                        "Failed to allocate `dirty' "
2627                                        "flash memory!\n");
2628                                 err = -1;
2629                                 goto jffs_garbage_collect_next_end;
2630                         }
2631                         D1(printk("Dirtying end of flash - too small\n"));
2632                         jffs_write_dummy_node(c, dirty_fm);
2633                         err = 0;
2634                         goto jffs_garbage_collect_next_end;
2635                 }
2636                 D1(printk("Reducing size of new node from %d to %d to avoid "
2637                           " exceeding free_chunk_size1\n",
2638                           size, free_chunk_size1));