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