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