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