]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/mtd/nand/nand_base.c
fs: jffs2: make jffs2 work zero oobavail
[karo-tx-linux.git] / drivers / mtd / nand / nand_base.c
1 /*
2  *  drivers/mtd/nand.c
3  *
4  *  Overview:
5  *   This is the generic MTD driver for NAND flash devices. It should be
6  *   capable of working with almost all NAND chips currently available.
7  *
8  *      Additional technical information is available on
9  *      http://www.linux-mtd.infradead.org/doc/nand.html
10  *
11  *  Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
12  *                2002-2006 Thomas Gleixner (tglx@linutronix.de)
13  *
14  *  Credits:
15  *      David Woodhouse for adding multichip support
16  *
17  *      Aleph One Ltd. and Toby Churchill Ltd. for supporting the
18  *      rework for 2K page size chips
19  *
20  *  TODO:
21  *      Enable cached programming for 2k page size chips
22  *      Check, if mtd->ecctype should be set to MTD_ECC_HW
23  *      if we have HW ECC support.
24  *      BBT table is not serialized, has to be fixed
25  *
26  * This program is free software; you can redistribute it and/or modify
27  * it under the terms of the GNU General Public License version 2 as
28  * published by the Free Software Foundation.
29  *
30  */
31
32 #include <linux/module.h>
33 #include <linux/delay.h>
34 #include <linux/errno.h>
35 #include <linux/err.h>
36 #include <linux/sched.h>
37 #include <linux/slab.h>
38 #include <linux/types.h>
39 #include <linux/mtd/mtd.h>
40 #include <linux/mtd/nand.h>
41 #include <linux/mtd/nand_ecc.h>
42 #include <linux/mtd/nand_bch.h>
43 #include <linux/interrupt.h>
44 #include <linux/bitops.h>
45 #include <linux/leds.h>
46 #include <linux/io.h>
47 #include <linux/mtd/partitions.h>
48
49 /* Define default oob placement schemes for large and small page devices */
50 static struct nand_ecclayout nand_oob_8 = {
51         .eccbytes = 3,
52         .eccpos = {0, 1, 2},
53         .oobfree = {
54                 {.offset = 3,
55                  .length = 2},
56                 {.offset = 6,
57                  .length = 2} }
58 };
59
60 static struct nand_ecclayout nand_oob_16 = {
61         .eccbytes = 6,
62         .eccpos = {0, 1, 2, 3, 6, 7},
63         .oobfree = {
64                 {.offset = 8,
65                  . length = 8} }
66 };
67
68 static struct nand_ecclayout nand_oob_64 = {
69         .eccbytes = 24,
70         .eccpos = {
71                    40, 41, 42, 43, 44, 45, 46, 47,
72                    48, 49, 50, 51, 52, 53, 54, 55,
73                    56, 57, 58, 59, 60, 61, 62, 63},
74         .oobfree = {
75                 {.offset = 2,
76                  .length = 38} }
77 };
78
79 static struct nand_ecclayout nand_oob_128 = {
80         .eccbytes = 48,
81         .eccpos = {
82                    80, 81, 82, 83, 84, 85, 86, 87,
83                    88, 89, 90, 91, 92, 93, 94, 95,
84                    96, 97, 98, 99, 100, 101, 102, 103,
85                    104, 105, 106, 107, 108, 109, 110, 111,
86                    112, 113, 114, 115, 116, 117, 118, 119,
87                    120, 121, 122, 123, 124, 125, 126, 127},
88         .oobfree = {
89                 {.offset = 2,
90                  .length = 78} }
91 };
92
93 static int nand_get_device(struct mtd_info *mtd, int new_state);
94
95 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
96                              struct mtd_oob_ops *ops);
97
98 /*
99  * For devices which display every fart in the system on a separate LED. Is
100  * compiled away when LED support is disabled.
101  */
102 DEFINE_LED_TRIGGER(nand_led_trigger);
103
104 static int check_offs_len(struct mtd_info *mtd,
105                                         loff_t ofs, uint64_t len)
106 {
107         struct nand_chip *chip = mtd->priv;
108         int ret = 0;
109
110         /* Start address must align on block boundary */
111         if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
112                 pr_debug("%s: unaligned address\n", __func__);
113                 ret = -EINVAL;
114         }
115
116         /* Length must align on block boundary */
117         if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
118                 pr_debug("%s: length not block aligned\n", __func__);
119                 ret = -EINVAL;
120         }
121
122         return ret;
123 }
124
125 /**
126  * nand_release_device - [GENERIC] release chip
127  * @mtd: MTD device structure
128  *
129  * Release chip lock and wake up anyone waiting on the device.
130  */
131 static void nand_release_device(struct mtd_info *mtd)
132 {
133         struct nand_chip *chip = mtd->priv;
134
135         /* Release the controller and the chip */
136         spin_lock(&chip->controller->lock);
137         chip->controller->active = NULL;
138         chip->state = FL_READY;
139         wake_up(&chip->controller->wq);
140         spin_unlock(&chip->controller->lock);
141 }
142
143 /**
144  * nand_read_byte - [DEFAULT] read one byte from the chip
145  * @mtd: MTD device structure
146  *
147  * Default read function for 8bit buswidth
148  */
149 static uint8_t nand_read_byte(struct mtd_info *mtd)
150 {
151         struct nand_chip *chip = mtd->priv;
152         return readb(chip->IO_ADDR_R);
153 }
154
155 /**
156  * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
157  * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
158  * @mtd: MTD device structure
159  *
160  * Default read function for 16bit buswidth with endianness conversion.
161  *
162  */
163 static uint8_t nand_read_byte16(struct mtd_info *mtd)
164 {
165         struct nand_chip *chip = mtd->priv;
166         return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
167 }
168
169 /**
170  * nand_read_word - [DEFAULT] read one word from the chip
171  * @mtd: MTD device structure
172  *
173  * Default read function for 16bit buswidth without endianness conversion.
174  */
175 static u16 nand_read_word(struct mtd_info *mtd)
176 {
177         struct nand_chip *chip = mtd->priv;
178         return readw(chip->IO_ADDR_R);
179 }
180
181 /**
182  * nand_select_chip - [DEFAULT] control CE line
183  * @mtd: MTD device structure
184  * @chipnr: chipnumber to select, -1 for deselect
185  *
186  * Default select function for 1 chip devices.
187  */
188 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
189 {
190         struct nand_chip *chip = mtd->priv;
191
192         switch (chipnr) {
193         case -1:
194                 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
195                 break;
196         case 0:
197                 break;
198
199         default:
200                 BUG();
201         }
202 }
203
204 /**
205  * nand_write_buf - [DEFAULT] write buffer to chip
206  * @mtd: MTD device structure
207  * @buf: data buffer
208  * @len: number of bytes to write
209  *
210  * Default write function for 8bit buswidth.
211  */
212 static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
213 {
214         struct nand_chip *chip = mtd->priv;
215
216         iowrite8_rep(chip->IO_ADDR_W, buf, len);
217 }
218
219 /**
220  * nand_read_buf - [DEFAULT] read chip data into buffer
221  * @mtd: MTD device structure
222  * @buf: buffer to store date
223  * @len: number of bytes to read
224  *
225  * Default read function for 8bit buswidth.
226  */
227 static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
228 {
229         struct nand_chip *chip = mtd->priv;
230
231         ioread8_rep(chip->IO_ADDR_R, buf, len);
232 }
233
234 /**
235  * nand_write_buf16 - [DEFAULT] write buffer to chip
236  * @mtd: MTD device structure
237  * @buf: data buffer
238  * @len: number of bytes to write
239  *
240  * Default write function for 16bit buswidth.
241  */
242 static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
243 {
244         struct nand_chip *chip = mtd->priv;
245         u16 *p = (u16 *) buf;
246
247         iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
248 }
249
250 /**
251  * nand_read_buf16 - [DEFAULT] read chip data into buffer
252  * @mtd: MTD device structure
253  * @buf: buffer to store date
254  * @len: number of bytes to read
255  *
256  * Default read function for 16bit buswidth.
257  */
258 static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
259 {
260         struct nand_chip *chip = mtd->priv;
261         u16 *p = (u16 *) buf;
262
263         ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
264 }
265
266 /**
267  * nand_block_bad - [DEFAULT] Read bad block marker from the chip
268  * @mtd: MTD device structure
269  * @ofs: offset from device start
270  * @getchip: 0, if the chip is already selected
271  *
272  * Check, if the block is bad.
273  */
274 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs, int getchip)
275 {
276         int page, chipnr, res = 0, i = 0;
277         struct nand_chip *chip = mtd->priv;
278         u16 bad;
279
280         if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
281                 ofs += mtd->erasesize - mtd->writesize;
282
283         page = (int)(ofs >> chip->page_shift) & chip->pagemask;
284
285         if (getchip) {
286                 chipnr = (int)(ofs >> chip->chip_shift);
287
288                 nand_get_device(mtd, FL_READING);
289
290                 /* Select the NAND device */
291                 chip->select_chip(mtd, chipnr);
292         }
293
294         do {
295                 if (chip->options & NAND_BUSWIDTH_16) {
296                         chip->cmdfunc(mtd, NAND_CMD_READOOB,
297                                         chip->badblockpos & 0xFE, page);
298                         bad = cpu_to_le16(chip->read_word(mtd));
299                         if (chip->badblockpos & 0x1)
300                                 bad >>= 8;
301                         else
302                                 bad &= 0xFF;
303                 } else {
304                         chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
305                                         page);
306                         bad = chip->read_byte(mtd);
307                 }
308
309                 if (likely(chip->badblockbits == 8))
310                         res = bad != 0xFF;
311                 else
312                         res = hweight8(bad) < chip->badblockbits;
313                 ofs += mtd->writesize;
314                 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
315                 i++;
316         } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
317
318         if (getchip) {
319                 chip->select_chip(mtd, -1);
320                 nand_release_device(mtd);
321         }
322
323         return res;
324 }
325
326 /**
327  * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
328  * @mtd: MTD device structure
329  * @ofs: offset from device start
330  *
331  * This is the default implementation, which can be overridden by a hardware
332  * specific driver. It provides the details for writing a bad block marker to a
333  * block.
334  */
335 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
336 {
337         struct nand_chip *chip = mtd->priv;
338         struct mtd_oob_ops ops;
339         uint8_t buf[2] = { 0, 0 };
340         int ret = 0, res, i = 0;
341
342         ops.datbuf = NULL;
343         ops.oobbuf = buf;
344         ops.ooboffs = chip->badblockpos;
345         if (chip->options & NAND_BUSWIDTH_16) {
346                 ops.ooboffs &= ~0x01;
347                 ops.len = ops.ooblen = 2;
348         } else {
349                 ops.len = ops.ooblen = 1;
350         }
351         ops.mode = MTD_OPS_PLACE_OOB;
352
353         /* Write to first/last page(s) if necessary */
354         if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
355                 ofs += mtd->erasesize - mtd->writesize;
356         do {
357                 res = nand_do_write_oob(mtd, ofs, &ops);
358                 if (!ret)
359                         ret = res;
360
361                 i++;
362                 ofs += mtd->writesize;
363         } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
364
365         return ret;
366 }
367
368 /**
369  * nand_block_markbad_lowlevel - mark a block bad
370  * @mtd: MTD device structure
371  * @ofs: offset from device start
372  *
373  * This function performs the generic NAND bad block marking steps (i.e., bad
374  * block table(s) and/or marker(s)). We only allow the hardware driver to
375  * specify how to write bad block markers to OOB (chip->block_markbad).
376  *
377  * We try operations in the following order:
378  *  (1) erase the affected block, to allow OOB marker to be written cleanly
379  *  (2) write bad block marker to OOB area of affected block (unless flag
380  *      NAND_BBT_NO_OOB_BBM is present)
381  *  (3) update the BBT
382  * Note that we retain the first error encountered in (2) or (3), finish the
383  * procedures, and dump the error in the end.
384 */
385 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
386 {
387         struct nand_chip *chip = mtd->priv;
388         int res, ret = 0;
389
390         if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
391                 struct erase_info einfo;
392
393                 /* Attempt erase before marking OOB */
394                 memset(&einfo, 0, sizeof(einfo));
395                 einfo.mtd = mtd;
396                 einfo.addr = ofs;
397                 einfo.len = 1ULL << chip->phys_erase_shift;
398                 nand_erase_nand(mtd, &einfo, 0);
399
400                 /* Write bad block marker to OOB */
401                 nand_get_device(mtd, FL_WRITING);
402                 ret = chip->block_markbad(mtd, ofs);
403                 nand_release_device(mtd);
404         }
405
406         /* Mark block bad in BBT */
407         if (chip->bbt) {
408                 res = nand_markbad_bbt(mtd, ofs);
409                 if (!ret)
410                         ret = res;
411         }
412
413         if (!ret)
414                 mtd->ecc_stats.badblocks++;
415
416         return ret;
417 }
418
419 /**
420  * nand_check_wp - [GENERIC] check if the chip is write protected
421  * @mtd: MTD device structure
422  *
423  * Check, if the device is write protected. The function expects, that the
424  * device is already selected.
425  */
426 static int nand_check_wp(struct mtd_info *mtd)
427 {
428         struct nand_chip *chip = mtd->priv;
429
430         /* Broken xD cards report WP despite being writable */
431         if (chip->options & NAND_BROKEN_XD)
432                 return 0;
433
434         /* Check the WP bit */
435         chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
436         return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
437 }
438
439 /**
440  * nand_block_checkbad - [GENERIC] Check if a block is marked bad
441  * @mtd: MTD device structure
442  * @ofs: offset from device start
443  * @getchip: 0, if the chip is already selected
444  * @allowbbt: 1, if its allowed to access the bbt area
445  *
446  * Check, if the block is bad. Either by reading the bad block table or
447  * calling of the scan function.
448  */
449 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int getchip,
450                                int allowbbt)
451 {
452         struct nand_chip *chip = mtd->priv;
453
454         if (!chip->bbt)
455                 return chip->block_bad(mtd, ofs, getchip);
456
457         /* Return info from the table */
458         return nand_isbad_bbt(mtd, ofs, allowbbt);
459 }
460
461 /**
462  * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
463  * @mtd: MTD device structure
464  * @timeo: Timeout
465  *
466  * Helper function for nand_wait_ready used when needing to wait in interrupt
467  * context.
468  */
469 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
470 {
471         struct nand_chip *chip = mtd->priv;
472         int i;
473
474         /* Wait for the device to get ready */
475         for (i = 0; i < timeo; i++) {
476                 if (chip->dev_ready(mtd))
477                         break;
478                 touch_softlockup_watchdog();
479                 mdelay(1);
480         }
481 }
482
483 /* Wait for the ready pin, after a command. The timeout is caught later. */
484 void nand_wait_ready(struct mtd_info *mtd)
485 {
486         struct nand_chip *chip = mtd->priv;
487         unsigned long timeo = jiffies + msecs_to_jiffies(20);
488
489         /* 400ms timeout */
490         if (in_interrupt() || oops_in_progress)
491                 return panic_nand_wait_ready(mtd, 400);
492
493         led_trigger_event(nand_led_trigger, LED_FULL);
494         /* Wait until command is processed or timeout occurs */
495         do {
496                 if (chip->dev_ready(mtd))
497                         break;
498                 touch_softlockup_watchdog();
499         } while (time_before(jiffies, timeo));
500         led_trigger_event(nand_led_trigger, LED_OFF);
501 }
502 EXPORT_SYMBOL_GPL(nand_wait_ready);
503
504 /**
505  * nand_command - [DEFAULT] Send command to NAND device
506  * @mtd: MTD device structure
507  * @command: the command to be sent
508  * @column: the column address for this command, -1 if none
509  * @page_addr: the page address for this command, -1 if none
510  *
511  * Send command to NAND device. This function is used for small page devices
512  * (512 Bytes per page).
513  */
514 static void nand_command(struct mtd_info *mtd, unsigned int command,
515                          int column, int page_addr)
516 {
517         register struct nand_chip *chip = mtd->priv;
518         int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
519
520         /* Write out the command to the device */
521         if (command == NAND_CMD_SEQIN) {
522                 int readcmd;
523
524                 if (column >= mtd->writesize) {
525                         /* OOB area */
526                         column -= mtd->writesize;
527                         readcmd = NAND_CMD_READOOB;
528                 } else if (column < 256) {
529                         /* First 256 bytes --> READ0 */
530                         readcmd = NAND_CMD_READ0;
531                 } else {
532                         column -= 256;
533                         readcmd = NAND_CMD_READ1;
534                 }
535                 chip->cmd_ctrl(mtd, readcmd, ctrl);
536                 ctrl &= ~NAND_CTRL_CHANGE;
537         }
538         chip->cmd_ctrl(mtd, command, ctrl);
539
540         /* Address cycle, when necessary */
541         ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
542         /* Serially input address */
543         if (column != -1) {
544                 /* Adjust columns for 16 bit buswidth */
545                 if (chip->options & NAND_BUSWIDTH_16)
546                         column >>= 1;
547                 chip->cmd_ctrl(mtd, column, ctrl);
548                 ctrl &= ~NAND_CTRL_CHANGE;
549         }
550         if (page_addr != -1) {
551                 chip->cmd_ctrl(mtd, page_addr, ctrl);
552                 ctrl &= ~NAND_CTRL_CHANGE;
553                 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
554                 /* One more address cycle for devices > 32MiB */
555                 if (chip->chipsize > (32 << 20))
556                         chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
557         }
558         chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
559
560         /*
561          * Program and erase have their own busy handlers status and sequential
562          * in needs no delay
563          */
564         switch (command) {
565
566         case NAND_CMD_PAGEPROG:
567         case NAND_CMD_ERASE1:
568         case NAND_CMD_ERASE2:
569         case NAND_CMD_SEQIN:
570         case NAND_CMD_STATUS:
571                 return;
572
573         case NAND_CMD_RESET:
574                 if (chip->dev_ready)
575                         break;
576                 udelay(chip->chip_delay);
577                 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
578                                NAND_CTRL_CLE | NAND_CTRL_CHANGE);
579                 chip->cmd_ctrl(mtd,
580                                NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
581                 while (!(chip->read_byte(mtd) & NAND_STATUS_READY))
582                                 ;
583                 return;
584
585                 /* This applies to read commands */
586         default:
587                 /*
588                  * If we don't have access to the busy pin, we apply the given
589                  * command delay
590                  */
591                 if (!chip->dev_ready) {
592                         udelay(chip->chip_delay);
593                         return;
594                 }
595         }
596         /*
597          * Apply this short delay always to ensure that we do wait tWB in
598          * any case on any machine.
599          */
600         ndelay(100);
601
602         nand_wait_ready(mtd);
603 }
604
605 /**
606  * nand_command_lp - [DEFAULT] Send command to NAND large page device
607  * @mtd: MTD device structure
608  * @command: the command to be sent
609  * @column: the column address for this command, -1 if none
610  * @page_addr: the page address for this command, -1 if none
611  *
612  * Send command to NAND device. This is the version for the new large page
613  * devices. We don't have the separate regions as we have in the small page
614  * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
615  */
616 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
617                             int column, int page_addr)
618 {
619         register struct nand_chip *chip = mtd->priv;
620
621         /* Emulate NAND_CMD_READOOB */
622         if (command == NAND_CMD_READOOB) {
623                 column += mtd->writesize;
624                 command = NAND_CMD_READ0;
625         }
626
627         /* Command latch cycle */
628         chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
629
630         if (column != -1 || page_addr != -1) {
631                 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
632
633                 /* Serially input address */
634                 if (column != -1) {
635                         /* Adjust columns for 16 bit buswidth */
636                         if (chip->options & NAND_BUSWIDTH_16)
637                                 column >>= 1;
638                         chip->cmd_ctrl(mtd, column, ctrl);
639                         ctrl &= ~NAND_CTRL_CHANGE;
640                         chip->cmd_ctrl(mtd, column >> 8, ctrl);
641                 }
642                 if (page_addr != -1) {
643                         chip->cmd_ctrl(mtd, page_addr, ctrl);
644                         chip->cmd_ctrl(mtd, page_addr >> 8,
645                                        NAND_NCE | NAND_ALE);
646                         /* One more address cycle for devices > 128MiB */
647                         if (chip->chipsize > (128 << 20))
648                                 chip->cmd_ctrl(mtd, page_addr >> 16,
649                                                NAND_NCE | NAND_ALE);
650                 }
651         }
652         chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
653
654         /*
655          * Program and erase have their own busy handlers status, sequential
656          * in, and deplete1 need no delay.
657          */
658         switch (command) {
659
660         case NAND_CMD_CACHEDPROG:
661         case NAND_CMD_PAGEPROG:
662         case NAND_CMD_ERASE1:
663         case NAND_CMD_ERASE2:
664         case NAND_CMD_SEQIN:
665         case NAND_CMD_RNDIN:
666         case NAND_CMD_STATUS:
667                 return;
668
669         case NAND_CMD_RESET:
670                 if (chip->dev_ready)
671                         break;
672                 udelay(chip->chip_delay);
673                 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
674                                NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
675                 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
676                                NAND_NCE | NAND_CTRL_CHANGE);
677                 while (!(chip->read_byte(mtd) & NAND_STATUS_READY))
678                                 ;
679                 return;
680
681         case NAND_CMD_RNDOUT:
682                 /* No ready / busy check necessary */
683                 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
684                                NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
685                 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
686                                NAND_NCE | NAND_CTRL_CHANGE);
687                 return;
688
689         case NAND_CMD_READ0:
690                 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
691                                NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
692                 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
693                                NAND_NCE | NAND_CTRL_CHANGE);
694
695                 /* This applies to read commands */
696         default:
697                 /*
698                  * If we don't have access to the busy pin, we apply the given
699                  * command delay.
700                  */
701                 if (!chip->dev_ready) {
702                         udelay(chip->chip_delay);
703                         return;
704                 }
705         }
706
707         /*
708          * Apply this short delay always to ensure that we do wait tWB in
709          * any case on any machine.
710          */
711         ndelay(100);
712
713         nand_wait_ready(mtd);
714 }
715
716 /**
717  * panic_nand_get_device - [GENERIC] Get chip for selected access
718  * @chip: the nand chip descriptor
719  * @mtd: MTD device structure
720  * @new_state: the state which is requested
721  *
722  * Used when in panic, no locks are taken.
723  */
724 static void panic_nand_get_device(struct nand_chip *chip,
725                       struct mtd_info *mtd, int new_state)
726 {
727         /* Hardware controller shared among independent devices */
728         chip->controller->active = chip;
729         chip->state = new_state;
730 }
731
732 /**
733  * nand_get_device - [GENERIC] Get chip for selected access
734  * @mtd: MTD device structure
735  * @new_state: the state which is requested
736  *
737  * Get the device and lock it for exclusive access
738  */
739 static int
740 nand_get_device(struct mtd_info *mtd, int new_state)
741 {
742         struct nand_chip *chip = mtd->priv;
743         spinlock_t *lock = &chip->controller->lock;
744         wait_queue_head_t *wq = &chip->controller->wq;
745         DECLARE_WAITQUEUE(wait, current);
746 retry:
747         spin_lock(lock);
748
749         /* Hardware controller shared among independent devices */
750         if (!chip->controller->active)
751                 chip->controller->active = chip;
752
753         if (chip->controller->active == chip && chip->state == FL_READY) {
754                 chip->state = new_state;
755                 spin_unlock(lock);
756                 return 0;
757         }
758         if (new_state == FL_PM_SUSPENDED) {
759                 if (chip->controller->active->state == FL_PM_SUSPENDED) {
760                         chip->state = FL_PM_SUSPENDED;
761                         spin_unlock(lock);
762                         return 0;
763                 }
764         }
765         set_current_state(TASK_UNINTERRUPTIBLE);
766         add_wait_queue(wq, &wait);
767         spin_unlock(lock);
768         schedule();
769         remove_wait_queue(wq, &wait);
770         goto retry;
771 }
772
773 /**
774  * panic_nand_wait - [GENERIC] wait until the command is done
775  * @mtd: MTD device structure
776  * @chip: NAND chip structure
777  * @timeo: timeout
778  *
779  * Wait for command done. This is a helper function for nand_wait used when
780  * we are in interrupt context. May happen when in panic and trying to write
781  * an oops through mtdoops.
782  */
783 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
784                             unsigned long timeo)
785 {
786         int i;
787         for (i = 0; i < timeo; i++) {
788                 if (chip->dev_ready) {
789                         if (chip->dev_ready(mtd))
790                                 break;
791                 } else {
792                         if (chip->read_byte(mtd) & NAND_STATUS_READY)
793                                 break;
794                 }
795                 mdelay(1);
796         }
797 }
798
799 /**
800  * nand_wait - [DEFAULT] wait until the command is done
801  * @mtd: MTD device structure
802  * @chip: NAND chip structure
803  *
804  * Wait for command done. This applies to erase and program only. Erase can
805  * take up to 400ms and program up to 20ms according to general NAND and
806  * SmartMedia specs.
807  */
808 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
809 {
810
811         int status, state = chip->state;
812         unsigned long timeo = (state == FL_ERASING ? 400 : 20);
813
814         led_trigger_event(nand_led_trigger, LED_FULL);
815
816         /*
817          * Apply this short delay always to ensure that we do wait tWB in any
818          * case on any machine.
819          */
820         ndelay(100);
821
822         chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
823
824         if (in_interrupt() || oops_in_progress)
825                 panic_nand_wait(mtd, chip, timeo);
826         else {
827                 timeo = jiffies + msecs_to_jiffies(timeo);
828                 while (time_before(jiffies, timeo)) {
829                         if (chip->dev_ready) {
830                                 if (chip->dev_ready(mtd))
831                                         break;
832                         } else {
833                                 if (chip->read_byte(mtd) & NAND_STATUS_READY)
834                                         break;
835                         }
836                         cond_resched();
837                 }
838         }
839         led_trigger_event(nand_led_trigger, LED_OFF);
840
841         status = (int)chip->read_byte(mtd);
842         /* This can happen if in case of timeout or buggy dev_ready */
843         WARN_ON(!(status & NAND_STATUS_READY));
844         return status;
845 }
846
847 /**
848  * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
849  * @mtd: mtd info
850  * @ofs: offset to start unlock from
851  * @len: length to unlock
852  * @invert: when = 0, unlock the range of blocks within the lower and
853  *                    upper boundary address
854  *          when = 1, unlock the range of blocks outside the boundaries
855  *                    of the lower and upper boundary address
856  *
857  * Returs unlock status.
858  */
859 static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
860                                         uint64_t len, int invert)
861 {
862         int ret = 0;
863         int status, page;
864         struct nand_chip *chip = mtd->priv;
865
866         /* Submit address of first page to unlock */
867         page = ofs >> chip->page_shift;
868         chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
869
870         /* Submit address of last page to unlock */
871         page = (ofs + len) >> chip->page_shift;
872         chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
873                                 (page | invert) & chip->pagemask);
874
875         /* Call wait ready function */
876         status = chip->waitfunc(mtd, chip);
877         /* See if device thinks it succeeded */
878         if (status & NAND_STATUS_FAIL) {
879                 pr_debug("%s: error status = 0x%08x\n",
880                                         __func__, status);
881                 ret = -EIO;
882         }
883
884         return ret;
885 }
886
887 /**
888  * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
889  * @mtd: mtd info
890  * @ofs: offset to start unlock from
891  * @len: length to unlock
892  *
893  * Returns unlock status.
894  */
895 int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
896 {
897         int ret = 0;
898         int chipnr;
899         struct nand_chip *chip = mtd->priv;
900
901         pr_debug("%s: start = 0x%012llx, len = %llu\n",
902                         __func__, (unsigned long long)ofs, len);
903
904         if (check_offs_len(mtd, ofs, len))
905                 ret = -EINVAL;
906
907         /* Align to last block address if size addresses end of the device */
908         if (ofs + len == mtd->size)
909                 len -= mtd->erasesize;
910
911         nand_get_device(mtd, FL_UNLOCKING);
912
913         /* Shift to get chip number */
914         chipnr = ofs >> chip->chip_shift;
915
916         chip->select_chip(mtd, chipnr);
917
918         /* Check, if it is write protected */
919         if (nand_check_wp(mtd)) {
920                 pr_debug("%s: device is write protected!\n",
921                                         __func__);
922                 ret = -EIO;
923                 goto out;
924         }
925
926         ret = __nand_unlock(mtd, ofs, len, 0);
927
928 out:
929         chip->select_chip(mtd, -1);
930         nand_release_device(mtd);
931
932         return ret;
933 }
934 EXPORT_SYMBOL(nand_unlock);
935
936 /**
937  * nand_lock - [REPLACEABLE] locks all blocks present in the device
938  * @mtd: mtd info
939  * @ofs: offset to start unlock from
940  * @len: length to unlock
941  *
942  * This feature is not supported in many NAND parts. 'Micron' NAND parts do
943  * have this feature, but it allows only to lock all blocks, not for specified
944  * range for block. Implementing 'lock' feature by making use of 'unlock', for
945  * now.
946  *
947  * Returns lock status.
948  */
949 int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
950 {
951         int ret = 0;
952         int chipnr, status, page;
953         struct nand_chip *chip = mtd->priv;
954
955         pr_debug("%s: start = 0x%012llx, len = %llu\n",
956                         __func__, (unsigned long long)ofs, len);
957
958         if (check_offs_len(mtd, ofs, len))
959                 ret = -EINVAL;
960
961         nand_get_device(mtd, FL_LOCKING);
962
963         /* Shift to get chip number */
964         chipnr = ofs >> chip->chip_shift;
965
966         chip->select_chip(mtd, chipnr);
967
968         /* Check, if it is write protected */
969         if (nand_check_wp(mtd)) {
970                 pr_debug("%s: device is write protected!\n",
971                                         __func__);
972                 status = MTD_ERASE_FAILED;
973                 ret = -EIO;
974                 goto out;
975         }
976
977         /* Submit address of first page to lock */
978         page = ofs >> chip->page_shift;
979         chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
980
981         /* Call wait ready function */
982         status = chip->waitfunc(mtd, chip);
983         /* See if device thinks it succeeded */
984         if (status & NAND_STATUS_FAIL) {
985                 pr_debug("%s: error status = 0x%08x\n",
986                                         __func__, status);
987                 ret = -EIO;
988                 goto out;
989         }
990
991         ret = __nand_unlock(mtd, ofs, len, 0x1);
992
993 out:
994         chip->select_chip(mtd, -1);
995         nand_release_device(mtd);
996
997         return ret;
998 }
999 EXPORT_SYMBOL(nand_lock);
1000
1001 /**
1002  * nand_read_page_raw - [INTERN] read raw page data without ecc
1003  * @mtd: mtd info structure
1004  * @chip: nand chip info structure
1005  * @buf: buffer to store read data
1006  * @oob_required: caller requires OOB data read to chip->oob_poi
1007  * @page: page number to read
1008  *
1009  * Not for syndrome calculating ECC controllers, which use a special oob layout.
1010  */
1011 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1012                               uint8_t *buf, int oob_required, int page)
1013 {
1014         chip->read_buf(mtd, buf, mtd->writesize);
1015         if (oob_required)
1016                 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1017         return 0;
1018 }
1019
1020 /**
1021  * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1022  * @mtd: mtd info structure
1023  * @chip: nand chip info structure
1024  * @buf: buffer to store read data
1025  * @oob_required: caller requires OOB data read to chip->oob_poi
1026  * @page: page number to read
1027  *
1028  * We need a special oob layout and handling even when OOB isn't used.
1029  */
1030 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1031                                        struct nand_chip *chip, uint8_t *buf,
1032                                        int oob_required, int page)
1033 {
1034         int eccsize = chip->ecc.size;
1035         int eccbytes = chip->ecc.bytes;
1036         uint8_t *oob = chip->oob_poi;
1037         int steps, size;
1038
1039         for (steps = chip->ecc.steps; steps > 0; steps--) {
1040                 chip->read_buf(mtd, buf, eccsize);
1041                 buf += eccsize;
1042
1043                 if (chip->ecc.prepad) {
1044                         chip->read_buf(mtd, oob, chip->ecc.prepad);
1045                         oob += chip->ecc.prepad;
1046                 }
1047
1048                 chip->read_buf(mtd, oob, eccbytes);
1049                 oob += eccbytes;
1050
1051                 if (chip->ecc.postpad) {
1052                         chip->read_buf(mtd, oob, chip->ecc.postpad);
1053                         oob += chip->ecc.postpad;
1054                 }
1055         }
1056
1057         size = mtd->oobsize - (oob - chip->oob_poi);
1058         if (size)
1059                 chip->read_buf(mtd, oob, size);
1060
1061         return 0;
1062 }
1063
1064 /**
1065  * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1066  * @mtd: mtd info structure
1067  * @chip: nand chip info structure
1068  * @buf: buffer to store read data
1069  * @oob_required: caller requires OOB data read to chip->oob_poi
1070  * @page: page number to read
1071  */
1072 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1073                                 uint8_t *buf, int oob_required, int page)
1074 {
1075         int i, eccsize = chip->ecc.size;
1076         int eccbytes = chip->ecc.bytes;
1077         int eccsteps = chip->ecc.steps;
1078         uint8_t *p = buf;
1079         uint8_t *ecc_calc = chip->buffers->ecccalc;
1080         uint8_t *ecc_code = chip->buffers->ecccode;
1081         uint32_t *eccpos = chip->ecc.layout->eccpos;
1082         unsigned int max_bitflips = 0;
1083
1084         chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1085
1086         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1087                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1088
1089         for (i = 0; i < chip->ecc.total; i++)
1090                 ecc_code[i] = chip->oob_poi[eccpos[i]];
1091
1092         eccsteps = chip->ecc.steps;
1093         p = buf;
1094
1095         for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1096                 int stat;
1097
1098                 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1099                 if (stat < 0) {
1100                         mtd->ecc_stats.failed++;
1101                 } else {
1102                         mtd->ecc_stats.corrected += stat;
1103                         max_bitflips = max_t(unsigned int, max_bitflips, stat);
1104                 }
1105         }
1106         return max_bitflips;
1107 }
1108
1109 /**
1110  * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1111  * @mtd: mtd info structure
1112  * @chip: nand chip info structure
1113  * @data_offs: offset of requested data within the page
1114  * @readlen: data length
1115  * @bufpoi: buffer to store read data
1116  */
1117 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1118                         uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi)
1119 {
1120         int start_step, end_step, num_steps;
1121         uint32_t *eccpos = chip->ecc.layout->eccpos;
1122         uint8_t *p;
1123         int data_col_addr, i, gaps = 0;
1124         int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1125         int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1126         int index = 0;
1127         unsigned int max_bitflips = 0;
1128
1129         /* Column address within the page aligned to ECC size (256bytes) */
1130         start_step = data_offs / chip->ecc.size;
1131         end_step = (data_offs + readlen - 1) / chip->ecc.size;
1132         num_steps = end_step - start_step + 1;
1133
1134         /* Data size aligned to ECC ecc.size */
1135         datafrag_len = num_steps * chip->ecc.size;
1136         eccfrag_len = num_steps * chip->ecc.bytes;
1137
1138         data_col_addr = start_step * chip->ecc.size;
1139         /* If we read not a page aligned data */
1140         if (data_col_addr != 0)
1141                 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1142
1143         p = bufpoi + data_col_addr;
1144         chip->read_buf(mtd, p, datafrag_len);
1145
1146         /* Calculate ECC */
1147         for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1148                 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1149
1150         /*
1151          * The performance is faster if we position offsets according to
1152          * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1153          */
1154         for (i = 0; i < eccfrag_len - 1; i++) {
1155                 if (eccpos[i + start_step * chip->ecc.bytes] + 1 !=
1156                         eccpos[i + start_step * chip->ecc.bytes + 1]) {
1157                         gaps = 1;
1158                         break;
1159                 }
1160         }
1161         if (gaps) {
1162                 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1163                 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1164         } else {
1165                 /*
1166                  * Send the command to read the particular ECC bytes take care
1167                  * about buswidth alignment in read_buf.
1168                  */
1169                 index = start_step * chip->ecc.bytes;
1170
1171                 aligned_pos = eccpos[index] & ~(busw - 1);
1172                 aligned_len = eccfrag_len;
1173                 if (eccpos[index] & (busw - 1))
1174                         aligned_len++;
1175                 if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1176                         aligned_len++;
1177
1178                 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1179                                         mtd->writesize + aligned_pos, -1);
1180                 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1181         }
1182
1183         for (i = 0; i < eccfrag_len; i++)
1184                 chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1185
1186         p = bufpoi + data_col_addr;
1187         for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1188                 int stat;
1189
1190                 stat = chip->ecc.correct(mtd, p,
1191                         &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1192                 if (stat < 0) {
1193                         mtd->ecc_stats.failed++;
1194                 } else {
1195                         mtd->ecc_stats.corrected += stat;
1196                         max_bitflips = max_t(unsigned int, max_bitflips, stat);
1197                 }
1198         }
1199         return max_bitflips;
1200 }
1201
1202 /**
1203  * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1204  * @mtd: mtd info structure
1205  * @chip: nand chip info structure
1206  * @buf: buffer to store read data
1207  * @oob_required: caller requires OOB data read to chip->oob_poi
1208  * @page: page number to read
1209  *
1210  * Not for syndrome calculating ECC controllers which need a special oob layout.
1211  */
1212 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1213                                 uint8_t *buf, int oob_required, int page)
1214 {
1215         int i, eccsize = chip->ecc.size;
1216         int eccbytes = chip->ecc.bytes;
1217         int eccsteps = chip->ecc.steps;
1218         uint8_t *p = buf;
1219         uint8_t *ecc_calc = chip->buffers->ecccalc;
1220         uint8_t *ecc_code = chip->buffers->ecccode;
1221         uint32_t *eccpos = chip->ecc.layout->eccpos;
1222         unsigned int max_bitflips = 0;
1223
1224         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1225                 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1226                 chip->read_buf(mtd, p, eccsize);
1227                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1228         }
1229         chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1230
1231         for (i = 0; i < chip->ecc.total; i++)
1232                 ecc_code[i] = chip->oob_poi[eccpos[i]];
1233
1234         eccsteps = chip->ecc.steps;
1235         p = buf;
1236
1237         for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1238                 int stat;
1239
1240                 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1241                 if (stat < 0) {
1242                         mtd->ecc_stats.failed++;
1243                 } else {
1244                         mtd->ecc_stats.corrected += stat;
1245                         max_bitflips = max_t(unsigned int, max_bitflips, stat);
1246                 }
1247         }
1248         return max_bitflips;
1249 }
1250
1251 /**
1252  * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1253  * @mtd: mtd info structure
1254  * @chip: nand chip info structure
1255  * @buf: buffer to store read data
1256  * @oob_required: caller requires OOB data read to chip->oob_poi
1257  * @page: page number to read
1258  *
1259  * Hardware ECC for large page chips, require OOB to be read first. For this
1260  * ECC mode, the write_page method is re-used from ECC_HW. These methods
1261  * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1262  * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1263  * the data area, by overwriting the NAND manufacturer bad block markings.
1264  */
1265 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1266         struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1267 {
1268         int i, eccsize = chip->ecc.size;
1269         int eccbytes = chip->ecc.bytes;
1270         int eccsteps = chip->ecc.steps;
1271         uint8_t *p = buf;
1272         uint8_t *ecc_code = chip->buffers->ecccode;
1273         uint32_t *eccpos = chip->ecc.layout->eccpos;
1274         uint8_t *ecc_calc = chip->buffers->ecccalc;
1275         unsigned int max_bitflips = 0;
1276
1277         /* Read the OOB area first */
1278         chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1279         chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1280         chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1281
1282         for (i = 0; i < chip->ecc.total; i++)
1283                 ecc_code[i] = chip->oob_poi[eccpos[i]];
1284
1285         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1286                 int stat;
1287
1288                 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1289                 chip->read_buf(mtd, p, eccsize);
1290                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1291
1292                 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1293                 if (stat < 0) {
1294                         mtd->ecc_stats.failed++;
1295                 } else {
1296                         mtd->ecc_stats.corrected += stat;
1297                         max_bitflips = max_t(unsigned int, max_bitflips, stat);
1298                 }
1299         }
1300         return max_bitflips;
1301 }
1302
1303 /**
1304  * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1305  * @mtd: mtd info structure
1306  * @chip: nand chip info structure
1307  * @buf: buffer to store read data
1308  * @oob_required: caller requires OOB data read to chip->oob_poi
1309  * @page: page number to read
1310  *
1311  * The hw generator calculates the error syndrome automatically. Therefore we
1312  * need a special oob layout and handling.
1313  */
1314 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1315                                    uint8_t *buf, int oob_required, int page)
1316 {
1317         int i, eccsize = chip->ecc.size;
1318         int eccbytes = chip->ecc.bytes;
1319         int eccsteps = chip->ecc.steps;
1320         uint8_t *p = buf;
1321         uint8_t *oob = chip->oob_poi;
1322         unsigned int max_bitflips = 0;
1323
1324         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1325                 int stat;
1326
1327                 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1328                 chip->read_buf(mtd, p, eccsize);
1329
1330                 if (chip->ecc.prepad) {
1331                         chip->read_buf(mtd, oob, chip->ecc.prepad);
1332                         oob += chip->ecc.prepad;
1333                 }
1334
1335                 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1336                 chip->read_buf(mtd, oob, eccbytes);
1337                 stat = chip->ecc.correct(mtd, p, oob, NULL);
1338
1339                 if (stat < 0) {
1340                         mtd->ecc_stats.failed++;
1341                 } else {
1342                         mtd->ecc_stats.corrected += stat;
1343                         max_bitflips = max_t(unsigned int, max_bitflips, stat);
1344                 }
1345
1346                 oob += eccbytes;
1347
1348                 if (chip->ecc.postpad) {
1349                         chip->read_buf(mtd, oob, chip->ecc.postpad);
1350                         oob += chip->ecc.postpad;
1351                 }
1352         }
1353
1354         /* Calculate remaining oob bytes */
1355         i = mtd->oobsize - (oob - chip->oob_poi);
1356         if (i)
1357                 chip->read_buf(mtd, oob, i);
1358
1359         return max_bitflips;
1360 }
1361
1362 /**
1363  * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1364  * @chip: nand chip structure
1365  * @oob: oob destination address
1366  * @ops: oob ops structure
1367  * @len: size of oob to transfer
1368  */
1369 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
1370                                   struct mtd_oob_ops *ops, size_t len)
1371 {
1372         switch (ops->mode) {
1373
1374         case MTD_OPS_PLACE_OOB:
1375         case MTD_OPS_RAW:
1376                 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1377                 return oob + len;
1378
1379         case MTD_OPS_AUTO_OOB: {
1380                 struct nand_oobfree *free = chip->ecc.layout->oobfree;
1381                 uint32_t boffs = 0, roffs = ops->ooboffs;
1382                 size_t bytes = 0;
1383
1384                 for (; free->length && len; free++, len -= bytes) {
1385                         /* Read request not from offset 0? */
1386                         if (unlikely(roffs)) {
1387                                 if (roffs >= free->length) {
1388                                         roffs -= free->length;
1389                                         continue;
1390                                 }
1391                                 boffs = free->offset + roffs;
1392                                 bytes = min_t(size_t, len,
1393                                               (free->length - roffs));
1394                                 roffs = 0;
1395                         } else {
1396                                 bytes = min_t(size_t, len, free->length);
1397                                 boffs = free->offset;
1398                         }
1399                         memcpy(oob, chip->oob_poi + boffs, bytes);
1400                         oob += bytes;
1401                 }
1402                 return oob;
1403         }
1404         default:
1405                 BUG();
1406         }
1407         return NULL;
1408 }
1409
1410 /**
1411  * nand_do_read_ops - [INTERN] Read data with ECC
1412  * @mtd: MTD device structure
1413  * @from: offset to read from
1414  * @ops: oob ops structure
1415  *
1416  * Internal function. Called with chip held.
1417  */
1418 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1419                             struct mtd_oob_ops *ops)
1420 {
1421         int chipnr, page, realpage, col, bytes, aligned, oob_required;
1422         struct nand_chip *chip = mtd->priv;
1423         struct mtd_ecc_stats stats;
1424         int ret = 0;
1425         uint32_t readlen = ops->len;
1426         uint32_t oobreadlen = ops->ooblen;
1427         uint32_t max_oobsize = ops->mode == MTD_OPS_AUTO_OOB ?
1428                 mtd->oobavail : mtd->oobsize;
1429
1430         uint8_t *bufpoi, *oob, *buf;
1431         unsigned int max_bitflips = 0;
1432
1433         stats = mtd->ecc_stats;
1434
1435         chipnr = (int)(from >> chip->chip_shift);
1436         chip->select_chip(mtd, chipnr);
1437
1438         realpage = (int)(from >> chip->page_shift);
1439         page = realpage & chip->pagemask;
1440
1441         col = (int)(from & (mtd->writesize - 1));
1442
1443         buf = ops->datbuf;
1444         oob = ops->oobbuf;
1445         oob_required = oob ? 1 : 0;
1446
1447         while (1) {
1448                 bytes = min(mtd->writesize - col, readlen);
1449                 aligned = (bytes == mtd->writesize);
1450
1451                 /* Is the current page in the buffer? */
1452                 if (realpage != chip->pagebuf || oob) {
1453                         bufpoi = aligned ? buf : chip->buffers->databuf;
1454
1455                         chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1456
1457                         /*
1458                          * Now read the page into the buffer.  Absent an error,
1459                          * the read methods return max bitflips per ecc step.
1460                          */
1461                         if (unlikely(ops->mode == MTD_OPS_RAW))
1462                                 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1463                                                               oob_required,
1464                                                               page);
1465                         else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1466                                  !oob)
1467                                 ret = chip->ecc.read_subpage(mtd, chip,
1468                                                         col, bytes, bufpoi);
1469                         else
1470                                 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1471                                                           oob_required, page);
1472                         if (ret < 0) {
1473                                 if (!aligned)
1474                                         /* Invalidate page cache */
1475                                         chip->pagebuf = -1;
1476                                 break;
1477                         }
1478
1479                         max_bitflips = max_t(unsigned int, max_bitflips, ret);
1480
1481                         /* Transfer not aligned data */
1482                         if (!aligned) {
1483                                 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
1484                                     !(mtd->ecc_stats.failed - stats.failed) &&
1485                                     (ops->mode != MTD_OPS_RAW)) {
1486                                         chip->pagebuf = realpage;
1487                                         chip->pagebuf_bitflips = ret;
1488                                 } else {
1489                                         /* Invalidate page cache */
1490                                         chip->pagebuf = -1;
1491                                 }
1492                                 memcpy(buf, chip->buffers->databuf + col, bytes);
1493                         }
1494
1495                         buf += bytes;
1496
1497                         if (unlikely(oob)) {
1498                                 int toread = min(oobreadlen, max_oobsize);
1499
1500                                 if (toread) {
1501                                         oob = nand_transfer_oob(chip,
1502                                                 oob, ops, toread);
1503                                         oobreadlen -= toread;
1504                                 }
1505                         }
1506
1507                         if (chip->options & NAND_NEED_READRDY) {
1508                                 /* Apply delay or wait for ready/busy pin */
1509                                 if (!chip->dev_ready)
1510                                         udelay(chip->chip_delay);
1511                                 else
1512                                         nand_wait_ready(mtd);
1513                         }
1514                 } else {
1515                         memcpy(buf, chip->buffers->databuf + col, bytes);
1516                         buf += bytes;
1517                         max_bitflips = max_t(unsigned int, max_bitflips,
1518                                              chip->pagebuf_bitflips);
1519                 }
1520
1521                 readlen -= bytes;
1522
1523                 if (!readlen)
1524                         break;
1525
1526                 /* For subsequent reads align to page boundary */
1527                 col = 0;
1528                 /* Increment page address */
1529                 realpage++;
1530
1531                 page = realpage & chip->pagemask;
1532                 /* Check, if we cross a chip boundary */
1533                 if (!page) {
1534                         chipnr++;
1535                         chip->select_chip(mtd, -1);
1536                         chip->select_chip(mtd, chipnr);
1537                 }
1538         }
1539         chip->select_chip(mtd, -1);
1540
1541         ops->retlen = ops->len - (size_t) readlen;
1542         if (oob)
1543                 ops->oobretlen = ops->ooblen - oobreadlen;
1544
1545         if (ret < 0)
1546                 return ret;
1547
1548         if (mtd->ecc_stats.failed - stats.failed)
1549                 return -EBADMSG;
1550
1551         return max_bitflips;
1552 }
1553
1554 /**
1555  * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
1556  * @mtd: MTD device structure
1557  * @from: offset to read from
1558  * @len: number of bytes to read
1559  * @retlen: pointer to variable to store the number of read bytes
1560  * @buf: the databuffer to put data
1561  *
1562  * Get hold of the chip and call nand_do_read.
1563  */
1564 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
1565                      size_t *retlen, uint8_t *buf)
1566 {
1567         struct mtd_oob_ops ops;
1568         int ret;
1569
1570         nand_get_device(mtd, FL_READING);
1571         ops.len = len;
1572         ops.datbuf = buf;
1573         ops.oobbuf = NULL;
1574         ops.mode = MTD_OPS_PLACE_OOB;
1575         ret = nand_do_read_ops(mtd, from, &ops);
1576         *retlen = ops.retlen;
1577         nand_release_device(mtd);
1578         return ret;
1579 }
1580
1581 /**
1582  * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
1583  * @mtd: mtd info structure
1584  * @chip: nand chip info structure
1585  * @page: page number to read
1586  */
1587 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1588                              int page)
1589 {
1590         chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1591         chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1592         return 0;
1593 }
1594
1595 /**
1596  * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
1597  *                          with syndromes
1598  * @mtd: mtd info structure
1599  * @chip: nand chip info structure
1600  * @page: page number to read
1601  */
1602 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1603                                   int page)
1604 {
1605         uint8_t *buf = chip->oob_poi;
1606         int length = mtd->oobsize;
1607         int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1608         int eccsize = chip->ecc.size;
1609         uint8_t *bufpoi = buf;
1610         int i, toread, sndrnd = 0, pos;
1611
1612         chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
1613         for (i = 0; i < chip->ecc.steps; i++) {
1614                 if (sndrnd) {
1615                         pos = eccsize + i * (eccsize + chunk);
1616                         if (mtd->writesize > 512)
1617                                 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
1618                         else
1619                                 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
1620                 } else
1621                         sndrnd = 1;
1622                 toread = min_t(int, length, chunk);
1623                 chip->read_buf(mtd, bufpoi, toread);
1624                 bufpoi += toread;
1625                 length -= toread;
1626         }
1627         if (length > 0)
1628                 chip->read_buf(mtd, bufpoi, length);
1629
1630         return 0;
1631 }
1632
1633 /**
1634  * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
1635  * @mtd: mtd info structure
1636  * @chip: nand chip info structure
1637  * @page: page number to write
1638  */
1639 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1640                               int page)
1641 {
1642         int status = 0;
1643         const uint8_t *buf = chip->oob_poi;
1644         int length = mtd->oobsize;
1645
1646         chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
1647         chip->write_buf(mtd, buf, length);
1648         /* Send command to program the OOB data */
1649         chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1650
1651         status = chip->waitfunc(mtd, chip);
1652
1653         return status & NAND_STATUS_FAIL ? -EIO : 0;
1654 }
1655
1656 /**
1657  * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
1658  *                           with syndrome - only for large page flash
1659  * @mtd: mtd info structure
1660  * @chip: nand chip info structure
1661  * @page: page number to write
1662  */
1663 static int nand_write_oob_syndrome(struct mtd_info *mtd,
1664                                    struct nand_chip *chip, int page)
1665 {
1666         int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1667         int eccsize = chip->ecc.size, length = mtd->oobsize;
1668         int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
1669         const uint8_t *bufpoi = chip->oob_poi;
1670
1671         /*
1672          * data-ecc-data-ecc ... ecc-oob
1673          * or
1674          * data-pad-ecc-pad-data-pad .... ecc-pad-oob
1675          */
1676         if (!chip->ecc.prepad && !chip->ecc.postpad) {
1677                 pos = steps * (eccsize + chunk);
1678                 steps = 0;
1679         } else
1680                 pos = eccsize;
1681
1682         chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
1683         for (i = 0; i < steps; i++) {
1684                 if (sndcmd) {
1685                         if (mtd->writesize <= 512) {
1686                                 uint32_t fill = 0xFFFFFFFF;
1687
1688                                 len = eccsize;
1689                                 while (len > 0) {
1690                                         int num = min_t(int, len, 4);
1691                                         chip->write_buf(mtd, (uint8_t *)&fill,
1692                                                         num);
1693                                         len -= num;
1694                                 }
1695                         } else {
1696                                 pos = eccsize + i * (eccsize + chunk);
1697                                 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
1698                         }
1699                 } else
1700                         sndcmd = 1;
1701                 len = min_t(int, length, chunk);
1702                 chip->write_buf(mtd, bufpoi, len);
1703                 bufpoi += len;
1704                 length -= len;
1705         }
1706         if (length > 0)
1707                 chip->write_buf(mtd, bufpoi, length);
1708
1709         chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1710         status = chip->waitfunc(mtd, chip);
1711
1712         return status & NAND_STATUS_FAIL ? -EIO : 0;
1713 }
1714
1715 /**
1716  * nand_do_read_oob - [INTERN] NAND read out-of-band
1717  * @mtd: MTD device structure
1718  * @from: offset to read from
1719  * @ops: oob operations description structure
1720  *
1721  * NAND read out-of-band data from the spare area.
1722  */
1723 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
1724                             struct mtd_oob_ops *ops)
1725 {
1726         int page, realpage, chipnr;
1727         struct nand_chip *chip = mtd->priv;
1728         struct mtd_ecc_stats stats;
1729         int readlen = ops->ooblen;
1730         int len;
1731         uint8_t *buf = ops->oobbuf;
1732         int ret = 0;
1733
1734         pr_debug("%s: from = 0x%08Lx, len = %i\n",
1735                         __func__, (unsigned long long)from, readlen);
1736
1737         stats = mtd->ecc_stats;
1738
1739         if (ops->mode == MTD_OPS_AUTO_OOB)
1740                 len = chip->ecc.layout->oobavail;
1741         else
1742                 len = mtd->oobsize;
1743
1744         if (len == 0)
1745                 return 0;
1746
1747         if (unlikely(ops->ooboffs >= len)) {
1748                 pr_debug("%s: attempt to start read outside oob\n",
1749                                 __func__);
1750                 return -EINVAL;
1751         }
1752
1753         /* Do not allow reads past end of device */
1754         if (unlikely(from >= mtd->size ||
1755                      ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
1756                                         (from >> chip->page_shift)) * len)) {
1757                 pr_debug("%s: attempt to read beyond end of device\n",
1758                                 __func__);
1759                 return -EINVAL;
1760         }
1761
1762         chipnr = (int)(from >> chip->chip_shift);
1763         chip->select_chip(mtd, chipnr);
1764
1765         /* Shift to get page */
1766         realpage = (int)(from >> chip->page_shift);
1767         page = realpage & chip->pagemask;
1768
1769         while (1) {
1770                 if (ops->mode == MTD_OPS_RAW)
1771                         ret = chip->ecc.read_oob_raw(mtd, chip, page);
1772                 else
1773                         ret = chip->ecc.read_oob(mtd, chip, page);
1774
1775                 if (ret < 0)
1776                         break;
1777
1778                 len = min(len, readlen);
1779                 buf = nand_transfer_oob(chip, buf, ops, len);
1780
1781                 if (chip->options & NAND_NEED_READRDY) {
1782                         /* Apply delay or wait for ready/busy pin */
1783                         if (!chip->dev_ready)
1784                                 udelay(chip->chip_delay);
1785                         else
1786                                 nand_wait_ready(mtd);
1787                 }
1788
1789                 readlen -= len;
1790                 if (!readlen)
1791                         break;
1792
1793                 /* Increment page address */
1794                 realpage++;
1795
1796                 page = realpage & chip->pagemask;
1797                 /* Check, if we cross a chip boundary */
1798                 if (!page) {
1799                         chipnr++;
1800                         chip->select_chip(mtd, -1);
1801                         chip->select_chip(mtd, chipnr);
1802                 }
1803         }
1804         chip->select_chip(mtd, -1);
1805
1806         ops->oobretlen = ops->ooblen - readlen;
1807
1808         if (ret < 0)
1809                 return ret;
1810
1811         if (mtd->ecc_stats.failed - stats.failed)
1812                 return -EBADMSG;
1813
1814         return  mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
1815 }
1816
1817 /**
1818  * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
1819  * @mtd: MTD device structure
1820  * @from: offset to read from
1821  * @ops: oob operation description structure
1822  *
1823  * NAND read data and/or out-of-band data.
1824  */
1825 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
1826                          struct mtd_oob_ops *ops)
1827 {
1828         int ret = -ENOTSUPP;
1829
1830         ops->retlen = 0;
1831
1832         /* Do not allow reads past end of device */
1833         if (ops->datbuf && (from + ops->len) > mtd->size) {
1834                 pr_debug("%s: attempt to read beyond end of device\n",
1835                                 __func__);
1836                 return -EINVAL;
1837         }
1838
1839         nand_get_device(mtd, FL_READING);
1840
1841         switch (ops->mode) {
1842         case MTD_OPS_PLACE_OOB:
1843         case MTD_OPS_AUTO_OOB:
1844         case MTD_OPS_RAW:
1845                 break;
1846
1847         default:
1848                 goto out;
1849         }
1850
1851         if (!ops->datbuf)
1852                 ret = nand_do_read_oob(mtd, from, ops);
1853         else
1854                 ret = nand_do_read_ops(mtd, from, ops);
1855
1856 out:
1857         nand_release_device(mtd);
1858         return ret;
1859 }
1860
1861
1862 /**
1863  * nand_write_page_raw - [INTERN] raw page write function
1864  * @mtd: mtd info structure
1865  * @chip: nand chip info structure
1866  * @buf: data buffer
1867  * @oob_required: must write chip->oob_poi to OOB
1868  *
1869  * Not for syndrome calculating ECC controllers, which use a special oob layout.
1870  */
1871 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1872                                 const uint8_t *buf, int oob_required)
1873 {
1874         chip->write_buf(mtd, buf, mtd->writesize);
1875         if (oob_required)
1876                 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
1877
1878         return 0;
1879 }
1880
1881 /**
1882  * nand_write_page_raw_syndrome - [INTERN] raw page write function
1883  * @mtd: mtd info structure
1884  * @chip: nand chip info structure
1885  * @buf: data buffer
1886  * @oob_required: must write chip->oob_poi to OOB
1887  *
1888  * We need a special oob layout and handling even when ECC isn't checked.
1889  */
1890 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
1891                                         struct nand_chip *chip,
1892                                         const uint8_t *buf, int oob_required)
1893 {
1894         int eccsize = chip->ecc.size;
1895         int eccbytes = chip->ecc.bytes;
1896         uint8_t *oob = chip->oob_poi;
1897         int steps, size;
1898
1899         for (steps = chip->ecc.steps; steps > 0; steps--) {
1900                 chip->write_buf(mtd, buf, eccsize);
1901                 buf += eccsize;
1902
1903                 if (chip->ecc.prepad) {
1904                         chip->write_buf(mtd, oob, chip->ecc.prepad);
1905                         oob += chip->ecc.prepad;
1906                 }
1907
1908                 chip->read_buf(mtd, oob, eccbytes);
1909                 oob += eccbytes;
1910
1911                 if (chip->ecc.postpad) {
1912                         chip->write_buf(mtd, oob, chip->ecc.postpad);
1913                         oob += chip->ecc.postpad;
1914                 }
1915         }
1916
1917         size = mtd->oobsize - (oob - chip->oob_poi);
1918         if (size)
1919                 chip->write_buf(mtd, oob, size);
1920
1921         return 0;
1922 }
1923 /**
1924  * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
1925  * @mtd: mtd info structure
1926  * @chip: nand chip info structure
1927  * @buf: data buffer
1928  * @oob_required: must write chip->oob_poi to OOB
1929  */
1930 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1931                                   const uint8_t *buf, int oob_required)
1932 {
1933         int i, eccsize = chip->ecc.size;
1934         int eccbytes = chip->ecc.bytes;
1935         int eccsteps = chip->ecc.steps;
1936         uint8_t *ecc_calc = chip->buffers->ecccalc;
1937         const uint8_t *p = buf;
1938         uint32_t *eccpos = chip->ecc.layout->eccpos;
1939
1940         /* Software ECC calculation */
1941         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1942                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1943
1944         for (i = 0; i < chip->ecc.total; i++)
1945                 chip->oob_poi[eccpos[i]] = ecc_calc[i];
1946
1947         return chip->ecc.write_page_raw(mtd, chip, buf, 1);
1948 }
1949
1950 /**
1951  * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
1952  * @mtd: mtd info structure
1953  * @chip: nand chip info structure
1954  * @buf: data buffer
1955  * @oob_required: must write chip->oob_poi to OOB
1956  */
1957 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1958                                   const uint8_t *buf, int oob_required)
1959 {
1960         int i, eccsize = chip->ecc.size;
1961         int eccbytes = chip->ecc.bytes;
1962         int eccsteps = chip->ecc.steps;
1963         uint8_t *ecc_calc = chip->buffers->ecccalc;
1964         const uint8_t *p = buf;
1965         uint32_t *eccpos = chip->ecc.layout->eccpos;
1966
1967         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1968                 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
1969                 chip->write_buf(mtd, p, eccsize);
1970                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1971         }
1972
1973         for (i = 0; i < chip->ecc.total; i++)
1974                 chip->oob_poi[eccpos[i]] = ecc_calc[i];
1975
1976         chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
1977
1978         return 0;
1979 }
1980
1981
1982 /**
1983  * nand_write_subpage_hwecc - [REPLACABLE] hardware ECC based subpage write
1984  * @mtd:        mtd info structure
1985  * @chip:       nand chip info structure
1986  * @offset:     column address of subpage within the page
1987  * @data_len:   data length
1988  * @buf:        data buffer
1989  * @oob_required: must write chip->oob_poi to OOB
1990  */
1991 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
1992                                 struct nand_chip *chip, uint32_t offset,
1993                                 uint32_t data_len, const uint8_t *buf,
1994                                 int oob_required)
1995 {
1996         uint8_t *oob_buf  = chip->oob_poi;
1997         uint8_t *ecc_calc = chip->buffers->ecccalc;
1998         int ecc_size      = chip->ecc.size;
1999         int ecc_bytes     = chip->ecc.bytes;
2000         int ecc_steps     = chip->ecc.steps;
2001         uint32_t *eccpos  = chip->ecc.layout->eccpos;
2002         uint32_t start_step = offset / ecc_size;
2003         uint32_t end_step   = (offset + data_len - 1) / ecc_size;
2004         int oob_bytes       = mtd->oobsize / ecc_steps;
2005         int step, i;
2006
2007         for (step = 0; step < ecc_steps; step++) {
2008                 /* configure controller for WRITE access */
2009                 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2010
2011                 /* write data (untouched subpages already masked by 0xFF) */
2012                 chip->write_buf(mtd, buf, ecc_size);
2013
2014                 /* mask ECC of un-touched subpages by padding 0xFF */
2015                 if ((step < start_step) || (step > end_step))
2016                         memset(ecc_calc, 0xff, ecc_bytes);
2017                 else
2018                         chip->ecc.calculate(mtd, buf, ecc_calc);
2019
2020                 /* mask OOB of un-touched subpages by padding 0xFF */
2021                 /* if oob_required, preserve OOB metadata of written subpage */
2022                 if (!oob_required || (step < start_step) || (step > end_step))
2023                         memset(oob_buf, 0xff, oob_bytes);
2024
2025                 buf += ecc_size;
2026                 ecc_calc += ecc_bytes;
2027                 oob_buf  += oob_bytes;
2028         }
2029
2030         /* copy calculated ECC for whole page to chip->buffer->oob */
2031         /* this include masked-value(0xFF) for unwritten subpages */
2032         ecc_calc = chip->buffers->ecccalc;
2033         for (i = 0; i < chip->ecc.total; i++)
2034                 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2035
2036         /* write OOB buffer to NAND device */
2037         chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2038
2039         return 0;
2040 }
2041
2042
2043 /**
2044  * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2045  * @mtd: mtd info structure
2046  * @chip: nand chip info structure
2047  * @buf: data buffer
2048  * @oob_required: must write chip->oob_poi to OOB
2049  *
2050  * The hw generator calculates the error syndrome automatically. Therefore we
2051  * need a special oob layout and handling.
2052  */
2053 static int nand_write_page_syndrome(struct mtd_info *mtd,
2054                                     struct nand_chip *chip,
2055                                     const uint8_t *buf, int oob_required)
2056 {
2057         int i, eccsize = chip->ecc.size;
2058         int eccbytes = chip->ecc.bytes;
2059         int eccsteps = chip->ecc.steps;
2060         const uint8_t *p = buf;
2061         uint8_t *oob = chip->oob_poi;
2062
2063         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2064
2065                 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2066                 chip->write_buf(mtd, p, eccsize);
2067
2068                 if (chip->ecc.prepad) {
2069                         chip->write_buf(mtd, oob, chip->ecc.prepad);
2070                         oob += chip->ecc.prepad;
2071                 }
2072
2073                 chip->ecc.calculate(mtd, p, oob);
2074                 chip->write_buf(mtd, oob, eccbytes);
2075                 oob += eccbytes;
2076
2077                 if (chip->ecc.postpad) {
2078                         chip->write_buf(mtd, oob, chip->ecc.postpad);
2079                         oob += chip->ecc.postpad;
2080                 }
2081         }
2082
2083         /* Calculate remaining oob bytes */
2084         i = mtd->oobsize - (oob - chip->oob_poi);
2085         if (i)
2086                 chip->write_buf(mtd, oob, i);
2087
2088         return 0;
2089 }
2090
2091 /**
2092  * nand_write_page - [REPLACEABLE] write one page
2093  * @mtd: MTD device structure
2094  * @chip: NAND chip descriptor
2095  * @offset: address offset within the page
2096  * @data_len: length of actual data to be written
2097  * @buf: the data to write
2098  * @oob_required: must write chip->oob_poi to OOB
2099  * @page: page number to write
2100  * @cached: cached programming
2101  * @raw: use _raw version of write_page
2102  */
2103 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2104                 uint32_t offset, int data_len, const uint8_t *buf,
2105                 int oob_required, int page, int cached, int raw)
2106 {
2107         int status, subpage;
2108
2109         if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2110                 chip->ecc.write_subpage)
2111                 subpage = offset || (data_len < mtd->writesize);
2112         else
2113                 subpage = 0;
2114
2115         chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2116
2117         if (unlikely(raw))
2118                 status = chip->ecc.write_page_raw(mtd, chip, buf,
2119                                                         oob_required);
2120         else if (subpage)
2121                 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2122                                                          buf, oob_required);
2123         else
2124                 status = chip->ecc.write_page(mtd, chip, buf, oob_required);
2125
2126         if (status < 0)
2127                 return status;
2128
2129         /*
2130          * Cached progamming disabled for now. Not sure if it's worth the
2131          * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
2132          */
2133         cached = 0;
2134
2135         if (!cached || !NAND_HAS_CACHEPROG(chip)) {
2136
2137                 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2138                 status = chip->waitfunc(mtd, chip);
2139                 /*
2140                  * See if operation failed and additional status checks are
2141                  * available.
2142                  */
2143                 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2144                         status = chip->errstat(mtd, chip, FL_WRITING, status,
2145                                                page);
2146
2147                 if (status & NAND_STATUS_FAIL)
2148                         return -EIO;
2149         } else {
2150                 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2151                 status = chip->waitfunc(mtd, chip);
2152         }
2153
2154         return 0;
2155 }
2156
2157 /**
2158  * nand_fill_oob - [INTERN] Transfer client buffer to oob
2159  * @mtd: MTD device structure
2160  * @oob: oob data buffer
2161  * @len: oob data write length
2162  * @ops: oob ops structure
2163  */
2164 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2165                               struct mtd_oob_ops *ops)
2166 {
2167         struct nand_chip *chip = mtd->priv;
2168
2169         /*
2170          * Initialise to all 0xFF, to avoid the possibility of left over OOB
2171          * data from a previous OOB read.
2172          */
2173         memset(chip->oob_poi, 0xff, mtd->oobsize);
2174
2175         switch (ops->mode) {
2176
2177         case MTD_OPS_PLACE_OOB:
2178         case MTD_OPS_RAW:
2179                 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2180                 return oob + len;
2181
2182         case MTD_OPS_AUTO_OOB: {
2183                 struct nand_oobfree *free = chip->ecc.layout->oobfree;
2184                 uint32_t boffs = 0, woffs = ops->ooboffs;
2185                 size_t bytes = 0;
2186
2187                 for (; free->length && len; free++, len -= bytes) {
2188                         /* Write request not from offset 0? */
2189                         if (unlikely(woffs)) {
2190                                 if (woffs >= free->length) {
2191                                         woffs -= free->length;
2192                                         continue;
2193                                 }
2194                                 boffs = free->offset + woffs;
2195                                 bytes = min_t(size_t, len,
2196                                               (free->length - woffs));
2197                                 woffs = 0;
2198                         } else {
2199                                 bytes = min_t(size_t, len, free->length);
2200                                 boffs = free->offset;
2201                         }
2202                         memcpy(chip->oob_poi + boffs, oob, bytes);
2203                         oob += bytes;
2204                 }
2205                 return oob;
2206         }
2207         default:
2208                 BUG();
2209         }
2210         return NULL;
2211 }
2212
2213 #define NOTALIGNED(x)   ((x & (chip->subpagesize - 1)) != 0)
2214
2215 /**
2216  * nand_do_write_ops - [INTERN] NAND write with ECC
2217  * @mtd: MTD device structure
2218  * @to: offset to write to
2219  * @ops: oob operations description structure
2220  *
2221  * NAND write with ECC.
2222  */
2223 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2224                              struct mtd_oob_ops *ops)
2225 {
2226         int chipnr, realpage, page, blockmask, column;
2227         struct nand_chip *chip = mtd->priv;
2228         uint32_t writelen = ops->len;
2229
2230         uint32_t oobwritelen = ops->ooblen;
2231         uint32_t oobmaxlen = ops->mode == MTD_OPS_AUTO_OOB ?
2232                                 mtd->oobavail : mtd->oobsize;
2233
2234         uint8_t *oob = ops->oobbuf;
2235         uint8_t *buf = ops->datbuf;
2236         int ret;
2237         int oob_required = oob ? 1 : 0;
2238
2239         ops->retlen = 0;
2240         if (!writelen)
2241                 return 0;
2242
2243         /* Reject writes, which are not page aligned */
2244         if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2245                 pr_notice("%s: attempt to write non page aligned data\n",
2246                            __func__);
2247                 return -EINVAL;
2248         }
2249
2250         column = to & (mtd->writesize - 1);
2251
2252         chipnr = (int)(to >> chip->chip_shift);
2253         chip->select_chip(mtd, chipnr);
2254
2255         /* Check, if it is write protected */
2256         if (nand_check_wp(mtd)) {
2257                 ret = -EIO;
2258                 goto err_out;
2259         }
2260
2261         realpage = (int)(to >> chip->page_shift);
2262         page = realpage & chip->pagemask;
2263         blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2264
2265         /* Invalidate the page cache, when we write to the cached page */
2266         if (to <= (chip->pagebuf << chip->page_shift) &&
2267             (chip->pagebuf << chip->page_shift) < (to + ops->len))
2268                 chip->pagebuf = -1;
2269
2270         /* Don't allow multipage oob writes with offset */
2271         if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2272                 ret = -EINVAL;
2273                 goto err_out;
2274         }
2275
2276         while (1) {
2277                 int bytes = mtd->writesize;
2278                 int cached = writelen > bytes && page != blockmask;
2279                 uint8_t *wbuf = buf;
2280
2281                 /* Partial page write? */
2282                 if (unlikely(column || writelen < (mtd->writesize - 1))) {
2283                         cached = 0;
2284                         bytes = min_t(int, bytes - column, (int) writelen);
2285                         chip->pagebuf = -1;
2286                         memset(chip->buffers->databuf, 0xff, mtd->writesize);
2287                         memcpy(&chip->buffers->databuf[column], buf, bytes);
2288                         wbuf = chip->buffers->databuf;
2289                 }
2290
2291                 if (unlikely(oob)) {
2292                         size_t len = min(oobwritelen, oobmaxlen);
2293                         oob = nand_fill_oob(mtd, oob, len, ops);
2294                         oobwritelen -= len;
2295                 } else {
2296                         /* We still need to erase leftover OOB data */
2297                         memset(chip->oob_poi, 0xff, mtd->oobsize);
2298                 }
2299                 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2300                                         oob_required, page, cached,
2301                                         (ops->mode == MTD_OPS_RAW));
2302                 if (ret)
2303                         break;
2304
2305                 writelen -= bytes;
2306                 if (!writelen)
2307                         break;
2308
2309                 column = 0;
2310                 buf += bytes;
2311                 realpage++;
2312
2313                 page = realpage & chip->pagemask;
2314                 /* Check, if we cross a chip boundary */
2315                 if (!page) {
2316                         chipnr++;
2317                         chip->select_chip(mtd, -1);
2318                         chip->select_chip(mtd, chipnr);
2319                 }
2320         }
2321
2322         ops->retlen = ops->len - writelen;
2323         if (unlikely(oob))
2324                 ops->oobretlen = ops->ooblen;
2325
2326 err_out:
2327         chip->select_chip(mtd, -1);
2328         return ret;
2329 }
2330
2331 /**
2332  * panic_nand_write - [MTD Interface] NAND write with ECC
2333  * @mtd: MTD device structure
2334  * @to: offset to write to
2335  * @len: number of bytes to write
2336  * @retlen: pointer to variable to store the number of written bytes
2337  * @buf: the data to write
2338  *
2339  * NAND write with ECC. Used when performing writes in interrupt context, this
2340  * may for example be called by mtdoops when writing an oops while in panic.
2341  */
2342 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2343                             size_t *retlen, const uint8_t *buf)
2344 {
2345         struct nand_chip *chip = mtd->priv;
2346         struct mtd_oob_ops ops;
2347         int ret;
2348
2349         /* Wait for the device to get ready */
2350         panic_nand_wait(mtd, chip, 400);
2351
2352         /* Grab the device */
2353         panic_nand_get_device(chip, mtd, FL_WRITING);
2354
2355         ops.len = len;
2356         ops.datbuf = (uint8_t *)buf;
2357         ops.oobbuf = NULL;
2358         ops.mode = MTD_OPS_PLACE_OOB;
2359
2360         ret = nand_do_write_ops(mtd, to, &ops);
2361
2362         *retlen = ops.retlen;
2363         return ret;
2364 }
2365
2366 /**
2367  * nand_write - [MTD Interface] NAND write with ECC
2368  * @mtd: MTD device structure
2369  * @to: offset to write to
2370  * @len: number of bytes to write
2371  * @retlen: pointer to variable to store the number of written bytes
2372  * @buf: the data to write
2373  *
2374  * NAND write with ECC.
2375  */
2376 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2377                           size_t *retlen, const uint8_t *buf)
2378 {
2379         struct mtd_oob_ops ops;
2380         int ret;
2381
2382         nand_get_device(mtd, FL_WRITING);
2383         ops.len = len;
2384         ops.datbuf = (uint8_t *)buf;
2385         ops.oobbuf = NULL;
2386         ops.mode = MTD_OPS_PLACE_OOB;
2387         ret = nand_do_write_ops(mtd, to, &ops);
2388         *retlen = ops.retlen;
2389         nand_release_device(mtd);
2390         return ret;
2391 }
2392
2393 /**
2394  * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2395  * @mtd: MTD device structure
2396  * @to: offset to write to
2397  * @ops: oob operation description structure
2398  *
2399  * NAND write out-of-band.
2400  */
2401 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2402                              struct mtd_oob_ops *ops)
2403 {
2404         int chipnr, page, status, len;
2405         struct nand_chip *chip = mtd->priv;
2406
2407         pr_debug("%s: to = 0x%08x, len = %i\n",
2408                          __func__, (unsigned int)to, (int)ops->ooblen);
2409
2410         if (ops->mode == MTD_OPS_AUTO_OOB)
2411                 len = chip->ecc.layout->oobavail;
2412         else
2413                 len = mtd->oobsize;
2414
2415         if (len == 0)
2416                 return 0;
2417
2418         /* Do not allow write past end of page */
2419         if ((ops->ooboffs + ops->ooblen) > len) {
2420                 pr_debug("%s: attempt to write past end of page\n",
2421                                 __func__);
2422                 return -EINVAL;
2423         }
2424
2425         if (unlikely(ops->ooboffs >= len)) {
2426                 pr_debug("%s: attempt to start write outside oob\n",
2427                                 __func__);
2428                 return -EINVAL;
2429         }
2430
2431         /* Do not allow write past end of device */
2432         if (unlikely(to >= mtd->size ||
2433                      ops->ooboffs + ops->ooblen >
2434                         ((mtd->size >> chip->page_shift) -
2435                          (to >> chip->page_shift)) * len)) {
2436                 pr_debug("%s: attempt to write beyond end of device\n",
2437                                 __func__);
2438                 return -EINVAL;
2439         }
2440
2441         chipnr = (int)(to >> chip->chip_shift);
2442         chip->select_chip(mtd, chipnr);
2443
2444         /* Shift to get page */
2445         page = (int)(to >> chip->page_shift);
2446
2447         /*
2448          * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2449          * of my DiskOnChip 2000 test units) will clear the whole data page too
2450          * if we don't do this. I have no clue why, but I seem to have 'fixed'
2451          * it in the doc2000 driver in August 1999.  dwmw2.
2452          */
2453         chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
2454
2455         /* Check, if it is write protected */
2456         if (nand_check_wp(mtd)) {
2457                 chip->select_chip(mtd, -1);
2458                 return -EROFS;
2459         }
2460
2461         /* Invalidate the page cache, if we write to the cached page */
2462         if (page == chip->pagebuf)
2463                 chip->pagebuf = -1;
2464
2465         nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
2466
2467         if (ops->mode == MTD_OPS_RAW)
2468                 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
2469         else
2470                 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
2471
2472         chip->select_chip(mtd, -1);
2473
2474         if (status)
2475                 return status;
2476
2477         ops->oobretlen = ops->ooblen;
2478
2479         return 0;
2480 }
2481
2482 /**
2483  * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
2484  * @mtd: MTD device structure
2485  * @to: offset to write to
2486  * @ops: oob operation description structure
2487  */
2488 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
2489                           struct mtd_oob_ops *ops)
2490 {
2491         int ret = -ENOTSUPP;
2492
2493         ops->retlen = 0;
2494
2495         /* Do not allow writes past end of device */
2496         if (ops->datbuf && (to + ops->len) > mtd->size) {
2497                 pr_debug("%s: attempt to write beyond end of device\n",
2498                                 __func__);
2499                 return -EINVAL;
2500         }
2501
2502         nand_get_device(mtd, FL_WRITING);
2503
2504         switch (ops->mode) {
2505         case MTD_OPS_PLACE_OOB:
2506         case MTD_OPS_AUTO_OOB:
2507         case MTD_OPS_RAW:
2508                 break;
2509
2510         default:
2511                 goto out;
2512         }
2513
2514         if (!ops->datbuf)
2515                 ret = nand_do_write_oob(mtd, to, ops);
2516         else
2517                 ret = nand_do_write_ops(mtd, to, ops);
2518
2519 out:
2520         nand_release_device(mtd);
2521         return ret;
2522 }
2523
2524 /**
2525  * single_erase_cmd - [GENERIC] NAND standard block erase command function
2526  * @mtd: MTD device structure
2527  * @page: the page address of the block which will be erased
2528  *
2529  * Standard erase command for NAND chips.
2530  */
2531 static void single_erase_cmd(struct mtd_info *mtd, int page)
2532 {
2533         struct nand_chip *chip = mtd->priv;
2534         /* Send commands to erase a block */
2535         chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2536         chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2537 }
2538
2539 /**
2540  * nand_erase - [MTD Interface] erase block(s)
2541  * @mtd: MTD device structure
2542  * @instr: erase instruction
2543  *
2544  * Erase one ore more blocks.
2545  */
2546 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
2547 {
2548         return nand_erase_nand(mtd, instr, 0);
2549 }
2550
2551 /**
2552  * nand_erase_nand - [INTERN] erase block(s)
2553  * @mtd: MTD device structure
2554  * @instr: erase instruction
2555  * @allowbbt: allow erasing the bbt area
2556  *
2557  * Erase one ore more blocks.
2558  */
2559 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
2560                     int allowbbt)
2561 {
2562         int page, status, pages_per_block, ret, chipnr;
2563         struct nand_chip *chip = mtd->priv;
2564         loff_t len;
2565
2566         pr_debug("%s: start = 0x%012llx, len = %llu\n",
2567                         __func__, (unsigned long long)instr->addr,
2568                         (unsigned long long)instr->len);
2569
2570         if (check_offs_len(mtd, instr->addr, instr->len))
2571                 return -EINVAL;
2572
2573         /* Grab the lock and see if the device is available */
2574         nand_get_device(mtd, FL_ERASING);
2575
2576         /* Shift to get first page */
2577         page = (int)(instr->addr >> chip->page_shift);
2578         chipnr = (int)(instr->addr >> chip->chip_shift);
2579
2580         /* Calculate pages in each block */
2581         pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
2582
2583         /* Select the NAND device */
2584         chip->select_chip(mtd, chipnr);
2585
2586         /* Check, if it is write protected */
2587         if (nand_check_wp(mtd)) {
2588                 pr_debug("%s: device is write protected!\n",
2589                                 __func__);
2590                 instr->state = MTD_ERASE_FAILED;
2591                 goto erase_exit;
2592         }
2593
2594         /* Loop through the pages */
2595         len = instr->len;
2596
2597         instr->state = MTD_ERASING;
2598
2599         while (len) {
2600                 /* Check if we have a bad block, we do not erase bad blocks! */
2601                 if (nand_block_checkbad(mtd, ((loff_t) page) <<
2602                                         chip->page_shift, 0, allowbbt)) {
2603                         pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
2604                                     __func__, page);
2605                         instr->state = MTD_ERASE_FAILED;
2606                         goto erase_exit;
2607                 }
2608
2609                 /*
2610                  * Invalidate the page cache, if we erase the block which
2611                  * contains the current cached page.
2612                  */
2613                 if (page <= chip->pagebuf && chip->pagebuf <
2614                     (page + pages_per_block))
2615                         chip->pagebuf = -1;
2616
2617                 chip->erase_cmd(mtd, page & chip->pagemask);
2618
2619                 status = chip->waitfunc(mtd, chip);
2620
2621                 /*
2622                  * See if operation failed and additional status checks are
2623                  * available
2624                  */
2625                 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2626                         status = chip->errstat(mtd, chip, FL_ERASING,
2627                                                status, page);
2628
2629                 /* See if block erase succeeded */
2630                 if (status & NAND_STATUS_FAIL) {
2631                         pr_debug("%s: failed erase, page 0x%08x\n",
2632                                         __func__, page);
2633                         instr->state = MTD_ERASE_FAILED;
2634                         instr->fail_addr =
2635                                 ((loff_t)page << chip->page_shift);
2636                         goto erase_exit;
2637                 }
2638
2639                 /* Increment page address and decrement length */
2640                 len -= (1ULL << chip->phys_erase_shift);
2641                 page += pages_per_block;
2642
2643                 /* Check, if we cross a chip boundary */
2644                 if (len && !(page & chip->pagemask)) {
2645                         chipnr++;
2646                         chip->select_chip(mtd, -1);
2647                         chip->select_chip(mtd, chipnr);
2648                 }
2649         }
2650         instr->state = MTD_ERASE_DONE;
2651
2652 erase_exit:
2653
2654         ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
2655
2656         /* Deselect and wake up anyone waiting on the device */
2657         chip->select_chip(mtd, -1);
2658         nand_release_device(mtd);
2659
2660         /* Do call back function */
2661         if (!ret)
2662                 mtd_erase_callback(instr);
2663
2664         /* Return more or less happy */
2665         return ret;
2666 }
2667
2668 /**
2669  * nand_sync - [MTD Interface] sync
2670  * @mtd: MTD device structure
2671  *
2672  * Sync is actually a wait for chip ready function.
2673  */
2674 static void nand_sync(struct mtd_info *mtd)
2675 {
2676         pr_debug("%s: called\n", __func__);
2677
2678         /* Grab the lock and see if the device is available */
2679         nand_get_device(mtd, FL_SYNCING);
2680         /* Release it and go back */
2681         nand_release_device(mtd);
2682 }
2683
2684 /**
2685  * nand_block_isbad - [MTD Interface] Check if block at offset is bad
2686  * @mtd: MTD device structure
2687  * @offs: offset relative to mtd start
2688  */
2689 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
2690 {
2691         return nand_block_checkbad(mtd, offs, 1, 0);
2692 }
2693
2694 /**
2695  * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
2696  * @mtd: MTD device structure
2697  * @ofs: offset relative to mtd start
2698  */
2699 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
2700 {
2701         int ret;
2702
2703         ret = nand_block_isbad(mtd, ofs);
2704         if (ret) {
2705                 /* If it was bad already, return success and do nothing */
2706                 if (ret > 0)
2707                         return 0;
2708                 return ret;
2709         }
2710
2711         return nand_block_markbad_lowlevel(mtd, ofs);
2712 }
2713
2714 /**
2715  * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
2716  * @mtd: MTD device structure
2717  * @chip: nand chip info structure
2718  * @addr: feature address.
2719  * @subfeature_param: the subfeature parameters, a four bytes array.
2720  */
2721 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
2722                         int addr, uint8_t *subfeature_param)
2723 {
2724         int status;
2725
2726         if (!chip->onfi_version ||
2727             !(le16_to_cpu(chip->onfi_params.opt_cmd)
2728               & ONFI_OPT_CMD_SET_GET_FEATURES))
2729                 return -EINVAL;
2730
2731         chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
2732         chip->write_buf(mtd, subfeature_param, ONFI_SUBFEATURE_PARAM_LEN);
2733         status = chip->waitfunc(mtd, chip);
2734         if (status & NAND_STATUS_FAIL)
2735                 return -EIO;
2736         return 0;
2737 }
2738
2739 /**
2740  * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
2741  * @mtd: MTD device structure
2742  * @chip: nand chip info structure
2743  * @addr: feature address.
2744  * @subfeature_param: the subfeature parameters, a four bytes array.
2745  */
2746 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
2747                         int addr, uint8_t *subfeature_param)
2748 {
2749         if (!chip->onfi_version ||
2750             !(le16_to_cpu(chip->onfi_params.opt_cmd)
2751               & ONFI_OPT_CMD_SET_GET_FEATURES))
2752                 return -EINVAL;
2753
2754         /* clear the sub feature parameters */
2755         memset(subfeature_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
2756
2757         chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
2758         chip->read_buf(mtd, subfeature_param, ONFI_SUBFEATURE_PARAM_LEN);
2759         return 0;
2760 }
2761
2762 /**
2763  * nand_suspend - [MTD Interface] Suspend the NAND flash
2764  * @mtd: MTD device structure
2765  */
2766 static int nand_suspend(struct mtd_info *mtd)
2767 {
2768         return nand_get_device(mtd, FL_PM_SUSPENDED);
2769 }
2770
2771 /**
2772  * nand_resume - [MTD Interface] Resume the NAND flash
2773  * @mtd: MTD device structure
2774  */
2775 static void nand_resume(struct mtd_info *mtd)
2776 {
2777         struct nand_chip *chip = mtd->priv;
2778
2779         if (chip->state == FL_PM_SUSPENDED)
2780                 nand_release_device(mtd);
2781         else
2782                 pr_err("%s called for a chip which is not in suspended state\n",
2783                         __func__);
2784 }
2785
2786 /* Set default functions */
2787 static void nand_set_defaults(struct nand_chip *chip, int busw)
2788 {
2789         /* check for proper chip_delay setup, set 20us if not */
2790         if (!chip->chip_delay)
2791                 chip->chip_delay = 20;
2792
2793         /* check, if a user supplied command function given */
2794         if (chip->cmdfunc == NULL)
2795                 chip->cmdfunc = nand_command;
2796
2797         /* check, if a user supplied wait function given */
2798         if (chip->waitfunc == NULL)
2799                 chip->waitfunc = nand_wait;
2800
2801         if (!chip->select_chip)
2802                 chip->select_chip = nand_select_chip;
2803
2804         /* set for ONFI nand */
2805         if (!chip->onfi_set_features)
2806                 chip->onfi_set_features = nand_onfi_set_features;
2807         if (!chip->onfi_get_features)
2808                 chip->onfi_get_features = nand_onfi_get_features;
2809
2810         /* If called twice, pointers that depend on busw may need to be reset */
2811         if (!chip->read_byte || chip->read_byte == nand_read_byte)
2812                 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
2813         if (!chip->read_word)
2814                 chip->read_word = nand_read_word;
2815         if (!chip->block_bad)
2816                 chip->block_bad = nand_block_bad;
2817         if (!chip->block_markbad)
2818                 chip->block_markbad = nand_default_block_markbad;
2819         if (!chip->write_buf || chip->write_buf == nand_write_buf)
2820                 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
2821         if (!chip->read_buf || chip->read_buf == nand_read_buf)
2822                 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
2823         if (!chip->scan_bbt)
2824                 chip->scan_bbt = nand_default_bbt;
2825
2826         if (!chip->controller) {
2827                 chip->controller = &chip->hwcontrol;
2828                 spin_lock_init(&chip->controller->lock);
2829                 init_waitqueue_head(&chip->controller->wq);
2830         }
2831
2832 }
2833
2834 /* Sanitize ONFI strings so we can safely print them */
2835 static void sanitize_string(uint8_t *s, size_t len)
2836 {
2837         ssize_t i;
2838
2839         /* Null terminate */
2840         s[len - 1] = 0;
2841
2842         /* Remove non printable chars */
2843         for (i = 0; i < len - 1; i++) {
2844                 if (s[i] < ' ' || s[i] > 127)
2845                         s[i] = '?';
2846         }
2847
2848         /* Remove trailing spaces */
2849         strim(s);
2850 }
2851
2852 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
2853 {
2854         int i;
2855         while (len--) {
2856                 crc ^= *p++ << 8;
2857                 for (i = 0; i < 8; i++)
2858                         crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
2859         }
2860
2861         return crc;
2862 }
2863
2864 /* Parse the Extended Parameter Page. */
2865 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
2866                 struct nand_chip *chip, struct nand_onfi_params *p)
2867 {
2868         struct onfi_ext_param_page *ep;
2869         struct onfi_ext_section *s;
2870         struct onfi_ext_ecc_info *ecc;
2871         uint8_t *cursor;
2872         int ret = -EINVAL;
2873         int len;
2874         int i;
2875
2876         len = le16_to_cpu(p->ext_param_page_length) * 16;
2877         ep = kmalloc(len, GFP_KERNEL);
2878         if (!ep)
2879                 return -ENOMEM;
2880
2881         /* Send our own NAND_CMD_PARAM. */
2882         chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
2883
2884         /* Use the Change Read Column command to skip the ONFI param pages. */
2885         chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
2886                         sizeof(*p) * p->num_of_param_pages , -1);
2887
2888         /* Read out the Extended Parameter Page. */
2889         chip->read_buf(mtd, (uint8_t *)ep, len);
2890         if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
2891                 != le16_to_cpu(ep->crc))) {
2892                 pr_debug("fail in the CRC.\n");
2893                 goto ext_out;
2894         }
2895
2896         /*
2897          * Check the signature.
2898          * Do not strictly follow the ONFI spec, maybe changed in future.
2899          */
2900         if (strncmp(ep->sig, "EPPS", 4)) {
2901                 pr_debug("The signature is invalid.\n");
2902                 goto ext_out;
2903         }
2904
2905         /* find the ECC section. */
2906         cursor = (uint8_t *)(ep + 1);
2907         for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
2908                 s = ep->sections + i;
2909                 if (s->type == ONFI_SECTION_TYPE_2)
2910                         break;
2911                 cursor += s->length * 16;
2912         }
2913         if (i == ONFI_EXT_SECTION_MAX) {
2914                 pr_debug("We can not find the ECC section.\n");
2915                 goto ext_out;
2916         }
2917
2918         /* get the info we want. */
2919         ecc = (struct onfi_ext_ecc_info *)cursor;
2920
2921         if (!ecc->codeword_size) {
2922                 pr_debug("Invalid codeword size\n");
2923                 goto ext_out;
2924         }
2925
2926         chip->ecc_strength_ds = ecc->ecc_bits;
2927         chip->ecc_step_ds = 1 << ecc->codeword_size;
2928         ret = 0;
2929
2930 ext_out:
2931         kfree(ep);
2932         return ret;
2933 }
2934
2935 /*
2936  * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
2937  */
2938 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
2939                                         int *busw)
2940 {
2941         struct nand_onfi_params *p = &chip->onfi_params;
2942         int i;
2943         int val;
2944
2945         /* Try ONFI for unknown chip or LP */
2946         chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
2947         if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
2948                 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
2949                 return 0;
2950
2951         /*
2952          * ONFI must be probed in 8-bit mode or with NAND_BUSWIDTH_AUTO, not
2953          * with NAND_BUSWIDTH_16
2954          */
2955         if (chip->options & NAND_BUSWIDTH_16) {
2956                 pr_err("ONFI cannot be probed in 16-bit mode; aborting\n");
2957                 return 0;
2958         }
2959
2960         chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
2961         for (i = 0; i < 3; i++) {
2962                 chip->read_buf(mtd, (uint8_t *)p, sizeof(*p));
2963                 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
2964                                 le16_to_cpu(p->crc)) {
2965                         break;
2966                 }
2967         }
2968
2969         if (i == 3) {
2970                 pr_err("Could not find valid ONFI parameter page; aborting\n");
2971                 return 0;
2972         }
2973
2974         /* Check version */
2975         val = le16_to_cpu(p->revision);
2976         if (val & (1 << 5))
2977                 chip->onfi_version = 23;
2978         else if (val & (1 << 4))
2979                 chip->onfi_version = 22;
2980         else if (val & (1 << 3))
2981                 chip->onfi_version = 21;
2982         else if (val & (1 << 2))
2983                 chip->onfi_version = 20;
2984         else if (val & (1 << 1))
2985                 chip->onfi_version = 10;
2986
2987         if (!chip->onfi_version) {
2988                 pr_info("%s: unsupported ONFI version: %d\n", __func__, val);
2989                 return 0;
2990         }
2991
2992         sanitize_string(p->manufacturer, sizeof(p->manufacturer));
2993         sanitize_string(p->model, sizeof(p->model));
2994         if (!mtd->name)
2995                 mtd->name = p->model;
2996
2997         mtd->writesize = le32_to_cpu(p->byte_per_page);
2998
2999         /*
3000          * pages_per_block and blocks_per_lun may not be a power-of-2 size
3001          * (don't ask me who thought of this...). MTD assumes that these
3002          * dimensions will be power-of-2, so just truncate the remaining area.
3003          */
3004         mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3005         mtd->erasesize *= mtd->writesize;
3006
3007         mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3008
3009         /* See erasesize comment */
3010         chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3011         chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3012         chip->bits_per_cell = p->bits_per_cell;
3013
3014         if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3015                 *busw = NAND_BUSWIDTH_16;
3016         else
3017                 *busw = 0;
3018
3019         if (p->ecc_bits != 0xff) {
3020                 chip->ecc_strength_ds = p->ecc_bits;
3021                 chip->ecc_step_ds = 512;
3022         } else if (chip->onfi_version >= 21 &&
3023                 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3024
3025                 /*
3026                  * The nand_flash_detect_ext_param_page() uses the
3027                  * Change Read Column command which maybe not supported
3028                  * by the chip->cmdfunc. So try to update the chip->cmdfunc
3029                  * now. We do not replace user supplied command function.
3030                  */
3031                 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3032                         chip->cmdfunc = nand_command_lp;
3033
3034                 /* The Extended Parameter Page is supported since ONFI 2.1. */
3035                 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3036                         pr_warn("Failed to detect ONFI extended param page\n");
3037         } else {
3038                 pr_warn("Could not retrieve ONFI ECC requirements\n");
3039         }
3040
3041         return 1;
3042 }
3043
3044 /*
3045  * nand_id_has_period - Check if an ID string has a given wraparound period
3046  * @id_data: the ID string
3047  * @arrlen: the length of the @id_data array
3048  * @period: the period of repitition
3049  *
3050  * Check if an ID string is repeated within a given sequence of bytes at
3051  * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3052  * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3053  * if the repetition has a period of @period; otherwise, returns zero.
3054  */
3055 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3056 {
3057         int i, j;
3058         for (i = 0; i < period; i++)
3059                 for (j = i + period; j < arrlen; j += period)
3060                         if (id_data[i] != id_data[j])
3061                                 return 0;
3062         return 1;
3063 }
3064
3065 /*
3066  * nand_id_len - Get the length of an ID string returned by CMD_READID
3067  * @id_data: the ID string
3068  * @arrlen: the length of the @id_data array
3069
3070  * Returns the length of the ID string, according to known wraparound/trailing
3071  * zero patterns. If no pattern exists, returns the length of the array.
3072  */
3073 static int nand_id_len(u8 *id_data, int arrlen)
3074 {
3075         int last_nonzero, period;
3076
3077         /* Find last non-zero byte */
3078         for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3079                 if (id_data[last_nonzero])
3080                         break;
3081
3082         /* All zeros */
3083         if (last_nonzero < 0)
3084                 return 0;
3085
3086         /* Calculate wraparound period */
3087         for (period = 1; period < arrlen; period++)
3088                 if (nand_id_has_period(id_data, arrlen, period))
3089                         break;
3090
3091         /* There's a repeated pattern */
3092         if (period < arrlen)
3093                 return period;
3094
3095         /* There are trailing zeros */
3096         if (last_nonzero < arrlen - 1)
3097                 return last_nonzero + 1;
3098
3099         /* No pattern detected */
3100         return arrlen;
3101 }
3102
3103 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3104 static int nand_get_bits_per_cell(u8 cellinfo)
3105 {
3106         int bits;
3107
3108         bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3109         bits >>= NAND_CI_CELLTYPE_SHIFT;
3110         return bits + 1;
3111 }
3112
3113 /*
3114  * Many new NAND share similar device ID codes, which represent the size of the
3115  * chip. The rest of the parameters must be decoded according to generic or
3116  * manufacturer-specific "extended ID" decoding patterns.
3117  */
3118 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
3119                                 u8 id_data[8], int *busw)
3120 {
3121         int extid, id_len;
3122         /* The 3rd id byte holds MLC / multichip data */
3123         chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3124         /* The 4th id byte is the important one */
3125         extid = id_data[3];
3126
3127         id_len = nand_id_len(id_data, 8);
3128
3129         /*
3130          * Field definitions are in the following datasheets:
3131          * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
3132          * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
3133          * Hynix MLC   (6 byte ID): Hynix H27UBG8T2B (p.22)
3134          *
3135          * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
3136          * ID to decide what to do.
3137          */
3138         if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
3139                         !nand_is_slc(chip) && id_data[5] != 0x00) {
3140                 /* Calc pagesize */
3141                 mtd->writesize = 2048 << (extid & 0x03);
3142                 extid >>= 2;
3143                 /* Calc oobsize */
3144                 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3145                 case 1:
3146                         mtd->oobsize = 128;
3147                         break;
3148                 case 2:
3149                         mtd->oobsize = 218;
3150                         break;
3151                 case 3:
3152                         mtd->oobsize = 400;
3153                         break;
3154                 case 4:
3155                         mtd->oobsize = 436;
3156                         break;
3157                 case 5:
3158                         mtd->oobsize = 512;
3159                         break;
3160                 case 6:
3161                 default: /* Other cases are "reserved" (unknown) */
3162                         mtd->oobsize = 640;
3163                         break;
3164                 }
3165                 extid >>= 2;
3166                 /* Calc blocksize */
3167                 mtd->erasesize = (128 * 1024) <<
3168                         (((extid >> 1) & 0x04) | (extid & 0x03));
3169                 *busw = 0;
3170         } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
3171                         !nand_is_slc(chip)) {
3172                 unsigned int tmp;
3173
3174                 /* Calc pagesize */
3175                 mtd->writesize = 2048 << (extid & 0x03);
3176                 extid >>= 2;
3177                 /* Calc oobsize */
3178                 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3179                 case 0:
3180                         mtd->oobsize = 128;
3181                         break;
3182                 case 1:
3183                         mtd->oobsize = 224;
3184                         break;
3185                 case 2:
3186                         mtd->oobsize = 448;
3187                         break;
3188                 case 3:
3189                         mtd->oobsize = 64;
3190                         break;
3191                 case 4:
3192                         mtd->oobsize = 32;
3193                         break;
3194                 case 5:
3195                         mtd->oobsize = 16;
3196                         break;
3197                 default:
3198                         mtd->oobsize = 640;
3199                         break;
3200                 }
3201                 extid >>= 2;
3202                 /* Calc blocksize */
3203                 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
3204                 if (tmp < 0x03)
3205                         mtd->erasesize = (128 * 1024) << tmp;
3206                 else if (tmp == 0x03)
3207                         mtd->erasesize = 768 * 1024;
3208                 else
3209                         mtd->erasesize = (64 * 1024) << tmp;
3210                 *busw = 0;
3211         } else {
3212                 /* Calc pagesize */
3213                 mtd->writesize = 1024 << (extid & 0x03);
3214                 extid >>= 2;
3215                 /* Calc oobsize */
3216                 mtd->oobsize = (8 << (extid & 0x01)) *
3217                         (mtd->writesize >> 9);
3218                 extid >>= 2;
3219                 /* Calc blocksize. Blocksize is multiples of 64KiB */
3220                 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3221                 extid >>= 2;
3222                 /* Get buswidth information */
3223                 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
3224
3225                 /*
3226                  * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
3227                  * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
3228                  * follows:
3229                  * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
3230                  *                         110b -> 24nm
3231                  * - ID byte 5, bit[7]:    1 -> BENAND, 0 -> raw SLC
3232                  */
3233                 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
3234                                 nand_is_slc(chip) &&
3235                                 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
3236                                 !(id_data[4] & 0x80) /* !BENAND */) {
3237                         mtd->oobsize = 32 * mtd->writesize >> 9;
3238                 }
3239
3240         }
3241 }
3242
3243 /*
3244  * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3245  * decodes a matching ID table entry and assigns the MTD size parameters for
3246  * the chip.
3247  */
3248 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
3249                                 struct nand_flash_dev *type, u8 id_data[8],
3250                                 int *busw)
3251 {
3252         int maf_id = id_data[0];
3253
3254         mtd->erasesize = type->erasesize;
3255         mtd->writesize = type->pagesize;
3256         mtd->oobsize = mtd->writesize / 32;
3257         *busw = type->options & NAND_BUSWIDTH_16;
3258
3259         /* All legacy ID NAND are small-page, SLC */
3260         chip->bits_per_cell = 1;
3261
3262         /*
3263          * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3264          * some Spansion chips have erasesize that conflicts with size
3265          * listed in nand_ids table.
3266          * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3267          */
3268         if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
3269                         && id_data[6] == 0x00 && id_data[7] == 0x00
3270                         && mtd->writesize == 512) {
3271                 mtd->erasesize = 128 * 1024;
3272                 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3273         }
3274 }
3275
3276 /*
3277  * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3278  * heuristic patterns using various detected parameters (e.g., manufacturer,
3279  * page size, cell-type information).
3280  */
3281 static void nand_decode_bbm_options(struct mtd_info *mtd,
3282                                     struct nand_chip *chip, u8 id_data[8])
3283 {
3284         int maf_id = id_data[0];
3285
3286         /* Set the bad block position */
3287         if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3288                 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3289         else
3290                 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3291
3292         /*
3293          * Bad block marker is stored in the last page of each block on Samsung
3294          * and Hynix MLC devices; stored in first two pages of each block on
3295          * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
3296          * AMD/Spansion, and Macronix.  All others scan only the first page.
3297          */
3298         if (!nand_is_slc(chip) &&
3299                         (maf_id == NAND_MFR_SAMSUNG ||
3300                          maf_id == NAND_MFR_HYNIX))
3301                 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
3302         else if ((nand_is_slc(chip) &&
3303                                 (maf_id == NAND_MFR_SAMSUNG ||
3304                                  maf_id == NAND_MFR_HYNIX ||
3305                                  maf_id == NAND_MFR_TOSHIBA ||
3306                                  maf_id == NAND_MFR_AMD ||
3307                                  maf_id == NAND_MFR_MACRONIX)) ||
3308                         (mtd->writesize == 2048 &&
3309                          maf_id == NAND_MFR_MICRON))
3310                 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
3311 }
3312
3313 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3314 {
3315         return type->id_len;
3316 }
3317
3318 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
3319                    struct nand_flash_dev *type, u8 *id_data, int *busw)
3320 {
3321         if (!strncmp(type->id, id_data, type->id_len)) {
3322                 mtd->writesize = type->pagesize;
3323                 mtd->erasesize = type->erasesize;
3324                 mtd->oobsize = type->oobsize;
3325
3326                 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3327                 chip->chipsize = (uint64_t)type->chipsize << 20;
3328                 chip->options |= type->options;
3329                 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3330                 chip->ecc_step_ds = NAND_ECC_STEP(type);
3331
3332                 *busw = type->options & NAND_BUSWIDTH_16;
3333
3334                 return true;
3335         }
3336         return false;
3337 }
3338
3339 /*
3340  * Get the flash and manufacturer id and lookup if the type is supported.
3341  */
3342 static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
3343                                                   struct nand_chip *chip,
3344                                                   int busw,
3345                                                   int *maf_id, int *dev_id,
3346                                                   struct nand_flash_dev *type)
3347 {
3348         int i, maf_idx;
3349         u8 id_data[8];
3350
3351         /* Select the device */
3352         chip->select_chip(mtd, 0);
3353
3354         /*
3355          * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3356          * after power-up.
3357          */
3358         chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
3359
3360         /* Send the command for reading device ID */
3361         chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3362
3363         /* Read manufacturer and device IDs */
3364         *maf_id = chip->read_byte(mtd);
3365         *dev_id = chip->read_byte(mtd);
3366
3367         /*
3368          * Try again to make sure, as some systems the bus-hold or other
3369          * interface concerns can cause random data which looks like a
3370          * possibly credible NAND flash to appear. If the two results do
3371          * not match, ignore the device completely.
3372          */
3373
3374         chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3375
3376         /* Read entire ID string */
3377         for (i = 0; i < 8; i++)
3378                 id_data[i] = chip->read_byte(mtd);
3379
3380         if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
3381                 pr_info("%s: second ID read did not match "
3382                         "%02x,%02x against %02x,%02x\n", __func__,
3383                         *maf_id, *dev_id, id_data[0], id_data[1]);
3384                 return ERR_PTR(-ENODEV);
3385         }
3386
3387         if (!type)
3388                 type = nand_flash_ids;
3389
3390         for (; type->name != NULL; type++) {
3391                 if (is_full_id_nand(type)) {
3392                         if (find_full_id_nand(mtd, chip, type, id_data, &busw))
3393                                 goto ident_done;
3394                 } else if (*dev_id == type->dev_id) {
3395                                 break;
3396                 }
3397         }
3398
3399         chip->onfi_version = 0;
3400         if (!type->name || !type->pagesize) {
3401                 /* Check is chip is ONFI compliant */
3402                 if (nand_flash_detect_onfi(mtd, chip, &busw))
3403                         goto ident_done;
3404         }
3405
3406         if (!type->name)
3407                 return ERR_PTR(-ENODEV);
3408
3409         if (!mtd->name)
3410                 mtd->name = type->name;
3411
3412         chip->chipsize = (uint64_t)type->chipsize << 20;
3413
3414         if (!type->pagesize && chip->init_size) {
3415                 /* Set the pagesize, oobsize, erasesize by the driver */
3416                 busw = chip->init_size(mtd, chip, id_data);
3417         } else if (!type->pagesize) {
3418                 /* Decode parameters from extended ID */
3419                 nand_decode_ext_id(mtd, chip, id_data, &busw);
3420         } else {
3421                 nand_decode_id(mtd, chip, type, id_data, &busw);
3422         }
3423         /* Get chip options */
3424         chip->options |= type->options;
3425
3426         /*
3427          * Check if chip is not a Samsung device. Do not clear the
3428          * options for chips which do not have an extended id.
3429          */
3430         if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
3431                 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
3432 ident_done:
3433
3434         /* Try to identify manufacturer */
3435         for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
3436                 if (nand_manuf_ids[maf_idx].id == *maf_id)
3437                         break;
3438         }
3439
3440         if (chip->options & NAND_BUSWIDTH_AUTO) {
3441                 WARN_ON(chip->options & NAND_BUSWIDTH_16);
3442                 chip->options |= busw;
3443                 nand_set_defaults(chip, busw);
3444         } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
3445                 /*
3446                  * Check, if buswidth is correct. Hardware drivers should set
3447                  * chip correct!
3448                  */
3449                 pr_info("NAND device: Manufacturer ID:"
3450                         " 0x%02x, Chip ID: 0x%02x (%s %s)\n", *maf_id,
3451                         *dev_id, nand_manuf_ids[maf_idx].name, mtd->name);
3452                 pr_warn("NAND bus width %d instead %d bit\n",
3453                            (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
3454                            busw ? 16 : 8);
3455                 return ERR_PTR(-EINVAL);
3456         }
3457
3458         nand_decode_bbm_options(mtd, chip, id_data);
3459
3460         /* Calculate the address shift from the page size */
3461         chip->page_shift = ffs(mtd->writesize) - 1;
3462         /* Convert chipsize to number of pages per chip -1 */
3463         chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
3464
3465         chip->bbt_erase_shift = chip->phys_erase_shift =
3466                 ffs(mtd->erasesize) - 1;
3467         if (chip->chipsize & 0xffffffff)
3468                 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
3469         else {
3470                 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
3471                 chip->chip_shift += 32 - 1;
3472         }
3473
3474         chip->badblockbits = 8;
3475         chip->erase_cmd = single_erase_cmd;
3476
3477         /* Do not replace user supplied command function! */
3478         if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3479                 chip->cmdfunc = nand_command_lp;
3480
3481         pr_info("NAND device: Manufacturer ID: 0x%02x, Chip ID: 0x%02x (%s %s)\n",
3482                 *maf_id, *dev_id, nand_manuf_ids[maf_idx].name,
3483                 chip->onfi_version ? chip->onfi_params.model : type->name);
3484
3485         pr_info("NAND device: %dMiB, %s, page size: %d, OOB size: %d\n",
3486                 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
3487                 mtd->writesize, mtd->oobsize);
3488
3489         return type;
3490 }
3491
3492 /**
3493  * nand_scan_ident - [NAND Interface] Scan for the NAND device
3494  * @mtd: MTD device structure
3495  * @maxchips: number of chips to scan for
3496  * @table: alternative NAND ID table
3497  *
3498  * This is the first phase of the normal nand_scan() function. It reads the
3499  * flash ID and sets up MTD fields accordingly.
3500  *
3501  * The mtd->owner field must be set to the module of the caller.
3502  */
3503 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
3504                     struct nand_flash_dev *table)
3505 {
3506         int i, busw, nand_maf_id, nand_dev_id;
3507         struct nand_chip *chip = mtd->priv;
3508         struct nand_flash_dev *type;
3509
3510         /* Get buswidth to select the correct functions */
3511         busw = chip->options & NAND_BUSWIDTH_16;
3512         /* Set the default functions */
3513         nand_set_defaults(chip, busw);
3514
3515         /* Read the flash type */
3516         type = nand_get_flash_type(mtd, chip, busw,
3517                                 &nand_maf_id, &nand_dev_id, table);
3518
3519         if (IS_ERR(type)) {
3520                 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
3521                         pr_warn("No NAND device found\n");
3522                 chip->select_chip(mtd, -1);
3523                 return PTR_ERR(type);
3524         }
3525
3526         chip->select_chip(mtd, -1);
3527
3528         /* Check for a chip array */
3529         for (i = 1; i < maxchips; i++) {
3530                 chip->select_chip(mtd, i);
3531                 /* See comment in nand_get_flash_type for reset */
3532                 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
3533                 /* Send the command for reading device ID */
3534                 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3535                 /* Read manufacturer and device IDs */
3536                 if (nand_maf_id != chip->read_byte(mtd) ||
3537                     nand_dev_id != chip->read_byte(mtd)) {
3538                         chip->select_chip(mtd, -1);
3539                         break;
3540                 }
3541                 chip->select_chip(mtd, -1);
3542         }
3543         if (i > 1)
3544                 pr_info("%d NAND chips detected\n", i);
3545
3546         /* Store the number of chips and calc total size for mtd */
3547         chip->numchips = i;
3548         mtd->size = i * chip->chipsize;
3549
3550         return 0;
3551 }
3552 EXPORT_SYMBOL(nand_scan_ident);
3553
3554
3555 /**
3556  * nand_scan_tail - [NAND Interface] Scan for the NAND device
3557  * @mtd: MTD device structure
3558  *
3559  * This is the second phase of the normal nand_scan() function. It fills out
3560  * all the uninitialized function pointers with the defaults and scans for a
3561  * bad block table if appropriate.
3562  */
3563 int nand_scan_tail(struct mtd_info *mtd)
3564 {
3565         int i;
3566         struct nand_chip *chip = mtd->priv;
3567
3568         /* New bad blocks should be marked in OOB, flash-based BBT, or both */
3569         BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
3570                         !(chip->bbt_options & NAND_BBT_USE_FLASH));
3571
3572         if (!(chip->options & NAND_OWN_BUFFERS))
3573                 chip->buffers = kmalloc(sizeof(*chip->buffers), GFP_KERNEL);
3574         if (!chip->buffers)
3575                 return -ENOMEM;
3576
3577         /* Set the internal oob buffer location, just after the page data */
3578         chip->oob_poi = chip->buffers->databuf + mtd->writesize;
3579
3580         /*
3581          * If no default placement scheme is given, select an appropriate one.
3582          */
3583         if (!chip->ecc.layout && (chip->ecc.mode != NAND_ECC_SOFT_BCH)) {
3584                 switch (mtd->oobsize) {
3585                 case 8:
3586                         chip->ecc.layout = &nand_oob_8;
3587                         break;
3588                 case 16:
3589                         chip->ecc.layout = &nand_oob_16;
3590                         break;
3591                 case 64:
3592                         chip->ecc.layout = &nand_oob_64;
3593                         break;
3594                 case 128:
3595                         chip->ecc.layout = &nand_oob_128;
3596                         break;
3597                 default:
3598                         pr_warn("No oob scheme defined for oobsize %d\n",
3599                                    mtd->oobsize);
3600                         BUG();
3601                 }
3602         }
3603
3604         if (!chip->write_page)
3605                 chip->write_page = nand_write_page;
3606
3607         /*
3608          * Check ECC mode, default to software if 3byte/512byte hardware ECC is
3609          * selected and we have 256 byte pagesize fallback to software ECC
3610          */
3611
3612         switch (chip->ecc.mode) {
3613         case NAND_ECC_HW_OOB_FIRST:
3614                 /* Similar to NAND_ECC_HW, but a separate read_page handle */
3615                 if (!chip->ecc.calculate || !chip->ecc.correct ||
3616                      !chip->ecc.hwctl) {
3617                         pr_warn("No ECC functions supplied; "
3618                                    "hardware ECC not possible\n");
3619                         BUG();
3620                 }
3621                 if (!chip->ecc.read_page)
3622                         chip->ecc.read_page = nand_read_page_hwecc_oob_first;
3623
3624         case NAND_ECC_HW:
3625                 /* Use standard hwecc read page function? */
3626                 if (!chip->ecc.read_page)
3627                         chip->ecc.read_page = nand_read_page_hwecc;
3628                 if (!chip->ecc.write_page)
3629                         chip->ecc.write_page = nand_write_page_hwecc;
3630                 if (!chip->ecc.read_page_raw)
3631                         chip->ecc.read_page_raw = nand_read_page_raw;
3632                 if (!chip->ecc.write_page_raw)
3633                         chip->ecc.write_page_raw = nand_write_page_raw;
3634                 if (!chip->ecc.read_oob)
3635                         chip->ecc.read_oob = nand_read_oob_std;
3636                 if (!chip->ecc.write_oob)
3637                         chip->ecc.write_oob = nand_write_oob_std;
3638                 if (!chip->ecc.read_subpage)
3639                         chip->ecc.read_subpage = nand_read_subpage;
3640                 if (!chip->ecc.write_subpage)
3641                         chip->ecc.write_subpage = nand_write_subpage_hwecc;
3642
3643         case NAND_ECC_HW_SYNDROME:
3644                 if ((!chip->ecc.calculate || !chip->ecc.correct ||
3645                      !chip->ecc.hwctl) &&
3646                     (!chip->ecc.read_page ||
3647                      chip->ecc.read_page == nand_read_page_hwecc ||
3648                      !chip->ecc.write_page ||
3649                      chip->ecc.write_page == nand_write_page_hwecc)) {
3650                         pr_warn("No ECC functions supplied; "
3651                                    "hardware ECC not possible\n");
3652                         BUG();
3653                 }
3654                 /* Use standard syndrome read/write page function? */
3655                 if (!chip->ecc.read_page)
3656                         chip->ecc.read_page = nand_read_page_syndrome;
3657                 if (!chip->ecc.write_page)
3658                         chip->ecc.write_page = nand_write_page_syndrome;
3659                 if (!chip->ecc.read_page_raw)
3660                         chip->ecc.read_page_raw = nand_read_page_raw_syndrome;
3661                 if (!chip->ecc.write_page_raw)
3662                         chip->ecc.write_page_raw = nand_write_page_raw_syndrome;
3663                 if (!chip->ecc.read_oob)
3664                         chip->ecc.read_oob = nand_read_oob_syndrome;
3665                 if (!chip->ecc.write_oob)
3666                         chip->ecc.write_oob = nand_write_oob_syndrome;
3667
3668                 if (mtd->writesize >= chip->ecc.size) {
3669                         if (!chip->ecc.strength) {
3670                                 pr_warn("Driver must set ecc.strength when using hardware ECC\n");
3671                                 BUG();
3672                         }
3673                         break;
3674                 }
3675                 pr_warn("%d byte HW ECC not possible on "
3676                            "%d byte page size, fallback to SW ECC\n",
3677                            chip->ecc.size, mtd->writesize);
3678                 chip->ecc.mode = NAND_ECC_SOFT;
3679
3680         case NAND_ECC_SOFT:
3681                 chip->ecc.calculate = nand_calculate_ecc;
3682                 chip->ecc.correct = nand_correct_data;
3683                 chip->ecc.read_page = nand_read_page_swecc;
3684                 chip->ecc.read_subpage = nand_read_subpage;
3685                 chip->ecc.write_page = nand_write_page_swecc;
3686                 chip->ecc.read_page_raw = nand_read_page_raw;
3687                 chip->ecc.write_page_raw = nand_write_page_raw;
3688                 chip->ecc.read_oob = nand_read_oob_std;
3689                 chip->ecc.write_oob = nand_write_oob_std;
3690                 if (!chip->ecc.size)
3691                         chip->ecc.size = 256;
3692                 chip->ecc.bytes = 3;
3693                 chip->ecc.strength = 1;
3694                 break;
3695
3696         case NAND_ECC_SOFT_BCH:
3697                 if (!mtd_nand_has_bch()) {
3698                         pr_warn("CONFIG_MTD_ECC_BCH not enabled\n");
3699                         BUG();
3700                 }
3701                 chip->ecc.calculate = nand_bch_calculate_ecc;
3702                 chip->ecc.correct = nand_bch_correct_data;
3703                 chip->ecc.read_page = nand_read_page_swecc;
3704                 chip->ecc.read_subpage = nand_read_subpage;
3705                 chip->ecc.write_page = nand_write_page_swecc;
3706                 chip->ecc.read_page_raw = nand_read_page_raw;
3707                 chip->ecc.write_page_raw = nand_write_page_raw;
3708                 chip->ecc.read_oob = nand_read_oob_std;
3709                 chip->ecc.write_oob = nand_write_oob_std;
3710                 /*
3711                  * Board driver should supply ecc.size and ecc.bytes values to
3712                  * select how many bits are correctable; see nand_bch_init()
3713                  * for details. Otherwise, default to 4 bits for large page
3714                  * devices.
3715                  */
3716                 if (!chip->ecc.size && (mtd->oobsize >= 64)) {
3717                         chip->ecc.size = 512;
3718                         chip->ecc.bytes = 7;
3719                 }
3720                 chip->ecc.priv = nand_bch_init(mtd,
3721                                                chip->ecc.size,
3722                                                chip->ecc.bytes,
3723                                                &chip->ecc.layout);
3724                 if (!chip->ecc.priv) {
3725                         pr_warn("BCH ECC initialization failed!\n");
3726                         BUG();
3727                 }
3728                 chip->ecc.strength =
3729                         chip->ecc.bytes * 8 / fls(8 * chip->ecc.size);
3730                 break;
3731
3732         case NAND_ECC_NONE:
3733                 pr_warn("NAND_ECC_NONE selected by board driver. "
3734                            "This is not recommended!\n");
3735                 chip->ecc.read_page = nand_read_page_raw;
3736                 chip->ecc.write_page = nand_write_page_raw;
3737                 chip->ecc.read_oob = nand_read_oob_std;
3738                 chip->ecc.read_page_raw = nand_read_page_raw;
3739                 chip->ecc.write_page_raw = nand_write_page_raw;
3740                 chip->ecc.write_oob = nand_write_oob_std;
3741                 chip->ecc.size = mtd->writesize;
3742                 chip->ecc.bytes = 0;
3743                 chip->ecc.strength = 0;
3744                 break;
3745
3746         default:
3747                 pr_warn("Invalid NAND_ECC_MODE %d\n", chip->ecc.mode);
3748                 BUG();
3749         }
3750
3751         /* For many systems, the standard OOB write also works for raw */
3752         if (!chip->ecc.read_oob_raw)
3753                 chip->ecc.read_oob_raw = chip->ecc.read_oob;
3754         if (!chip->ecc.write_oob_raw)
3755                 chip->ecc.write_oob_raw = chip->ecc.write_oob;
3756
3757         /*
3758          * The number of bytes available for a client to place data into
3759          * the out of band area.
3760          */
3761         chip->ecc.layout->oobavail = 0;
3762         for (i = 0; chip->ecc.layout->oobfree[i].length
3763                         && i < ARRAY_SIZE(chip->ecc.layout->oobfree); i++)
3764                 chip->ecc.layout->oobavail +=
3765                         chip->ecc.layout->oobfree[i].length;
3766         mtd->oobavail = chip->ecc.layout->oobavail;
3767
3768         /*
3769          * Set the number of read / write steps for one page depending on ECC
3770          * mode.
3771          */
3772         chip->ecc.steps = mtd->writesize / chip->ecc.size;
3773         if (chip->ecc.steps * chip->ecc.size != mtd->writesize) {
3774                 pr_warn("Invalid ECC parameters\n");
3775                 BUG();
3776         }
3777         chip->ecc.total = chip->ecc.steps * chip->ecc.bytes;
3778
3779         /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
3780         if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
3781                 switch (chip->ecc.steps) {
3782                 case 2:
3783                         mtd->subpage_sft = 1;
3784                         break;
3785                 case 4:
3786                 case 8:
3787                 case 16:
3788                         mtd->subpage_sft = 2;
3789                         break;
3790                 }
3791         }
3792         chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
3793
3794         /* Initialize state */
3795         chip->state = FL_READY;
3796
3797         /* Invalidate the pagebuffer reference */
3798         chip->pagebuf = -1;
3799
3800         /* Large page NAND with SOFT_ECC should support subpage reads */
3801         if ((chip->ecc.mode == NAND_ECC_SOFT) && (chip->page_shift > 9))
3802                 chip->options |= NAND_SUBPAGE_READ;
3803
3804         /* Fill in remaining MTD driver data */
3805         mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
3806         mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
3807                                                 MTD_CAP_NANDFLASH;
3808         mtd->_erase = nand_erase;
3809         mtd->_point = NULL;
3810         mtd->_unpoint = NULL;
3811         mtd->_read = nand_read;
3812         mtd->_write = nand_write;
3813         mtd->_panic_write = panic_nand_write;
3814         mtd->_read_oob = nand_read_oob;
3815         mtd->_write_oob = nand_write_oob;
3816         mtd->_sync = nand_sync;
3817         mtd->_lock = NULL;
3818         mtd->_unlock = NULL;
3819         mtd->_suspend = nand_suspend;
3820         mtd->_resume = nand_resume;
3821         mtd->_block_isbad = nand_block_isbad;
3822         mtd->_block_markbad = nand_block_markbad;
3823         mtd->writebufsize = mtd->writesize;
3824
3825         /* propagate ecc info to mtd_info */
3826         mtd->ecclayout = chip->ecc.layout;
3827         mtd->ecc_strength = chip->ecc.strength;
3828         mtd->ecc_step_size = chip->ecc.size;
3829         /*
3830          * Initialize bitflip_threshold to its default prior scan_bbt() call.
3831          * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
3832          * properly set.
3833          */
3834         if (!mtd->bitflip_threshold)
3835                 mtd->bitflip_threshold = mtd->ecc_strength;
3836
3837         /* Check, if we should skip the bad block table scan */
3838         if (chip->options & NAND_SKIP_BBTSCAN)
3839                 return 0;
3840
3841         /* Build bad block table */
3842         return chip->scan_bbt(mtd);
3843 }
3844 EXPORT_SYMBOL(nand_scan_tail);
3845
3846 /*
3847  * is_module_text_address() isn't exported, and it's mostly a pointless
3848  * test if this is a module _anyway_ -- they'd have to try _really_ hard
3849  * to call us from in-kernel code if the core NAND support is modular.
3850  */
3851 #ifdef MODULE
3852 #define caller_is_module() (1)
3853 #else
3854 #define caller_is_module() \
3855         is_module_text_address((unsigned long)__builtin_return_address(0))
3856 #endif
3857
3858 /**
3859  * nand_scan - [NAND Interface] Scan for the NAND device
3860  * @mtd: MTD device structure
3861  * @maxchips: number of chips to scan for
3862  *
3863  * This fills out all the uninitialized function pointers with the defaults.
3864  * The flash ID is read and the mtd/chip structures are filled with the
3865  * appropriate values. The mtd->owner field must be set to the module of the
3866  * caller.
3867  */
3868 int nand_scan(struct mtd_info *mtd, int maxchips)
3869 {
3870         int ret;
3871
3872         /* Many callers got this wrong, so check for it for a while... */
3873         if (!mtd->owner && caller_is_module()) {
3874                 pr_crit("%s called with NULL mtd->owner!\n", __func__);
3875                 BUG();
3876         }
3877
3878         ret = nand_scan_ident(mtd, maxchips, NULL);
3879         if (!ret)
3880                 ret = nand_scan_tail(mtd);
3881         return ret;
3882 }
3883 EXPORT_SYMBOL(nand_scan);
3884
3885 /**
3886  * nand_release - [NAND Interface] Free resources held by the NAND device
3887  * @mtd: MTD device structure
3888  */
3889 void nand_release(struct mtd_info *mtd)
3890 {
3891         struct nand_chip *chip = mtd->priv;
3892
3893         if (chip->ecc.mode == NAND_ECC_SOFT_BCH)
3894                 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
3895
3896         mtd_device_unregister(mtd);
3897
3898         /* Free bad block table memory */
3899         kfree(chip->bbt);
3900         if (!(chip->options & NAND_OWN_BUFFERS))
3901                 kfree(chip->buffers);
3902
3903         /* Free bad block descriptor memory */
3904         if (chip->badblock_pattern && chip->badblock_pattern->options
3905                         & NAND_BBT_DYNAMICSTRUCT)
3906                 kfree(chip->badblock_pattern);
3907 }
3908 EXPORT_SYMBOL_GPL(nand_release);
3909
3910 static int __init nand_base_init(void)
3911 {
3912         led_trigger_register_simple("nand-disk", &nand_led_trigger);
3913         return 0;
3914 }
3915
3916 static void __exit nand_base_exit(void)
3917 {
3918         led_trigger_unregister_simple(nand_led_trigger);
3919 }
3920
3921 module_init(nand_base_init);
3922 module_exit(nand_base_exit);
3923
3924 MODULE_LICENSE("GPL");
3925 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
3926 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
3927 MODULE_DESCRIPTION("Generic NAND flash driver code");