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