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