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