[MTD] NAND: Fix broken bad block table scan
[safe/jmp/linux-2.6] / drivers / mtd / nand / nand_bbt.c
1 /*
2  *  drivers/mtd/nand_bbt.c
3  *
4  *  Overview:
5  *   Bad block table support for the NAND driver
6  *   
7  *  Copyright (C) 2004 Thomas Gleixner (tglx@linutronix.de)
8  *
9  * $Id: nand_bbt.c,v 1.33 2005/06/14 15:47:56 gleixner Exp $
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License version 2 as
13  * published by the Free Software Foundation.
14  *
15  * Description:
16  *
17  * When nand_scan_bbt is called, then it tries to find the bad block table 
18  * depending on the options in the bbt descriptor(s). If a bbt is found 
19  * then the contents are read and the memory based bbt is created. If a 
20  * mirrored bbt is selected then the mirror is searched too and the
21  * versions are compared. If the mirror has a greater version number 
22  * than the mirror bbt is used to build the memory based bbt.
23  * If the tables are not versioned, then we "or" the bad block information.
24  * If one of the bbt's is out of date or does not exist it is (re)created. 
25  * If no bbt exists at all then the device is scanned for factory marked 
26  * good / bad blocks and the bad block tables are created. 
27  *
28  * For manufacturer created bbts like the one found on M-SYS DOC devices 
29  * the bbt is searched and read but never created
30  *
31  * The autogenerated bad block table is located in the last good blocks 
32  * of the device. The table is mirrored, so it can be updated eventually. 
33  * The table is marked in the oob area with an ident pattern and a version 
34  * number which indicates which of both tables is more up to date.
35  *
36  * The table uses 2 bits per block
37  * 11b:         block is good
38  * 00b:         block is factory marked bad
39  * 01b, 10b:    block is marked bad due to wear
40  *
41  * The memory bad block table uses the following scheme:
42  * 00b:         block is good
43  * 01b:         block is marked bad due to wear
44  * 10b:         block is reserved (to protect the bbt area)
45  * 11b:         block is factory marked bad
46  * 
47  * Multichip devices like DOC store the bad block info per floor.
48  *
49  * Following assumptions are made:
50  * - bbts start at a page boundary, if autolocated on a block boundary
51  * - the space neccecary for a bbt in FLASH does not exceed a block boundary
52  * 
53  */
54
55 #include <linux/slab.h>
56 #include <linux/types.h>
57 #include <linux/mtd/mtd.h>
58 #include <linux/mtd/nand.h>
59 #include <linux/mtd/nand_ecc.h>
60 #include <linux/mtd/compatmac.h>
61 #include <linux/bitops.h>
62 #include <linux/delay.h>
63
64
65 /** 
66  * check_pattern - [GENERIC] check if a pattern is in the buffer
67  * @buf:        the buffer to search
68  * @len:        the length of buffer to search
69  * @paglen:     the pagelength
70  * @td:         search pattern descriptor
71  *
72  * Check for a pattern at the given place. Used to search bad block
73  * tables and good / bad block identifiers.
74  * If the SCAN_EMPTY option is set then check, if all bytes except the
75  * pattern area contain 0xff
76  *
77 */
78 static int check_pattern (uint8_t *buf, int len, int paglen, struct nand_bbt_descr *td)
79 {
80         int i, end = 0;
81         uint8_t *p = buf;
82
83         end = paglen + td->offs;
84         if (td->options & NAND_BBT_SCANEMPTY) {
85                 for (i = 0; i < end; i++) {
86                         if (p[i] != 0xff)
87                                 return -1;
88                 }
89         }       
90         p += end;
91         
92         /* Compare the pattern */
93         for (i = 0; i < td->len; i++) {
94                 if (p[i] != td->pattern[i])
95                         return -1;
96         }
97
98         if (td->options & NAND_BBT_SCANEMPTY) {
99                 p += td->len;
100                 end += td->len;
101                 for (i = end; i < len; i++) {
102                         if (*p++ != 0xff)
103                                 return -1;
104                 }
105         }
106         return 0;
107 }
108
109 /** 
110  * check_short_pattern - [GENERIC] check if a pattern is in the buffer
111  * @buf:        the buffer to search
112  * @len:        the length of buffer to search
113  * @paglen:     the pagelength
114  * @td:         search pattern descriptor
115  *
116  * Check for a pattern at the given place. Used to search bad block
117  * tables and good / bad block identifiers. Same as check_pattern, but 
118  * no optional empty check and the pattern is expected to start
119  * at offset 0.
120  *
121 */
122 static int check_short_pattern (uint8_t *buf, int len, int paglen, struct nand_bbt_descr *td)
123 {
124         int i;
125         uint8_t *p = buf;
126
127         /* Compare the pattern */
128         for (i = 0; i < td->len; i++) {
129                 if (p[i] != td->pattern[i])
130                         return -1;
131         }
132         return 0;
133 }
134
135 /**
136  * read_bbt - [GENERIC] Read the bad block table starting from page
137  * @mtd:        MTD device structure
138  * @buf:        temporary buffer
139  * @page:       the starting page
140  * @num:        the number of bbt descriptors to read
141  * @bits:       number of bits per block
142  * @offs:       offset in the memory table
143  * @reserved_block_code:        Pattern to identify reserved blocks
144  *
145  * Read the bad block table starting from page.
146  *
147  */
148 static int read_bbt (struct mtd_info *mtd, uint8_t *buf, int page, int num, 
149         int bits, int offs, int reserved_block_code)
150 {
151         int res, i, j, act = 0;
152         struct nand_chip *this = mtd->priv;
153         size_t retlen, len, totlen;
154         loff_t from;
155         uint8_t msk = (uint8_t) ((1 << bits) - 1);
156
157         totlen = (num * bits) >> 3;
158         from = ((loff_t)page) << this->page_shift;
159         
160         while (totlen) {
161                 len = min (totlen, (size_t) (1 << this->bbt_erase_shift));
162                 res = mtd->read_ecc (mtd, from, len, &retlen, buf, NULL, this->autooob);
163                 if (res < 0) {
164                         if (retlen != len) {
165                                 printk (KERN_INFO "nand_bbt: Error reading bad block table\n");
166                                 return res;
167                         }
168                         printk (KERN_WARNING "nand_bbt: ECC error while reading bad block table\n");
169                 }       
170
171                 /* Analyse data */
172                 for (i = 0; i < len; i++) {
173                         uint8_t dat = buf[i];
174                         for (j = 0; j < 8; j += bits, act += 2) {
175                                 uint8_t tmp = (dat >> j) & msk;
176                                 if (tmp == msk)
177                                         continue;
178                                 if (reserved_block_code &&
179                                     (tmp == reserved_block_code)) {
180                                         printk (KERN_DEBUG "nand_read_bbt: Reserved block at 0x%08x\n",
181                                                 ((offs << 2) + (act >> 1)) << this->bbt_erase_shift);
182                                         this->bbt[offs + (act >> 3)] |= 0x2 << (act & 0x06);
183                                         continue;
184                                 }
185                                 /* Leave it for now, if its matured we can move this
186                                  * message to MTD_DEBUG_LEVEL0 */
187                                 printk (KERN_DEBUG "nand_read_bbt: Bad block at 0x%08x\n",
188                                         ((offs << 2) + (act >> 1)) << this->bbt_erase_shift);
189                                 /* Factory marked bad or worn out ? */  
190                                 if (tmp == 0)
191                                         this->bbt[offs + (act >> 3)] |= 0x3 << (act & 0x06);
192                                 else
193                                         this->bbt[offs + (act >> 3)] |= 0x1 << (act & 0x06);
194                         }       
195                 }
196                 totlen -= len;
197                 from += len;
198         }
199         return 0;
200 }
201
202 /**
203  * read_abs_bbt - [GENERIC] Read the bad block table starting at a given page
204  * @mtd:        MTD device structure
205  * @buf:        temporary buffer
206  * @td:         descriptor for the bad block table 
207  * @chip:       read the table for a specific chip, -1 read all chips.
208  *              Applies only if NAND_BBT_PERCHIP option is set
209  *
210  * Read the bad block table for all chips starting at a given page
211  * We assume that the bbt bits are in consecutive order.
212 */
213 static int read_abs_bbt (struct mtd_info *mtd, uint8_t *buf, struct nand_bbt_descr *td, int chip)
214 {
215         struct nand_chip *this = mtd->priv;
216         int res = 0, i;
217         int bits;
218
219         bits = td->options & NAND_BBT_NRBITS_MSK;
220         if (td->options & NAND_BBT_PERCHIP) {
221                 int offs = 0;
222                 for (i = 0; i < this->numchips; i++) {
223                         if (chip == -1 || chip == i)
224                                 res = read_bbt (mtd, buf, td->pages[i], this->chipsize >> this->bbt_erase_shift, bits, offs, td->reserved_block_code);
225                         if (res)
226                                 return res;
227                         offs += this->chipsize >> (this->bbt_erase_shift + 2);
228                 }
229         } else {
230                 res = read_bbt (mtd, buf, td->pages[0], mtd->size >> this->bbt_erase_shift, bits, 0, td->reserved_block_code);
231                 if (res)
232                         return res;
233         }
234         return 0;
235 }
236
237 /**
238  * read_abs_bbts - [GENERIC] Read the bad block table(s) for all chips starting at a given page
239  * @mtd:        MTD device structure
240  * @buf:        temporary buffer
241  * @td:         descriptor for the bad block table 
242  * @md:         descriptor for the bad block table mirror
243  *
244  * Read the bad block table(s) for all chips starting at a given page
245  * We assume that the bbt bits are in consecutive order.
246  *
247 */
248 static int read_abs_bbts (struct mtd_info *mtd, uint8_t *buf, struct nand_bbt_descr *td,
249         struct nand_bbt_descr *md)
250 {
251         struct nand_chip *this = mtd->priv;
252
253         /* Read the primary version, if available */    
254         if (td->options & NAND_BBT_VERSION) {
255                 nand_read_raw (mtd, buf, td->pages[0] << this->page_shift, mtd->oobblock, mtd->oobsize); 
256                 td->version[0] = buf[mtd->oobblock + td->veroffs];
257                 printk (KERN_DEBUG "Bad block table at page %d, version 0x%02X\n", td->pages[0], td->version[0]);
258         }
259
260         /* Read the mirror version, if available */     
261         if (md && (md->options & NAND_BBT_VERSION)) {
262                 nand_read_raw (mtd, buf, md->pages[0] << this->page_shift, mtd->oobblock, mtd->oobsize); 
263                 md->version[0] = buf[mtd->oobblock + md->veroffs];
264                 printk (KERN_DEBUG "Bad block table at page %d, version 0x%02X\n", md->pages[0], md->version[0]);
265         }
266
267         return 1;
268 }
269
270 /**
271  * create_bbt - [GENERIC] Create a bad block table by scanning the device
272  * @mtd:        MTD device structure
273  * @buf:        temporary buffer
274  * @bd:         descriptor for the good/bad block search pattern
275  * @chip:       create the table for a specific chip, -1 read all chips.
276  *              Applies only if NAND_BBT_PERCHIP option is set
277  *
278  * Create a bad block table by scanning the device
279  * for the given good/bad block identify pattern
280  */
281 static int create_bbt (struct mtd_info *mtd, uint8_t *buf, struct nand_bbt_descr *bd, int chip)
282 {
283         struct nand_chip *this = mtd->priv;
284         int i, j, numblocks, len, scanlen;
285         int startblock;
286         loff_t from;
287         size_t readlen, ooblen;
288
289         printk (KERN_INFO "Scanning device for bad blocks\n");
290
291         if (bd->options & NAND_BBT_SCANALLPAGES)
292                 len = 1 << (this->bbt_erase_shift - this->page_shift);
293         else {
294                 if (bd->options & NAND_BBT_SCAN2NDPAGE)
295                         len = 2;
296                 else    
297                         len = 1;
298         }
299
300         if (!(bd->options & NAND_BBT_SCANEMPTY)) {
301                 /* We need only read few bytes from the OOB area */
302                 scanlen = ooblen = 0;
303                 readlen = bd->len;
304         } else {
305                 /* Full page content should be read */
306                 scanlen = mtd->oobblock + mtd->oobsize;
307                 readlen = len * mtd->oobblock;
308                 ooblen = len * mtd->oobsize;
309         }
310
311         if (chip == -1) {
312                 /* Note that numblocks is 2 * (real numblocks) here, see i+=2 below as it
313                  * makes shifting and masking less painful */
314                 numblocks = mtd->size >> (this->bbt_erase_shift - 1);
315                 startblock = 0;
316                 from = 0;
317         } else {
318                 if (chip >= this->numchips) {
319                         printk (KERN_WARNING "create_bbt(): chipnr (%d) > available chips (%d)\n",
320                                 chip + 1, this->numchips);
321                         return -EINVAL;
322                 }
323                 numblocks = this->chipsize >> (this->bbt_erase_shift - 1);
324                 startblock = chip * numblocks;
325                 numblocks += startblock;
326                 from = startblock << (this->bbt_erase_shift - 1);
327         }
328         
329         for (i = startblock; i < numblocks;) {
330                 int ret;
331                 
332                 if (bd->options & NAND_BBT_SCANEMPTY)
333                         if ((ret = nand_read_raw (mtd, buf, from, readlen, ooblen)))
334                                 return ret;
335
336                 for (j = 0; j < len; j++) {
337                         if (!(bd->options & NAND_BBT_SCANEMPTY)) {
338                                 size_t retlen;
339                                 
340                                 /* No need to read pages fully, just read required OOB bytes */
341                                 ret = mtd->read_oob(mtd, from + j * mtd->oobblock + bd->offs,
342                                                         readlen, &retlen, &buf[0]);
343                                 if (ret)
344                                         return ret;
345
346                                 if (check_short_pattern (&buf[j * scanlen], scanlen, mtd->oobblock, bd)) {
347                                         this->bbt[i >> 3] |= 0x03 << (i & 0x6);
348                                         printk (KERN_WARNING "Bad eraseblock %d at 0x%08x\n", 
349                                                 i >> 1, (unsigned int) from);
350                                         break;
351                                 }
352                         } else {
353                                 if (check_pattern (&buf[j * scanlen], scanlen, mtd->oobblock, bd)) {
354                                         this->bbt[i >> 3] |= 0x03 << (i & 0x6);
355                                         printk (KERN_WARNING "Bad eraseblock %d at 0x%08x\n", 
356                                                 i >> 1, (unsigned int) from);
357                                         break;
358                                 }
359                         }
360                 }
361                 i += 2;
362                 from += (1 << this->bbt_erase_shift);
363         }
364         return 0;
365 }
366
367 /**
368  * search_bbt - [GENERIC] scan the device for a specific bad block table
369  * @mtd:        MTD device structure
370  * @buf:        temporary buffer
371  * @td:         descriptor for the bad block table
372  *
373  * Read the bad block table by searching for a given ident pattern.
374  * Search is preformed either from the beginning up or from the end of 
375  * the device downwards. The search starts always at the start of a
376  * block.
377  * If the option NAND_BBT_PERCHIP is given, each chip is searched 
378  * for a bbt, which contains the bad block information of this chip.
379  * This is neccecary to provide support for certain DOC devices.
380  *
381  * The bbt ident pattern resides in the oob area of the first page 
382  * in a block. 
383  */
384 static int search_bbt (struct mtd_info *mtd, uint8_t *buf, struct nand_bbt_descr *td)
385 {
386         struct nand_chip *this = mtd->priv;
387         int i, chips;
388         int bits, startblock, block, dir;
389         int scanlen = mtd->oobblock + mtd->oobsize;
390         int bbtblocks;
391
392         /* Search direction top -> down ? */
393         if (td->options & NAND_BBT_LASTBLOCK) {
394                 startblock = (mtd->size >> this->bbt_erase_shift) -1;
395                 dir = -1;
396         } else {
397                 startblock = 0; 
398                 dir = 1;
399         }       
400         
401         /* Do we have a bbt per chip ? */
402         if (td->options & NAND_BBT_PERCHIP) {
403                 chips = this->numchips;
404                 bbtblocks = this->chipsize >> this->bbt_erase_shift;
405                 startblock &= bbtblocks - 1;
406         } else {
407                 chips = 1;
408                 bbtblocks = mtd->size >> this->bbt_erase_shift;
409         }
410         
411         /* Number of bits for each erase block in the bbt */
412         bits = td->options & NAND_BBT_NRBITS_MSK;
413         
414         for (i = 0; i < chips; i++) {
415                 /* Reset version information */
416                 td->version[i] = 0;     
417                 td->pages[i] = -1;
418                 /* Scan the maximum number of blocks */
419                 for (block = 0; block < td->maxblocks; block++) {
420                         int actblock = startblock + dir * block;
421                         /* Read first page */
422                         nand_read_raw (mtd, buf, actblock << this->bbt_erase_shift, mtd->oobblock, mtd->oobsize); 
423                         if (!check_pattern(buf, scanlen, mtd->oobblock, td)) {
424                                 td->pages[i] = actblock << (this->bbt_erase_shift - this->page_shift);
425                                 if (td->options & NAND_BBT_VERSION) {
426                                         td->version[i] = buf[mtd->oobblock + td->veroffs];
427                                 }
428                                 break;
429                         }
430                 }
431                 startblock += this->chipsize >> this->bbt_erase_shift;
432         }
433         /* Check, if we found a bbt for each requested chip */
434         for (i = 0; i < chips; i++) {
435                 if (td->pages[i] == -1)
436                         printk (KERN_WARNING "Bad block table not found for chip %d\n", i);
437                 else
438                         printk (KERN_DEBUG "Bad block table found at page %d, version 0x%02X\n", td->pages[i], td->version[i]);
439         }
440         return 0;       
441 }
442
443 /**
444  * search_read_bbts - [GENERIC] scan the device for bad block table(s)
445  * @mtd:        MTD device structure
446  * @buf:        temporary buffer
447  * @td:         descriptor for the bad block table 
448  * @md:         descriptor for the bad block table mirror
449  *
450  * Search and read the bad block table(s)
451 */
452 static int search_read_bbts (struct mtd_info *mtd, uint8_t *buf, 
453         struct nand_bbt_descr *td, struct nand_bbt_descr *md)
454 {
455         /* Search the primary table */
456         search_bbt (mtd, buf, td);
457                 
458         /* Search the mirror table */
459         if (md)
460                 search_bbt (mtd, buf, md);
461         
462         /* Force result check */
463         return 1;       
464 }
465         
466
467 /** 
468  * write_bbt - [GENERIC] (Re)write the bad block table
469  *
470  * @mtd:        MTD device structure
471  * @buf:        temporary buffer
472  * @td:         descriptor for the bad block table 
473  * @md:         descriptor for the bad block table mirror
474  * @chipsel:    selector for a specific chip, -1 for all
475  *
476  * (Re)write the bad block table
477  *
478 */
479 static int write_bbt (struct mtd_info *mtd, uint8_t *buf, 
480         struct nand_bbt_descr *td, struct nand_bbt_descr *md, int chipsel)
481 {
482         struct nand_chip *this = mtd->priv;
483         struct nand_oobinfo oobinfo;
484         struct erase_info einfo;
485         int i, j, res, chip = 0;
486         int bits, startblock, dir, page, offs, numblocks, sft, sftmsk;
487         int nrchips, bbtoffs, pageoffs;
488         uint8_t msk[4];
489         uint8_t rcode = td->reserved_block_code;
490         size_t retlen, len = 0;
491         loff_t to;
492
493         if (!rcode)
494                 rcode = 0xff;
495         /* Write bad block table per chip rather than per device ? */
496         if (td->options & NAND_BBT_PERCHIP) {
497                 numblocks = (int) (this->chipsize >> this->bbt_erase_shift);
498                 /* Full device write or specific chip ? */      
499                 if (chipsel == -1) {
500                         nrchips = this->numchips;
501                 } else {
502                         nrchips = chipsel + 1;
503                         chip = chipsel;
504                 }
505         } else {
506                 numblocks = (int) (mtd->size >> this->bbt_erase_shift);
507                 nrchips = 1;
508         }       
509         
510         /* Loop through the chips */
511         for (; chip < nrchips; chip++) {
512                 
513                 /* There was already a version of the table, reuse the page 
514                  * This applies for absolute placement too, as we have the 
515                  * page nr. in td->pages.
516                  */
517                 if (td->pages[chip] != -1) {
518                         page = td->pages[chip];
519                         goto write;
520                 }       
521
522                 /* Automatic placement of the bad block table */
523                 /* Search direction top -> down ? */
524                 if (td->options & NAND_BBT_LASTBLOCK) {
525                         startblock = numblocks * (chip + 1) - 1;
526                         dir = -1;
527                 } else {
528                         startblock = chip * numblocks;
529                         dir = 1;
530                 }       
531
532                 for (i = 0; i < td->maxblocks; i++) {
533                         int block = startblock + dir * i;
534                         /* Check, if the block is bad */
535                         switch ((this->bbt[block >> 2] >> (2 * (block & 0x03))) & 0x03) {
536                         case 0x01:
537                         case 0x03:
538                                 continue;
539                         }
540                         page = block << (this->bbt_erase_shift - this->page_shift);
541                         /* Check, if the block is used by the mirror table */
542                         if (!md || md->pages[chip] != page)
543                                 goto write;
544                 }
545                 printk (KERN_ERR "No space left to write bad block table\n");
546                 return -ENOSPC;
547 write:  
548
549                 /* Set up shift count and masks for the flash table */
550                 bits = td->options & NAND_BBT_NRBITS_MSK;
551                 switch (bits) {
552                 case 1: sft = 3; sftmsk = 0x07; msk[0] = 0x00; msk[1] = 0x01; msk[2] = ~rcode; msk[3] = 0x01; break;
553                 case 2: sft = 2; sftmsk = 0x06; msk[0] = 0x00; msk[1] = 0x01; msk[2] = ~rcode; msk[3] = 0x03; break;
554                 case 4: sft = 1; sftmsk = 0x04; msk[0] = 0x00; msk[1] = 0x0C; msk[2] = ~rcode; msk[3] = 0x0f; break;
555                 case 8: sft = 0; sftmsk = 0x00; msk[0] = 0x00; msk[1] = 0x0F; msk[2] = ~rcode; msk[3] = 0xff; break;
556                 default: return -EINVAL;
557                 }
558                 
559                 bbtoffs = chip * (numblocks >> 2);
560                 
561                 to = ((loff_t) page) << this->page_shift;
562
563                 memcpy (&oobinfo, this->autooob, sizeof(oobinfo));
564                 oobinfo.useecc = MTD_NANDECC_PLACEONLY;
565                 
566                 /* Must we save the block contents ? */
567                 if (td->options & NAND_BBT_SAVECONTENT) {
568                         /* Make it block aligned */
569                         to &= ~((loff_t) ((1 << this->bbt_erase_shift) - 1));
570                         len = 1 << this->bbt_erase_shift;
571                         res = mtd->read_ecc (mtd, to, len, &retlen, buf, &buf[len], &oobinfo);
572                         if (res < 0) {
573                                 if (retlen != len) {
574                                         printk (KERN_INFO "nand_bbt: Error reading block for writing the bad block table\n");
575                                         return res;
576                                 }
577                                 printk (KERN_WARNING "nand_bbt: ECC error while reading block for writing bad block table\n");
578                         }
579                         /* Calc the byte offset in the buffer */
580                         pageoffs = page - (int)(to >> this->page_shift);
581                         offs = pageoffs << this->page_shift;
582                         /* Preset the bbt area with 0xff */
583                         memset (&buf[offs], 0xff, (size_t)(numblocks >> sft));
584                         /* Preset the bbt's oob area with 0xff */
585                         memset (&buf[len + pageoffs * mtd->oobsize], 0xff,
586                                 ((len >> this->page_shift) - pageoffs) * mtd->oobsize);
587                         if (td->options & NAND_BBT_VERSION) {
588                                 buf[len + (pageoffs * mtd->oobsize) + td->veroffs] = td->version[chip];
589                         }
590                 } else {
591                         /* Calc length */
592                         len = (size_t) (numblocks >> sft);
593                         /* Make it page aligned ! */
594                         len = (len + (mtd->oobblock-1)) & ~(mtd->oobblock-1);
595                         /* Preset the buffer with 0xff */
596                         memset (buf, 0xff, len + (len >> this->page_shift) * mtd->oobsize);
597                         offs = 0;
598                         /* Pattern is located in oob area of first page */
599                         memcpy (&buf[len + td->offs], td->pattern, td->len);
600                         if (td->options & NAND_BBT_VERSION) {
601                                 buf[len + td->veroffs] = td->version[chip];
602                         }
603                 }
604         
605                 /* walk through the memory table */
606                 for (i = 0; i < numblocks; ) {
607                         uint8_t dat;
608                         dat = this->bbt[bbtoffs + (i >> 2)];
609                         for (j = 0; j < 4; j++ , i++) {
610                                 int sftcnt = (i << (3 - sft)) & sftmsk;
611                                 /* Do not store the reserved bbt blocks ! */
612                                 buf[offs + (i >> sft)] &= ~(msk[dat & 0x03] << sftcnt);
613                                 dat >>= 2;
614                         }
615                 }
616                 
617                 memset (&einfo, 0, sizeof (einfo));
618                 einfo.mtd = mtd;
619                 einfo.addr = (unsigned long) to;
620                 einfo.len = 1 << this->bbt_erase_shift;
621                 res = nand_erase_nand (mtd, &einfo, 1);
622                 if (res < 0) {
623                         printk (KERN_WARNING "nand_bbt: Error during block erase: %d\n", res);
624                         return res;
625                 }
626         
627                 res = mtd->write_ecc (mtd, to, len, &retlen, buf, &buf[len], &oobinfo);
628                 if (res < 0) {
629                         printk (KERN_WARNING "nand_bbt: Error while writing bad block table %d\n", res);
630                         return res;
631                 }
632                 printk (KERN_DEBUG "Bad block table written to 0x%08x, version 0x%02X\n", 
633                         (unsigned int) to, td->version[chip]);
634         
635                 /* Mark it as used */
636                 td->pages[chip] = page;
637         }       
638         return 0;
639 }
640
641 /**
642  * nand_memory_bbt - [GENERIC] create a memory based bad block table
643  * @mtd:        MTD device structure
644  * @bd:         descriptor for the good/bad block search pattern
645  *
646  * The function creates a memory based bbt by scanning the device 
647  * for manufacturer / software marked good / bad blocks
648 */
649 static inline int nand_memory_bbt (struct mtd_info *mtd, struct nand_bbt_descr *bd)
650 {
651         struct nand_chip *this = mtd->priv;
652
653         bd->options &= ~NAND_BBT_SCANEMPTY;
654         return create_bbt (mtd, this->data_buf, bd, -1);
655 }
656
657 /**
658  * check_create - [GENERIC] create and write bbt(s) if neccecary
659  * @mtd:        MTD device structure
660  * @buf:        temporary buffer
661  * @bd:         descriptor for the good/bad block search pattern
662  *
663  * The function checks the results of the previous call to read_bbt
664  * and creates / updates the bbt(s) if neccecary
665  * Creation is neccecary if no bbt was found for the chip/device
666  * Update is neccecary if one of the tables is missing or the
667  * version nr. of one table is less than the other
668 */
669 static int check_create (struct mtd_info *mtd, uint8_t *buf, struct nand_bbt_descr *bd)
670 {
671         int i, chips, writeops, chipsel, res;
672         struct nand_chip *this = mtd->priv;
673         struct nand_bbt_descr *td = this->bbt_td;
674         struct nand_bbt_descr *md = this->bbt_md;
675         struct nand_bbt_descr *rd, *rd2;
676
677         /* Do we have a bbt per chip ? */
678         if (td->options & NAND_BBT_PERCHIP) 
679                 chips = this->numchips;
680         else 
681                 chips = 1;
682         
683         for (i = 0; i < chips; i++) {
684                 writeops = 0;
685                 rd = NULL;
686                 rd2 = NULL;
687                 /* Per chip or per device ? */
688                 chipsel = (td->options & NAND_BBT_PERCHIP) ? i : -1;
689                 /* Mirrored table avilable ? */
690                 if (md) {
691                         if (td->pages[i] == -1 && md->pages[i] == -1) {
692                                 writeops = 0x03;
693                                 goto create;
694                         }
695
696                         if (td->pages[i] == -1) {
697                                 rd = md;                                
698                                 td->version[i] = md->version[i];
699                                 writeops = 1;
700                                 goto writecheck;
701                         }
702
703                         if (md->pages[i] == -1) {
704                                 rd = td;
705                                 md->version[i] = td->version[i];
706                                 writeops = 2;
707                                 goto writecheck;
708                         }
709
710                         if (td->version[i] == md->version[i]) {
711                                 rd = td;
712                                 if (!(td->options & NAND_BBT_VERSION))
713                                         rd2 = md;
714                                 goto writecheck;
715                         }       
716
717                         if (((int8_t) (td->version[i] - md->version[i])) > 0) {
718                                 rd = td;
719                                 md->version[i] = td->version[i];
720                                 writeops = 2;
721                         } else {
722                                 rd = md;
723                                 td->version[i] = md->version[i];
724                                 writeops = 1;
725                         }
726
727                         goto writecheck;
728
729                 } else {
730                         if (td->pages[i] == -1) {
731                                 writeops = 0x01;
732                                 goto create;
733                         }
734                         rd = td;
735                         goto writecheck;
736                 }
737 create:
738                 /* Create the bad block table by scanning the device ? */
739                 if (!(td->options & NAND_BBT_CREATE))
740                         continue;       
741                 
742                 /* Create the table in memory by scanning the chip(s) */
743                 create_bbt (mtd, buf, bd, chipsel);
744                 
745                 td->version[i] = 1;
746                 if (md)
747                         md->version[i] = 1;     
748 writecheck:     
749                 /* read back first ? */
750                 if (rd)
751                         read_abs_bbt (mtd, buf, rd, chipsel);
752                 /* If they weren't versioned, read both. */
753                 if (rd2)
754                         read_abs_bbt (mtd, buf, rd2, chipsel);
755
756                 /* Write the bad block table to the device ? */
757                 if ((writeops & 0x01) && (td->options & NAND_BBT_WRITE)) {
758                         res = write_bbt (mtd, buf, td, md, chipsel);
759                         if (res < 0)
760                                 return res;
761                 }
762                 
763                 /* Write the mirror bad block table to the device ? */
764                 if ((writeops & 0x02) && md && (md->options & NAND_BBT_WRITE)) {
765                         res = write_bbt (mtd, buf, md, td, chipsel);
766                         if (res < 0)
767                                 return res;
768                 }
769         }
770         return 0;       
771 }
772
773 /**
774  * mark_bbt_regions - [GENERIC] mark the bad block table regions 
775  * @mtd:        MTD device structure
776  * @td:         bad block table descriptor
777  *
778  * The bad block table regions are marked as "bad" to prevent
779  * accidental erasures / writes. The regions are identified by
780  * the mark 0x02.
781 */
782 static void mark_bbt_region (struct mtd_info *mtd, struct nand_bbt_descr *td)
783 {
784         struct nand_chip *this = mtd->priv;
785         int i, j, chips, block, nrblocks, update;
786         uint8_t oldval, newval;
787
788         /* Do we have a bbt per chip ? */
789         if (td->options & NAND_BBT_PERCHIP) {
790                 chips = this->numchips;
791                 nrblocks = (int)(this->chipsize >> this->bbt_erase_shift);
792         } else {
793                 chips = 1;
794                 nrblocks = (int)(mtd->size >> this->bbt_erase_shift);
795         }       
796         
797         for (i = 0; i < chips; i++) {
798                 if ((td->options & NAND_BBT_ABSPAGE) ||
799                     !(td->options & NAND_BBT_WRITE)) {
800                         if (td->pages[i] == -1) continue;
801                         block = td->pages[i] >> (this->bbt_erase_shift - this->page_shift);
802                         block <<= 1;            
803                         oldval = this->bbt[(block >> 3)];
804                         newval = oldval | (0x2 << (block & 0x06));
805                         this->bbt[(block >> 3)] = newval;
806                         if ((oldval != newval) && td->reserved_block_code)
807                                 nand_update_bbt(mtd, block << (this->bbt_erase_shift - 1));
808                         continue;
809                 }
810                 update = 0;
811                 if (td->options & NAND_BBT_LASTBLOCK)
812                         block = ((i + 1) * nrblocks) - td->maxblocks;
813                 else    
814                         block = i * nrblocks;
815                 block <<= 1;    
816                 for (j = 0; j < td->maxblocks; j++) {
817                         oldval = this->bbt[(block >> 3)];
818                         newval = oldval | (0x2 << (block & 0x06));
819                         this->bbt[(block >> 3)] = newval;
820                         if (oldval != newval) update = 1;
821                         block += 2;
822                 }       
823                 /* If we want reserved blocks to be recorded to flash, and some
824                    new ones have been marked, then we need to update the stored
825                    bbts.  This should only happen once. */
826                 if (update && td->reserved_block_code)
827                         nand_update_bbt(mtd, (block - 2) << (this->bbt_erase_shift - 1));
828         }
829 }
830
831 /**
832  * nand_scan_bbt - [NAND Interface] scan, find, read and maybe create bad block table(s)
833  * @mtd:        MTD device structure
834  * @bd:         descriptor for the good/bad block search pattern
835  *
836  * The function checks, if a bad block table(s) is/are already 
837  * available. If not it scans the device for manufacturer
838  * marked good / bad blocks and writes the bad block table(s) to
839  * the selected place.
840  *
841  * The bad block table memory is allocated here. It must be freed
842  * by calling the nand_free_bbt function.
843  *
844 */
845 int nand_scan_bbt (struct mtd_info *mtd, struct nand_bbt_descr *bd)
846 {
847         struct nand_chip *this = mtd->priv;
848         int len, res = 0;
849         uint8_t *buf;
850         struct nand_bbt_descr *td = this->bbt_td;
851         struct nand_bbt_descr *md = this->bbt_md;
852
853         len = mtd->size >> (this->bbt_erase_shift + 2);
854         /* Allocate memory (2bit per block) */
855         this->bbt = kmalloc (len, GFP_KERNEL);
856         if (!this->bbt) {
857                 printk (KERN_ERR "nand_scan_bbt: Out of memory\n");
858                 return -ENOMEM;
859         }
860         /* Clear the memory bad block table */
861         memset (this->bbt, 0x00, len);
862
863         /* If no primary table decriptor is given, scan the device
864          * to build a memory based bad block table
865          */
866         if (!td) {
867                 if ((res = nand_memory_bbt(mtd, bd))) {
868                         printk (KERN_ERR "nand_bbt: Can't scan flash and build the RAM-based BBT\n");
869                         kfree (this->bbt);
870                         this->bbt = NULL;
871                 }
872                 return res;
873         }
874
875         /* Allocate a temporary buffer for one eraseblock incl. oob */
876         len = (1 << this->bbt_erase_shift);
877         len += (len >> this->page_shift) * mtd->oobsize;
878         buf = kmalloc (len, GFP_KERNEL);
879         if (!buf) {
880                 printk (KERN_ERR "nand_bbt: Out of memory\n");
881                 kfree (this->bbt);
882                 this->bbt = NULL;
883                 return -ENOMEM;
884         }
885         
886         /* Is the bbt at a given page ? */
887         if (td->options & NAND_BBT_ABSPAGE) {
888                 res = read_abs_bbts (mtd, buf, td, md);
889         } else {        
890                 /* Search the bad block table using a pattern in oob */
891                 res = search_read_bbts (mtd, buf, td, md);
892         }       
893
894         if (res) 
895                 res = check_create (mtd, buf, bd);
896         
897         /* Prevent the bbt regions from erasing / writing */
898         mark_bbt_region (mtd, td);
899         if (md)
900                 mark_bbt_region (mtd, md);
901         
902         kfree (buf);
903         return res;
904 }
905
906
907 /**
908  * nand_update_bbt - [NAND Interface] update bad block table(s) 
909  * @mtd:        MTD device structure
910  * @offs:       the offset of the newly marked block
911  *
912  * The function updates the bad block table(s)
913 */
914 int nand_update_bbt (struct mtd_info *mtd, loff_t offs)
915 {
916         struct nand_chip *this = mtd->priv;
917         int len, res = 0, writeops = 0;
918         int chip, chipsel;
919         uint8_t *buf;
920         struct nand_bbt_descr *td = this->bbt_td;
921         struct nand_bbt_descr *md = this->bbt_md;
922
923         if (!this->bbt || !td)
924                 return -EINVAL;
925
926         len = mtd->size >> (this->bbt_erase_shift + 2);
927         /* Allocate a temporary buffer for one eraseblock incl. oob */
928         len = (1 << this->bbt_erase_shift);
929         len += (len >> this->page_shift) * mtd->oobsize;
930         buf = kmalloc (len, GFP_KERNEL);
931         if (!buf) {
932                 printk (KERN_ERR "nand_update_bbt: Out of memory\n");
933                 return -ENOMEM;
934         }
935         
936         writeops = md != NULL ? 0x03 : 0x01;
937
938         /* Do we have a bbt per chip ? */
939         if (td->options & NAND_BBT_PERCHIP) {
940                 chip = (int) (offs >> this->chip_shift);
941                 chipsel = chip;
942         } else {
943                 chip = 0;
944                 chipsel = -1;
945         }
946
947         td->version[chip]++;
948         if (md)
949                 md->version[chip]++;    
950
951         /* Write the bad block table to the device ? */
952         if ((writeops & 0x01) && (td->options & NAND_BBT_WRITE)) {
953                 res = write_bbt (mtd, buf, td, md, chipsel);
954                 if (res < 0)
955                         goto out;
956         }
957         /* Write the mirror bad block table to the device ? */
958         if ((writeops & 0x02) && md && (md->options & NAND_BBT_WRITE)) {
959                 res = write_bbt (mtd, buf, md, td, chipsel);
960         }
961
962 out:    
963         kfree (buf);
964         return res;
965 }
966
967 /* Define some generic bad / good block scan pattern which are used 
968  * while scanning a device for factory marked good / bad blocks. */
969 static uint8_t scan_ff_pattern[] = { 0xff, 0xff };
970
971 static struct nand_bbt_descr smallpage_memorybased = {
972         .options = NAND_BBT_SCAN2NDPAGE,
973         .offs = 5,
974         .len = 1,
975         .pattern = scan_ff_pattern
976 };
977
978 static struct nand_bbt_descr largepage_memorybased = {
979         .options = 0,
980         .offs = 0,
981         .len = 2,
982         .pattern = scan_ff_pattern
983 };
984
985 static struct nand_bbt_descr smallpage_flashbased = {
986         .options = NAND_BBT_SCANEMPTY | NAND_BBT_SCANALLPAGES,
987         .offs = 5,
988         .len = 1,
989         .pattern = scan_ff_pattern
990 };
991
992 static struct nand_bbt_descr largepage_flashbased = {
993         .options = NAND_BBT_SCANEMPTY | NAND_BBT_SCANALLPAGES,
994         .offs = 0,
995         .len = 2,
996         .pattern = scan_ff_pattern
997 };
998
999 static uint8_t scan_agand_pattern[] = { 0x1C, 0x71, 0xC7, 0x1C, 0x71, 0xC7 };
1000
1001 static struct nand_bbt_descr agand_flashbased = {
1002         .options = NAND_BBT_SCANEMPTY | NAND_BBT_SCANALLPAGES,
1003         .offs = 0x20,
1004         .len = 6,
1005         .pattern = scan_agand_pattern
1006 };
1007
1008 /* Generic flash bbt decriptors
1009 */
1010 static uint8_t bbt_pattern[] = {'B', 'b', 't', '0' };
1011 static uint8_t mirror_pattern[] = {'1', 't', 'b', 'B' };
1012
1013 static struct nand_bbt_descr bbt_main_descr = {
1014         .options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE 
1015                 | NAND_BBT_2BIT | NAND_BBT_VERSION | NAND_BBT_PERCHIP,
1016         .offs = 8,
1017         .len = 4,
1018         .veroffs = 12,
1019         .maxblocks = 4,
1020         .pattern = bbt_pattern
1021 };
1022
1023 static struct nand_bbt_descr bbt_mirror_descr = {
1024         .options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE 
1025                 | NAND_BBT_2BIT | NAND_BBT_VERSION | NAND_BBT_PERCHIP,
1026         .offs = 8,
1027         .len = 4,
1028         .veroffs = 12,
1029         .maxblocks = 4,
1030         .pattern = mirror_pattern
1031 };
1032
1033 /**
1034  * nand_default_bbt - [NAND Interface] Select a default bad block table for the device 
1035  * @mtd:        MTD device structure
1036  *
1037  * This function selects the default bad block table
1038  * support for the device and calls the nand_scan_bbt function
1039  *
1040 */
1041 int nand_default_bbt (struct mtd_info *mtd)
1042 {
1043         struct nand_chip *this = mtd->priv;
1044         
1045         /* Default for AG-AND. We must use a flash based 
1046          * bad block table as the devices have factory marked
1047          * _good_ blocks. Erasing those blocks leads to loss
1048          * of the good / bad information, so we _must_ store
1049          * this information in a good / bad table during 
1050          * startup
1051         */
1052         if (this->options & NAND_IS_AND) {
1053                 /* Use the default pattern descriptors */
1054                 if (!this->bbt_td) {    
1055                         this->bbt_td = &bbt_main_descr;
1056                         this->bbt_md = &bbt_mirror_descr;
1057                 }       
1058                 this->options |= NAND_USE_FLASH_BBT;
1059                 return nand_scan_bbt (mtd, &agand_flashbased);
1060         }
1061         
1062         
1063         /* Is a flash based bad block table requested ? */
1064         if (this->options & NAND_USE_FLASH_BBT) {
1065                 /* Use the default pattern descriptors */       
1066                 if (!this->bbt_td) {    
1067                         this->bbt_td = &bbt_main_descr;
1068                         this->bbt_md = &bbt_mirror_descr;
1069                 }
1070                 if (!this->badblock_pattern) {
1071                         this->badblock_pattern = (mtd->oobblock > 512) ?
1072                                 &largepage_flashbased : &smallpage_flashbased;
1073                 }
1074         } else {
1075                 this->bbt_td = NULL;
1076                 this->bbt_md = NULL;
1077                 if (!this->badblock_pattern) {
1078                         this->badblock_pattern = (mtd->oobblock > 512) ?
1079                                 &largepage_memorybased : &smallpage_memorybased;
1080                 }
1081         }
1082         return nand_scan_bbt (mtd, this->badblock_pattern);
1083 }
1084
1085 /**
1086  * nand_isbad_bbt - [NAND Interface] Check if a block is bad 
1087  * @mtd:        MTD device structure
1088  * @offs:       offset in the device
1089  * @allowbbt:   allow access to bad block table region
1090  *
1091 */
1092 int nand_isbad_bbt (struct mtd_info *mtd, loff_t offs, int allowbbt)
1093 {
1094         struct nand_chip *this = mtd->priv;
1095         int block;
1096         uint8_t res;
1097         
1098         /* Get block number * 2 */
1099         block = (int) (offs >> (this->bbt_erase_shift - 1));
1100         res = (this->bbt[block >> 3] >> (block & 0x06)) & 0x03;
1101
1102         DEBUG (MTD_DEBUG_LEVEL2, "nand_isbad_bbt(): bbt info for offs 0x%08x: (block %d) 0x%02x\n", 
1103                 (unsigned int)offs, block >> 1, res);
1104
1105         switch ((int)res) {
1106         case 0x00:      return 0;
1107         case 0x01:      return 1;
1108         case 0x02:      return allowbbt ? 0 : 1;
1109         }
1110         return 1;
1111 }
1112
1113 EXPORT_SYMBOL (nand_scan_bbt);
1114 EXPORT_SYMBOL (nand_default_bbt);