Merge branch 'master' of /home/tglx/work/kernel/git/mtd-2.6/
[pandora-kernel.git] / fs / jffs2 / wbuf.c
1 /*
2  * JFFS2 -- Journalling Flash File System, Version 2.
3  *
4  * Copyright (C) 2001-2003 Red Hat, Inc.
5  * Copyright (C) 2004 Thomas Gleixner <tglx@linutronix.de>
6  *
7  * Created by David Woodhouse <dwmw2@infradead.org>
8  * Modified debugged and enhanced by Thomas Gleixner <tglx@linutronix.de>
9  *
10  * For licensing information, see the file 'LICENCE' in this directory.
11  *
12  * $Id: wbuf.c,v 1.100 2005/09/30 13:59:13 dedekind Exp $
13  *
14  */
15
16 #include <linux/kernel.h>
17 #include <linux/slab.h>
18 #include <linux/mtd/mtd.h>
19 #include <linux/crc32.h>
20 #include <linux/mtd/nand.h>
21 #include <linux/jiffies.h>
22
23 #include "nodelist.h"
24
25 /* For testing write failures */
26 #undef BREAKME
27 #undef BREAKMEHEADER
28
29 #ifdef BREAKME
30 static unsigned char *brokenbuf;
31 #endif
32
33 #define PAGE_DIV(x) ( ((unsigned long)(x) / (unsigned long)(c->wbuf_pagesize)) * (unsigned long)(c->wbuf_pagesize) )
34 #define PAGE_MOD(x) ( (unsigned long)(x) % (unsigned long)(c->wbuf_pagesize) )
35
36 /* max. erase failures before we mark a block bad */
37 #define MAX_ERASE_FAILURES      2
38
39 struct jffs2_inodirty {
40         uint32_t ino;
41         struct jffs2_inodirty *next;
42 };
43
44 static struct jffs2_inodirty inodirty_nomem;
45
46 static int jffs2_wbuf_pending_for_ino(struct jffs2_sb_info *c, uint32_t ino)
47 {
48         struct jffs2_inodirty *this = c->wbuf_inodes;
49
50         /* If a malloc failed, consider _everything_ dirty */
51         if (this == &inodirty_nomem)
52                 return 1;
53
54         /* If ino == 0, _any_ non-GC writes mean 'yes' */
55         if (this && !ino)
56                 return 1;
57
58         /* Look to see if the inode in question is pending in the wbuf */
59         while (this) {
60                 if (this->ino == ino)
61                         return 1;
62                 this = this->next;
63         }
64         return 0;
65 }
66
67 static void jffs2_clear_wbuf_ino_list(struct jffs2_sb_info *c)
68 {
69         struct jffs2_inodirty *this;
70
71         this = c->wbuf_inodes;
72
73         if (this != &inodirty_nomem) {
74                 while (this) {
75                         struct jffs2_inodirty *next = this->next;
76                         kfree(this);
77                         this = next;
78                 }
79         }
80         c->wbuf_inodes = NULL;
81 }
82
83 static void jffs2_wbuf_dirties_inode(struct jffs2_sb_info *c, uint32_t ino)
84 {
85         struct jffs2_inodirty *new;
86
87         /* Mark the superblock dirty so that kupdated will flush... */
88         jffs2_erase_pending_trigger(c);
89
90         if (jffs2_wbuf_pending_for_ino(c, ino))
91                 return;
92
93         new = kmalloc(sizeof(*new), GFP_KERNEL);
94         if (!new) {
95                 D1(printk(KERN_DEBUG "No memory to allocate inodirty. Fallback to all considered dirty\n"));
96                 jffs2_clear_wbuf_ino_list(c);
97                 c->wbuf_inodes = &inodirty_nomem;
98                 return;
99         }
100         new->ino = ino;
101         new->next = c->wbuf_inodes;
102         c->wbuf_inodes = new;
103         return;
104 }
105
106 static inline void jffs2_refile_wbuf_blocks(struct jffs2_sb_info *c)
107 {
108         struct list_head *this, *next;
109         static int n;
110
111         if (list_empty(&c->erasable_pending_wbuf_list))
112                 return;
113
114         list_for_each_safe(this, next, &c->erasable_pending_wbuf_list) {
115                 struct jffs2_eraseblock *jeb = list_entry(this, struct jffs2_eraseblock, list);
116
117                 D1(printk(KERN_DEBUG "Removing eraseblock at 0x%08x from erasable_pending_wbuf_list...\n", jeb->offset));
118                 list_del(this);
119                 if ((jiffies + (n++)) & 127) {
120                         /* Most of the time, we just erase it immediately. Otherwise we
121                            spend ages scanning it on mount, etc. */
122                         D1(printk(KERN_DEBUG "...and adding to erase_pending_list\n"));
123                         list_add_tail(&jeb->list, &c->erase_pending_list);
124                         c->nr_erasing_blocks++;
125                         jffs2_erase_pending_trigger(c);
126                 } else {
127                         /* Sometimes, however, we leave it elsewhere so it doesn't get
128                            immediately reused, and we spread the load a bit. */
129                         D1(printk(KERN_DEBUG "...and adding to erasable_list\n"));
130                         list_add_tail(&jeb->list, &c->erasable_list);
131                 }
132         }
133 }
134
135 #define REFILE_NOTEMPTY 0
136 #define REFILE_ANYWAY   1
137
138 static void jffs2_block_refile(struct jffs2_sb_info *c, struct jffs2_eraseblock *jeb, int allow_empty)
139 {
140         D1(printk("About to refile bad block at %08x\n", jeb->offset));
141
142         /* File the existing block on the bad_used_list.... */
143         if (c->nextblock == jeb)
144                 c->nextblock = NULL;
145         else /* Not sure this should ever happen... need more coffee */
146                 list_del(&jeb->list);
147         if (jeb->first_node) {
148                 D1(printk("Refiling block at %08x to bad_used_list\n", jeb->offset));
149                 list_add(&jeb->list, &c->bad_used_list);
150         } else {
151                 BUG_ON(allow_empty == REFILE_NOTEMPTY);
152                 /* It has to have had some nodes or we couldn't be here */
153                 D1(printk("Refiling block at %08x to erase_pending_list\n", jeb->offset));
154                 list_add(&jeb->list, &c->erase_pending_list);
155                 c->nr_erasing_blocks++;
156                 jffs2_erase_pending_trigger(c);
157         }
158
159         /* Adjust its size counts accordingly */
160         c->wasted_size += jeb->free_size;
161         c->free_size -= jeb->free_size;
162         jeb->wasted_size += jeb->free_size;
163         jeb->free_size = 0;
164
165         jffs2_dbg_dump_block_lists_nolock(c);
166         jffs2_dbg_acct_sanity_check_nolock(c,jeb);
167         jffs2_dbg_acct_paranoia_check_nolock(c, jeb);
168 }
169
170 /* Recover from failure to write wbuf. Recover the nodes up to the
171  * wbuf, not the one which we were starting to try to write. */
172
173 static void jffs2_wbuf_recover(struct jffs2_sb_info *c)
174 {
175         struct jffs2_eraseblock *jeb, *new_jeb;
176         struct jffs2_raw_node_ref **first_raw, **raw;
177         size_t retlen;
178         int ret;
179         unsigned char *buf;
180         uint32_t start, end, ofs, len;
181
182         spin_lock(&c->erase_completion_lock);
183
184         jeb = &c->blocks[c->wbuf_ofs / c->sector_size];
185
186         jffs2_block_refile(c, jeb, REFILE_NOTEMPTY);
187
188         /* Find the first node to be recovered, by skipping over every
189            node which ends before the wbuf starts, or which is obsolete. */
190         first_raw = &jeb->first_node;
191         while (*first_raw &&
192                (ref_obsolete(*first_raw) ||
193                 (ref_offset(*first_raw)+ref_totlen(c, jeb, *first_raw)) < c->wbuf_ofs)) {
194                 D1(printk(KERN_DEBUG "Skipping node at 0x%08x(%d)-0x%08x which is either before 0x%08x or obsolete\n",
195                           ref_offset(*first_raw), ref_flags(*first_raw),
196                           (ref_offset(*first_raw) + ref_totlen(c, jeb, *first_raw)),
197                           c->wbuf_ofs));
198                 first_raw = &(*first_raw)->next_phys;
199         }
200
201         if (!*first_raw) {
202                 /* All nodes were obsolete. Nothing to recover. */
203                 D1(printk(KERN_DEBUG "No non-obsolete nodes to be recovered. Just filing block bad\n"));
204                 spin_unlock(&c->erase_completion_lock);
205                 return;
206         }
207
208         start = ref_offset(*first_raw);
209         end = ref_offset(*first_raw) + ref_totlen(c, jeb, *first_raw);
210
211         /* Find the last node to be recovered */
212         raw = first_raw;
213         while ((*raw)) {
214                 if (!ref_obsolete(*raw))
215                         end = ref_offset(*raw) + ref_totlen(c, jeb, *raw);
216
217                 raw = &(*raw)->next_phys;
218         }
219         spin_unlock(&c->erase_completion_lock);
220
221         D1(printk(KERN_DEBUG "wbuf recover %08x-%08x\n", start, end));
222
223         buf = NULL;
224         if (start < c->wbuf_ofs) {
225                 /* First affected node was already partially written.
226                  * Attempt to reread the old data into our buffer. */
227
228                 buf = kmalloc(end - start, GFP_KERNEL);
229                 if (!buf) {
230                         printk(KERN_CRIT "Malloc failure in wbuf recovery. Data loss ensues.\n");
231
232                         goto read_failed;
233                 }
234
235                 /* Do the read... */
236                 if (jffs2_cleanmarker_oob(c))
237                         ret = c->mtd->read_ecc(c->mtd, start, c->wbuf_ofs - start, &retlen, buf, NULL, c->oobinfo);
238                 else
239                         ret = c->mtd->read(c->mtd, start, c->wbuf_ofs - start, &retlen, buf);
240
241                 if (ret == -EBADMSG && retlen == c->wbuf_ofs - start) {
242                         /* ECC recovered */
243                         ret = 0;
244                 }
245                 if (ret || retlen != c->wbuf_ofs - start) {
246                         printk(KERN_CRIT "Old data are already lost in wbuf recovery. Data loss ensues.\n");
247
248                         kfree(buf);
249                         buf = NULL;
250                 read_failed:
251                         first_raw = &(*first_raw)->next_phys;
252                         /* If this was the only node to be recovered, give up */
253                         if (!(*first_raw))
254                                 return;
255
256                         /* It wasn't. Go on and try to recover nodes complete in the wbuf */
257                         start = ref_offset(*first_raw);
258                 } else {
259                         /* Read succeeded. Copy the remaining data from the wbuf */
260                         memcpy(buf + (c->wbuf_ofs - start), c->wbuf, end - c->wbuf_ofs);
261                 }
262         }
263         /* OK... we're to rewrite (end-start) bytes of data from first_raw onwards.
264            Either 'buf' contains the data, or we find it in the wbuf */
265
266
267         /* ... and get an allocation of space from a shiny new block instead */
268         ret = jffs2_reserve_space_gc(c, end-start, &len, JFFS2_SUMMARY_NOSUM_SIZE);
269         if (ret) {
270                 printk(KERN_WARNING "Failed to allocate space for wbuf recovery. Data loss ensues.\n");
271                 kfree(buf);
272                 return;
273         }
274         ofs = write_ofs(c);
275
276         if (end-start >= c->wbuf_pagesize) {
277                 /* Need to do another write immediately, but it's possible
278                    that this is just because the wbuf itself is completely
279                    full, and there's nothing earlier read back from the
280                    flash. Hence 'buf' isn't necessarily what we're writing
281                    from. */
282                 unsigned char *rewrite_buf = buf?:c->wbuf;
283                 uint32_t towrite = (end-start) - ((end-start)%c->wbuf_pagesize);
284
285                 D1(printk(KERN_DEBUG "Write 0x%x bytes at 0x%08x in wbuf recover\n",
286                           towrite, ofs));
287
288 #ifdef BREAKMEHEADER
289                 static int breakme;
290                 if (breakme++ == 20) {
291                         printk(KERN_NOTICE "Faking write error at 0x%08x\n", ofs);
292                         breakme = 0;
293                         c->mtd->write_ecc(c->mtd, ofs, towrite, &retlen,
294                                           brokenbuf, NULL, c->oobinfo);
295                         ret = -EIO;
296                 } else
297 #endif
298                 if (jffs2_cleanmarker_oob(c))
299                         ret = c->mtd->write_ecc(c->mtd, ofs, towrite, &retlen,
300                                                 rewrite_buf, NULL, c->oobinfo);
301                 else
302                         ret = c->mtd->write(c->mtd, ofs, towrite, &retlen, rewrite_buf);
303
304                 if (ret || retlen != towrite) {
305                         /* Argh. We tried. Really we did. */
306                         printk(KERN_CRIT "Recovery of wbuf failed due to a second write error\n");
307                         kfree(buf);
308
309                         if (retlen) {
310                                 struct jffs2_raw_node_ref *raw2;
311
312                                 raw2 = jffs2_alloc_raw_node_ref();
313                                 if (!raw2)
314                                         return;
315
316                                 raw2->flash_offset = ofs | REF_OBSOLETE;
317
318                                 jffs2_add_physical_node_ref(c, raw2, ref_totlen(c, jeb, *first_raw), NULL);
319                         }
320                         return;
321                 }
322                 printk(KERN_NOTICE "Recovery of wbuf succeeded to %08x\n", ofs);
323
324                 c->wbuf_len = (end - start) - towrite;
325                 c->wbuf_ofs = ofs + towrite;
326                 memmove(c->wbuf, rewrite_buf + towrite, c->wbuf_len);
327                 /* Don't muck about with c->wbuf_inodes. False positives are harmless. */
328                 kfree(buf);
329         } else {
330                 /* OK, now we're left with the dregs in whichever buffer we're using */
331                 if (buf) {
332                         memcpy(c->wbuf, buf, end-start);
333                         kfree(buf);
334                 } else {
335                         memmove(c->wbuf, c->wbuf + (start - c->wbuf_ofs), end - start);
336                 }
337                 c->wbuf_ofs = ofs;
338                 c->wbuf_len = end - start;
339         }
340
341         /* Now sort out the jffs2_raw_node_refs, moving them from the old to the next block */
342         new_jeb = &c->blocks[ofs / c->sector_size];
343
344         spin_lock(&c->erase_completion_lock);
345         if (new_jeb->first_node) {
346                 /* Odd, but possible with ST flash later maybe */
347                 new_jeb->last_node->next_phys = *first_raw;
348         } else {
349                 new_jeb->first_node = *first_raw;
350         }
351
352         raw = first_raw;
353         while (*raw) {
354                 uint32_t rawlen = ref_totlen(c, jeb, *raw);
355
356                 D1(printk(KERN_DEBUG "Refiling block of %08x at %08x(%d) to %08x\n",
357                           rawlen, ref_offset(*raw), ref_flags(*raw), ofs));
358
359                 if (ref_obsolete(*raw)) {
360                         /* Shouldn't really happen much */
361                         new_jeb->dirty_size += rawlen;
362                         new_jeb->free_size -= rawlen;
363                         c->dirty_size += rawlen;
364                 } else {
365                         new_jeb->used_size += rawlen;
366                         new_jeb->free_size -= rawlen;
367                         jeb->dirty_size += rawlen;
368                         jeb->used_size  -= rawlen;
369                         c->dirty_size += rawlen;
370                 }
371                 c->free_size -= rawlen;
372                 (*raw)->flash_offset = ofs | ref_flags(*raw);
373                 ofs += rawlen;
374                 new_jeb->last_node = *raw;
375
376                 raw = &(*raw)->next_phys;
377         }
378
379         /* Fix up the original jeb now it's on the bad_list */
380         *first_raw = NULL;
381         if (first_raw == &jeb->first_node) {
382                 jeb->last_node = NULL;
383                 D1(printk(KERN_DEBUG "Failing block at %08x is now empty. Moving to erase_pending_list\n", jeb->offset));
384                 list_del(&jeb->list);
385                 list_add(&jeb->list, &c->erase_pending_list);
386                 c->nr_erasing_blocks++;
387                 jffs2_erase_pending_trigger(c);
388         }
389         else
390                 jeb->last_node = container_of(first_raw, struct jffs2_raw_node_ref, next_phys);
391
392         jffs2_dbg_acct_sanity_check_nolock(c, jeb);
393         jffs2_dbg_acct_paranoia_check_nolock(c, jeb);
394
395         jffs2_dbg_acct_sanity_check_nolock(c, new_jeb);
396         jffs2_dbg_acct_paranoia_check_nolock(c, new_jeb);
397
398         spin_unlock(&c->erase_completion_lock);
399
400         D1(printk(KERN_DEBUG "wbuf recovery completed OK\n"));
401 }
402
403 /* Meaning of pad argument:
404    0: Do not pad. Probably pointless - we only ever use this when we can't pad anyway.
405    1: Pad, do not adjust nextblock free_size
406    2: Pad, adjust nextblock free_size
407 */
408 #define NOPAD           0
409 #define PAD_NOACCOUNT   1
410 #define PAD_ACCOUNTING  2
411
412 static int __jffs2_flush_wbuf(struct jffs2_sb_info *c, int pad)
413 {
414         int ret;
415         size_t retlen;
416
417         /* Nothing to do if not write-buffering the flash. In particular, we shouldn't
418            del_timer() the timer we never initialised. */
419         if (!jffs2_is_writebuffered(c))
420                 return 0;
421
422         if (!down_trylock(&c->alloc_sem)) {
423                 up(&c->alloc_sem);
424                 printk(KERN_CRIT "jffs2_flush_wbuf() called with alloc_sem not locked!\n");
425                 BUG();
426         }
427
428         if (!c->wbuf_len)       /* already checked c->wbuf above */
429                 return 0;
430
431         /* claim remaining space on the page
432            this happens, if we have a change to a new block,
433            or if fsync forces us to flush the writebuffer.
434            if we have a switch to next page, we will not have
435            enough remaining space for this.
436         */
437         if (pad ) {
438                 c->wbuf_len = PAD(c->wbuf_len);
439
440                 /* Pad with JFFS2_DIRTY_BITMASK initially.  this helps out ECC'd NOR
441                    with 8 byte page size */
442                 memset(c->wbuf + c->wbuf_len, 0, c->wbuf_pagesize - c->wbuf_len);
443
444                 if ( c->wbuf_len + sizeof(struct jffs2_unknown_node) < c->wbuf_pagesize) {
445                         struct jffs2_unknown_node *padnode = (void *)(c->wbuf + c->wbuf_len);
446                         padnode->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK);
447                         padnode->nodetype = cpu_to_je16(JFFS2_NODETYPE_PADDING);
448                         padnode->totlen = cpu_to_je32(c->wbuf_pagesize - c->wbuf_len);
449                         padnode->hdr_crc = cpu_to_je32(crc32(0, padnode, sizeof(*padnode)-4));
450                 }
451         }
452         /* else jffs2_flash_writev has actually filled in the rest of the
453            buffer for us, and will deal with the node refs etc. later. */
454
455 #ifdef BREAKME
456         static int breakme;
457         if (breakme++ == 20) {
458                 printk(KERN_NOTICE "Faking write error at 0x%08x\n", c->wbuf_ofs);
459                 breakme = 0;
460                 c->mtd->write_ecc(c->mtd, c->wbuf_ofs, c->wbuf_pagesize,
461                                         &retlen, brokenbuf, NULL, c->oobinfo);
462                 ret = -EIO;
463         } else
464 #endif
465
466         if (jffs2_cleanmarker_oob(c))
467                 ret = c->mtd->write_ecc(c->mtd, c->wbuf_ofs, c->wbuf_pagesize, &retlen, c->wbuf, NULL, c->oobinfo);
468         else
469                 ret = c->mtd->write(c->mtd, c->wbuf_ofs, c->wbuf_pagesize, &retlen, c->wbuf);
470
471         if (ret || retlen != c->wbuf_pagesize) {
472                 if (ret)
473                         printk(KERN_WARNING "jffs2_flush_wbuf(): Write failed with %d\n",ret);
474                 else {
475                         printk(KERN_WARNING "jffs2_flush_wbuf(): Write was short: %zd instead of %d\n",
476                                 retlen, c->wbuf_pagesize);
477                         ret = -EIO;
478                 }
479
480                 jffs2_wbuf_recover(c);
481
482                 return ret;
483         }
484
485         /* Adjust free size of the block if we padded. */
486         if (pad) {
487                 struct jffs2_eraseblock *jeb;
488                 struct jffs2_raw_node_ref *ref;
489                 uint32_t waste = c->wbuf_pagesize - c->wbuf_len;
490
491                 jeb = &c->blocks[c->wbuf_ofs / c->sector_size];
492
493                 D1(printk(KERN_DEBUG "jffs2_flush_wbuf() adjusting free_size of %sblock at %08x\n",
494                           (jeb==c->nextblock)?"next":"", jeb->offset));
495
496                 /* wbuf_pagesize - wbuf_len is the amount of space that's to be
497                    padded. If there is less free space in the block than that,
498                    something screwed up */
499                 if (jeb->free_size < waste) {
500                         printk(KERN_CRIT "jffs2_flush_wbuf(): Accounting error. wbuf at 0x%08x has 0x%03x bytes, 0x%03x left.\n",
501                                c->wbuf_ofs, c->wbuf_len, waste);
502                         printk(KERN_CRIT "jffs2_flush_wbuf(): But free_size for block at 0x%08x is only 0x%08x\n",
503                                jeb->offset, jeb->free_size);
504                         BUG();
505                 }
506                 ref = jffs2_alloc_raw_node_ref();
507                 if (!ref)
508                         return -ENOMEM;
509                 ref->flash_offset = c->wbuf_ofs + c->wbuf_len;
510                 ref->flash_offset |= REF_OBSOLETE;
511
512                 spin_lock(&c->erase_completion_lock);
513
514                 jffs2_link_node_ref(c, jeb, ref, waste, NULL);
515                 /* FIXME: that made it count as dirty. Convert to wasted */
516                 jeb->dirty_size -= waste;
517                 c->dirty_size -= waste;
518                 jeb->wasted_size += waste;
519                 c->wasted_size += waste;
520         } else
521                 spin_lock(&c->erase_completion_lock);
522
523         /* Stick any now-obsoleted blocks on the erase_pending_list */
524         jffs2_refile_wbuf_blocks(c);
525         jffs2_clear_wbuf_ino_list(c);
526         spin_unlock(&c->erase_completion_lock);
527
528         memset(c->wbuf,0xff,c->wbuf_pagesize);
529         /* adjust write buffer offset, else we get a non contiguous write bug */
530         c->wbuf_ofs += c->wbuf_pagesize;
531         c->wbuf_len = 0;
532         return 0;
533 }
534
535 /* Trigger garbage collection to flush the write-buffer.
536    If ino arg is zero, do it if _any_ real (i.e. not GC) writes are
537    outstanding. If ino arg non-zero, do it only if a write for the
538    given inode is outstanding. */
539 int jffs2_flush_wbuf_gc(struct jffs2_sb_info *c, uint32_t ino)
540 {
541         uint32_t old_wbuf_ofs;
542         uint32_t old_wbuf_len;
543         int ret = 0;
544
545         D1(printk(KERN_DEBUG "jffs2_flush_wbuf_gc() called for ino #%u...\n", ino));
546
547         if (!c->wbuf)
548                 return 0;
549
550         down(&c->alloc_sem);
551         if (!jffs2_wbuf_pending_for_ino(c, ino)) {
552                 D1(printk(KERN_DEBUG "Ino #%d not pending in wbuf. Returning\n", ino));
553                 up(&c->alloc_sem);
554                 return 0;
555         }
556
557         old_wbuf_ofs = c->wbuf_ofs;
558         old_wbuf_len = c->wbuf_len;
559
560         if (c->unchecked_size) {
561                 /* GC won't make any progress for a while */
562                 D1(printk(KERN_DEBUG "jffs2_flush_wbuf_gc() padding. Not finished checking\n"));
563                 down_write(&c->wbuf_sem);
564                 ret = __jffs2_flush_wbuf(c, PAD_ACCOUNTING);
565                 /* retry flushing wbuf in case jffs2_wbuf_recover
566                    left some data in the wbuf */
567                 if (ret)
568                         ret = __jffs2_flush_wbuf(c, PAD_ACCOUNTING);
569                 up_write(&c->wbuf_sem);
570         } else while (old_wbuf_len &&
571                       old_wbuf_ofs == c->wbuf_ofs) {
572
573                 up(&c->alloc_sem);
574
575                 D1(printk(KERN_DEBUG "jffs2_flush_wbuf_gc() calls gc pass\n"));
576
577                 ret = jffs2_garbage_collect_pass(c);
578                 if (ret) {
579                         /* GC failed. Flush it with padding instead */
580                         down(&c->alloc_sem);
581                         down_write(&c->wbuf_sem);
582                         ret = __jffs2_flush_wbuf(c, PAD_ACCOUNTING);
583                         /* retry flushing wbuf in case jffs2_wbuf_recover
584                            left some data in the wbuf */
585                         if (ret)
586                                 ret = __jffs2_flush_wbuf(c, PAD_ACCOUNTING);
587                         up_write(&c->wbuf_sem);
588                         break;
589                 }
590                 down(&c->alloc_sem);
591         }
592
593         D1(printk(KERN_DEBUG "jffs2_flush_wbuf_gc() ends...\n"));
594
595         up(&c->alloc_sem);
596         return ret;
597 }
598
599 /* Pad write-buffer to end and write it, wasting space. */
600 int jffs2_flush_wbuf_pad(struct jffs2_sb_info *c)
601 {
602         int ret;
603
604         if (!c->wbuf)
605                 return 0;
606
607         down_write(&c->wbuf_sem);
608         ret = __jffs2_flush_wbuf(c, PAD_NOACCOUNT);
609         /* retry - maybe wbuf recover left some data in wbuf. */
610         if (ret)
611                 ret = __jffs2_flush_wbuf(c, PAD_NOACCOUNT);
612         up_write(&c->wbuf_sem);
613
614         return ret;
615 }
616
617 static size_t jffs2_fill_wbuf(struct jffs2_sb_info *c, const uint8_t *buf,
618                               size_t len)
619 {
620         if (len && !c->wbuf_len && (len >= c->wbuf_pagesize))
621                 return 0;
622
623         if (len > (c->wbuf_pagesize - c->wbuf_len))
624                 len = c->wbuf_pagesize - c->wbuf_len;
625         memcpy(c->wbuf + c->wbuf_len, buf, len);
626         c->wbuf_len += (uint32_t) len;
627         return len;
628 }
629
630 int jffs2_flash_writev(struct jffs2_sb_info *c, const struct kvec *invecs,
631                        unsigned long count, loff_t to, size_t *retlen,
632                        uint32_t ino)
633 {
634         struct jffs2_eraseblock *jeb;
635         size_t wbuf_retlen, donelen = 0;
636         uint32_t outvec_to = to;
637         int ret, invec;
638
639         /* If not writebuffered flash, don't bother */
640         if (!jffs2_is_writebuffered(c))
641                 return jffs2_flash_direct_writev(c, invecs, count, to, retlen);
642
643         down_write(&c->wbuf_sem);
644
645         /* If wbuf_ofs is not initialized, set it to target address */
646         if (c->wbuf_ofs == 0xFFFFFFFF) {
647                 c->wbuf_ofs = PAGE_DIV(to);
648                 c->wbuf_len = PAGE_MOD(to);
649                 memset(c->wbuf,0xff,c->wbuf_pagesize);
650         }
651
652         /*
653          * Sanity checks on target address.  It's permitted to write
654          * at PAD(c->wbuf_len+c->wbuf_ofs), and it's permitted to
655          * write at the beginning of a new erase block. Anything else,
656          * and you die.  New block starts at xxx000c (0-b = block
657          * header)
658          */
659         if (SECTOR_ADDR(to) != SECTOR_ADDR(c->wbuf_ofs)) {
660                 /* It's a write to a new block */
661                 if (c->wbuf_len) {
662                         D1(printk(KERN_DEBUG "jffs2_flash_writev() to 0x%lx "
663                                   "causes flush of wbuf at 0x%08x\n",
664                                   (unsigned long)to, c->wbuf_ofs));
665                         ret = __jffs2_flush_wbuf(c, PAD_NOACCOUNT);
666                         if (ret)
667                                 goto outerr;
668                 }
669                 /* set pointer to new block */
670                 c->wbuf_ofs = PAGE_DIV(to);
671                 c->wbuf_len = PAGE_MOD(to);
672         }
673
674         if (to != PAD(c->wbuf_ofs + c->wbuf_len)) {
675                 /* We're not writing immediately after the writebuffer. Bad. */
676                 printk(KERN_CRIT "jffs2_flash_writev(): Non-contiguous write "
677                        "to %08lx\n", (unsigned long)to);
678                 if (c->wbuf_len)
679                         printk(KERN_CRIT "wbuf was previously %08x-%08x\n",
680                                c->wbuf_ofs, c->wbuf_ofs+c->wbuf_len);
681                 BUG();
682         }
683
684         /* adjust alignment offset */
685         if (c->wbuf_len != PAGE_MOD(to)) {
686                 c->wbuf_len = PAGE_MOD(to);
687                 /* take care of alignment to next page */
688                 if (!c->wbuf_len) {
689                         c->wbuf_len = c->wbuf_pagesize;
690                         ret = __jffs2_flush_wbuf(c, NOPAD);
691                         if (ret)
692                                 goto outerr;
693                 }
694         }
695
696         for (invec = 0; invec < count; invec++) {
697                 int vlen = invecs[invec].iov_len;
698                 uint8_t *v = invecs[invec].iov_base;
699
700                 wbuf_retlen = jffs2_fill_wbuf(c, v, vlen);
701
702                 if (c->wbuf_len == c->wbuf_pagesize) {
703                         ret = __jffs2_flush_wbuf(c, NOPAD);
704                         if (ret)
705                                 goto outerr;
706                 }
707                 vlen -= wbuf_retlen;
708                 outvec_to += wbuf_retlen;
709                 donelen += wbuf_retlen;
710                 v += wbuf_retlen;
711
712                 if (vlen >= c->wbuf_pagesize) {
713                         ret = c->mtd->write(c->mtd, outvec_to, PAGE_DIV(vlen),
714                                             &wbuf_retlen, v);
715                         if (ret < 0 || wbuf_retlen != PAGE_DIV(vlen))
716                                 goto outfile;
717
718                         vlen -= wbuf_retlen;
719                         outvec_to += wbuf_retlen;
720                         c->wbuf_ofs = outvec_to;
721                         donelen += wbuf_retlen;
722                         v += wbuf_retlen;
723                 }
724
725                 wbuf_retlen = jffs2_fill_wbuf(c, v, vlen);
726                 if (c->wbuf_len == c->wbuf_pagesize) {
727                         ret = __jffs2_flush_wbuf(c, NOPAD);
728                         if (ret)
729                                 goto outerr;
730                 }
731
732                 outvec_to += wbuf_retlen;
733                 donelen += wbuf_retlen;
734         }
735
736         /*
737          * If there's a remainder in the wbuf and it's a non-GC write,
738          * remember that the wbuf affects this ino
739          */
740         *retlen = donelen;
741
742         if (jffs2_sum_active()) {
743                 int res = jffs2_sum_add_kvec(c, invecs, count, (uint32_t) to);
744                 if (res)
745                         return res;
746         }
747
748         if (c->wbuf_len && ino)
749                 jffs2_wbuf_dirties_inode(c, ino);
750
751         ret = 0;
752         up_write(&c->wbuf_sem);
753         return ret;
754
755 outfile:
756         /*
757          * At this point we have no problem, c->wbuf is empty. However
758          * refile nextblock to avoid writing again to same address.
759          */
760
761         spin_lock(&c->erase_completion_lock);
762
763         jeb = &c->blocks[outvec_to / c->sector_size];
764         jffs2_block_refile(c, jeb, REFILE_ANYWAY);
765
766         spin_unlock(&c->erase_completion_lock);
767
768 outerr:
769         *retlen = 0;
770         up_write(&c->wbuf_sem);
771         return ret;
772 }
773
774 /*
775  *      This is the entry for flash write.
776  *      Check, if we work on NAND FLASH, if so build an kvec and write it via vritev
777 */
778 int jffs2_flash_write(struct jffs2_sb_info *c, loff_t ofs, size_t len, size_t *retlen, const u_char *buf)
779 {
780         struct kvec vecs[1];
781
782         if (!jffs2_is_writebuffered(c))
783                 return jffs2_flash_direct_write(c, ofs, len, retlen, buf);
784
785         vecs[0].iov_base = (unsigned char *) buf;
786         vecs[0].iov_len = len;
787         return jffs2_flash_writev(c, vecs, 1, ofs, retlen, 0);
788 }
789
790 /*
791         Handle readback from writebuffer and ECC failure return
792 */
793 int jffs2_flash_read(struct jffs2_sb_info *c, loff_t ofs, size_t len, size_t *retlen, u_char *buf)
794 {
795         loff_t  orbf = 0, owbf = 0, lwbf = 0;
796         int     ret;
797
798         if (!jffs2_is_writebuffered(c))
799                 return c->mtd->read(c->mtd, ofs, len, retlen, buf);
800
801         /* Read flash */
802         down_read(&c->wbuf_sem);
803         if (jffs2_cleanmarker_oob(c))
804                 ret = c->mtd->read_ecc(c->mtd, ofs, len, retlen, buf, NULL, c->oobinfo);
805         else
806                 ret = c->mtd->read(c->mtd, ofs, len, retlen, buf);
807
808         if ( (ret == -EBADMSG) && (*retlen == len) ) {
809                 printk(KERN_WARNING "mtd->read(0x%zx bytes from 0x%llx) returned ECC error\n",
810                        len, ofs);
811                 /*
812                  * We have the raw data without ECC correction in the buffer, maybe
813                  * we are lucky and all data or parts are correct. We check the node.
814                  * If data are corrupted node check will sort it out.
815                  * We keep this block, it will fail on write or erase and the we
816                  * mark it bad. Or should we do that now? But we should give him a chance.
817                  * Maybe we had a system crash or power loss before the ecc write or
818                  * a erase was completed.
819                  * So we return success. :)
820                  */
821                 ret = 0;
822         }
823
824         /* if no writebuffer available or write buffer empty, return */
825         if (!c->wbuf_pagesize || !c->wbuf_len)
826                 goto exit;
827
828         /* if we read in a different block, return */
829         if (SECTOR_ADDR(ofs) != SECTOR_ADDR(c->wbuf_ofs))
830                 goto exit;
831
832         if (ofs >= c->wbuf_ofs) {
833                 owbf = (ofs - c->wbuf_ofs);     /* offset in write buffer */
834                 if (owbf > c->wbuf_len)         /* is read beyond write buffer ? */
835                         goto exit;
836                 lwbf = c->wbuf_len - owbf;      /* number of bytes to copy */
837                 if (lwbf > len)
838                         lwbf = len;
839         } else {
840                 orbf = (c->wbuf_ofs - ofs);     /* offset in read buffer */
841                 if (orbf > len)                 /* is write beyond write buffer ? */
842                         goto exit;
843                 lwbf = len - orbf;              /* number of bytes to copy */
844                 if (lwbf > c->wbuf_len)
845                         lwbf = c->wbuf_len;
846         }
847         if (lwbf > 0)
848                 memcpy(buf+orbf,c->wbuf+owbf,lwbf);
849
850 exit:
851         up_read(&c->wbuf_sem);
852         return ret;
853 }
854
855 /*
856  *      Check, if the out of band area is empty
857  */
858 int jffs2_check_oob_empty( struct jffs2_sb_info *c, struct jffs2_eraseblock *jeb, int mode)
859 {
860         unsigned char *buf;
861         int     ret = 0;
862         int     i,len,page;
863         size_t  retlen;
864         int     oob_size;
865
866         /* allocate a buffer for all oob data in this sector */
867         oob_size = c->mtd->oobsize;
868         len = 4 * oob_size;
869         buf = kmalloc(len, GFP_KERNEL);
870         if (!buf) {
871                 printk(KERN_NOTICE "jffs2_check_oob_empty(): allocation of temporary data buffer for oob check failed\n");
872                 return -ENOMEM;
873         }
874         /*
875          * if mode = 0, we scan for a total empty oob area, else we have
876          * to take care of the cleanmarker in the first page of the block
877         */
878         ret = jffs2_flash_read_oob(c, jeb->offset, len , &retlen, buf);
879         if (ret) {
880                 D1(printk(KERN_WARNING "jffs2_check_oob_empty(): Read OOB failed %d for block at %08x\n", ret, jeb->offset));
881                 goto out;
882         }
883
884         if (retlen < len) {
885                 D1(printk(KERN_WARNING "jffs2_check_oob_empty(): Read OOB return short read "
886                           "(%zd bytes not %d) for block at %08x\n", retlen, len, jeb->offset));
887                 ret = -EIO;
888                 goto out;
889         }
890
891         /* Special check for first page */
892         for(i = 0; i < oob_size ; i++) {
893                 /* Yeah, we know about the cleanmarker. */
894                 if (mode && i >= c->fsdata_pos &&
895                     i < c->fsdata_pos + c->fsdata_len)
896                         continue;
897
898                 if (buf[i] != 0xFF) {
899                         D2(printk(KERN_DEBUG "Found %02x at %x in OOB for %08x\n",
900                                   buf[i], i, jeb->offset));
901                         ret = 1;
902                         goto out;
903                 }
904         }
905
906         /* we know, we are aligned :) */
907         for (page = oob_size; page < len; page += sizeof(long)) {
908                 unsigned long dat = *(unsigned long *)(&buf[page]);
909                 if(dat != -1) {
910                         ret = 1;
911                         goto out;
912                 }
913         }
914
915 out:
916         kfree(buf);
917
918         return ret;
919 }
920
921 /*
922 *       Scan for a valid cleanmarker and for bad blocks
923 *       For virtual blocks (concatenated physical blocks) check the cleanmarker
924 *       only in the first page of the first physical block, but scan for bad blocks in all
925 *       physical blocks
926 */
927 int jffs2_check_nand_cleanmarker (struct jffs2_sb_info *c, struct jffs2_eraseblock *jeb)
928 {
929         struct jffs2_unknown_node n;
930         unsigned char buf[2 * NAND_MAX_OOBSIZE];
931         unsigned char *p;
932         int ret, i, cnt, retval = 0;
933         size_t retlen, offset;
934         int oob_size;
935
936         offset = jeb->offset;
937         oob_size = c->mtd->oobsize;
938
939         /* Loop through the physical blocks */
940         for (cnt = 0; cnt < (c->sector_size / c->mtd->erasesize); cnt++) {
941                 /* Check first if the block is bad. */
942                 if (c->mtd->block_isbad (c->mtd, offset)) {
943                         D1 (printk (KERN_WARNING "jffs2_check_nand_cleanmarker(): Bad block at %08x\n", jeb->offset));
944                         return 2;
945                 }
946                 /*
947                    *    We read oob data from page 0 and 1 of the block.
948                    *    page 0 contains cleanmarker and badblock info
949                    *    page 1 contains failure count of this block
950                  */
951                 ret = c->mtd->read_oob (c->mtd, offset, oob_size << 1, &retlen, buf);
952
953                 if (ret) {
954                         D1 (printk (KERN_WARNING "jffs2_check_nand_cleanmarker(): Read OOB failed %d for block at %08x\n", ret, jeb->offset));
955                         return ret;
956                 }
957                 if (retlen < (oob_size << 1)) {
958                         D1 (printk (KERN_WARNING "jffs2_check_nand_cleanmarker(): Read OOB return short read (%zd bytes not %d) for block at %08x\n", retlen, oob_size << 1, jeb->offset));
959                         return -EIO;
960                 }
961
962                 /* Check cleanmarker only on the first physical block */
963                 if (!cnt) {
964                         n.magic = cpu_to_je16 (JFFS2_MAGIC_BITMASK);
965                         n.nodetype = cpu_to_je16 (JFFS2_NODETYPE_CLEANMARKER);
966                         n.totlen = cpu_to_je32 (8);
967                         p = (unsigned char *) &n;
968
969                         for (i = 0; i < c->fsdata_len; i++) {
970                                 if (buf[c->fsdata_pos + i] != p[i]) {
971                                         retval = 1;
972                                 }
973                         }
974                         D1(if (retval == 1) {
975                                 printk(KERN_WARNING "jffs2_check_nand_cleanmarker(): Cleanmarker node not detected in block at %08x\n", jeb->offset);
976                                 printk(KERN_WARNING "OOB at %08x was ", offset);
977                                 for (i=0; i < oob_size; i++) {
978                                         printk("%02x ", buf[i]);
979                                 }
980                                 printk("\n");
981                         })
982                 }
983                 offset += c->mtd->erasesize;
984         }
985         return retval;
986 }
987
988 int jffs2_write_nand_cleanmarker(struct jffs2_sb_info *c, struct jffs2_eraseblock *jeb)
989 {
990         struct  jffs2_unknown_node n;
991         int     ret;
992         size_t  retlen;
993
994         n.magic = cpu_to_je16(JFFS2_MAGIC_BITMASK);
995         n.nodetype = cpu_to_je16(JFFS2_NODETYPE_CLEANMARKER);
996         n.totlen = cpu_to_je32(8);
997
998         ret = jffs2_flash_write_oob(c, jeb->offset + c->fsdata_pos, c->fsdata_len, &retlen, (unsigned char *)&n);
999
1000         if (ret) {
1001                 D1(printk(KERN_WARNING "jffs2_write_nand_cleanmarker(): Write failed for block at %08x: error %d\n", jeb->offset, ret));
1002                 return ret;
1003         }
1004         if (retlen != c->fsdata_len) {
1005                 D1(printk(KERN_WARNING "jffs2_write_nand_cleanmarker(): Short write for block at %08x: %zd not %d\n", jeb->offset, retlen, c->fsdata_len));
1006                 return ret;
1007         }
1008         return 0;
1009 }
1010
1011 /*
1012  * On NAND we try to mark this block bad. If the block was erased more
1013  * than MAX_ERASE_FAILURES we mark it finaly bad.
1014  * Don't care about failures. This block remains on the erase-pending
1015  * or badblock list as long as nobody manipulates the flash with
1016  * a bootloader or something like that.
1017  */
1018
1019 int jffs2_write_nand_badblock(struct jffs2_sb_info *c, struct jffs2_eraseblock *jeb, uint32_t bad_offset)
1020 {
1021         int     ret;
1022
1023         /* if the count is < max, we try to write the counter to the 2nd page oob area */
1024         if( ++jeb->bad_count < MAX_ERASE_FAILURES)
1025                 return 0;
1026
1027         if (!c->mtd->block_markbad)
1028                 return 1; // What else can we do?
1029
1030         D1(printk(KERN_WARNING "jffs2_write_nand_badblock(): Marking bad block at %08x\n", bad_offset));
1031         ret = c->mtd->block_markbad(c->mtd, bad_offset);
1032
1033         if (ret) {
1034                 D1(printk(KERN_WARNING "jffs2_write_nand_badblock(): Write failed for block at %08x: error %d\n", jeb->offset, ret));
1035                 return ret;
1036         }
1037         return 1;
1038 }
1039
1040 #define NAND_JFFS2_OOB16_FSDALEN        8
1041
1042 static struct nand_oobinfo jffs2_oobinfo_docecc = {
1043         .useecc = MTD_NANDECC_PLACE,
1044         .eccbytes = 6,
1045         .eccpos = {0,1,2,3,4,5}
1046 };
1047
1048
1049 static int jffs2_nand_set_oobinfo(struct jffs2_sb_info *c)
1050 {
1051         struct nand_oobinfo *oinfo = &c->mtd->oobinfo;
1052
1053         /* Do this only, if we have an oob buffer */
1054         if (!c->mtd->oobsize)
1055                 return 0;
1056
1057         /* Cleanmarker is out-of-band, so inline size zero */
1058         c->cleanmarker_size = 0;
1059
1060         /* Should we use autoplacement ? */
1061         if (oinfo && oinfo->useecc == MTD_NANDECC_AUTOPLACE) {
1062                 D1(printk(KERN_DEBUG "JFFS2 using autoplace on NAND\n"));
1063                 /* Get the position of the free bytes */
1064                 if (!oinfo->oobfree[0][1]) {
1065                         printk (KERN_WARNING "jffs2_nand_set_oobinfo(): Eeep. Autoplacement selected and no empty space in oob\n");
1066                         return -ENOSPC;
1067                 }
1068                 c->fsdata_pos = oinfo->oobfree[0][0];
1069                 c->fsdata_len = oinfo->oobfree[0][1];
1070                 if (c->fsdata_len > 8)
1071                         c->fsdata_len = 8;
1072         } else {
1073                 /* This is just a legacy fallback and should go away soon */
1074                 switch(c->mtd->ecctype) {
1075                 case MTD_ECC_RS_DiskOnChip:
1076                         printk(KERN_WARNING "JFFS2 using DiskOnChip hardware ECC without autoplacement. Fix it!\n");
1077                         c->oobinfo = &jffs2_oobinfo_docecc;
1078                         c->fsdata_pos = 6;
1079                         c->fsdata_len = NAND_JFFS2_OOB16_FSDALEN;
1080                         c->badblock_pos = 15;
1081                         break;
1082
1083                 default:
1084                         D1(printk(KERN_DEBUG "JFFS2 on NAND. No autoplacment info found\n"));
1085                         return -EINVAL;
1086                 }
1087         }
1088         return 0;
1089 }
1090
1091 int jffs2_nand_flash_setup(struct jffs2_sb_info *c)
1092 {
1093         int res;
1094
1095         /* Initialise write buffer */
1096         init_rwsem(&c->wbuf_sem);
1097         c->wbuf_pagesize = c->mtd->writesize;
1098         c->wbuf_ofs = 0xFFFFFFFF;
1099
1100         c->wbuf = kmalloc(c->wbuf_pagesize, GFP_KERNEL);
1101         if (!c->wbuf)
1102                 return -ENOMEM;
1103
1104         res = jffs2_nand_set_oobinfo(c);
1105
1106 #ifdef BREAKME
1107         if (!brokenbuf)
1108                 brokenbuf = kmalloc(c->wbuf_pagesize, GFP_KERNEL);
1109         if (!brokenbuf) {
1110                 kfree(c->wbuf);
1111                 return -ENOMEM;
1112         }
1113         memset(brokenbuf, 0xdb, c->wbuf_pagesize);
1114 #endif
1115         return res;
1116 }
1117
1118 void jffs2_nand_flash_cleanup(struct jffs2_sb_info *c)
1119 {
1120         kfree(c->wbuf);
1121 }
1122
1123 int jffs2_dataflash_setup(struct jffs2_sb_info *c) {
1124         c->cleanmarker_size = 0;                /* No cleanmarkers needed */
1125
1126         /* Initialize write buffer */
1127         init_rwsem(&c->wbuf_sem);
1128
1129
1130         c->wbuf_pagesize =  c->mtd->erasesize;
1131
1132         /* Find a suitable c->sector_size
1133          * - Not too much sectors
1134          * - Sectors have to be at least 4 K + some bytes
1135          * - All known dataflashes have erase sizes of 528 or 1056
1136          * - we take at least 8 eraseblocks and want to have at least 8K size
1137          * - The concatenation should be a power of 2
1138         */
1139
1140         c->sector_size = 8 * c->mtd->erasesize;
1141
1142         while (c->sector_size < 8192) {
1143                 c->sector_size *= 2;
1144         }
1145
1146         /* It may be necessary to adjust the flash size */
1147         c->flash_size = c->mtd->size;
1148
1149         if ((c->flash_size % c->sector_size) != 0) {
1150                 c->flash_size = (c->flash_size / c->sector_size) * c->sector_size;
1151                 printk(KERN_WARNING "JFFS2 flash size adjusted to %dKiB\n", c->flash_size);
1152         };
1153
1154         c->wbuf_ofs = 0xFFFFFFFF;
1155         c->wbuf = kmalloc(c->wbuf_pagesize, GFP_KERNEL);
1156         if (!c->wbuf)
1157                 return -ENOMEM;
1158
1159         printk(KERN_INFO "JFFS2 write-buffering enabled buffer (%d) erasesize (%d)\n", c->wbuf_pagesize, c->sector_size);
1160
1161         return 0;
1162 }
1163
1164 void jffs2_dataflash_cleanup(struct jffs2_sb_info *c) {
1165         kfree(c->wbuf);
1166 }
1167
1168 int jffs2_nor_wbuf_flash_setup(struct jffs2_sb_info *c) {
1169         /* Cleanmarker currently occupies whole programming regions,
1170          * either one or 2 for 8Byte STMicro flashes. */
1171         c->cleanmarker_size = max(16u, c->mtd->writesize);
1172
1173         /* Initialize write buffer */
1174         init_rwsem(&c->wbuf_sem);
1175         c->wbuf_pagesize = c->mtd->writesize;
1176         c->wbuf_ofs = 0xFFFFFFFF;
1177
1178         c->wbuf = kmalloc(c->wbuf_pagesize, GFP_KERNEL);
1179         if (!c->wbuf)
1180                 return -ENOMEM;
1181
1182         return 0;
1183 }
1184
1185 void jffs2_nor_wbuf_flash_cleanup(struct jffs2_sb_info *c) {
1186         kfree(c->wbuf);
1187 }