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