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