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