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