mtd: rawnand: Use nanddev_get/set_ecc_requirements() when relevant
[linux-2.6-microblaze.git] / drivers / mtd / nand / raw / nand_base.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  Overview:
4  *   This is the generic MTD driver for NAND flash devices. It should be
5  *   capable of working with almost all NAND chips currently available.
6  *
7  *      Additional technical information is available on
8  *      http://www.linux-mtd.infradead.org/doc/nand.html
9  *
10  *  Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
11  *                2002-2006 Thomas Gleixner (tglx@linutronix.de)
12  *
13  *  Credits:
14  *      David Woodhouse for adding multichip support
15  *
16  *      Aleph One Ltd. and Toby Churchill Ltd. for supporting the
17  *      rework for 2K page size chips
18  *
19  *  TODO:
20  *      Enable cached programming for 2k page size chips
21  *      Check, if mtd->ecctype should be set to MTD_ECC_HW
22  *      if we have HW ECC support.
23  *      BBT table is not serialized, has to be fixed
24  */
25
26 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
27
28 #include <linux/module.h>
29 #include <linux/delay.h>
30 #include <linux/errno.h>
31 #include <linux/err.h>
32 #include <linux/sched.h>
33 #include <linux/slab.h>
34 #include <linux/mm.h>
35 #include <linux/types.h>
36 #include <linux/mtd/mtd.h>
37 #include <linux/mtd/nand_ecc.h>
38 #include <linux/mtd/nand_bch.h>
39 #include <linux/interrupt.h>
40 #include <linux/bitops.h>
41 #include <linux/io.h>
42 #include <linux/mtd/partitions.h>
43 #include <linux/of.h>
44 #include <linux/gpio/consumer.h>
45
46 #include "internals.h"
47
48 /* Define default oob placement schemes for large and small page devices */
49 static int nand_ooblayout_ecc_sp(struct mtd_info *mtd, int section,
50                                  struct mtd_oob_region *oobregion)
51 {
52         struct nand_chip *chip = mtd_to_nand(mtd);
53         struct nand_ecc_ctrl *ecc = &chip->ecc;
54
55         if (section > 1)
56                 return -ERANGE;
57
58         if (!section) {
59                 oobregion->offset = 0;
60                 if (mtd->oobsize == 16)
61                         oobregion->length = 4;
62                 else
63                         oobregion->length = 3;
64         } else {
65                 if (mtd->oobsize == 8)
66                         return -ERANGE;
67
68                 oobregion->offset = 6;
69                 oobregion->length = ecc->total - 4;
70         }
71
72         return 0;
73 }
74
75 static int nand_ooblayout_free_sp(struct mtd_info *mtd, int section,
76                                   struct mtd_oob_region *oobregion)
77 {
78         if (section > 1)
79                 return -ERANGE;
80
81         if (mtd->oobsize == 16) {
82                 if (section)
83                         return -ERANGE;
84
85                 oobregion->length = 8;
86                 oobregion->offset = 8;
87         } else {
88                 oobregion->length = 2;
89                 if (!section)
90                         oobregion->offset = 3;
91                 else
92                         oobregion->offset = 6;
93         }
94
95         return 0;
96 }
97
98 const struct mtd_ooblayout_ops nand_ooblayout_sp_ops = {
99         .ecc = nand_ooblayout_ecc_sp,
100         .free = nand_ooblayout_free_sp,
101 };
102 EXPORT_SYMBOL_GPL(nand_ooblayout_sp_ops);
103
104 static int nand_ooblayout_ecc_lp(struct mtd_info *mtd, int section,
105                                  struct mtd_oob_region *oobregion)
106 {
107         struct nand_chip *chip = mtd_to_nand(mtd);
108         struct nand_ecc_ctrl *ecc = &chip->ecc;
109
110         if (section || !ecc->total)
111                 return -ERANGE;
112
113         oobregion->length = ecc->total;
114         oobregion->offset = mtd->oobsize - oobregion->length;
115
116         return 0;
117 }
118
119 static int nand_ooblayout_free_lp(struct mtd_info *mtd, int section,
120                                   struct mtd_oob_region *oobregion)
121 {
122         struct nand_chip *chip = mtd_to_nand(mtd);
123         struct nand_ecc_ctrl *ecc = &chip->ecc;
124
125         if (section)
126                 return -ERANGE;
127
128         oobregion->length = mtd->oobsize - ecc->total - 2;
129         oobregion->offset = 2;
130
131         return 0;
132 }
133
134 const struct mtd_ooblayout_ops nand_ooblayout_lp_ops = {
135         .ecc = nand_ooblayout_ecc_lp,
136         .free = nand_ooblayout_free_lp,
137 };
138 EXPORT_SYMBOL_GPL(nand_ooblayout_lp_ops);
139
140 /*
141  * Support the old "large page" layout used for 1-bit Hamming ECC where ECC
142  * are placed at a fixed offset.
143  */
144 static int nand_ooblayout_ecc_lp_hamming(struct mtd_info *mtd, int section,
145                                          struct mtd_oob_region *oobregion)
146 {
147         struct nand_chip *chip = mtd_to_nand(mtd);
148         struct nand_ecc_ctrl *ecc = &chip->ecc;
149
150         if (section)
151                 return -ERANGE;
152
153         switch (mtd->oobsize) {
154         case 64:
155                 oobregion->offset = 40;
156                 break;
157         case 128:
158                 oobregion->offset = 80;
159                 break;
160         default:
161                 return -EINVAL;
162         }
163
164         oobregion->length = ecc->total;
165         if (oobregion->offset + oobregion->length > mtd->oobsize)
166                 return -ERANGE;
167
168         return 0;
169 }
170
171 static int nand_ooblayout_free_lp_hamming(struct mtd_info *mtd, int section,
172                                           struct mtd_oob_region *oobregion)
173 {
174         struct nand_chip *chip = mtd_to_nand(mtd);
175         struct nand_ecc_ctrl *ecc = &chip->ecc;
176         int ecc_offset = 0;
177
178         if (section < 0 || section > 1)
179                 return -ERANGE;
180
181         switch (mtd->oobsize) {
182         case 64:
183                 ecc_offset = 40;
184                 break;
185         case 128:
186                 ecc_offset = 80;
187                 break;
188         default:
189                 return -EINVAL;
190         }
191
192         if (section == 0) {
193                 oobregion->offset = 2;
194                 oobregion->length = ecc_offset - 2;
195         } else {
196                 oobregion->offset = ecc_offset + ecc->total;
197                 oobregion->length = mtd->oobsize - oobregion->offset;
198         }
199
200         return 0;
201 }
202
203 static const struct mtd_ooblayout_ops nand_ooblayout_lp_hamming_ops = {
204         .ecc = nand_ooblayout_ecc_lp_hamming,
205         .free = nand_ooblayout_free_lp_hamming,
206 };
207
208 static int nand_pairing_dist3_get_info(struct mtd_info *mtd, int page,
209                                        struct mtd_pairing_info *info)
210 {
211         int lastpage = (mtd->erasesize / mtd->writesize) - 1;
212         int dist = 3;
213
214         if (page == lastpage)
215                 dist = 2;
216
217         if (!page || (page & 1)) {
218                 info->group = 0;
219                 info->pair = (page + 1) / 2;
220         } else {
221                 info->group = 1;
222                 info->pair = (page + 1 - dist) / 2;
223         }
224
225         return 0;
226 }
227
228 static int nand_pairing_dist3_get_wunit(struct mtd_info *mtd,
229                                         const struct mtd_pairing_info *info)
230 {
231         int lastpair = ((mtd->erasesize / mtd->writesize) - 1) / 2;
232         int page = info->pair * 2;
233         int dist = 3;
234
235         if (!info->group && !info->pair)
236                 return 0;
237
238         if (info->pair == lastpair && info->group)
239                 dist = 2;
240
241         if (!info->group)
242                 page--;
243         else if (info->pair)
244                 page += dist - 1;
245
246         if (page >= mtd->erasesize / mtd->writesize)
247                 return -EINVAL;
248
249         return page;
250 }
251
252 const struct mtd_pairing_scheme dist3_pairing_scheme = {
253         .ngroups = 2,
254         .get_info = nand_pairing_dist3_get_info,
255         .get_wunit = nand_pairing_dist3_get_wunit,
256 };
257
258 static int check_offs_len(struct nand_chip *chip, loff_t ofs, uint64_t len)
259 {
260         int ret = 0;
261
262         /* Start address must align on block boundary */
263         if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
264                 pr_debug("%s: unaligned address\n", __func__);
265                 ret = -EINVAL;
266         }
267
268         /* Length must align on block boundary */
269         if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
270                 pr_debug("%s: length not block aligned\n", __func__);
271                 ret = -EINVAL;
272         }
273
274         return ret;
275 }
276
277 /**
278  * nand_extract_bits - Copy unaligned bits from one buffer to another one
279  * @dst: destination buffer
280  * @dst_off: bit offset at which the writing starts
281  * @src: source buffer
282  * @src_off: bit offset at which the reading starts
283  * @nbits: number of bits to copy from @src to @dst
284  *
285  * Copy bits from one memory region to another (overlap authorized).
286  */
287 void nand_extract_bits(u8 *dst, unsigned int dst_off, const u8 *src,
288                        unsigned int src_off, unsigned int nbits)
289 {
290         unsigned int tmp, n;
291
292         dst += dst_off / 8;
293         dst_off %= 8;
294         src += src_off / 8;
295         src_off %= 8;
296
297         while (nbits) {
298                 n = min3(8 - dst_off, 8 - src_off, nbits);
299
300                 tmp = (*src >> src_off) & GENMASK(n - 1, 0);
301                 *dst &= ~GENMASK(n - 1 + dst_off, dst_off);
302                 *dst |= tmp << dst_off;
303
304                 dst_off += n;
305                 if (dst_off >= 8) {
306                         dst++;
307                         dst_off -= 8;
308                 }
309
310                 src_off += n;
311                 if (src_off >= 8) {
312                         src++;
313                         src_off -= 8;
314                 }
315
316                 nbits -= n;
317         }
318 }
319 EXPORT_SYMBOL_GPL(nand_extract_bits);
320
321 /**
322  * nand_select_target() - Select a NAND target (A.K.A. die)
323  * @chip: NAND chip object
324  * @cs: the CS line to select. Note that this CS id is always from the chip
325  *      PoV, not the controller one
326  *
327  * Select a NAND target so that further operations executed on @chip go to the
328  * selected NAND target.
329  */
330 void nand_select_target(struct nand_chip *chip, unsigned int cs)
331 {
332         /*
333          * cs should always lie between 0 and nanddev_ntargets(), when that's
334          * not the case it's a bug and the caller should be fixed.
335          */
336         if (WARN_ON(cs > nanddev_ntargets(&chip->base)))
337                 return;
338
339         chip->cur_cs = cs;
340
341         if (chip->legacy.select_chip)
342                 chip->legacy.select_chip(chip, cs);
343 }
344 EXPORT_SYMBOL_GPL(nand_select_target);
345
346 /**
347  * nand_deselect_target() - Deselect the currently selected target
348  * @chip: NAND chip object
349  *
350  * Deselect the currently selected NAND target. The result of operations
351  * executed on @chip after the target has been deselected is undefined.
352  */
353 void nand_deselect_target(struct nand_chip *chip)
354 {
355         if (chip->legacy.select_chip)
356                 chip->legacy.select_chip(chip, -1);
357
358         chip->cur_cs = -1;
359 }
360 EXPORT_SYMBOL_GPL(nand_deselect_target);
361
362 /**
363  * nand_release_device - [GENERIC] release chip
364  * @chip: NAND chip object
365  *
366  * Release chip lock and wake up anyone waiting on the device.
367  */
368 static void nand_release_device(struct nand_chip *chip)
369 {
370         /* Release the controller and the chip */
371         mutex_unlock(&chip->controller->lock);
372         mutex_unlock(&chip->lock);
373 }
374
375 /**
376  * nand_bbm_get_next_page - Get the next page for bad block markers
377  * @chip: NAND chip object
378  * @page: First page to start checking for bad block marker usage
379  *
380  * Returns an integer that corresponds to the page offset within a block, for
381  * a page that is used to store bad block markers. If no more pages are
382  * available, -EINVAL is returned.
383  */
384 int nand_bbm_get_next_page(struct nand_chip *chip, int page)
385 {
386         struct mtd_info *mtd = nand_to_mtd(chip);
387         int last_page = ((mtd->erasesize - mtd->writesize) >>
388                          chip->page_shift) & chip->pagemask;
389         unsigned int bbm_flags = NAND_BBM_FIRSTPAGE | NAND_BBM_SECONDPAGE
390                 | NAND_BBM_LASTPAGE;
391
392         if (page == 0 && !(chip->options & bbm_flags))
393                 return 0;
394         if (page == 0 && chip->options & NAND_BBM_FIRSTPAGE)
395                 return 0;
396         if (page <= 1 && chip->options & NAND_BBM_SECONDPAGE)
397                 return 1;
398         if (page <= last_page && chip->options & NAND_BBM_LASTPAGE)
399                 return last_page;
400
401         return -EINVAL;
402 }
403
404 /**
405  * nand_block_bad - [DEFAULT] Read bad block marker from the chip
406  * @chip: NAND chip object
407  * @ofs: offset from device start
408  *
409  * Check, if the block is bad.
410  */
411 static int nand_block_bad(struct nand_chip *chip, loff_t ofs)
412 {
413         int first_page, page_offset;
414         int res;
415         u8 bad;
416
417         first_page = (int)(ofs >> chip->page_shift) & chip->pagemask;
418         page_offset = nand_bbm_get_next_page(chip, 0);
419
420         while (page_offset >= 0) {
421                 res = chip->ecc.read_oob(chip, first_page + page_offset);
422                 if (res < 0)
423                         return res;
424
425                 bad = chip->oob_poi[chip->badblockpos];
426
427                 if (likely(chip->badblockbits == 8))
428                         res = bad != 0xFF;
429                 else
430                         res = hweight8(bad) < chip->badblockbits;
431                 if (res)
432                         return res;
433
434                 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
435         }
436
437         return 0;
438 }
439
440 static int nand_isbad_bbm(struct nand_chip *chip, loff_t ofs)
441 {
442         if (chip->options & NAND_NO_BBM_QUIRK)
443                 return 0;
444
445         if (chip->legacy.block_bad)
446                 return chip->legacy.block_bad(chip, ofs);
447
448         return nand_block_bad(chip, ofs);
449 }
450
451 /**
452  * nand_get_device - [GENERIC] Get chip for selected access
453  * @chip: NAND chip structure
454  *
455  * Lock the device and its controller for exclusive access
456  *
457  * Return: -EBUSY if the chip has been suspended, 0 otherwise
458  */
459 static int nand_get_device(struct nand_chip *chip)
460 {
461         mutex_lock(&chip->lock);
462         if (chip->suspended) {
463                 mutex_unlock(&chip->lock);
464                 return -EBUSY;
465         }
466         mutex_lock(&chip->controller->lock);
467
468         return 0;
469 }
470
471 /**
472  * nand_check_wp - [GENERIC] check if the chip is write protected
473  * @chip: NAND chip object
474  *
475  * Check, if the device is write protected. The function expects, that the
476  * device is already selected.
477  */
478 static int nand_check_wp(struct nand_chip *chip)
479 {
480         u8 status;
481         int ret;
482
483         /* Broken xD cards report WP despite being writable */
484         if (chip->options & NAND_BROKEN_XD)
485                 return 0;
486
487         /* Check the WP bit */
488         ret = nand_status_op(chip, &status);
489         if (ret)
490                 return ret;
491
492         return status & NAND_STATUS_WP ? 0 : 1;
493 }
494
495 /**
496  * nand_fill_oob - [INTERN] Transfer client buffer to oob
497  * @chip: NAND chip object
498  * @oob: oob data buffer
499  * @len: oob data write length
500  * @ops: oob ops structure
501  */
502 static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len,
503                               struct mtd_oob_ops *ops)
504 {
505         struct mtd_info *mtd = nand_to_mtd(chip);
506         int ret;
507
508         /*
509          * Initialise to all 0xFF, to avoid the possibility of left over OOB
510          * data from a previous OOB read.
511          */
512         memset(chip->oob_poi, 0xff, mtd->oobsize);
513
514         switch (ops->mode) {
515
516         case MTD_OPS_PLACE_OOB:
517         case MTD_OPS_RAW:
518                 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
519                 return oob + len;
520
521         case MTD_OPS_AUTO_OOB:
522                 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
523                                                   ops->ooboffs, len);
524                 BUG_ON(ret);
525                 return oob + len;
526
527         default:
528                 BUG();
529         }
530         return NULL;
531 }
532
533 /**
534  * nand_do_write_oob - [MTD Interface] NAND write out-of-band
535  * @chip: NAND chip object
536  * @to: offset to write to
537  * @ops: oob operation description structure
538  *
539  * NAND write out-of-band.
540  */
541 static int nand_do_write_oob(struct nand_chip *chip, loff_t to,
542                              struct mtd_oob_ops *ops)
543 {
544         struct mtd_info *mtd = nand_to_mtd(chip);
545         int chipnr, page, status, len, ret;
546
547         pr_debug("%s: to = 0x%08x, len = %i\n",
548                          __func__, (unsigned int)to, (int)ops->ooblen);
549
550         len = mtd_oobavail(mtd, ops);
551
552         /* Do not allow write past end of page */
553         if ((ops->ooboffs + ops->ooblen) > len) {
554                 pr_debug("%s: attempt to write past end of page\n",
555                                 __func__);
556                 return -EINVAL;
557         }
558
559         chipnr = (int)(to >> chip->chip_shift);
560
561         /*
562          * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
563          * of my DiskOnChip 2000 test units) will clear the whole data page too
564          * if we don't do this. I have no clue why, but I seem to have 'fixed'
565          * it in the doc2000 driver in August 1999.  dwmw2.
566          */
567         ret = nand_reset(chip, chipnr);
568         if (ret)
569                 return ret;
570
571         nand_select_target(chip, chipnr);
572
573         /* Shift to get page */
574         page = (int)(to >> chip->page_shift);
575
576         /* Check, if it is write protected */
577         if (nand_check_wp(chip)) {
578                 nand_deselect_target(chip);
579                 return -EROFS;
580         }
581
582         /* Invalidate the page cache, if we write to the cached page */
583         if (page == chip->pagecache.page)
584                 chip->pagecache.page = -1;
585
586         nand_fill_oob(chip, ops->oobbuf, ops->ooblen, ops);
587
588         if (ops->mode == MTD_OPS_RAW)
589                 status = chip->ecc.write_oob_raw(chip, page & chip->pagemask);
590         else
591                 status = chip->ecc.write_oob(chip, page & chip->pagemask);
592
593         nand_deselect_target(chip);
594
595         if (status)
596                 return status;
597
598         ops->oobretlen = ops->ooblen;
599
600         return 0;
601 }
602
603 /**
604  * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
605  * @chip: NAND chip object
606  * @ofs: offset from device start
607  *
608  * This is the default implementation, which can be overridden by a hardware
609  * specific driver. It provides the details for writing a bad block marker to a
610  * block.
611  */
612 static int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
613 {
614         struct mtd_info *mtd = nand_to_mtd(chip);
615         struct mtd_oob_ops ops;
616         uint8_t buf[2] = { 0, 0 };
617         int ret = 0, res, page_offset;
618
619         memset(&ops, 0, sizeof(ops));
620         ops.oobbuf = buf;
621         ops.ooboffs = chip->badblockpos;
622         if (chip->options & NAND_BUSWIDTH_16) {
623                 ops.ooboffs &= ~0x01;
624                 ops.len = ops.ooblen = 2;
625         } else {
626                 ops.len = ops.ooblen = 1;
627         }
628         ops.mode = MTD_OPS_PLACE_OOB;
629
630         page_offset = nand_bbm_get_next_page(chip, 0);
631
632         while (page_offset >= 0) {
633                 res = nand_do_write_oob(chip,
634                                         ofs + (page_offset * mtd->writesize),
635                                         &ops);
636
637                 if (!ret)
638                         ret = res;
639
640                 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
641         }
642
643         return ret;
644 }
645
646 /**
647  * nand_markbad_bbm - mark a block by updating the BBM
648  * @chip: NAND chip object
649  * @ofs: offset of the block to mark bad
650  */
651 int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
652 {
653         if (chip->legacy.block_markbad)
654                 return chip->legacy.block_markbad(chip, ofs);
655
656         return nand_default_block_markbad(chip, ofs);
657 }
658
659 /**
660  * nand_block_markbad_lowlevel - mark a block bad
661  * @chip: NAND chip object
662  * @ofs: offset from device start
663  *
664  * This function performs the generic NAND bad block marking steps (i.e., bad
665  * block table(s) and/or marker(s)). We only allow the hardware driver to
666  * specify how to write bad block markers to OOB (chip->legacy.block_markbad).
667  *
668  * We try operations in the following order:
669  *
670  *  (1) erase the affected block, to allow OOB marker to be written cleanly
671  *  (2) write bad block marker to OOB area of affected block (unless flag
672  *      NAND_BBT_NO_OOB_BBM is present)
673  *  (3) update the BBT
674  *
675  * Note that we retain the first error encountered in (2) or (3), finish the
676  * procedures, and dump the error in the end.
677 */
678 static int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
679 {
680         struct mtd_info *mtd = nand_to_mtd(chip);
681         int res, ret = 0;
682
683         if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
684                 struct erase_info einfo;
685
686                 /* Attempt erase before marking OOB */
687                 memset(&einfo, 0, sizeof(einfo));
688                 einfo.addr = ofs;
689                 einfo.len = 1ULL << chip->phys_erase_shift;
690                 nand_erase_nand(chip, &einfo, 0);
691
692                 /* Write bad block marker to OOB */
693                 ret = nand_get_device(chip);
694                 if (ret)
695                         return ret;
696
697                 ret = nand_markbad_bbm(chip, ofs);
698                 nand_release_device(chip);
699         }
700
701         /* Mark block bad in BBT */
702         if (chip->bbt) {
703                 res = nand_markbad_bbt(chip, ofs);
704                 if (!ret)
705                         ret = res;
706         }
707
708         if (!ret)
709                 mtd->ecc_stats.badblocks++;
710
711         return ret;
712 }
713
714 /**
715  * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
716  * @mtd: MTD device structure
717  * @ofs: offset from device start
718  *
719  * Check if the block is marked as reserved.
720  */
721 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
722 {
723         struct nand_chip *chip = mtd_to_nand(mtd);
724
725         if (!chip->bbt)
726                 return 0;
727         /* Return info from the table */
728         return nand_isreserved_bbt(chip, ofs);
729 }
730
731 /**
732  * nand_block_checkbad - [GENERIC] Check if a block is marked bad
733  * @chip: NAND chip object
734  * @ofs: offset from device start
735  * @allowbbt: 1, if its allowed to access the bbt area
736  *
737  * Check, if the block is bad. Either by reading the bad block table or
738  * calling of the scan function.
739  */
740 static int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
741 {
742         /* Return info from the table */
743         if (chip->bbt)
744                 return nand_isbad_bbt(chip, ofs, allowbbt);
745
746         return nand_isbad_bbm(chip, ofs);
747 }
748
749 /**
750  * nand_soft_waitrdy - Poll STATUS reg until RDY bit is set to 1
751  * @chip: NAND chip structure
752  * @timeout_ms: Timeout in ms
753  *
754  * Poll the STATUS register using ->exec_op() until the RDY bit becomes 1.
755  * If that does not happen whitin the specified timeout, -ETIMEDOUT is
756  * returned.
757  *
758  * This helper is intended to be used when the controller does not have access
759  * to the NAND R/B pin.
760  *
761  * Be aware that calling this helper from an ->exec_op() implementation means
762  * ->exec_op() must be re-entrant.
763  *
764  * Return 0 if the NAND chip is ready, a negative error otherwise.
765  */
766 int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
767 {
768         const struct nand_sdr_timings *timings;
769         u8 status = 0;
770         int ret;
771
772         if (!nand_has_exec_op(chip))
773                 return -ENOTSUPP;
774
775         /* Wait tWB before polling the STATUS reg. */
776         timings = nand_get_sdr_timings(nand_get_interface_config(chip));
777         ndelay(PSEC_TO_NSEC(timings->tWB_max));
778
779         ret = nand_status_op(chip, NULL);
780         if (ret)
781                 return ret;
782
783         /*
784          * +1 below is necessary because if we are now in the last fraction
785          * of jiffy and msecs_to_jiffies is 1 then we will wait only that
786          * small jiffy fraction - possibly leading to false timeout
787          */
788         timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
789         do {
790                 ret = nand_read_data_op(chip, &status, sizeof(status), true,
791                                         false);
792                 if (ret)
793                         break;
794
795                 if (status & NAND_STATUS_READY)
796                         break;
797
798                 /*
799                  * Typical lowest execution time for a tR on most NANDs is 10us,
800                  * use this as polling delay before doing something smarter (ie.
801                  * deriving a delay from the timeout value, timeout_ms/ratio).
802                  */
803                 udelay(10);
804         } while (time_before(jiffies, timeout_ms));
805
806         /*
807          * We have to exit READ_STATUS mode in order to read real data on the
808          * bus in case the WAITRDY instruction is preceding a DATA_IN
809          * instruction.
810          */
811         nand_exit_status_op(chip);
812
813         if (ret)
814                 return ret;
815
816         return status & NAND_STATUS_READY ? 0 : -ETIMEDOUT;
817 };
818 EXPORT_SYMBOL_GPL(nand_soft_waitrdy);
819
820 /**
821  * nand_gpio_waitrdy - Poll R/B GPIO pin until ready
822  * @chip: NAND chip structure
823  * @gpiod: GPIO descriptor of R/B pin
824  * @timeout_ms: Timeout in ms
825  *
826  * Poll the R/B GPIO pin until it becomes ready. If that does not happen
827  * whitin the specified timeout, -ETIMEDOUT is returned.
828  *
829  * This helper is intended to be used when the controller has access to the
830  * NAND R/B pin over GPIO.
831  *
832  * Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.
833  */
834 int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
835                       unsigned long timeout_ms)
836 {
837
838         /*
839          * Wait until R/B pin indicates chip is ready or timeout occurs.
840          * +1 below is necessary because if we are now in the last fraction
841          * of jiffy and msecs_to_jiffies is 1 then we will wait only that
842          * small jiffy fraction - possibly leading to false timeout.
843          */
844         timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
845         do {
846                 if (gpiod_get_value_cansleep(gpiod))
847                         return 0;
848
849                 cond_resched();
850         } while (time_before(jiffies, timeout_ms));
851
852         return gpiod_get_value_cansleep(gpiod) ? 0 : -ETIMEDOUT;
853 };
854 EXPORT_SYMBOL_GPL(nand_gpio_waitrdy);
855
856 /**
857  * panic_nand_wait - [GENERIC] wait until the command is done
858  * @chip: NAND chip structure
859  * @timeo: timeout
860  *
861  * Wait for command done. This is a helper function for nand_wait used when
862  * we are in interrupt context. May happen when in panic and trying to write
863  * an oops through mtdoops.
864  */
865 void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
866 {
867         int i;
868         for (i = 0; i < timeo; i++) {
869                 if (chip->legacy.dev_ready) {
870                         if (chip->legacy.dev_ready(chip))
871                                 break;
872                 } else {
873                         int ret;
874                         u8 status;
875
876                         ret = nand_read_data_op(chip, &status, sizeof(status),
877                                                 true, false);
878                         if (ret)
879                                 return;
880
881                         if (status & NAND_STATUS_READY)
882                                 break;
883                 }
884                 mdelay(1);
885         }
886 }
887
888 static bool nand_supports_get_features(struct nand_chip *chip, int addr)
889 {
890         return (chip->parameters.supports_set_get_features &&
891                 test_bit(addr, chip->parameters.get_feature_list));
892 }
893
894 static bool nand_supports_set_features(struct nand_chip *chip, int addr)
895 {
896         return (chip->parameters.supports_set_get_features &&
897                 test_bit(addr, chip->parameters.set_feature_list));
898 }
899
900 /**
901  * nand_reset_interface - Reset data interface and timings
902  * @chip: The NAND chip
903  * @chipnr: Internal die id
904  *
905  * Reset the Data interface and timings to ONFI mode 0.
906  *
907  * Returns 0 for success or negative error code otherwise.
908  */
909 static int nand_reset_interface(struct nand_chip *chip, int chipnr)
910 {
911         const struct nand_controller_ops *ops = chip->controller->ops;
912         int ret;
913
914         if (!nand_controller_can_setup_interface(chip))
915                 return 0;
916
917         /*
918          * The ONFI specification says:
919          * "
920          * To transition from NV-DDR or NV-DDR2 to the SDR data
921          * interface, the host shall use the Reset (FFh) command
922          * using SDR timing mode 0. A device in any timing mode is
923          * required to recognize Reset (FFh) command issued in SDR
924          * timing mode 0.
925          * "
926          *
927          * Configure the data interface in SDR mode and set the
928          * timings to timing mode 0.
929          */
930
931         chip->current_interface_config = nand_get_reset_interface_config();
932         ret = ops->setup_interface(chip, chipnr,
933                                    chip->current_interface_config);
934         if (ret)
935                 pr_err("Failed to configure data interface to SDR timing mode 0\n");
936
937         return ret;
938 }
939
940 /**
941  * nand_setup_interface - Setup the best data interface and timings
942  * @chip: The NAND chip
943  * @chipnr: Internal die id
944  *
945  * Configure what has been reported to be the best data interface and NAND
946  * timings supported by the chip and the driver.
947  *
948  * Returns 0 for success or negative error code otherwise.
949  */
950 static int nand_setup_interface(struct nand_chip *chip, int chipnr)
951 {
952         const struct nand_controller_ops *ops = chip->controller->ops;
953         u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = { };
954         int ret;
955
956         if (!nand_controller_can_setup_interface(chip))
957                 return 0;
958
959         /*
960          * A nand_reset_interface() put both the NAND chip and the NAND
961          * controller in timings mode 0. If the default mode for this chip is
962          * also 0, no need to proceed to the change again. Plus, at probe time,
963          * nand_setup_interface() uses ->set/get_features() which would
964          * fail anyway as the parameter page is not available yet.
965          */
966         if (!chip->best_interface_config)
967                 return 0;
968
969         tmode_param[0] = chip->best_interface_config->timings.mode;
970
971         /* Change the mode on the chip side (if supported by the NAND chip) */
972         if (nand_supports_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE)) {
973                 nand_select_target(chip, chipnr);
974                 ret = nand_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
975                                         tmode_param);
976                 nand_deselect_target(chip);
977                 if (ret)
978                         return ret;
979         }
980
981         /* Change the mode on the controller side */
982         ret = ops->setup_interface(chip, chipnr, chip->best_interface_config);
983         if (ret)
984                 return ret;
985
986         /* Check the mode has been accepted by the chip, if supported */
987         if (!nand_supports_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE))
988                 goto update_interface_config;
989
990         memset(tmode_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
991         nand_select_target(chip, chipnr);
992         ret = nand_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
993                                 tmode_param);
994         nand_deselect_target(chip);
995         if (ret)
996                 goto err_reset_chip;
997
998         if (tmode_param[0] != chip->best_interface_config->timings.mode) {
999                 pr_warn("timing mode %d not acknowledged by the NAND chip\n",
1000                         chip->best_interface_config->timings.mode);
1001                 goto err_reset_chip;
1002         }
1003
1004 update_interface_config:
1005         chip->current_interface_config = chip->best_interface_config;
1006
1007         return 0;
1008
1009 err_reset_chip:
1010         /*
1011          * Fallback to mode 0 if the chip explicitly did not ack the chosen
1012          * timing mode.
1013          */
1014         nand_reset_interface(chip, chipnr);
1015         nand_select_target(chip, chipnr);
1016         nand_reset_op(chip);
1017         nand_deselect_target(chip);
1018
1019         return ret;
1020 }
1021
1022 /**
1023  * nand_choose_best_sdr_timings - Pick up the best SDR timings that both the
1024  *                                NAND controller and the NAND chip support
1025  * @chip: the NAND chip
1026  * @iface: the interface configuration (can eventually be updated)
1027  * @spec_timings: specific timings, when not fitting the ONFI specification
1028  *
1029  * If specific timings are provided, use them. Otherwise, retrieve supported
1030  * timing modes from ONFI information.
1031  */
1032 int nand_choose_best_sdr_timings(struct nand_chip *chip,
1033                                  struct nand_interface_config *iface,
1034                                  struct nand_sdr_timings *spec_timings)
1035 {
1036         const struct nand_controller_ops *ops = chip->controller->ops;
1037         int best_mode = 0, mode, ret;
1038
1039         iface->type = NAND_SDR_IFACE;
1040
1041         if (spec_timings) {
1042                 iface->timings.sdr = *spec_timings;
1043                 iface->timings.mode = onfi_find_closest_sdr_mode(spec_timings);
1044
1045                 /* Verify the controller supports the requested interface */
1046                 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
1047                                            iface);
1048                 if (!ret) {
1049                         chip->best_interface_config = iface;
1050                         return ret;
1051                 }
1052
1053                 /* Fallback to slower modes */
1054                 best_mode = iface->timings.mode;
1055         } else if (chip->parameters.onfi) {
1056                 best_mode = fls(chip->parameters.onfi->async_timing_mode) - 1;
1057         }
1058
1059         for (mode = best_mode; mode >= 0; mode--) {
1060                 onfi_fill_interface_config(chip, iface, NAND_SDR_IFACE, mode);
1061
1062                 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
1063                                            iface);
1064                 if (!ret)
1065                         break;
1066         }
1067
1068         chip->best_interface_config = iface;
1069
1070         return 0;
1071 }
1072
1073 /**
1074  * nand_choose_interface_config - find the best data interface and timings
1075  * @chip: The NAND chip
1076  *
1077  * Find the best data interface and NAND timings supported by the chip
1078  * and the driver. Eventually let the NAND manufacturer driver propose his own
1079  * set of timings.
1080  *
1081  * After this function nand_chip->interface_config is initialized with the best
1082  * timing mode available.
1083  *
1084  * Returns 0 for success or negative error code otherwise.
1085  */
1086 static int nand_choose_interface_config(struct nand_chip *chip)
1087 {
1088         struct nand_interface_config *iface;
1089         int ret;
1090
1091         if (!nand_controller_can_setup_interface(chip))
1092                 return 0;
1093
1094         iface = kzalloc(sizeof(*iface), GFP_KERNEL);
1095         if (!iface)
1096                 return -ENOMEM;
1097
1098         if (chip->ops.choose_interface_config)
1099                 ret = chip->ops.choose_interface_config(chip, iface);
1100         else
1101                 ret = nand_choose_best_sdr_timings(chip, iface, NULL);
1102
1103         if (ret)
1104                 kfree(iface);
1105
1106         return ret;
1107 }
1108
1109 /**
1110  * nand_fill_column_cycles - fill the column cycles of an address
1111  * @chip: The NAND chip
1112  * @addrs: Array of address cycles to fill
1113  * @offset_in_page: The offset in the page
1114  *
1115  * Fills the first or the first two bytes of the @addrs field depending
1116  * on the NAND bus width and the page size.
1117  *
1118  * Returns the number of cycles needed to encode the column, or a negative
1119  * error code in case one of the arguments is invalid.
1120  */
1121 static int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs,
1122                                    unsigned int offset_in_page)
1123 {
1124         struct mtd_info *mtd = nand_to_mtd(chip);
1125
1126         /* Make sure the offset is less than the actual page size. */
1127         if (offset_in_page > mtd->writesize + mtd->oobsize)
1128                 return -EINVAL;
1129
1130         /*
1131          * On small page NANDs, there's a dedicated command to access the OOB
1132          * area, and the column address is relative to the start of the OOB
1133          * area, not the start of the page. Asjust the address accordingly.
1134          */
1135         if (mtd->writesize <= 512 && offset_in_page >= mtd->writesize)
1136                 offset_in_page -= mtd->writesize;
1137
1138         /*
1139          * The offset in page is expressed in bytes, if the NAND bus is 16-bit
1140          * wide, then it must be divided by 2.
1141          */
1142         if (chip->options & NAND_BUSWIDTH_16) {
1143                 if (WARN_ON(offset_in_page % 2))
1144                         return -EINVAL;
1145
1146                 offset_in_page /= 2;
1147         }
1148
1149         addrs[0] = offset_in_page;
1150
1151         /*
1152          * Small page NANDs use 1 cycle for the columns, while large page NANDs
1153          * need 2
1154          */
1155         if (mtd->writesize <= 512)
1156                 return 1;
1157
1158         addrs[1] = offset_in_page >> 8;
1159
1160         return 2;
1161 }
1162
1163 static int nand_sp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1164                                      unsigned int offset_in_page, void *buf,
1165                                      unsigned int len)
1166 {
1167         const struct nand_sdr_timings *sdr =
1168                 nand_get_sdr_timings(nand_get_interface_config(chip));
1169         struct mtd_info *mtd = nand_to_mtd(chip);
1170         u8 addrs[4];
1171         struct nand_op_instr instrs[] = {
1172                 NAND_OP_CMD(NAND_CMD_READ0, 0),
1173                 NAND_OP_ADDR(3, addrs, PSEC_TO_NSEC(sdr->tWB_max)),
1174                 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1175                                  PSEC_TO_NSEC(sdr->tRR_min)),
1176                 NAND_OP_DATA_IN(len, buf, 0),
1177         };
1178         struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1179         int ret;
1180
1181         /* Drop the DATA_IN instruction if len is set to 0. */
1182         if (!len)
1183                 op.ninstrs--;
1184
1185         if (offset_in_page >= mtd->writesize)
1186                 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1187         else if (offset_in_page >= 256 &&
1188                  !(chip->options & NAND_BUSWIDTH_16))
1189                 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1190
1191         ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1192         if (ret < 0)
1193                 return ret;
1194
1195         addrs[1] = page;
1196         addrs[2] = page >> 8;
1197
1198         if (chip->options & NAND_ROW_ADDR_3) {
1199                 addrs[3] = page >> 16;
1200                 instrs[1].ctx.addr.naddrs++;
1201         }
1202
1203         return nand_exec_op(chip, &op);
1204 }
1205
1206 static int nand_lp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1207                                      unsigned int offset_in_page, void *buf,
1208                                      unsigned int len)
1209 {
1210         const struct nand_sdr_timings *sdr =
1211                 nand_get_sdr_timings(nand_get_interface_config(chip));
1212         u8 addrs[5];
1213         struct nand_op_instr instrs[] = {
1214                 NAND_OP_CMD(NAND_CMD_READ0, 0),
1215                 NAND_OP_ADDR(4, addrs, 0),
1216                 NAND_OP_CMD(NAND_CMD_READSTART, PSEC_TO_NSEC(sdr->tWB_max)),
1217                 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1218                                  PSEC_TO_NSEC(sdr->tRR_min)),
1219                 NAND_OP_DATA_IN(len, buf, 0),
1220         };
1221         struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1222         int ret;
1223
1224         /* Drop the DATA_IN instruction if len is set to 0. */
1225         if (!len)
1226                 op.ninstrs--;
1227
1228         ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1229         if (ret < 0)
1230                 return ret;
1231
1232         addrs[2] = page;
1233         addrs[3] = page >> 8;
1234
1235         if (chip->options & NAND_ROW_ADDR_3) {
1236                 addrs[4] = page >> 16;
1237                 instrs[1].ctx.addr.naddrs++;
1238         }
1239
1240         return nand_exec_op(chip, &op);
1241 }
1242
1243 /**
1244  * nand_read_page_op - Do a READ PAGE operation
1245  * @chip: The NAND chip
1246  * @page: page to read
1247  * @offset_in_page: offset within the page
1248  * @buf: buffer used to store the data
1249  * @len: length of the buffer
1250  *
1251  * This function issues a READ PAGE operation.
1252  * This function does not select/unselect the CS line.
1253  *
1254  * Returns 0 on success, a negative error code otherwise.
1255  */
1256 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1257                       unsigned int offset_in_page, void *buf, unsigned int len)
1258 {
1259         struct mtd_info *mtd = nand_to_mtd(chip);
1260
1261         if (len && !buf)
1262                 return -EINVAL;
1263
1264         if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1265                 return -EINVAL;
1266
1267         if (nand_has_exec_op(chip)) {
1268                 if (mtd->writesize > 512)
1269                         return nand_lp_exec_read_page_op(chip, page,
1270                                                          offset_in_page, buf,
1271                                                          len);
1272
1273                 return nand_sp_exec_read_page_op(chip, page, offset_in_page,
1274                                                  buf, len);
1275         }
1276
1277         chip->legacy.cmdfunc(chip, NAND_CMD_READ0, offset_in_page, page);
1278         if (len)
1279                 chip->legacy.read_buf(chip, buf, len);
1280
1281         return 0;
1282 }
1283 EXPORT_SYMBOL_GPL(nand_read_page_op);
1284
1285 /**
1286  * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1287  * @chip: The NAND chip
1288  * @page: parameter page to read
1289  * @buf: buffer used to store the data
1290  * @len: length of the buffer
1291  *
1292  * This function issues a READ PARAMETER PAGE operation.
1293  * This function does not select/unselect the CS line.
1294  *
1295  * Returns 0 on success, a negative error code otherwise.
1296  */
1297 int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1298                             unsigned int len)
1299 {
1300         unsigned int i;
1301         u8 *p = buf;
1302
1303         if (len && !buf)
1304                 return -EINVAL;
1305
1306         if (nand_has_exec_op(chip)) {
1307                 const struct nand_sdr_timings *sdr =
1308                         nand_get_sdr_timings(nand_get_interface_config(chip));
1309                 struct nand_op_instr instrs[] = {
1310                         NAND_OP_CMD(NAND_CMD_PARAM, 0),
1311                         NAND_OP_ADDR(1, &page, PSEC_TO_NSEC(sdr->tWB_max)),
1312                         NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1313                                          PSEC_TO_NSEC(sdr->tRR_min)),
1314                         NAND_OP_8BIT_DATA_IN(len, buf, 0),
1315                 };
1316                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1317
1318                 /* Drop the DATA_IN instruction if len is set to 0. */
1319                 if (!len)
1320                         op.ninstrs--;
1321
1322                 return nand_exec_op(chip, &op);
1323         }
1324
1325         chip->legacy.cmdfunc(chip, NAND_CMD_PARAM, page, -1);
1326         for (i = 0; i < len; i++)
1327                 p[i] = chip->legacy.read_byte(chip);
1328
1329         return 0;
1330 }
1331
1332 /**
1333  * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1334  * @chip: The NAND chip
1335  * @offset_in_page: offset within the page
1336  * @buf: buffer used to store the data
1337  * @len: length of the buffer
1338  * @force_8bit: force 8-bit bus access
1339  *
1340  * This function issues a CHANGE READ COLUMN operation.
1341  * This function does not select/unselect the CS line.
1342  *
1343  * Returns 0 on success, a negative error code otherwise.
1344  */
1345 int nand_change_read_column_op(struct nand_chip *chip,
1346                                unsigned int offset_in_page, void *buf,
1347                                unsigned int len, bool force_8bit)
1348 {
1349         struct mtd_info *mtd = nand_to_mtd(chip);
1350
1351         if (len && !buf)
1352                 return -EINVAL;
1353
1354         if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1355                 return -EINVAL;
1356
1357         /* Small page NANDs do not support column change. */
1358         if (mtd->writesize <= 512)
1359                 return -ENOTSUPP;
1360
1361         if (nand_has_exec_op(chip)) {
1362                 const struct nand_sdr_timings *sdr =
1363                         nand_get_sdr_timings(nand_get_interface_config(chip));
1364                 u8 addrs[2] = {};
1365                 struct nand_op_instr instrs[] = {
1366                         NAND_OP_CMD(NAND_CMD_RNDOUT, 0),
1367                         NAND_OP_ADDR(2, addrs, 0),
1368                         NAND_OP_CMD(NAND_CMD_RNDOUTSTART,
1369                                     PSEC_TO_NSEC(sdr->tCCS_min)),
1370                         NAND_OP_DATA_IN(len, buf, 0),
1371                 };
1372                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1373                 int ret;
1374
1375                 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1376                 if (ret < 0)
1377                         return ret;
1378
1379                 /* Drop the DATA_IN instruction if len is set to 0. */
1380                 if (!len)
1381                         op.ninstrs--;
1382
1383                 instrs[3].ctx.data.force_8bit = force_8bit;
1384
1385                 return nand_exec_op(chip, &op);
1386         }
1387
1388         chip->legacy.cmdfunc(chip, NAND_CMD_RNDOUT, offset_in_page, -1);
1389         if (len)
1390                 chip->legacy.read_buf(chip, buf, len);
1391
1392         return 0;
1393 }
1394 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1395
1396 /**
1397  * nand_read_oob_op - Do a READ OOB operation
1398  * @chip: The NAND chip
1399  * @page: page to read
1400  * @offset_in_oob: offset within the OOB area
1401  * @buf: buffer used to store the data
1402  * @len: length of the buffer
1403  *
1404  * This function issues a READ OOB operation.
1405  * This function does not select/unselect the CS line.
1406  *
1407  * Returns 0 on success, a negative error code otherwise.
1408  */
1409 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1410                      unsigned int offset_in_oob, void *buf, unsigned int len)
1411 {
1412         struct mtd_info *mtd = nand_to_mtd(chip);
1413
1414         if (len && !buf)
1415                 return -EINVAL;
1416
1417         if (offset_in_oob + len > mtd->oobsize)
1418                 return -EINVAL;
1419
1420         if (nand_has_exec_op(chip))
1421                 return nand_read_page_op(chip, page,
1422                                          mtd->writesize + offset_in_oob,
1423                                          buf, len);
1424
1425         chip->legacy.cmdfunc(chip, NAND_CMD_READOOB, offset_in_oob, page);
1426         if (len)
1427                 chip->legacy.read_buf(chip, buf, len);
1428
1429         return 0;
1430 }
1431 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1432
1433 static int nand_exec_prog_page_op(struct nand_chip *chip, unsigned int page,
1434                                   unsigned int offset_in_page, const void *buf,
1435                                   unsigned int len, bool prog)
1436 {
1437         const struct nand_sdr_timings *sdr =
1438                 nand_get_sdr_timings(nand_get_interface_config(chip));
1439         struct mtd_info *mtd = nand_to_mtd(chip);
1440         u8 addrs[5] = {};
1441         struct nand_op_instr instrs[] = {
1442                 /*
1443                  * The first instruction will be dropped if we're dealing
1444                  * with a large page NAND and adjusted if we're dealing
1445                  * with a small page NAND and the page offset is > 255.
1446                  */
1447                 NAND_OP_CMD(NAND_CMD_READ0, 0),
1448                 NAND_OP_CMD(NAND_CMD_SEQIN, 0),
1449                 NAND_OP_ADDR(0, addrs, PSEC_TO_NSEC(sdr->tADL_min)),
1450                 NAND_OP_DATA_OUT(len, buf, 0),
1451                 NAND_OP_CMD(NAND_CMD_PAGEPROG, PSEC_TO_NSEC(sdr->tWB_max)),
1452                 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1453         };
1454         struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1455         int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
1456         int ret;
1457         u8 status;
1458
1459         if (naddrs < 0)
1460                 return naddrs;
1461
1462         addrs[naddrs++] = page;
1463         addrs[naddrs++] = page >> 8;
1464         if (chip->options & NAND_ROW_ADDR_3)
1465                 addrs[naddrs++] = page >> 16;
1466
1467         instrs[2].ctx.addr.naddrs = naddrs;
1468
1469         /* Drop the last two instructions if we're not programming the page. */
1470         if (!prog) {
1471                 op.ninstrs -= 2;
1472                 /* Also drop the DATA_OUT instruction if empty. */
1473                 if (!len)
1474                         op.ninstrs--;
1475         }
1476
1477         if (mtd->writesize <= 512) {
1478                 /*
1479                  * Small pages need some more tweaking: we have to adjust the
1480                  * first instruction depending on the page offset we're trying
1481                  * to access.
1482                  */
1483                 if (offset_in_page >= mtd->writesize)
1484                         instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1485                 else if (offset_in_page >= 256 &&
1486                          !(chip->options & NAND_BUSWIDTH_16))
1487                         instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1488         } else {
1489                 /*
1490                  * Drop the first command if we're dealing with a large page
1491                  * NAND.
1492                  */
1493                 op.instrs++;
1494                 op.ninstrs--;
1495         }
1496
1497         ret = nand_exec_op(chip, &op);
1498         if (!prog || ret)
1499                 return ret;
1500
1501         ret = nand_status_op(chip, &status);
1502         if (ret)
1503                 return ret;
1504
1505         return status;
1506 }
1507
1508 /**
1509  * nand_prog_page_begin_op - starts a PROG PAGE operation
1510  * @chip: The NAND chip
1511  * @page: page to write
1512  * @offset_in_page: offset within the page
1513  * @buf: buffer containing the data to write to the page
1514  * @len: length of the buffer
1515  *
1516  * This function issues the first half of a PROG PAGE operation.
1517  * This function does not select/unselect the CS line.
1518  *
1519  * Returns 0 on success, a negative error code otherwise.
1520  */
1521 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1522                             unsigned int offset_in_page, const void *buf,
1523                             unsigned int len)
1524 {
1525         struct mtd_info *mtd = nand_to_mtd(chip);
1526
1527         if (len && !buf)
1528                 return -EINVAL;
1529
1530         if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1531                 return -EINVAL;
1532
1533         if (nand_has_exec_op(chip))
1534                 return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1535                                               len, false);
1536
1537         chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page, page);
1538
1539         if (buf)
1540                 chip->legacy.write_buf(chip, buf, len);
1541
1542         return 0;
1543 }
1544 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1545
1546 /**
1547  * nand_prog_page_end_op - ends a PROG PAGE operation
1548  * @chip: The NAND chip
1549  *
1550  * This function issues the second half of a PROG PAGE operation.
1551  * This function does not select/unselect the CS line.
1552  *
1553  * Returns 0 on success, a negative error code otherwise.
1554  */
1555 int nand_prog_page_end_op(struct nand_chip *chip)
1556 {
1557         int ret;
1558         u8 status;
1559
1560         if (nand_has_exec_op(chip)) {
1561                 const struct nand_sdr_timings *sdr =
1562                         nand_get_sdr_timings(nand_get_interface_config(chip));
1563                 struct nand_op_instr instrs[] = {
1564                         NAND_OP_CMD(NAND_CMD_PAGEPROG,
1565                                     PSEC_TO_NSEC(sdr->tWB_max)),
1566                         NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1567                 };
1568                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1569
1570                 ret = nand_exec_op(chip, &op);
1571                 if (ret)
1572                         return ret;
1573
1574                 ret = nand_status_op(chip, &status);
1575                 if (ret)
1576                         return ret;
1577         } else {
1578                 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1579                 ret = chip->legacy.waitfunc(chip);
1580                 if (ret < 0)
1581                         return ret;
1582
1583                 status = ret;
1584         }
1585
1586         if (status & NAND_STATUS_FAIL)
1587                 return -EIO;
1588
1589         return 0;
1590 }
1591 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1592
1593 /**
1594  * nand_prog_page_op - Do a full PROG PAGE operation
1595  * @chip: The NAND chip
1596  * @page: page to write
1597  * @offset_in_page: offset within the page
1598  * @buf: buffer containing the data to write to the page
1599  * @len: length of the buffer
1600  *
1601  * This function issues a full PROG PAGE operation.
1602  * This function does not select/unselect the CS line.
1603  *
1604  * Returns 0 on success, a negative error code otherwise.
1605  */
1606 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1607                       unsigned int offset_in_page, const void *buf,
1608                       unsigned int len)
1609 {
1610         struct mtd_info *mtd = nand_to_mtd(chip);
1611         int status;
1612
1613         if (!len || !buf)
1614                 return -EINVAL;
1615
1616         if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1617                 return -EINVAL;
1618
1619         if (nand_has_exec_op(chip)) {
1620                 status = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1621                                                 len, true);
1622         } else {
1623                 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page,
1624                                      page);
1625                 chip->legacy.write_buf(chip, buf, len);
1626                 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1627                 status = chip->legacy.waitfunc(chip);
1628         }
1629
1630         if (status & NAND_STATUS_FAIL)
1631                 return -EIO;
1632
1633         return 0;
1634 }
1635 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1636
1637 /**
1638  * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1639  * @chip: The NAND chip
1640  * @offset_in_page: offset within the page
1641  * @buf: buffer containing the data to send to the NAND
1642  * @len: length of the buffer
1643  * @force_8bit: force 8-bit bus access
1644  *
1645  * This function issues a CHANGE WRITE COLUMN operation.
1646  * This function does not select/unselect the CS line.
1647  *
1648  * Returns 0 on success, a negative error code otherwise.
1649  */
1650 int nand_change_write_column_op(struct nand_chip *chip,
1651                                 unsigned int offset_in_page,
1652                                 const void *buf, unsigned int len,
1653                                 bool force_8bit)
1654 {
1655         struct mtd_info *mtd = nand_to_mtd(chip);
1656
1657         if (len && !buf)
1658                 return -EINVAL;
1659
1660         if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1661                 return -EINVAL;
1662
1663         /* Small page NANDs do not support column change. */
1664         if (mtd->writesize <= 512)
1665                 return -ENOTSUPP;
1666
1667         if (nand_has_exec_op(chip)) {
1668                 const struct nand_sdr_timings *sdr =
1669                         nand_get_sdr_timings(nand_get_interface_config(chip));
1670                 u8 addrs[2];
1671                 struct nand_op_instr instrs[] = {
1672                         NAND_OP_CMD(NAND_CMD_RNDIN, 0),
1673                         NAND_OP_ADDR(2, addrs, PSEC_TO_NSEC(sdr->tCCS_min)),
1674                         NAND_OP_DATA_OUT(len, buf, 0),
1675                 };
1676                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1677                 int ret;
1678
1679                 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1680                 if (ret < 0)
1681                         return ret;
1682
1683                 instrs[2].ctx.data.force_8bit = force_8bit;
1684
1685                 /* Drop the DATA_OUT instruction if len is set to 0. */
1686                 if (!len)
1687                         op.ninstrs--;
1688
1689                 return nand_exec_op(chip, &op);
1690         }
1691
1692         chip->legacy.cmdfunc(chip, NAND_CMD_RNDIN, offset_in_page, -1);
1693         if (len)
1694                 chip->legacy.write_buf(chip, buf, len);
1695
1696         return 0;
1697 }
1698 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1699
1700 /**
1701  * nand_readid_op - Do a READID operation
1702  * @chip: The NAND chip
1703  * @addr: address cycle to pass after the READID command
1704  * @buf: buffer used to store the ID
1705  * @len: length of the buffer
1706  *
1707  * This function sends a READID command and reads back the ID returned by the
1708  * NAND.
1709  * This function does not select/unselect the CS line.
1710  *
1711  * Returns 0 on success, a negative error code otherwise.
1712  */
1713 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1714                    unsigned int len)
1715 {
1716         unsigned int i;
1717         u8 *id = buf;
1718
1719         if (len && !buf)
1720                 return -EINVAL;
1721
1722         if (nand_has_exec_op(chip)) {
1723                 const struct nand_sdr_timings *sdr =
1724                         nand_get_sdr_timings(nand_get_interface_config(chip));
1725                 struct nand_op_instr instrs[] = {
1726                         NAND_OP_CMD(NAND_CMD_READID, 0),
1727                         NAND_OP_ADDR(1, &addr, PSEC_TO_NSEC(sdr->tADL_min)),
1728                         NAND_OP_8BIT_DATA_IN(len, buf, 0),
1729                 };
1730                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1731
1732                 /* Drop the DATA_IN instruction if len is set to 0. */
1733                 if (!len)
1734                         op.ninstrs--;
1735
1736                 return nand_exec_op(chip, &op);
1737         }
1738
1739         chip->legacy.cmdfunc(chip, NAND_CMD_READID, addr, -1);
1740
1741         for (i = 0; i < len; i++)
1742                 id[i] = chip->legacy.read_byte(chip);
1743
1744         return 0;
1745 }
1746 EXPORT_SYMBOL_GPL(nand_readid_op);
1747
1748 /**
1749  * nand_status_op - Do a STATUS operation
1750  * @chip: The NAND chip
1751  * @status: out variable to store the NAND status
1752  *
1753  * This function sends a STATUS command and reads back the status returned by
1754  * the NAND.
1755  * This function does not select/unselect the CS line.
1756  *
1757  * Returns 0 on success, a negative error code otherwise.
1758  */
1759 int nand_status_op(struct nand_chip *chip, u8 *status)
1760 {
1761         if (nand_has_exec_op(chip)) {
1762                 const struct nand_sdr_timings *sdr =
1763                         nand_get_sdr_timings(nand_get_interface_config(chip));
1764                 struct nand_op_instr instrs[] = {
1765                         NAND_OP_CMD(NAND_CMD_STATUS,
1766                                     PSEC_TO_NSEC(sdr->tADL_min)),
1767                         NAND_OP_8BIT_DATA_IN(1, status, 0),
1768                 };
1769                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1770
1771                 if (!status)
1772                         op.ninstrs--;
1773
1774                 return nand_exec_op(chip, &op);
1775         }
1776
1777         chip->legacy.cmdfunc(chip, NAND_CMD_STATUS, -1, -1);
1778         if (status)
1779                 *status = chip->legacy.read_byte(chip);
1780
1781         return 0;
1782 }
1783 EXPORT_SYMBOL_GPL(nand_status_op);
1784
1785 /**
1786  * nand_exit_status_op - Exit a STATUS operation
1787  * @chip: The NAND chip
1788  *
1789  * This function sends a READ0 command to cancel the effect of the STATUS
1790  * command to avoid reading only the status until a new read command is sent.
1791  *
1792  * This function does not select/unselect the CS line.
1793  *
1794  * Returns 0 on success, a negative error code otherwise.
1795  */
1796 int nand_exit_status_op(struct nand_chip *chip)
1797 {
1798         if (nand_has_exec_op(chip)) {
1799                 struct nand_op_instr instrs[] = {
1800                         NAND_OP_CMD(NAND_CMD_READ0, 0),
1801                 };
1802                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1803
1804                 return nand_exec_op(chip, &op);
1805         }
1806
1807         chip->legacy.cmdfunc(chip, NAND_CMD_READ0, -1, -1);
1808
1809         return 0;
1810 }
1811
1812 /**
1813  * nand_erase_op - Do an erase operation
1814  * @chip: The NAND chip
1815  * @eraseblock: block to erase
1816  *
1817  * This function sends an ERASE command and waits for the NAND to be ready
1818  * before returning.
1819  * This function does not select/unselect the CS line.
1820  *
1821  * Returns 0 on success, a negative error code otherwise.
1822  */
1823 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1824 {
1825         unsigned int page = eraseblock <<
1826                             (chip->phys_erase_shift - chip->page_shift);
1827         int ret;
1828         u8 status;
1829
1830         if (nand_has_exec_op(chip)) {
1831                 const struct nand_sdr_timings *sdr =
1832                         nand_get_sdr_timings(nand_get_interface_config(chip));
1833                 u8 addrs[3] = { page, page >> 8, page >> 16 };
1834                 struct nand_op_instr instrs[] = {
1835                         NAND_OP_CMD(NAND_CMD_ERASE1, 0),
1836                         NAND_OP_ADDR(2, addrs, 0),
1837                         NAND_OP_CMD(NAND_CMD_ERASE2,
1838                                     PSEC_TO_MSEC(sdr->tWB_max)),
1839                         NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tBERS_max), 0),
1840                 };
1841                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1842
1843                 if (chip->options & NAND_ROW_ADDR_3)
1844                         instrs[1].ctx.addr.naddrs++;
1845
1846                 ret = nand_exec_op(chip, &op);
1847                 if (ret)
1848                         return ret;
1849
1850                 ret = nand_status_op(chip, &status);
1851                 if (ret)
1852                         return ret;
1853         } else {
1854                 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE1, -1, page);
1855                 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE2, -1, -1);
1856
1857                 ret = chip->legacy.waitfunc(chip);
1858                 if (ret < 0)
1859                         return ret;
1860
1861                 status = ret;
1862         }
1863
1864         if (status & NAND_STATUS_FAIL)
1865                 return -EIO;
1866
1867         return 0;
1868 }
1869 EXPORT_SYMBOL_GPL(nand_erase_op);
1870
1871 /**
1872  * nand_set_features_op - Do a SET FEATURES operation
1873  * @chip: The NAND chip
1874  * @feature: feature id
1875  * @data: 4 bytes of data
1876  *
1877  * This function sends a SET FEATURES command and waits for the NAND to be
1878  * ready before returning.
1879  * This function does not select/unselect the CS line.
1880  *
1881  * Returns 0 on success, a negative error code otherwise.
1882  */
1883 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1884                                 const void *data)
1885 {
1886         const u8 *params = data;
1887         int i, ret;
1888
1889         if (nand_has_exec_op(chip)) {
1890                 const struct nand_sdr_timings *sdr =
1891                         nand_get_sdr_timings(nand_get_interface_config(chip));
1892                 struct nand_op_instr instrs[] = {
1893                         NAND_OP_CMD(NAND_CMD_SET_FEATURES, 0),
1894                         NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tADL_min)),
1895                         NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
1896                                               PSEC_TO_NSEC(sdr->tWB_max)),
1897                         NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max), 0),
1898                 };
1899                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1900
1901                 return nand_exec_op(chip, &op);
1902         }
1903
1904         chip->legacy.cmdfunc(chip, NAND_CMD_SET_FEATURES, feature, -1);
1905         for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1906                 chip->legacy.write_byte(chip, params[i]);
1907
1908         ret = chip->legacy.waitfunc(chip);
1909         if (ret < 0)
1910                 return ret;
1911
1912         if (ret & NAND_STATUS_FAIL)
1913                 return -EIO;
1914
1915         return 0;
1916 }
1917
1918 /**
1919  * nand_get_features_op - Do a GET FEATURES operation
1920  * @chip: The NAND chip
1921  * @feature: feature id
1922  * @data: 4 bytes of data
1923  *
1924  * This function sends a GET FEATURES command and waits for the NAND to be
1925  * ready before returning.
1926  * This function does not select/unselect the CS line.
1927  *
1928  * Returns 0 on success, a negative error code otherwise.
1929  */
1930 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1931                                 void *data)
1932 {
1933         u8 *params = data;
1934         int i;
1935
1936         if (nand_has_exec_op(chip)) {
1937                 const struct nand_sdr_timings *sdr =
1938                         nand_get_sdr_timings(nand_get_interface_config(chip));
1939                 struct nand_op_instr instrs[] = {
1940                         NAND_OP_CMD(NAND_CMD_GET_FEATURES, 0),
1941                         NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tWB_max)),
1942                         NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max),
1943                                          PSEC_TO_NSEC(sdr->tRR_min)),
1944                         NAND_OP_8BIT_DATA_IN(ONFI_SUBFEATURE_PARAM_LEN,
1945                                              data, 0),
1946                 };
1947                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1948
1949                 return nand_exec_op(chip, &op);
1950         }
1951
1952         chip->legacy.cmdfunc(chip, NAND_CMD_GET_FEATURES, feature, -1);
1953         for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1954                 params[i] = chip->legacy.read_byte(chip);
1955
1956         return 0;
1957 }
1958
1959 static int nand_wait_rdy_op(struct nand_chip *chip, unsigned int timeout_ms,
1960                             unsigned int delay_ns)
1961 {
1962         if (nand_has_exec_op(chip)) {
1963                 struct nand_op_instr instrs[] = {
1964                         NAND_OP_WAIT_RDY(PSEC_TO_MSEC(timeout_ms),
1965                                          PSEC_TO_NSEC(delay_ns)),
1966                 };
1967                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1968
1969                 return nand_exec_op(chip, &op);
1970         }
1971
1972         /* Apply delay or wait for ready/busy pin */
1973         if (!chip->legacy.dev_ready)
1974                 udelay(chip->legacy.chip_delay);
1975         else
1976                 nand_wait_ready(chip);
1977
1978         return 0;
1979 }
1980
1981 /**
1982  * nand_reset_op - Do a reset operation
1983  * @chip: The NAND chip
1984  *
1985  * This function sends a RESET command and waits for the NAND to be ready
1986  * before returning.
1987  * This function does not select/unselect the CS line.
1988  *
1989  * Returns 0 on success, a negative error code otherwise.
1990  */
1991 int nand_reset_op(struct nand_chip *chip)
1992 {
1993         if (nand_has_exec_op(chip)) {
1994                 const struct nand_sdr_timings *sdr =
1995                         nand_get_sdr_timings(nand_get_interface_config(chip));
1996                 struct nand_op_instr instrs[] = {
1997                         NAND_OP_CMD(NAND_CMD_RESET, PSEC_TO_NSEC(sdr->tWB_max)),
1998                         NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tRST_max), 0),
1999                 };
2000                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2001
2002                 return nand_exec_op(chip, &op);
2003         }
2004
2005         chip->legacy.cmdfunc(chip, NAND_CMD_RESET, -1, -1);
2006
2007         return 0;
2008 }
2009 EXPORT_SYMBOL_GPL(nand_reset_op);
2010
2011 /**
2012  * nand_read_data_op - Read data from the NAND
2013  * @chip: The NAND chip
2014  * @buf: buffer used to store the data
2015  * @len: length of the buffer
2016  * @force_8bit: force 8-bit bus access
2017  * @check_only: do not actually run the command, only checks if the
2018  *              controller driver supports it
2019  *
2020  * This function does a raw data read on the bus. Usually used after launching
2021  * another NAND operation like nand_read_page_op().
2022  * This function does not select/unselect the CS line.
2023  *
2024  * Returns 0 on success, a negative error code otherwise.
2025  */
2026 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
2027                       bool force_8bit, bool check_only)
2028 {
2029         if (!len || !buf)
2030                 return -EINVAL;
2031
2032         if (nand_has_exec_op(chip)) {
2033                 struct nand_op_instr instrs[] = {
2034                         NAND_OP_DATA_IN(len, buf, 0),
2035                 };
2036                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2037
2038                 instrs[0].ctx.data.force_8bit = force_8bit;
2039
2040                 if (check_only)
2041                         return nand_check_op(chip, &op);
2042
2043                 return nand_exec_op(chip, &op);
2044         }
2045
2046         if (check_only)
2047                 return 0;
2048
2049         if (force_8bit) {
2050                 u8 *p = buf;
2051                 unsigned int i;
2052
2053                 for (i = 0; i < len; i++)
2054                         p[i] = chip->legacy.read_byte(chip);
2055         } else {
2056                 chip->legacy.read_buf(chip, buf, len);
2057         }
2058
2059         return 0;
2060 }
2061 EXPORT_SYMBOL_GPL(nand_read_data_op);
2062
2063 /**
2064  * nand_write_data_op - Write data from the NAND
2065  * @chip: The NAND chip
2066  * @buf: buffer containing the data to send on the bus
2067  * @len: length of the buffer
2068  * @force_8bit: force 8-bit bus access
2069  *
2070  * This function does a raw data write on the bus. Usually used after launching
2071  * another NAND operation like nand_write_page_begin_op().
2072  * This function does not select/unselect the CS line.
2073  *
2074  * Returns 0 on success, a negative error code otherwise.
2075  */
2076 int nand_write_data_op(struct nand_chip *chip, const void *buf,
2077                        unsigned int len, bool force_8bit)
2078 {
2079         if (!len || !buf)
2080                 return -EINVAL;
2081
2082         if (nand_has_exec_op(chip)) {
2083                 struct nand_op_instr instrs[] = {
2084                         NAND_OP_DATA_OUT(len, buf, 0),
2085                 };
2086                 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2087
2088                 instrs[0].ctx.data.force_8bit = force_8bit;
2089
2090                 return nand_exec_op(chip, &op);
2091         }
2092
2093         if (force_8bit) {
2094                 const u8 *p = buf;
2095                 unsigned int i;
2096
2097                 for (i = 0; i < len; i++)
2098                         chip->legacy.write_byte(chip, p[i]);
2099         } else {
2100                 chip->legacy.write_buf(chip, buf, len);
2101         }
2102
2103         return 0;
2104 }
2105 EXPORT_SYMBOL_GPL(nand_write_data_op);
2106
2107 /**
2108  * struct nand_op_parser_ctx - Context used by the parser
2109  * @instrs: array of all the instructions that must be addressed
2110  * @ninstrs: length of the @instrs array
2111  * @subop: Sub-operation to be passed to the NAND controller
2112  *
2113  * This structure is used by the core to split NAND operations into
2114  * sub-operations that can be handled by the NAND controller.
2115  */
2116 struct nand_op_parser_ctx {
2117         const struct nand_op_instr *instrs;
2118         unsigned int ninstrs;
2119         struct nand_subop subop;
2120 };
2121
2122 /**
2123  * nand_op_parser_must_split_instr - Checks if an instruction must be split
2124  * @pat: the parser pattern element that matches @instr
2125  * @instr: pointer to the instruction to check
2126  * @start_offset: this is an in/out parameter. If @instr has already been
2127  *                split, then @start_offset is the offset from which to start
2128  *                (either an address cycle or an offset in the data buffer).
2129  *                Conversely, if the function returns true (ie. instr must be
2130  *                split), this parameter is updated to point to the first
2131  *                data/address cycle that has not been taken care of.
2132  *
2133  * Some NAND controllers are limited and cannot send X address cycles with a
2134  * unique operation, or cannot read/write more than Y bytes at the same time.
2135  * In this case, split the instruction that does not fit in a single
2136  * controller-operation into two or more chunks.
2137  *
2138  * Returns true if the instruction must be split, false otherwise.
2139  * The @start_offset parameter is also updated to the offset at which the next
2140  * bundle of instruction must start (if an address or a data instruction).
2141  */
2142 static bool
2143 nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat,
2144                                 const struct nand_op_instr *instr,
2145                                 unsigned int *start_offset)
2146 {
2147         switch (pat->type) {
2148         case NAND_OP_ADDR_INSTR:
2149                 if (!pat->ctx.addr.maxcycles)
2150                         break;
2151
2152                 if (instr->ctx.addr.naddrs - *start_offset >
2153                     pat->ctx.addr.maxcycles) {
2154                         *start_offset += pat->ctx.addr.maxcycles;
2155                         return true;
2156                 }
2157                 break;
2158
2159         case NAND_OP_DATA_IN_INSTR:
2160         case NAND_OP_DATA_OUT_INSTR:
2161                 if (!pat->ctx.data.maxlen)
2162                         break;
2163
2164                 if (instr->ctx.data.len - *start_offset >
2165                     pat->ctx.data.maxlen) {
2166                         *start_offset += pat->ctx.data.maxlen;
2167                         return true;
2168                 }
2169                 break;
2170
2171         default:
2172                 break;
2173         }
2174
2175         return false;
2176 }
2177
2178 /**
2179  * nand_op_parser_match_pat - Checks if a pattern matches the instructions
2180  *                            remaining in the parser context
2181  * @pat: the pattern to test
2182  * @ctx: the parser context structure to match with the pattern @pat
2183  *
2184  * Check if @pat matches the set or a sub-set of instructions remaining in @ctx.
2185  * Returns true if this is the case, false ortherwise. When true is returned,
2186  * @ctx->subop is updated with the set of instructions to be passed to the
2187  * controller driver.
2188  */
2189 static bool
2190 nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
2191                          struct nand_op_parser_ctx *ctx)
2192 {
2193         unsigned int instr_offset = ctx->subop.first_instr_start_off;
2194         const struct nand_op_instr *end = ctx->instrs + ctx->ninstrs;
2195         const struct nand_op_instr *instr = ctx->subop.instrs;
2196         unsigned int i, ninstrs;
2197
2198         for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
2199                 /*
2200                  * The pattern instruction does not match the operation
2201                  * instruction. If the instruction is marked optional in the
2202                  * pattern definition, we skip the pattern element and continue
2203                  * to the next one. If the element is mandatory, there's no
2204                  * match and we can return false directly.
2205                  */
2206                 if (instr->type != pat->elems[i].type) {
2207                         if (!pat->elems[i].optional)
2208                                 return false;
2209
2210                         continue;
2211                 }
2212
2213                 /*
2214                  * Now check the pattern element constraints. If the pattern is
2215                  * not able to handle the whole instruction in a single step,
2216                  * we have to split it.
2217                  * The last_instr_end_off value comes back updated to point to
2218                  * the position where we have to split the instruction (the
2219                  * start of the next subop chunk).
2220                  */
2221                 if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
2222                                                     &instr_offset)) {
2223                         ninstrs++;
2224                         i++;
2225                         break;
2226                 }
2227
2228                 instr++;
2229                 ninstrs++;
2230                 instr_offset = 0;
2231         }
2232
2233         /*
2234          * This can happen if all instructions of a pattern are optional.
2235          * Still, if there's not at least one instruction handled by this
2236          * pattern, this is not a match, and we should try the next one (if
2237          * any).
2238          */
2239         if (!ninstrs)
2240                 return false;
2241
2242         /*
2243          * We had a match on the pattern head, but the pattern may be longer
2244          * than the instructions we're asked to execute. We need to make sure
2245          * there's no mandatory elements in the pattern tail.
2246          */
2247         for (; i < pat->nelems; i++) {
2248                 if (!pat->elems[i].optional)
2249                         return false;
2250         }
2251
2252         /*
2253          * We have a match: update the subop structure accordingly and return
2254          * true.
2255          */
2256         ctx->subop.ninstrs = ninstrs;
2257         ctx->subop.last_instr_end_off = instr_offset;
2258
2259         return true;
2260 }
2261
2262 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
2263 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2264 {
2265         const struct nand_op_instr *instr;
2266         char *prefix = "      ";
2267         unsigned int i;
2268
2269         pr_debug("executing subop (CS%d):\n", ctx->subop.cs);
2270
2271         for (i = 0; i < ctx->ninstrs; i++) {
2272                 instr = &ctx->instrs[i];
2273
2274                 if (instr == &ctx->subop.instrs[0])
2275                         prefix = "    ->";
2276
2277                 nand_op_trace(prefix, instr);
2278
2279                 if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
2280                         prefix = "      ";
2281         }
2282 }
2283 #else
2284 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2285 {
2286         /* NOP */
2287 }
2288 #endif
2289
2290 static int nand_op_parser_cmp_ctx(const struct nand_op_parser_ctx *a,
2291                                   const struct nand_op_parser_ctx *b)
2292 {
2293         if (a->subop.ninstrs < b->subop.ninstrs)
2294                 return -1;
2295         else if (a->subop.ninstrs > b->subop.ninstrs)
2296                 return 1;
2297
2298         if (a->subop.last_instr_end_off < b->subop.last_instr_end_off)
2299                 return -1;
2300         else if (a->subop.last_instr_end_off > b->subop.last_instr_end_off)
2301                 return 1;
2302
2303         return 0;
2304 }
2305
2306 /**
2307  * nand_op_parser_exec_op - exec_op parser
2308  * @chip: the NAND chip
2309  * @parser: patterns description provided by the controller driver
2310  * @op: the NAND operation to address
2311  * @check_only: when true, the function only checks if @op can be handled but
2312  *              does not execute the operation
2313  *
2314  * Helper function designed to ease integration of NAND controller drivers that
2315  * only support a limited set of instruction sequences. The supported sequences
2316  * are described in @parser, and the framework takes care of splitting @op into
2317  * multiple sub-operations (if required) and pass them back to the ->exec()
2318  * callback of the matching pattern if @check_only is set to false.
2319  *
2320  * NAND controller drivers should call this function from their own ->exec_op()
2321  * implementation.
2322  *
2323  * Returns 0 on success, a negative error code otherwise. A failure can be
2324  * caused by an unsupported operation (none of the supported patterns is able
2325  * to handle the requested operation), or an error returned by one of the
2326  * matching pattern->exec() hook.
2327  */
2328 int nand_op_parser_exec_op(struct nand_chip *chip,
2329                            const struct nand_op_parser *parser,
2330                            const struct nand_operation *op, bool check_only)
2331 {
2332         struct nand_op_parser_ctx ctx = {
2333                 .subop.cs = op->cs,
2334                 .subop.instrs = op->instrs,
2335                 .instrs = op->instrs,
2336                 .ninstrs = op->ninstrs,
2337         };
2338         unsigned int i;
2339
2340         while (ctx.subop.instrs < op->instrs + op->ninstrs) {
2341                 const struct nand_op_parser_pattern *pattern;
2342                 struct nand_op_parser_ctx best_ctx;
2343                 int ret, best_pattern = -1;
2344
2345                 for (i = 0; i < parser->npatterns; i++) {
2346                         struct nand_op_parser_ctx test_ctx = ctx;
2347
2348                         pattern = &parser->patterns[i];
2349                         if (!nand_op_parser_match_pat(pattern, &test_ctx))
2350                                 continue;
2351
2352                         if (best_pattern >= 0 &&
2353                             nand_op_parser_cmp_ctx(&test_ctx, &best_ctx) <= 0)
2354                                 continue;
2355
2356                         best_pattern = i;
2357                         best_ctx = test_ctx;
2358                 }
2359
2360                 if (best_pattern < 0) {
2361                         pr_debug("->exec_op() parser: pattern not found!\n");
2362                         return -ENOTSUPP;
2363                 }
2364
2365                 ctx = best_ctx;
2366                 nand_op_parser_trace(&ctx);
2367
2368                 if (!check_only) {
2369                         pattern = &parser->patterns[best_pattern];
2370                         ret = pattern->exec(chip, &ctx.subop);
2371                         if (ret)
2372                                 return ret;
2373                 }
2374
2375                 /*
2376                  * Update the context structure by pointing to the start of the
2377                  * next subop.
2378                  */
2379                 ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
2380                 if (ctx.subop.last_instr_end_off)
2381                         ctx.subop.instrs -= 1;
2382
2383                 ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
2384         }
2385
2386         return 0;
2387 }
2388 EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
2389
2390 static bool nand_instr_is_data(const struct nand_op_instr *instr)
2391 {
2392         return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
2393                          instr->type == NAND_OP_DATA_OUT_INSTR);
2394 }
2395
2396 static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
2397                                       unsigned int instr_idx)
2398 {
2399         return subop && instr_idx < subop->ninstrs;
2400 }
2401
2402 static unsigned int nand_subop_get_start_off(const struct nand_subop *subop,
2403                                              unsigned int instr_idx)
2404 {
2405         if (instr_idx)
2406                 return 0;
2407
2408         return subop->first_instr_start_off;
2409 }
2410
2411 /**
2412  * nand_subop_get_addr_start_off - Get the start offset in an address array
2413  * @subop: The entire sub-operation
2414  * @instr_idx: Index of the instruction inside the sub-operation
2415  *
2416  * During driver development, one could be tempted to directly use the
2417  * ->addr.addrs field of address instructions. This is wrong as address
2418  * instructions might be split.
2419  *
2420  * Given an address instruction, returns the offset of the first cycle to issue.
2421  */
2422 unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
2423                                            unsigned int instr_idx)
2424 {
2425         if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2426                     subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2427                 return 0;
2428
2429         return nand_subop_get_start_off(subop, instr_idx);
2430 }
2431 EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
2432
2433 /**
2434  * nand_subop_get_num_addr_cyc - Get the remaining address cycles to assert
2435  * @subop: The entire sub-operation
2436  * @instr_idx: Index of the instruction inside the sub-operation
2437  *
2438  * During driver development, one could be tempted to directly use the
2439  * ->addr->naddrs field of a data instruction. This is wrong as instructions
2440  * might be split.
2441  *
2442  * Given an address instruction, returns the number of address cycle to issue.
2443  */
2444 unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
2445                                          unsigned int instr_idx)
2446 {
2447         int start_off, end_off;
2448
2449         if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2450                     subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2451                 return 0;
2452
2453         start_off = nand_subop_get_addr_start_off(subop, instr_idx);
2454
2455         if (instr_idx == subop->ninstrs - 1 &&
2456             subop->last_instr_end_off)
2457                 end_off = subop->last_instr_end_off;
2458         else
2459                 end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
2460
2461         return end_off - start_off;
2462 }
2463 EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
2464
2465 /**
2466  * nand_subop_get_data_start_off - Get the start offset in a data array
2467  * @subop: The entire sub-operation
2468  * @instr_idx: Index of the instruction inside the sub-operation
2469  *
2470  * During driver development, one could be tempted to directly use the
2471  * ->data->buf.{in,out} field of data instructions. This is wrong as data
2472  * instructions might be split.
2473  *
2474  * Given a data instruction, returns the offset to start from.
2475  */
2476 unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
2477                                            unsigned int instr_idx)
2478 {
2479         if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2480                     !nand_instr_is_data(&subop->instrs[instr_idx])))
2481                 return 0;
2482
2483         return nand_subop_get_start_off(subop, instr_idx);
2484 }
2485 EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
2486
2487 /**
2488  * nand_subop_get_data_len - Get the number of bytes to retrieve
2489  * @subop: The entire sub-operation
2490  * @instr_idx: Index of the instruction inside the sub-operation
2491  *
2492  * During driver development, one could be tempted to directly use the
2493  * ->data->len field of a data instruction. This is wrong as data instructions
2494  * might be split.
2495  *
2496  * Returns the length of the chunk of data to send/receive.
2497  */
2498 unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
2499                                      unsigned int instr_idx)
2500 {
2501         int start_off = 0, end_off;
2502
2503         if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2504                     !nand_instr_is_data(&subop->instrs[instr_idx])))
2505                 return 0;
2506
2507         start_off = nand_subop_get_data_start_off(subop, instr_idx);
2508
2509         if (instr_idx == subop->ninstrs - 1 &&
2510             subop->last_instr_end_off)
2511                 end_off = subop->last_instr_end_off;
2512         else
2513                 end_off = subop->instrs[instr_idx].ctx.data.len;
2514
2515         return end_off - start_off;
2516 }
2517 EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
2518
2519 /**
2520  * nand_reset - Reset and initialize a NAND device
2521  * @chip: The NAND chip
2522  * @chipnr: Internal die id
2523  *
2524  * Save the timings data structure, then apply SDR timings mode 0 (see
2525  * nand_reset_interface for details), do the reset operation, and apply
2526  * back the previous timings.
2527  *
2528  * Returns 0 on success, a negative error code otherwise.
2529  */
2530 int nand_reset(struct nand_chip *chip, int chipnr)
2531 {
2532         int ret;
2533
2534         ret = nand_reset_interface(chip, chipnr);
2535         if (ret)
2536                 return ret;
2537
2538         /*
2539          * The CS line has to be released before we can apply the new NAND
2540          * interface settings, hence this weird nand_select_target()
2541          * nand_deselect_target() dance.
2542          */
2543         nand_select_target(chip, chipnr);
2544         ret = nand_reset_op(chip);
2545         nand_deselect_target(chip);
2546         if (ret)
2547                 return ret;
2548
2549         ret = nand_setup_interface(chip, chipnr);
2550         if (ret)
2551                 return ret;
2552
2553         return 0;
2554 }
2555 EXPORT_SYMBOL_GPL(nand_reset);
2556
2557 /**
2558  * nand_get_features - wrapper to perform a GET_FEATURE
2559  * @chip: NAND chip info structure
2560  * @addr: feature address
2561  * @subfeature_param: the subfeature parameters, a four bytes array
2562  *
2563  * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2564  * operation cannot be handled.
2565  */
2566 int nand_get_features(struct nand_chip *chip, int addr,
2567                       u8 *subfeature_param)
2568 {
2569         if (!nand_supports_get_features(chip, addr))
2570                 return -ENOTSUPP;
2571
2572         if (chip->legacy.get_features)
2573                 return chip->legacy.get_features(chip, addr, subfeature_param);
2574
2575         return nand_get_features_op(chip, addr, subfeature_param);
2576 }
2577
2578 /**
2579  * nand_set_features - wrapper to perform a SET_FEATURE
2580  * @chip: NAND chip info structure
2581  * @addr: feature address
2582  * @subfeature_param: the subfeature parameters, a four bytes array
2583  *
2584  * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2585  * operation cannot be handled.
2586  */
2587 int nand_set_features(struct nand_chip *chip, int addr,
2588                       u8 *subfeature_param)
2589 {
2590         if (!nand_supports_set_features(chip, addr))
2591                 return -ENOTSUPP;
2592
2593         if (chip->legacy.set_features)
2594                 return chip->legacy.set_features(chip, addr, subfeature_param);
2595
2596         return nand_set_features_op(chip, addr, subfeature_param);
2597 }
2598
2599 /**
2600  * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
2601  * @buf: buffer to test
2602  * @len: buffer length
2603  * @bitflips_threshold: maximum number of bitflips
2604  *
2605  * Check if a buffer contains only 0xff, which means the underlying region
2606  * has been erased and is ready to be programmed.
2607  * The bitflips_threshold specify the maximum number of bitflips before
2608  * considering the region is not erased.
2609  * Note: The logic of this function has been extracted from the memweight
2610  * implementation, except that nand_check_erased_buf function exit before
2611  * testing the whole buffer if the number of bitflips exceed the
2612  * bitflips_threshold value.
2613  *
2614  * Returns a positive number of bitflips less than or equal to
2615  * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2616  * threshold.
2617  */
2618 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
2619 {
2620         const unsigned char *bitmap = buf;
2621         int bitflips = 0;
2622         int weight;
2623
2624         for (; len && ((uintptr_t)bitmap) % sizeof(long);
2625              len--, bitmap++) {
2626                 weight = hweight8(*bitmap);
2627                 bitflips += BITS_PER_BYTE - weight;
2628                 if (unlikely(bitflips > bitflips_threshold))
2629                         return -EBADMSG;
2630         }
2631
2632         for (; len >= sizeof(long);
2633              len -= sizeof(long), bitmap += sizeof(long)) {
2634                 unsigned long d = *((unsigned long *)bitmap);
2635                 if (d == ~0UL)
2636                         continue;
2637                 weight = hweight_long(d);
2638                 bitflips += BITS_PER_LONG - weight;
2639                 if (unlikely(bitflips > bitflips_threshold))
2640                         return -EBADMSG;
2641         }
2642
2643         for (; len > 0; len--, bitmap++) {
2644                 weight = hweight8(*bitmap);
2645                 bitflips += BITS_PER_BYTE - weight;
2646                 if (unlikely(bitflips > bitflips_threshold))
2647                         return -EBADMSG;
2648         }
2649
2650         return bitflips;
2651 }
2652
2653 /**
2654  * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
2655  *                               0xff data
2656  * @data: data buffer to test
2657  * @datalen: data length
2658  * @ecc: ECC buffer
2659  * @ecclen: ECC length
2660  * @extraoob: extra OOB buffer
2661  * @extraooblen: extra OOB length
2662  * @bitflips_threshold: maximum number of bitflips
2663  *
2664  * Check if a data buffer and its associated ECC and OOB data contains only
2665  * 0xff pattern, which means the underlying region has been erased and is
2666  * ready to be programmed.
2667  * The bitflips_threshold specify the maximum number of bitflips before
2668  * considering the region as not erased.
2669  *
2670  * Note:
2671  * 1/ ECC algorithms are working on pre-defined block sizes which are usually
2672  *    different from the NAND page size. When fixing bitflips, ECC engines will
2673  *    report the number of errors per chunk, and the NAND core infrastructure
2674  *    expect you to return the maximum number of bitflips for the whole page.
2675  *    This is why you should always use this function on a single chunk and
2676  *    not on the whole page. After checking each chunk you should update your
2677  *    max_bitflips value accordingly.
2678  * 2/ When checking for bitflips in erased pages you should not only check
2679  *    the payload data but also their associated ECC data, because a user might
2680  *    have programmed almost all bits to 1 but a few. In this case, we
2681  *    shouldn't consider the chunk as erased, and checking ECC bytes prevent
2682  *    this case.
2683  * 3/ The extraoob argument is optional, and should be used if some of your OOB
2684  *    data are protected by the ECC engine.
2685  *    It could also be used if you support subpages and want to attach some
2686  *    extra OOB data to an ECC chunk.
2687  *
2688  * Returns a positive number of bitflips less than or equal to
2689  * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2690  * threshold. In case of success, the passed buffers are filled with 0xff.
2691  */
2692 int nand_check_erased_ecc_chunk(void *data, int datalen,
2693                                 void *ecc, int ecclen,
2694                                 void *extraoob, int extraooblen,
2695                                 int bitflips_threshold)
2696 {
2697         int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
2698
2699         data_bitflips = nand_check_erased_buf(data, datalen,
2700                                               bitflips_threshold);
2701         if (data_bitflips < 0)
2702                 return data_bitflips;
2703
2704         bitflips_threshold -= data_bitflips;
2705
2706         ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
2707         if (ecc_bitflips < 0)
2708                 return ecc_bitflips;
2709
2710         bitflips_threshold -= ecc_bitflips;
2711
2712         extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
2713                                                   bitflips_threshold);
2714         if (extraoob_bitflips < 0)
2715                 return extraoob_bitflips;
2716
2717         if (data_bitflips)
2718                 memset(data, 0xff, datalen);
2719
2720         if (ecc_bitflips)
2721                 memset(ecc, 0xff, ecclen);
2722
2723         if (extraoob_bitflips)
2724                 memset(extraoob, 0xff, extraooblen);
2725
2726         return data_bitflips + ecc_bitflips + extraoob_bitflips;
2727 }
2728 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
2729
2730 /**
2731  * nand_read_page_raw_notsupp - dummy read raw page function
2732  * @chip: nand chip info structure
2733  * @buf: buffer to store read data
2734  * @oob_required: caller requires OOB data read to chip->oob_poi
2735  * @page: page number to read
2736  *
2737  * Returns -ENOTSUPP unconditionally.
2738  */
2739 int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf,
2740                                int oob_required, int page)
2741 {
2742         return -ENOTSUPP;
2743 }
2744
2745 /**
2746  * nand_read_page_raw - [INTERN] read raw page data without ecc
2747  * @chip: nand chip info structure
2748  * @buf: buffer to store read data
2749  * @oob_required: caller requires OOB data read to chip->oob_poi
2750  * @page: page number to read
2751  *
2752  * Not for syndrome calculating ECC controllers, which use a special oob layout.
2753  */
2754 int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
2755                        int page)
2756 {
2757         struct mtd_info *mtd = nand_to_mtd(chip);
2758         int ret;
2759
2760         ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
2761         if (ret)
2762                 return ret;
2763
2764         if (oob_required) {
2765                 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
2766                                         false, false);
2767                 if (ret)
2768                         return ret;
2769         }
2770
2771         return 0;
2772 }
2773 EXPORT_SYMBOL(nand_read_page_raw);
2774
2775 /**
2776  * nand_monolithic_read_page_raw - Monolithic page read in raw mode
2777  * @chip: NAND chip info structure
2778  * @buf: buffer to store read data
2779  * @oob_required: caller requires OOB data read to chip->oob_poi
2780  * @page: page number to read
2781  *
2782  * This is a raw page read, ie. without any error detection/correction.
2783  * Monolithic means we are requesting all the relevant data (main plus
2784  * eventually OOB) to be loaded in the NAND cache and sent over the
2785  * bus (from the NAND chip to the NAND controller) in a single
2786  * operation. This is an alternative to nand_read_page_raw(), which
2787  * first reads the main data, and if the OOB data is requested too,
2788  * then reads more data on the bus.
2789  */
2790 int nand_monolithic_read_page_raw(struct nand_chip *chip, u8 *buf,
2791                                   int oob_required, int page)
2792 {
2793         struct mtd_info *mtd = nand_to_mtd(chip);
2794         unsigned int size = mtd->writesize;
2795         u8 *read_buf = buf;
2796         int ret;
2797
2798         if (oob_required) {
2799                 size += mtd->oobsize;
2800
2801                 if (buf != chip->data_buf)
2802                         read_buf = nand_get_data_buf(chip);
2803         }
2804
2805         ret = nand_read_page_op(chip, page, 0, read_buf, size);
2806         if (ret)
2807                 return ret;
2808
2809         if (buf != chip->data_buf)
2810                 memcpy(buf, read_buf, mtd->writesize);
2811
2812         return 0;
2813 }
2814 EXPORT_SYMBOL(nand_monolithic_read_page_raw);
2815
2816 /**
2817  * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
2818  * @chip: nand chip info structure
2819  * @buf: buffer to store read data
2820  * @oob_required: caller requires OOB data read to chip->oob_poi
2821  * @page: page number to read
2822  *
2823  * We need a special oob layout and handling even when OOB isn't used.
2824  */
2825 static int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf,
2826                                        int oob_required, int page)
2827 {
2828         struct mtd_info *mtd = nand_to_mtd(chip);
2829         int eccsize = chip->ecc.size;
2830         int eccbytes = chip->ecc.bytes;
2831         uint8_t *oob = chip->oob_poi;
2832         int steps, size, ret;
2833
2834         ret = nand_read_page_op(chip, page, 0, NULL, 0);
2835         if (ret)
2836                 return ret;
2837
2838         for (steps = chip->ecc.steps; steps > 0; steps--) {
2839                 ret = nand_read_data_op(chip, buf, eccsize, false, false);
2840                 if (ret)
2841                         return ret;
2842
2843                 buf += eccsize;
2844
2845                 if (chip->ecc.prepad) {
2846                         ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2847                                                 false, false);
2848                         if (ret)
2849                                 return ret;
2850
2851                         oob += chip->ecc.prepad;
2852                 }
2853
2854                 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
2855                 if (ret)
2856                         return ret;
2857
2858                 oob += eccbytes;
2859
2860                 if (chip->ecc.postpad) {
2861                         ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2862                                                 false, false);
2863                         if (ret)
2864                                 return ret;
2865
2866                         oob += chip->ecc.postpad;
2867                 }
2868         }
2869
2870         size = mtd->oobsize - (oob - chip->oob_poi);
2871         if (size) {
2872                 ret = nand_read_data_op(chip, oob, size, false, false);
2873                 if (ret)
2874                         return ret;
2875         }
2876
2877         return 0;
2878 }
2879
2880 /**
2881  * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
2882  * @chip: nand chip info structure
2883  * @buf: buffer to store read data
2884  * @oob_required: caller requires OOB data read to chip->oob_poi
2885  * @page: page number to read
2886  */
2887 static int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf,
2888                                 int oob_required, int page)
2889 {
2890         struct mtd_info *mtd = nand_to_mtd(chip);
2891         int i, eccsize = chip->ecc.size, ret;
2892         int eccbytes = chip->ecc.bytes;
2893         int eccsteps = chip->ecc.steps;
2894         uint8_t *p = buf;
2895         uint8_t *ecc_calc = chip->ecc.calc_buf;
2896         uint8_t *ecc_code = chip->ecc.code_buf;
2897         unsigned int max_bitflips = 0;
2898
2899         chip->ecc.read_page_raw(chip, buf, 1, page);
2900
2901         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2902                 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2903
2904         ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2905                                          chip->ecc.total);
2906         if (ret)
2907                 return ret;
2908
2909         eccsteps = chip->ecc.steps;
2910         p = buf;
2911
2912         for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2913                 int stat;
2914
2915                 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
2916                 if (stat < 0) {
2917                         mtd->ecc_stats.failed++;
2918                 } else {
2919                         mtd->ecc_stats.corrected += stat;
2920                         max_bitflips = max_t(unsigned int, max_bitflips, stat);
2921                 }
2922         }
2923         return max_bitflips;
2924 }
2925
2926 /**
2927  * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
2928  * @chip: nand chip info structure
2929  * @data_offs: offset of requested data within the page
2930  * @readlen: data length
2931  * @bufpoi: buffer to store read data
2932  * @page: page number to read
2933  */
2934 static int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs,
2935                              uint32_t readlen, uint8_t *bufpoi, int page)
2936 {
2937         struct mtd_info *mtd = nand_to_mtd(chip);
2938         int start_step, end_step, num_steps, ret;
2939         uint8_t *p;
2940         int data_col_addr, i, gaps = 0;
2941         int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
2942         int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
2943         int index, section = 0;
2944         unsigned int max_bitflips = 0;
2945         struct mtd_oob_region oobregion = { };
2946
2947         /* Column address within the page aligned to ECC size (256bytes) */
2948         start_step = data_offs / chip->ecc.size;
2949         end_step = (data_offs + readlen - 1) / chip->ecc.size;
2950         num_steps = end_step - start_step + 1;
2951         index = start_step * chip->ecc.bytes;
2952
2953         /* Data size aligned to ECC ecc.size */
2954         datafrag_len = num_steps * chip->ecc.size;
2955         eccfrag_len = num_steps * chip->ecc.bytes;
2956
2957         data_col_addr = start_step * chip->ecc.size;
2958         /* If we read not a page aligned data */
2959         p = bufpoi + data_col_addr;
2960         ret = nand_read_page_op(chip, page, data_col_addr, p, datafrag_len);
2961         if (ret)
2962                 return ret;
2963
2964         /* Calculate ECC */
2965         for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
2966                 chip->ecc.calculate(chip, p, &chip->ecc.calc_buf[i]);
2967
2968         /*
2969          * The performance is faster if we position offsets according to
2970          * ecc.pos. Let's make sure that there are no gaps in ECC positions.
2971          */
2972         ret = mtd_ooblayout_find_eccregion(mtd, index, &section, &oobregion);
2973         if (ret)
2974                 return ret;
2975
2976         if (oobregion.length < eccfrag_len)
2977                 gaps = 1;
2978
2979         if (gaps) {
2980                 ret = nand_change_read_column_op(chip, mtd->writesize,
2981                                                  chip->oob_poi, mtd->oobsize,
2982                                                  false);
2983                 if (ret)
2984                         return ret;
2985         } else {
2986                 /*
2987                  * Send the command to read the particular ECC bytes take care
2988                  * about buswidth alignment in read_buf.
2989                  */
2990                 aligned_pos = oobregion.offset & ~(busw - 1);
2991                 aligned_len = eccfrag_len;
2992                 if (oobregion.offset & (busw - 1))
2993                         aligned_len++;
2994                 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
2995                     (busw - 1))
2996                         aligned_len++;
2997
2998                 ret = nand_change_read_column_op(chip,
2999                                                  mtd->writesize + aligned_pos,
3000                                                  &chip->oob_poi[aligned_pos],
3001                                                  aligned_len, false);
3002                 if (ret)
3003                         return ret;
3004         }
3005
3006         ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
3007                                          chip->oob_poi, index, eccfrag_len);
3008         if (ret)
3009                 return ret;
3010
3011         p = bufpoi + data_col_addr;
3012         for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
3013                 int stat;
3014
3015                 stat = chip->ecc.correct(chip, p, &chip->ecc.code_buf[i],
3016                                          &chip->ecc.calc_buf[i]);
3017                 if (stat == -EBADMSG &&
3018                     (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3019                         /* check for empty pages with bitflips */
3020                         stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3021                                                 &chip->ecc.code_buf[i],
3022                                                 chip->ecc.bytes,
3023                                                 NULL, 0,
3024                                                 chip->ecc.strength);
3025                 }
3026
3027                 if (stat < 0) {
3028                         mtd->ecc_stats.failed++;
3029                 } else {
3030                         mtd->ecc_stats.corrected += stat;
3031                         max_bitflips = max_t(unsigned int, max_bitflips, stat);
3032                 }
3033         }
3034         return max_bitflips;
3035 }
3036
3037 /**
3038  * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
3039  * @chip: nand chip info structure
3040  * @buf: buffer to store read data
3041  * @oob_required: caller requires OOB data read to chip->oob_poi
3042  * @page: page number to read
3043  *
3044  * Not for syndrome calculating ECC controllers which need a special oob layout.
3045  */
3046 static int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf,
3047                                 int oob_required, int page)
3048 {
3049         struct mtd_info *mtd = nand_to_mtd(chip);
3050         int i, eccsize = chip->ecc.size, ret;
3051         int eccbytes = chip->ecc.bytes;
3052         int eccsteps = chip->ecc.steps;
3053         uint8_t *p = buf;
3054         uint8_t *ecc_calc = chip->ecc.calc_buf;
3055         uint8_t *ecc_code = chip->ecc.code_buf;
3056         unsigned int max_bitflips = 0;
3057
3058         ret = nand_read_page_op(chip, page, 0, NULL, 0);
3059         if (ret)
3060                 return ret;
3061
3062         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3063                 chip->ecc.hwctl(chip, NAND_ECC_READ);
3064
3065                 ret = nand_read_data_op(chip, p, eccsize, false, false);
3066                 if (ret)
3067                         return ret;
3068
3069                 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3070         }
3071
3072         ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false,
3073                                 false);
3074         if (ret)
3075                 return ret;
3076
3077         ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3078                                          chip->ecc.total);
3079         if (ret)
3080                 return ret;
3081
3082         eccsteps = chip->ecc.steps;
3083         p = buf;
3084
3085         for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3086                 int stat;
3087
3088                 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
3089                 if (stat == -EBADMSG &&
3090                     (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3091                         /* check for empty pages with bitflips */
3092                         stat = nand_check_erased_ecc_chunk(p, eccsize,
3093                                                 &ecc_code[i], eccbytes,
3094                                                 NULL, 0,
3095                                                 chip->ecc.strength);
3096                 }
3097
3098                 if (stat < 0) {
3099                         mtd->ecc_stats.failed++;
3100                 } else {
3101                         mtd->ecc_stats.corrected += stat;
3102                         max_bitflips = max_t(unsigned int, max_bitflips, stat);
3103                 }
3104         }
3105         return max_bitflips;
3106 }
3107
3108 /**
3109  * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
3110  * @chip: nand chip info structure
3111  * @buf: buffer to store read data
3112  * @oob_required: caller requires OOB data read to chip->oob_poi
3113  * @page: page number to read
3114  *
3115  * The hw generator calculates the error syndrome automatically. Therefore we
3116  * need a special oob layout and handling.
3117  */
3118 static int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf,
3119                                    int oob_required, int page)
3120 {
3121         struct mtd_info *mtd = nand_to_mtd(chip);
3122         int ret, i, eccsize = chip->ecc.size;
3123         int eccbytes = chip->ecc.bytes;
3124         int eccsteps = chip->ecc.steps;
3125         int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
3126         uint8_t *p = buf;
3127         uint8_t *oob = chip->oob_poi;
3128         unsigned int max_bitflips = 0;
3129
3130         ret = nand_read_page_op(chip, page, 0, NULL, 0);
3131         if (ret)
3132                 return ret;
3133
3134         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3135                 int stat;
3136
3137                 chip->ecc.hwctl(chip, NAND_ECC_READ);
3138
3139                 ret = nand_read_data_op(chip, p, eccsize, false, false);
3140                 if (ret)
3141                         return ret;
3142
3143                 if (chip->ecc.prepad) {
3144                         ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3145                                                 false, false);
3146                         if (ret)
3147                                 return ret;
3148
3149                         oob += chip->ecc.prepad;
3150                 }
3151
3152                 chip->ecc.hwctl(chip, NAND_ECC_READSYN);
3153
3154                 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
3155                 if (ret)
3156                         return ret;
3157
3158                 stat = chip->ecc.correct(chip, p, oob, NULL);
3159
3160                 oob += eccbytes;
3161
3162                 if (chip->ecc.postpad) {
3163                         ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3164                                                 false, false);
3165                         if (ret)
3166                                 return ret;
3167
3168                         oob += chip->ecc.postpad;
3169                 }
3170
3171                 if (stat == -EBADMSG &&
3172                     (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3173                         /* check for empty pages with bitflips */
3174                         stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3175                                                            oob - eccpadbytes,
3176                                                            eccpadbytes,
3177                                                            NULL, 0,
3178                                                            chip->ecc.strength);
3179                 }
3180
3181                 if (stat < 0) {
3182                         mtd->ecc_stats.failed++;
3183                 } else {
3184                         mtd->ecc_stats.corrected += stat;
3185                         max_bitflips = max_t(unsigned int, max_bitflips, stat);
3186                 }
3187         }
3188
3189         /* Calculate remaining oob bytes */
3190         i = mtd->oobsize - (oob - chip->oob_poi);
3191         if (i) {
3192                 ret = nand_read_data_op(chip, oob, i, false, false);
3193                 if (ret)
3194                         return ret;
3195         }
3196
3197         return max_bitflips;
3198 }
3199
3200 /**
3201  * nand_transfer_oob - [INTERN] Transfer oob to client buffer
3202  * @chip: NAND chip object
3203  * @oob: oob destination address
3204  * @ops: oob ops structure
3205  * @len: size of oob to transfer
3206  */
3207 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
3208                                   struct mtd_oob_ops *ops, size_t len)
3209 {
3210         struct mtd_info *mtd = nand_to_mtd(chip);
3211         int ret;
3212
3213         switch (ops->mode) {
3214
3215         case MTD_OPS_PLACE_OOB:
3216         case MTD_OPS_RAW:
3217                 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
3218                 return oob + len;
3219
3220         case MTD_OPS_AUTO_OOB:
3221                 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
3222                                                   ops->ooboffs, len);
3223                 BUG_ON(ret);
3224                 return oob + len;
3225
3226         default:
3227                 BUG();
3228         }
3229         return NULL;
3230 }
3231
3232 /**
3233  * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
3234  * @chip: NAND chip object
3235  * @retry_mode: the retry mode to use
3236  *
3237  * Some vendors supply a special command to shift the Vt threshold, to be used
3238  * when there are too many bitflips in a page (i.e., ECC error). After setting
3239  * a new threshold, the host should retry reading the page.
3240  */
3241 static int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
3242 {
3243         pr_debug("setting READ RETRY mode %d\n", retry_mode);
3244
3245         if (retry_mode >= chip->read_retries)
3246                 return -EINVAL;
3247
3248         if (!chip->ops.setup_read_retry)
3249                 return -EOPNOTSUPP;
3250
3251         return chip->ops.setup_read_retry(chip, retry_mode);
3252 }
3253
3254 static void nand_wait_readrdy(struct nand_chip *chip)
3255 {
3256         const struct nand_sdr_timings *sdr;
3257
3258         if (!(chip->options & NAND_NEED_READRDY))
3259                 return;
3260
3261         sdr = nand_get_sdr_timings(nand_get_interface_config(chip));
3262         WARN_ON(nand_wait_rdy_op(chip, PSEC_TO_MSEC(sdr->tR_max), 0));
3263 }
3264
3265 /**
3266  * nand_do_read_ops - [INTERN] Read data with ECC
3267  * @chip: NAND chip object
3268  * @from: offset to read from
3269  * @ops: oob ops structure
3270  *
3271  * Internal function. Called with chip held.
3272  */
3273 static int nand_do_read_ops(struct nand_chip *chip, loff_t from,
3274                             struct mtd_oob_ops *ops)
3275 {
3276         int chipnr, page, realpage, col, bytes, aligned, oob_required;
3277         struct mtd_info *mtd = nand_to_mtd(chip);
3278         int ret = 0;
3279         uint32_t readlen = ops->len;
3280         uint32_t oobreadlen = ops->ooblen;
3281         uint32_t max_oobsize = mtd_oobavail(mtd, ops);
3282
3283         uint8_t *bufpoi, *oob, *buf;
3284         int use_bounce_buf;
3285         unsigned int max_bitflips = 0;
3286         int retry_mode = 0;
3287         bool ecc_fail = false;
3288
3289         chipnr = (int)(from >> chip->chip_shift);
3290         nand_select_target(chip, chipnr);
3291
3292         realpage = (int)(from >> chip->page_shift);
3293         page = realpage & chip->pagemask;
3294
3295         col = (int)(from & (mtd->writesize - 1));
3296
3297         buf = ops->datbuf;
3298         oob = ops->oobbuf;
3299         oob_required = oob ? 1 : 0;
3300
3301         while (1) {
3302                 struct mtd_ecc_stats ecc_stats = mtd->ecc_stats;
3303
3304                 bytes = min(mtd->writesize - col, readlen);
3305                 aligned = (bytes == mtd->writesize);
3306
3307                 if (!aligned)
3308                         use_bounce_buf = 1;
3309                 else if (chip->options & NAND_USES_DMA)
3310                         use_bounce_buf = !virt_addr_valid(buf) ||
3311                                          !IS_ALIGNED((unsigned long)buf,
3312                                                      chip->buf_align);
3313                 else
3314                         use_bounce_buf = 0;
3315
3316                 /* Is the current page in the buffer? */
3317                 if (realpage != chip->pagecache.page || oob) {
3318                         bufpoi = use_bounce_buf ? chip->data_buf : buf;
3319
3320                         if (use_bounce_buf && aligned)
3321                                 pr_debug("%s: using read bounce buffer for buf@%p\n",
3322                                                  __func__, buf);
3323
3324 read_retry:
3325                         /*
3326                          * Now read the page into the buffer.  Absent an error,
3327                          * the read methods return max bitflips per ecc step.
3328                          */
3329                         if (unlikely(ops->mode == MTD_OPS_RAW))
3330                                 ret = chip->ecc.read_page_raw(chip, bufpoi,
3331                                                               oob_required,
3332                                                               page);
3333                         else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
3334                                  !oob)
3335                                 ret = chip->ecc.read_subpage(chip, col, bytes,
3336                                                              bufpoi, page);
3337                         else
3338                                 ret = chip->ecc.read_page(chip, bufpoi,
3339                                                           oob_required, page);
3340                         if (ret < 0) {
3341                                 if (use_bounce_buf)
3342                                         /* Invalidate page cache */
3343                                         chip->pagecache.page = -1;
3344                                 break;
3345                         }
3346
3347                         /*
3348                          * Copy back the data in the initial buffer when reading
3349                          * partial pages or when a bounce buffer is required.
3350                          */
3351                         if (use_bounce_buf) {
3352                                 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
3353                                     !(mtd->ecc_stats.failed - ecc_stats.failed) &&
3354                                     (ops->mode != MTD_OPS_RAW)) {
3355                                         chip->pagecache.page = realpage;
3356                                         chip->pagecache.bitflips = ret;
3357                                 } else {
3358                                         /* Invalidate page cache */
3359                                         chip->pagecache.page = -1;
3360                                 }
3361                                 memcpy(buf, bufpoi + col, bytes);
3362                         }
3363
3364                         if (unlikely(oob)) {
3365                                 int toread = min(oobreadlen, max_oobsize);
3366
3367                                 if (toread) {
3368                                         oob = nand_transfer_oob(chip, oob, ops,
3369                                                                 toread);
3370                                         oobreadlen -= toread;
3371                                 }
3372                         }
3373
3374                         nand_wait_readrdy(chip);
3375
3376                         if (mtd->ecc_stats.failed - ecc_stats.failed) {
3377                                 if (retry_mode + 1 < chip->read_retries) {
3378                                         retry_mode++;
3379                                         ret = nand_setup_read_retry(chip,
3380                                                         retry_mode);
3381                                         if (ret < 0)
3382                                                 break;
3383
3384                                         /* Reset ecc_stats; retry */
3385                                         mtd->ecc_stats = ecc_stats;
3386                                         goto read_retry;
3387                                 } else {
3388                                         /* No more retry modes; real failure */
3389                                         ecc_fail = true;
3390                                 }
3391                         }
3392
3393                         buf += bytes;
3394                         max_bitflips = max_t(unsigned int, max_bitflips, ret);
3395                 } else {
3396                         memcpy(buf, chip->data_buf + col, bytes);
3397                         buf += bytes;
3398                         max_bitflips = max_t(unsigned int, max_bitflips,
3399                                              chip->pagecache.bitflips);
3400                 }
3401
3402                 readlen -= bytes;
3403
3404                 /* Reset to retry mode 0 */
3405                 if (retry_mode) {
3406                         ret = nand_setup_read_retry(chip, 0);
3407                         if (ret < 0)
3408                                 break;
3409                         retry_mode = 0;
3410                 }
3411
3412                 if (!readlen)
3413                         break;
3414
3415                 /* For subsequent reads align to page boundary */
3416                 col = 0;
3417                 /* Increment page address */
3418                 realpage++;
3419
3420                 page = realpage & chip->pagemask;
3421                 /* Check, if we cross a chip boundary */
3422                 if (!page) {
3423                         chipnr++;
3424                         nand_deselect_target(chip);
3425                         nand_select_target(chip, chipnr);
3426                 }
3427         }
3428         nand_deselect_target(chip);
3429
3430         ops->retlen = ops->len - (size_t) readlen;
3431         if (oob)
3432                 ops->oobretlen = ops->ooblen - oobreadlen;
3433
3434         if (ret < 0)
3435                 return ret;
3436
3437         if (ecc_fail)
3438                 return -EBADMSG;
3439
3440         return max_bitflips;
3441 }
3442
3443 /**
3444  * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
3445  * @chip: nand chip info structure
3446  * @page: page number to read
3447  */
3448 int nand_read_oob_std(struct nand_chip *chip, int page)
3449 {
3450         struct mtd_info *mtd = nand_to_mtd(chip);
3451
3452         return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3453 }
3454 EXPORT_SYMBOL(nand_read_oob_std);
3455
3456 /**
3457  * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
3458  *                          with syndromes
3459  * @chip: nand chip info structure
3460  * @page: page number to read
3461  */
3462 static int nand_read_oob_syndrome(struct nand_chip *chip, int page)
3463 {
3464         struct mtd_info *mtd = nand_to_mtd(chip);
3465         int length = mtd->oobsize;
3466         int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3467         int eccsize = chip->ecc.size;
3468         uint8_t *bufpoi = chip->oob_poi;
3469         int i, toread, sndrnd = 0, pos, ret;
3470
3471         ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
3472         if (ret)
3473                 return ret;
3474
3475         for (i = 0; i < chip->ecc.steps; i++) {
3476                 if (sndrnd) {
3477                         int ret;
3478
3479                         pos = eccsize + i * (eccsize + chunk);
3480                         if (mtd->writesize > 512)
3481                                 ret = nand_change_read_column_op(chip, pos,
3482                                                                  NULL, 0,
3483                                                                  false);
3484                         else
3485                                 ret = nand_read_page_op(chip, page, pos, NULL,
3486                                                         0);
3487
3488                         if (ret)
3489                                 return ret;
3490                 } else
3491                         sndrnd = 1;
3492                 toread = min_t(int, length, chunk);
3493
3494                 ret = nand_read_data_op(chip, bufpoi, toread, false, false);
3495                 if (ret)
3496                         return ret;
3497
3498                 bufpoi += toread;
3499                 length -= toread;
3500         }
3501         if (length > 0) {
3502                 ret = nand_read_data_op(chip, bufpoi, length, false, false);
3503                 if (ret)
3504                         return ret;
3505         }
3506
3507         return 0;
3508 }
3509
3510 /**
3511  * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
3512  * @chip: nand chip info structure
3513  * @page: page number to write
3514  */
3515 int nand_write_oob_std(struct nand_chip *chip, int page)
3516 {
3517         struct mtd_info *mtd = nand_to_mtd(chip);
3518
3519         return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
3520                                  mtd->oobsize);
3521 }
3522 EXPORT_SYMBOL(nand_write_oob_std);
3523
3524 /**
3525  * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
3526  *                           with syndrome - only for large page flash
3527  * @chip: nand chip info structure
3528  * @page: page number to write
3529  */
3530 static int nand_write_oob_syndrome(struct nand_chip *chip, int page)
3531 {
3532         struct mtd_info *mtd = nand_to_mtd(chip);
3533         int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3534         int eccsize = chip->ecc.size, length = mtd->oobsize;
3535         int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
3536         const uint8_t *bufpoi = chip->oob_poi;
3537
3538         /*
3539          * data-ecc-data-ecc ... ecc-oob
3540          * or
3541          * data-pad-ecc-pad-data-pad .... ecc-pad-oob
3542          */
3543         if (!chip->ecc.prepad && !chip->ecc.postpad) {
3544                 pos = steps * (eccsize + chunk);
3545                 steps = 0;
3546         } else
3547                 pos = eccsize;
3548
3549         ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
3550         if (ret)
3551                 return ret;
3552
3553         for (i = 0; i < steps; i++) {
3554                 if (sndcmd) {
3555                         if (mtd->writesize <= 512) {
3556                                 uint32_t fill = 0xFFFFFFFF;
3557
3558                                 len = eccsize;
3559                                 while (len > 0) {
3560                                         int num = min_t(int, len, 4);
3561
3562                                         ret = nand_write_data_op(chip, &fill,
3563                                                                  num, false);
3564                                         if (ret)
3565                                                 return ret;
3566
3567                                         len -= num;
3568                                 }
3569                         } else {
3570                                 pos = eccsize + i * (eccsize + chunk);
3571                                 ret = nand_change_write_column_op(chip, pos,
3572                                                                   NULL, 0,
3573                                                                   false);
3574                                 if (ret)
3575                                         return ret;
3576                         }
3577                 } else
3578                         sndcmd = 1;
3579                 len = min_t(int, length, chunk);
3580
3581                 ret = nand_write_data_op(chip, bufpoi, len, false);
3582                 if (ret)
3583                         return ret;
3584
3585                 bufpoi += len;
3586                 length -= len;
3587         }
3588         if (length > 0) {
3589                 ret = nand_write_data_op(chip, bufpoi, length, false);
3590                 if (ret)
3591                         return ret;
3592         }
3593
3594         return nand_prog_page_end_op(chip);
3595 }
3596
3597 /**
3598  * nand_do_read_oob - [INTERN] NAND read out-of-band
3599  * @chip: NAND chip object
3600  * @from: offset to read from
3601  * @ops: oob operations description structure
3602  *
3603  * NAND read out-of-band data from the spare area.
3604  */
3605 static int nand_do_read_oob(struct nand_chip *chip, loff_t from,
3606                             struct mtd_oob_ops *ops)
3607 {
3608         struct mtd_info *mtd = nand_to_mtd(chip);
3609         unsigned int max_bitflips = 0;
3610         int page, realpage, chipnr;
3611         struct mtd_ecc_stats stats;
3612         int readlen = ops->ooblen;
3613         int len;
3614         uint8_t *buf = ops->oobbuf;
3615         int ret = 0;
3616
3617         pr_debug("%s: from = 0x%08Lx, len = %i\n",
3618                         __func__, (unsigned long long)from, readlen);
3619
3620         stats = mtd->ecc_stats;
3621
3622         len = mtd_oobavail(mtd, ops);
3623
3624         chipnr = (int)(from >> chip->chip_shift);
3625         nand_select_target(chip, chipnr);
3626
3627         /* Shift to get page */
3628         realpage = (int)(from >> chip->page_shift);
3629         page = realpage & chip->pagemask;
3630
3631         while (1) {
3632                 if (ops->mode == MTD_OPS_RAW)
3633                         ret = chip->ecc.read_oob_raw(chip, page);
3634                 else
3635                         ret = chip->ecc.read_oob(chip, page);
3636
3637                 if (ret < 0)
3638                         break;
3639
3640                 len = min(len, readlen);
3641                 buf = nand_transfer_oob(chip, buf, ops, len);
3642
3643                 nand_wait_readrdy(chip);
3644
3645                 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3646
3647                 readlen -= len;
3648                 if (!readlen)
3649                         break;
3650
3651                 /* Increment page address */
3652                 realpage++;
3653
3654                 page = realpage & chip->pagemask;
3655                 /* Check, if we cross a chip boundary */
3656                 if (!page) {
3657                         chipnr++;
3658                         nand_deselect_target(chip);
3659                         nand_select_target(chip, chipnr);
3660                 }
3661         }
3662         nand_deselect_target(chip);
3663
3664         ops->oobretlen = ops->ooblen - readlen;
3665
3666         if (ret < 0)
3667                 return ret;
3668
3669         if (mtd->ecc_stats.failed - stats.failed)
3670                 return -EBADMSG;
3671
3672         return max_bitflips;
3673 }
3674
3675 /**
3676  * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
3677  * @mtd: MTD device structure
3678  * @from: offset to read from
3679  * @ops: oob operation description structure
3680  *
3681  * NAND read data and/or out-of-band data.
3682  */
3683 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
3684                          struct mtd_oob_ops *ops)
3685 {
3686         struct nand_chip *chip = mtd_to_nand(mtd);
3687         int ret;
3688
3689         ops->retlen = 0;
3690
3691         if (ops->mode != MTD_OPS_PLACE_OOB &&
3692             ops->mode != MTD_OPS_AUTO_OOB &&
3693             ops->mode != MTD_OPS_RAW)
3694                 return -ENOTSUPP;
3695
3696         ret = nand_get_device(chip);
3697         if (ret)
3698                 return ret;
3699
3700         if (!ops->datbuf)
3701                 ret = nand_do_read_oob(chip, from, ops);
3702         else
3703                 ret = nand_do_read_ops(chip, from, ops);
3704
3705         nand_release_device(chip);
3706         return ret;
3707 }
3708
3709 /**
3710  * nand_write_page_raw_notsupp - dummy raw page write function
3711  * @chip: nand chip info structure
3712  * @buf: data buffer
3713  * @oob_required: must write chip->oob_poi to OOB
3714  * @page: page number to write
3715  *
3716  * Returns -ENOTSUPP unconditionally.
3717  */
3718 int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf,
3719                                 int oob_required, int page)
3720 {
3721         return -ENOTSUPP;
3722 }
3723
3724 /**
3725  * nand_write_page_raw - [INTERN] raw page write function
3726  * @chip: nand chip info structure
3727  * @buf: data buffer
3728  * @oob_required: must write chip->oob_poi to OOB
3729  * @page: page number to write
3730  *
3731  * Not for syndrome calculating ECC controllers, which use a special oob layout.
3732  */
3733 int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
3734                         int oob_required, int page)
3735 {
3736         struct mtd_info *mtd = nand_to_mtd(chip);
3737         int ret;
3738
3739         ret = nand_prog_page_begin_op(chip, page, 0, buf, mtd->writesize);
3740         if (ret)
3741                 return ret;
3742
3743         if (oob_required) {
3744                 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
3745                                          false);
3746                 if (ret)
3747                         return ret;
3748         }
3749
3750         return nand_prog_page_end_op(chip);
3751 }
3752 EXPORT_SYMBOL(nand_write_page_raw);
3753
3754 /**
3755  * nand_monolithic_write_page_raw - Monolithic page write in raw mode
3756  * @chip: NAND chip info structure
3757  * @buf: data buffer to write
3758  * @oob_required: must write chip->oob_poi to OOB
3759  * @page: page number to write
3760  *
3761  * This is a raw page write, ie. without any error detection/correction.
3762  * Monolithic means we are requesting all the relevant data (main plus
3763  * eventually OOB) to be sent over the bus and effectively programmed
3764  * into the NAND chip arrays in a single operation. This is an
3765  * alternative to nand_write_page_raw(), which first sends the main
3766  * data, then eventually send the OOB data by latching more data
3767  * cycles on the NAND bus, and finally sends the program command to
3768  * synchronyze the NAND chip cache.
3769  */
3770 int nand_monolithic_write_page_raw(struct nand_chip *chip, const u8 *buf,
3771                                    int oob_required, int page)
3772 {
3773         struct mtd_info *mtd = nand_to_mtd(chip);
3774         unsigned int size = mtd->writesize;
3775         u8 *write_buf = (u8 *)buf;
3776
3777         if (oob_required) {
3778                 size += mtd->oobsize;
3779
3780                 if (buf != chip->data_buf) {
3781                         write_buf = nand_get_data_buf(chip);
3782                         memcpy(write_buf, buf, mtd->writesize);
3783                 }
3784         }
3785
3786         return nand_prog_page_op(chip, page, 0, write_buf, size);
3787 }
3788 EXPORT_SYMBOL(nand_monolithic_write_page_raw);
3789
3790 /**
3791  * nand_write_page_raw_syndrome - [INTERN] raw page write function
3792  * @chip: nand chip info structure
3793  * @buf: data buffer
3794  * @oob_required: must write chip->oob_poi to OOB
3795  * @page: page number to write
3796  *
3797  * We need a special oob layout and handling even when ECC isn't checked.
3798  */
3799 static int nand_write_page_raw_syndrome(struct nand_chip *chip,
3800                                         const uint8_t *buf, int oob_required,
3801                                         int page)
3802 {
3803         struct mtd_info *mtd = nand_to_mtd(chip);
3804         int eccsize = chip->ecc.size;
3805         int eccbytes = chip->ecc.bytes;
3806         uint8_t *oob = chip->oob_poi;
3807         int steps, size, ret;
3808
3809         ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3810         if (ret)
3811                 return ret;
3812
3813         for (steps = chip->ecc.steps; steps > 0; steps--) {
3814                 ret = nand_write_data_op(chip, buf, eccsize, false);
3815                 if (ret)
3816                         return ret;
3817
3818                 buf += eccsize;
3819
3820                 if (chip->ecc.prepad) {
3821                         ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3822                                                  false);
3823                         if (ret)
3824                                 return ret;
3825
3826                         oob += chip->ecc.prepad;
3827                 }
3828
3829                 ret = nand_write_data_op(chip, oob, eccbytes, false);
3830                 if (ret)
3831                         return ret;
3832
3833                 oob += eccbytes;
3834
3835                 if (chip->ecc.postpad) {
3836                         ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3837                                                  false);
3838                         if (ret)
3839                                 return ret;
3840
3841                         oob += chip->ecc.postpad;
3842                 }
3843         }
3844
3845         size = mtd->oobsize - (oob - chip->oob_poi);
3846         if (size) {
3847                 ret = nand_write_data_op(chip, oob, size, false);
3848                 if (ret)
3849                         return ret;
3850         }
3851
3852         return nand_prog_page_end_op(chip);
3853 }
3854 /**
3855  * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
3856  * @chip: nand chip info structure
3857  * @buf: data buffer
3858  * @oob_required: must write chip->oob_poi to OOB
3859  * @page: page number to write
3860  */
3861 static int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf,
3862                                  int oob_required, int page)
3863 {
3864         struct mtd_info *mtd = nand_to_mtd(chip);
3865         int i, eccsize = chip->ecc.size, ret;
3866         int eccbytes = chip->ecc.bytes;
3867         int eccsteps = chip->ecc.steps;
3868         uint8_t *ecc_calc = chip->ecc.calc_buf;
3869         const uint8_t *p = buf;
3870
3871         /* Software ECC calculation */
3872         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
3873                 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3874
3875         ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3876                                          chip->ecc.total);
3877         if (ret)
3878                 return ret;
3879
3880         return chip->ecc.write_page_raw(chip, buf, 1, page);
3881 }
3882
3883 /**
3884  * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
3885  * @chip: nand chip info structure
3886  * @buf: data buffer
3887  * @oob_required: must write chip->oob_poi to OOB
3888  * @page: page number to write
3889  */
3890 static int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf,
3891                                  int oob_required, int page)
3892 {
3893         struct mtd_info *mtd = nand_to_mtd(chip);
3894         int i, eccsize = chip->ecc.size, ret;
3895         int eccbytes = chip->ecc.bytes;
3896         int eccsteps = chip->ecc.steps;
3897         uint8_t *ecc_calc = chip->ecc.calc_buf;
3898         const uint8_t *p = buf;
3899
3900         ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3901         if (ret)
3902                 return ret;
3903
3904         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3905                 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3906
3907                 ret = nand_write_data_op(chip, p, eccsize, false);
3908                 if (ret)
3909                         return ret;
3910
3911                 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3912         }
3913
3914         ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3915                                          chip->ecc.total);
3916         if (ret)
3917                 return ret;
3918
3919         ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3920         if (ret)
3921                 return ret;
3922
3923         return nand_prog_page_end_op(chip);
3924 }
3925
3926
3927 /**
3928  * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
3929  * @chip:       nand chip info structure
3930  * @offset:     column address of subpage within the page
3931  * @data_len:   data length
3932  * @buf:        data buffer
3933  * @oob_required: must write chip->oob_poi to OOB
3934  * @page: page number to write
3935  */
3936 static int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset,
3937                                     uint32_t data_len, const uint8_t *buf,
3938                                     int oob_required, int page)
3939 {
3940         struct mtd_info *mtd = nand_to_mtd(chip);
3941         uint8_t *oob_buf  = chip->oob_poi;
3942         uint8_t *ecc_calc = chip->ecc.calc_buf;
3943         int ecc_size      = chip->ecc.size;
3944         int ecc_bytes     = chip->ecc.bytes;
3945         int ecc_steps     = chip->ecc.steps;
3946         uint32_t start_step = offset / ecc_size;
3947         uint32_t end_step   = (offset + data_len - 1) / ecc_size;
3948         int oob_bytes       = mtd->oobsize / ecc_steps;
3949         int step, ret;
3950
3951         ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3952         if (ret)
3953                 return ret;
3954
3955         for (step = 0; step < ecc_steps; step++) {
3956                 /* configure controller for WRITE access */
3957                 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3958
3959                 /* write data (untouched subpages already masked by 0xFF) */
3960                 ret = nand_write_data_op(chip, buf, ecc_size, false);
3961                 if (ret)
3962                         return ret;
3963
3964                 /* mask ECC of un-touched subpages by padding 0xFF */
3965                 if ((step < start_step) || (step > end_step))
3966                         memset(ecc_calc, 0xff, ecc_bytes);
3967                 else
3968                         chip->ecc.calculate(chip, buf, ecc_calc);
3969
3970                 /* mask OOB of un-touched subpages by padding 0xFF */
3971                 /* if oob_required, preserve OOB metadata of written subpage */
3972                 if (!oob_required || (step < start_step) || (step > end_step))
3973                         memset(oob_buf, 0xff, oob_bytes);
3974
3975                 buf += ecc_size;
3976                 ecc_calc += ecc_bytes;
3977                 oob_buf  += oob_bytes;
3978         }
3979
3980         /* copy calculated ECC for whole page to chip->buffer->oob */
3981         /* this include masked-value(0xFF) for unwritten subpages */
3982         ecc_calc = chip->ecc.calc_buf;
3983         ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3984                                          chip->ecc.total);
3985         if (ret)
3986                 return ret;
3987
3988         /* write OOB buffer to NAND device */
3989         ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3990         if (ret)
3991                 return ret;
3992
3993         return nand_prog_page_end_op(chip);
3994 }
3995
3996
3997 /**
3998  * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
3999  * @chip: nand chip info structure
4000  * @buf: data buffer
4001  * @oob_required: must write chip->oob_poi to OOB
4002  * @page: page number to write
4003  *
4004  * The hw generator calculates the error syndrome automatically. Therefore we
4005  * need a special oob layout and handling.
4006  */
4007 static int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf,
4008                                     int oob_required, int page)
4009 {
4010         struct mtd_info *mtd = nand_to_mtd(chip);
4011         int i, eccsize = chip->ecc.size;
4012         int eccbytes = chip->ecc.bytes;
4013         int eccsteps = chip->ecc.steps;
4014         const uint8_t *p = buf;
4015         uint8_t *oob = chip->oob_poi;
4016         int ret;
4017
4018         ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4019         if (ret)
4020                 return ret;
4021
4022         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4023                 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4024
4025                 ret = nand_write_data_op(chip, p, eccsize, false);
4026                 if (ret)
4027                         return ret;
4028
4029                 if (chip->ecc.prepad) {
4030                         ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4031                                                  false);
4032                         if (ret)
4033                                 return ret;
4034
4035                         oob += chip->ecc.prepad;
4036                 }
4037
4038                 chip->ecc.calculate(chip, p, oob);
4039
4040                 ret = nand_write_data_op(chip, oob, eccbytes, false);
4041                 if (ret)
4042                         return ret;
4043
4044                 oob += eccbytes;
4045
4046                 if (chip->ecc.postpad) {
4047                         ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4048                                                  false);
4049                         if (ret)
4050                                 return ret;
4051
4052                         oob += chip->ecc.postpad;
4053                 }
4054         }
4055
4056         /* Calculate remaining oob bytes */
4057         i = mtd->oobsize - (oob - chip->oob_poi);
4058         if (i) {
4059                 ret = nand_write_data_op(chip, oob, i, false);
4060                 if (ret)
4061                         return ret;
4062         }
4063
4064         return nand_prog_page_end_op(chip);
4065 }
4066
4067 /**
4068  * nand_write_page - write one page
4069  * @chip: NAND chip descriptor
4070  * @offset: address offset within the page
4071  * @data_len: length of actual data to be written
4072  * @buf: the data to write
4073  * @oob_required: must write chip->oob_poi to OOB
4074  * @page: page number to write
4075  * @raw: use _raw version of write_page
4076  */
4077 static int nand_write_page(struct nand_chip *chip, uint32_t offset,
4078                            int data_len, const uint8_t *buf, int oob_required,
4079                            int page, int raw)
4080 {
4081         struct mtd_info *mtd = nand_to_mtd(chip);
4082         int status, subpage;
4083
4084         if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
4085                 chip->ecc.write_subpage)
4086                 subpage = offset || (data_len < mtd->writesize);
4087         else
4088                 subpage = 0;
4089
4090         if (unlikely(raw))
4091                 status = chip->ecc.write_page_raw(chip, buf, oob_required,
4092                                                   page);
4093         else if (subpage)
4094                 status = chip->ecc.write_subpage(chip, offset, data_len, buf,
4095                                                  oob_required, page);
4096         else
4097                 status = chip->ecc.write_page(chip, buf, oob_required, page);
4098
4099         if (status < 0)
4100                 return status;
4101
4102         return 0;
4103 }
4104
4105 #define NOTALIGNED(x)   ((x & (chip->subpagesize - 1)) != 0)
4106
4107 /**
4108  * nand_do_write_ops - [INTERN] NAND write with ECC
4109  * @chip: NAND chip object
4110  * @to: offset to write to
4111  * @ops: oob operations description structure
4112  *
4113  * NAND write with ECC.
4114  */
4115 static int nand_do_write_ops(struct nand_chip *chip, loff_t to,
4116                              struct mtd_oob_ops *ops)
4117 {
4118         struct mtd_info *mtd = nand_to_mtd(chip);
4119         int chipnr, realpage, page, column;
4120         uint32_t writelen = ops->len;
4121
4122         uint32_t oobwritelen = ops->ooblen;
4123         uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
4124
4125         uint8_t *oob = ops->oobbuf;
4126         uint8_t *buf = ops->datbuf;
4127         int ret;
4128         int oob_required = oob ? 1 : 0;
4129
4130         ops->retlen = 0;
4131         if (!writelen)
4132                 return 0;
4133
4134         /* Reject writes, which are not page aligned */
4135         if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
4136                 pr_notice("%s: attempt to write non page aligned data\n",
4137                            __func__);
4138                 return -EINVAL;
4139         }
4140
4141         column = to & (mtd->writesize - 1);
4142
4143         chipnr = (int)(to >> chip->chip_shift);
4144         nand_select_target(chip, chipnr);
4145
4146         /* Check, if it is write protected */
4147         if (nand_check_wp(chip)) {
4148                 ret = -EIO;
4149                 goto err_out;
4150         }
4151
4152         realpage = (int)(to >> chip->page_shift);
4153         page = realpage & chip->pagemask;
4154
4155         /* Invalidate the page cache, when we write to the cached page */
4156         if (to <= ((loff_t)chip->pagecache.page << chip->page_shift) &&
4157             ((loff_t)chip->pagecache.page << chip->page_shift) < (to + ops->len))
4158                 chip->pagecache.page = -1;
4159
4160         /* Don't allow multipage oob writes with offset */
4161         if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
4162                 ret = -EINVAL;
4163                 goto err_out;
4164         }
4165
4166         while (1) {
4167                 int bytes = mtd->writesize;
4168                 uint8_t *wbuf = buf;
4169                 int use_bounce_buf;
4170                 int part_pagewr = (column || writelen < mtd->writesize);
4171
4172                 if (part_pagewr)
4173                         use_bounce_buf = 1;
4174                 else if (chip->options & NAND_USES_DMA)
4175                         use_bounce_buf = !virt_addr_valid(buf) ||
4176                                          !IS_ALIGNED((unsigned long)buf,
4177                                                      chip->buf_align);
4178                 else
4179                         use_bounce_buf = 0;
4180
4181                 /*
4182                  * Copy the data from the initial buffer when doing partial page
4183                  * writes or when a bounce buffer is required.
4184                  */
4185                 if (use_bounce_buf) {
4186                         pr_debug("%s: using write bounce buffer for buf@%p\n",
4187                                          __func__, buf);
4188                         if (part_pagewr)
4189                                 bytes = min_t(int, bytes - column, writelen);
4190                         wbuf = nand_get_data_buf(chip);
4191                         memset(wbuf, 0xff, mtd->writesize);
4192                         memcpy(&wbuf[column], buf, bytes);
4193                 }
4194
4195                 if (unlikely(oob)) {
4196                         size_t len = min(oobwritelen, oobmaxlen);
4197                         oob = nand_fill_oob(chip, oob, len, ops);
4198                         oobwritelen -= len;
4199                 } else {
4200                         /* We still need to erase leftover OOB data */
4201                         memset(chip->oob_poi, 0xff, mtd->oobsize);
4202                 }
4203
4204                 ret = nand_write_page(chip, column, bytes, wbuf,
4205                                       oob_required, page,
4206                                       (ops->mode == MTD_OPS_RAW));
4207                 if (ret)
4208                         break;
4209
4210                 writelen -= bytes;
4211                 if (!writelen)
4212                         break;
4213
4214                 column = 0;
4215                 buf += bytes;
4216                 realpage++;
4217
4218                 page = realpage & chip->pagemask;
4219                 /* Check, if we cross a chip boundary */
4220                 if (!page) {
4221                         chipnr++;
4222                         nand_deselect_target(chip);
4223                         nand_select_target(chip, chipnr);
4224                 }
4225         }
4226
4227         ops->retlen = ops->len - writelen;
4228         if (unlikely(oob))
4229                 ops->oobretlen = ops->ooblen;
4230
4231 err_out:
4232         nand_deselect_target(chip);
4233         return ret;
4234 }
4235
4236 /**
4237  * panic_nand_write - [MTD Interface] NAND write with ECC
4238  * @mtd: MTD device structure
4239  * @to: offset to write to
4240  * @len: number of bytes to write
4241  * @retlen: pointer to variable to store the number of written bytes
4242  * @buf: the data to write
4243  *
4244  * NAND write with ECC. Used when performing writes in interrupt context, this
4245  * may for example be called by mtdoops when writing an oops while in panic.
4246  */
4247 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
4248                             size_t *retlen, const uint8_t *buf)
4249 {
4250         struct nand_chip *chip = mtd_to_nand(mtd);
4251         int chipnr = (int)(to >> chip->chip_shift);
4252         struct mtd_oob_ops ops;
4253         int ret;
4254
4255         nand_select_target(chip, chipnr);
4256
4257         /* Wait for the device to get ready */
4258         panic_nand_wait(chip, 400);
4259
4260         memset(&ops, 0, sizeof(ops));
4261         ops.len = len;
4262         ops.datbuf = (uint8_t *)buf;
4263         ops.mode = MTD_OPS_PLACE_OOB;
4264
4265         ret = nand_do_write_ops(chip, to, &ops);
4266
4267         *retlen = ops.retlen;
4268         return ret;
4269 }
4270
4271 /**
4272  * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
4273  * @mtd: MTD device structure
4274  * @to: offset to write to
4275  * @ops: oob operation description structure
4276  */
4277 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
4278                           struct mtd_oob_ops *ops)
4279 {
4280         struct nand_chip *chip = mtd_to_nand(mtd);
4281         int ret;
4282
4283         ops->retlen = 0;
4284
4285         ret = nand_get_device(chip);
4286         if (ret)
4287                 return ret;
4288
4289         switch (ops->mode) {
4290         case MTD_OPS_PLACE_OOB:
4291         case MTD_OPS_AUTO_OOB:
4292         case MTD_OPS_RAW:
4293                 break;
4294
4295         default:
4296                 goto out;
4297         }
4298
4299         if (!ops->datbuf)
4300                 ret = nand_do_write_oob(chip, to, ops);
4301         else
4302                 ret = nand_do_write_ops(chip, to, ops);
4303
4304 out:
4305         nand_release_device(chip);
4306         return ret;
4307 }
4308
4309 /**
4310  * nand_erase - [MTD Interface] erase block(s)
4311  * @mtd: MTD device structure
4312  * @instr: erase instruction
4313  *
4314  * Erase one ore more blocks.
4315  */
4316 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
4317 {
4318         return nand_erase_nand(mtd_to_nand(mtd), instr, 0);
4319 }
4320
4321 /**
4322  * nand_erase_nand - [INTERN] erase block(s)
4323  * @chip: NAND chip object
4324  * @instr: erase instruction
4325  * @allowbbt: allow erasing the bbt area
4326  *
4327  * Erase one ore more blocks.
4328  */
4329 int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr,
4330                     int allowbbt)
4331 {
4332         int page, pages_per_block, ret, chipnr;
4333         loff_t len;
4334
4335         pr_debug("%s: start = 0x%012llx, len = %llu\n",
4336                         __func__, (unsigned long long)instr->addr,
4337                         (unsigned long long)instr->len);
4338
4339         if (check_offs_len(chip, instr->addr, instr->len))
4340                 return -EINVAL;
4341
4342         /* Grab the lock and see if the device is available */
4343         ret = nand_get_device(chip);
4344         if (ret)
4345                 return ret;
4346
4347         /* Shift to get first page */
4348         page = (int)(instr->addr >> chip->page_shift);
4349         chipnr = (int)(instr->addr >> chip->chip_shift);
4350
4351         /* Calculate pages in each block */
4352         pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
4353
4354         /* Select the NAND device */
4355         nand_select_target(chip, chipnr);
4356
4357         /* Check, if it is write protected */
4358         if (nand_check_wp(chip)) {
4359                 pr_debug("%s: device is write protected!\n",
4360                                 __func__);
4361                 ret = -EIO;
4362                 goto erase_exit;
4363         }
4364
4365         /* Loop through the pages */
4366         len = instr->len;
4367
4368         while (len) {
4369                 /* Check if we have a bad block, we do not erase bad blocks! */
4370                 if (nand_block_checkbad(chip, ((loff_t) page) <<
4371                                         chip->page_shift, allowbbt)) {
4372                         pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
4373                                     __func__, page);
4374                         ret = -EIO;
4375                         goto erase_exit;
4376                 }
4377
4378                 /*
4379                  * Invalidate the page cache, if we erase the block which
4380                  * contains the current cached page.
4381                  */
4382                 if (page <= chip->pagecache.page && chip->pagecache.page <
4383                     (page + pages_per_block))
4384                         chip->pagecache.page = -1;
4385
4386                 ret = nand_erase_op(chip, (page & chip->pagemask) >>
4387                                     (chip->phys_erase_shift - chip->page_shift));
4388                 if (ret) {
4389                         pr_debug("%s: failed erase, page 0x%08x\n",
4390                                         __func__, page);
4391                         instr->fail_addr =
4392                                 ((loff_t)page << chip->page_shift);
4393                         goto erase_exit;
4394                 }
4395
4396                 /* Increment page address and decrement length */
4397                 len -= (1ULL << chip->phys_erase_shift);
4398                 page += pages_per_block;
4399
4400                 /* Check, if we cross a chip boundary */
4401                 if (len && !(page & chip->pagemask)) {
4402                         chipnr++;
4403                         nand_deselect_target(chip);
4404                         nand_select_target(chip, chipnr);
4405                 }
4406         }
4407
4408         ret = 0;
4409 erase_exit:
4410
4411         /* Deselect and wake up anyone waiting on the device */
4412         nand_deselect_target(chip);
4413         nand_release_device(chip);
4414
4415         /* Return more or less happy */
4416         return ret;
4417 }
4418
4419 /**
4420  * nand_sync - [MTD Interface] sync
4421  * @mtd: MTD device structure
4422  *
4423  * Sync is actually a wait for chip ready function.
4424  */
4425 static void nand_sync(struct mtd_info *mtd)
4426 {
4427         struct nand_chip *chip = mtd_to_nand(mtd);
4428
4429         pr_debug("%s: called\n", __func__);
4430
4431         /* Grab the lock and see if the device is available */
4432         WARN_ON(nand_get_device(chip));
4433         /* Release it and go back */
4434         nand_release_device(chip);
4435 }
4436
4437 /**
4438  * nand_block_isbad - [MTD Interface] Check if block at offset is bad
4439  * @mtd: MTD device structure
4440  * @offs: offset relative to mtd start
4441  */
4442 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
4443 {
4444         struct nand_chip *chip = mtd_to_nand(mtd);
4445         int chipnr = (int)(offs >> chip->chip_shift);
4446         int ret;
4447
4448         /* Select the NAND device */
4449         ret = nand_get_device(chip);
4450         if (ret)
4451                 return ret;
4452
4453         nand_select_target(chip, chipnr);
4454
4455         ret = nand_block_checkbad(chip, offs, 0);
4456
4457         nand_deselect_target(chip);
4458         nand_release_device(chip);
4459
4460         return ret;
4461 }
4462
4463 /**
4464  * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
4465  * @mtd: MTD device structure
4466  * @ofs: offset relative to mtd start
4467  */
4468 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
4469 {
4470         int ret;
4471
4472         ret = nand_block_isbad(mtd, ofs);
4473         if (ret) {
4474                 /* If it was bad already, return success and do nothing */
4475                 if (ret > 0)
4476                         return 0;
4477                 return ret;
4478         }
4479
4480         return nand_block_markbad_lowlevel(mtd_to_nand(mtd), ofs);
4481 }
4482
4483 /**
4484  * nand_suspend - [MTD Interface] Suspend the NAND flash
4485  * @mtd: MTD device structure
4486  *
4487  * Returns 0 for success or negative error code otherwise.
4488  */
4489 static int nand_suspend(struct mtd_info *mtd)
4490 {
4491         struct nand_chip *chip = mtd_to_nand(mtd);
4492         int ret = 0;
4493
4494         mutex_lock(&chip->lock);
4495         if (chip->ops.suspend)
4496                 ret = chip->ops.suspend(chip);
4497         if (!ret)
4498                 chip->suspended = 1;
4499         mutex_unlock(&chip->lock);
4500
4501         return ret;
4502 }
4503
4504 /**
4505  * nand_resume - [MTD Interface] Resume the NAND flash
4506  * @mtd: MTD device structure
4507  */
4508 static void nand_resume(struct mtd_info *mtd)
4509 {
4510         struct nand_chip *chip = mtd_to_nand(mtd);
4511
4512         mutex_lock(&chip->lock);
4513         if (chip->suspended) {
4514                 if (chip->ops.resume)
4515                         chip->ops.resume(chip);
4516                 chip->suspended = 0;
4517         } else {
4518                 pr_err("%s called for a chip which is not in suspended state\n",
4519                         __func__);
4520         }
4521         mutex_unlock(&chip->lock);
4522 }
4523
4524 /**
4525  * nand_shutdown - [MTD Interface] Finish the current NAND operation and
4526  *                 prevent further operations
4527  * @mtd: MTD device structure
4528  */
4529 static void nand_shutdown(struct mtd_info *mtd)
4530 {
4531         nand_suspend(mtd);
4532 }
4533
4534 /**
4535  * nand_lock - [MTD Interface] Lock the NAND flash
4536  * @mtd: MTD device structure
4537  * @ofs: offset byte address
4538  * @len: number of bytes to lock (must be a multiple of block/page size)
4539  */
4540 static int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4541 {
4542         struct nand_chip *chip = mtd_to_nand(mtd);
4543
4544         if (!chip->ops.lock_area)
4545                 return -ENOTSUPP;
4546
4547         return chip->ops.lock_area(chip, ofs, len);
4548 }
4549
4550 /**
4551  * nand_unlock - [MTD Interface] Unlock the NAND flash
4552  * @mtd: MTD device structure
4553  * @ofs: offset byte address
4554  * @len: number of bytes to unlock (must be a multiple of block/page size)
4555  */
4556 static int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4557 {
4558         struct nand_chip *chip = mtd_to_nand(mtd);
4559
4560         if (!chip->ops.unlock_area)
4561                 return -ENOTSUPP;
4562
4563         return chip->ops.unlock_area(chip, ofs, len);
4564 }
4565
4566 /* Set default functions */
4567 static void nand_set_defaults(struct nand_chip *chip)
4568 {
4569         /* If no controller is provided, use the dummy, legacy one. */
4570         if (!chip->controller) {
4571                 chip->controller = &chip->legacy.dummy_controller;
4572                 nand_controller_init(chip->controller);
4573         }
4574
4575         nand_legacy_set_defaults(chip);
4576
4577         if (!chip->buf_align)
4578                 chip->buf_align = 1;
4579 }
4580
4581 /* Sanitize ONFI strings so we can safely print them */
4582 void sanitize_string(uint8_t *s, size_t len)
4583 {
4584         ssize_t i;
4585
4586         /* Null terminate */
4587         s[len - 1] = 0;
4588
4589         /* Remove non printable chars */
4590         for (i = 0; i < len - 1; i++) {
4591                 if (s[i] < ' ' || s[i] > 127)
4592                         s[i] = '?';
4593         }
4594
4595         /* Remove trailing spaces */
4596         strim(s);
4597 }
4598
4599 /*
4600  * nand_id_has_period - Check if an ID string has a given wraparound period
4601  * @id_data: the ID string
4602  * @arrlen: the length of the @id_data array
4603  * @period: the period of repitition
4604  *
4605  * Check if an ID string is repeated within a given sequence of bytes at
4606  * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4607  * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4608  * if the repetition has a period of @period; otherwise, returns zero.
4609  */
4610 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4611 {
4612         int i, j;
4613         for (i = 0; i < period; i++)
4614                 for (j = i + period; j < arrlen; j += period)
4615                         if (id_data[i] != id_data[j])
4616                                 return 0;
4617         return 1;
4618 }
4619
4620 /*
4621  * nand_id_len - Get the length of an ID string returned by CMD_READID
4622  * @id_data: the ID string
4623  * @arrlen: the length of the @id_data array
4624
4625  * Returns the length of the ID string, according to known wraparound/trailing
4626  * zero patterns. If no pattern exists, returns the length of the array.
4627  */
4628 static int nand_id_len(u8 *id_data, int arrlen)
4629 {
4630         int last_nonzero, period;
4631
4632         /* Find last non-zero byte */
4633         for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4634                 if (id_data[last_nonzero])
4635                         break;
4636
4637         /* All zeros */
4638         if (last_nonzero < 0)
4639                 return 0;
4640
4641         /* Calculate wraparound period */
4642         for (period = 1; period < arrlen; period++)
4643                 if (nand_id_has_period(id_data, arrlen, period))
4644                         break;
4645
4646         /* There's a repeated pattern */
4647         if (period < arrlen)
4648                 return period;
4649
4650         /* There are trailing zeros */
4651         if (last_nonzero < arrlen - 1)
4652                 return last_nonzero + 1;
4653
4654         /* No pattern detected */
4655         return arrlen;
4656 }
4657
4658 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4659 static int nand_get_bits_per_cell(u8 cellinfo)
4660 {
4661         int bits;
4662
4663         bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4664         bits >>= NAND_CI_CELLTYPE_SHIFT;
4665         return bits + 1;
4666 }
4667
4668 /*
4669  * Many new NAND share similar device ID codes, which represent the size of the
4670  * chip. The rest of the parameters must be decoded according to generic or
4671  * manufacturer-specific "extended ID" decoding patterns.
4672  */
4673 void nand_decode_ext_id(struct nand_chip *chip)
4674 {
4675         struct nand_memory_organization *memorg;
4676         struct mtd_info *mtd = nand_to_mtd(chip);
4677         int extid;
4678         u8 *id_data = chip->id.data;
4679
4680         memorg = nanddev_get_memorg(&chip->base);
4681
4682         /* The 3rd id byte holds MLC / multichip data */
4683         memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4684         /* The 4th id byte is the important one */
4685         extid = id_data[3];
4686
4687         /* Calc pagesize */
4688         memorg->pagesize = 1024 << (extid & 0x03);
4689         mtd->writesize = memorg->pagesize;
4690         extid >>= 2;
4691         /* Calc oobsize */
4692         memorg->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
4693         mtd->oobsize = memorg->oobsize;
4694         extid >>= 2;
4695         /* Calc blocksize. Blocksize is multiples of 64KiB */
4696         memorg->pages_per_eraseblock = ((64 * 1024) << (extid & 0x03)) /
4697                                        memorg->pagesize;
4698         mtd->erasesize = (64 * 1024) << (extid & 0x03);
4699         extid >>= 2;
4700         /* Get buswidth information */
4701         if (extid & 0x1)
4702                 chip->options |= NAND_BUSWIDTH_16;
4703 }
4704 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
4705
4706 /*
4707  * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4708  * decodes a matching ID table entry and assigns the MTD size parameters for
4709  * the chip.
4710  */
4711 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
4712 {
4713         struct mtd_info *mtd = nand_to_mtd(chip);
4714         struct nand_memory_organization *memorg;
4715
4716         memorg = nanddev_get_memorg(&chip->base);
4717
4718         memorg->pages_per_eraseblock = type->erasesize / type->pagesize;
4719         mtd->erasesize = type->erasesize;
4720         memorg->pagesize = type->pagesize;
4721         mtd->writesize = memorg->pagesize;
4722         memorg->oobsize = memorg->pagesize / 32;
4723         mtd->oobsize = memorg->oobsize;
4724
4725         /* All legacy ID NAND are small-page, SLC */
4726         memorg->bits_per_cell = 1;
4727 }
4728
4729 /*
4730  * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4731  * heuristic patterns using various detected parameters (e.g., manufacturer,
4732  * page size, cell-type information).
4733  */
4734 static void nand_decode_bbm_options(struct nand_chip *chip)
4735 {
4736         struct mtd_info *mtd = nand_to_mtd(chip);
4737
4738         /* Set the bad block position */
4739         if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4740                 chip->badblockpos = NAND_BBM_POS_LARGE;
4741         else
4742                 chip->badblockpos = NAND_BBM_POS_SMALL;
4743 }
4744
4745 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4746 {
4747         return type->id_len;
4748 }
4749
4750 static bool find_full_id_nand(struct nand_chip *chip,
4751                               struct nand_flash_dev *type)
4752 {
4753         struct nand_device *base = &chip->base;
4754         struct nand_ecc_props requirements;
4755         struct mtd_info *mtd = nand_to_mtd(chip);
4756         struct nand_memory_organization *memorg;
4757         u8 *id_data = chip->id.data;
4758
4759         memorg = nanddev_get_memorg(&chip->base);
4760
4761         if (!strncmp(type->id, id_data, type->id_len)) {
4762                 memorg->pagesize = type->pagesize;
4763                 mtd->writesize = memorg->pagesize;
4764                 memorg->pages_per_eraseblock = type->erasesize /
4765                                                type->pagesize;
4766                 mtd->erasesize = type->erasesize;
4767                 memorg->oobsize = type->oobsize;
4768                 mtd->oobsize = memorg->oobsize;
4769
4770                 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4771                 memorg->eraseblocks_per_lun =
4772                         DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4773                                            memorg->pagesize *
4774                                            memorg->pages_per_eraseblock);
4775                 chip->options |= type->options;
4776                 requirements.strength = NAND_ECC_STRENGTH(type);
4777                 requirements.step_size = NAND_ECC_STEP(type);
4778                 nanddev_set_ecc_requirements(base, &requirements);
4779
4780                 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4781                 if (!chip->parameters.model)
4782                         return false;
4783
4784                 return true;
4785         }
4786         return false;
4787 }
4788
4789 /*
4790  * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
4791  * compliant and does not have a full-id or legacy-id entry in the nand_ids
4792  * table.
4793  */
4794 static void nand_manufacturer_detect(struct nand_chip *chip)
4795 {
4796         /*
4797          * Try manufacturer detection if available and use
4798          * nand_decode_ext_id() otherwise.
4799          */
4800         if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4801             chip->manufacturer.desc->ops->detect) {
4802                 struct nand_memory_organization *memorg;
4803
4804                 memorg = nanddev_get_memorg(&chip->base);
4805
4806                 /* The 3rd id byte holds MLC / multichip data */
4807                 memorg->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
4808                 chip->manufacturer.desc->ops->detect(chip);
4809         } else {
4810                 nand_decode_ext_id(chip);
4811         }
4812 }
4813
4814 /*
4815  * Manufacturer initialization. This function is called for all NANDs including
4816  * ONFI and JEDEC compliant ones.
4817  * Manufacturer drivers should put all their specific initialization code in
4818  * their ->init() hook.
4819  */
4820 static int nand_manufacturer_init(struct nand_chip *chip)
4821 {
4822         if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
4823             !chip->manufacturer.desc->ops->init)
4824                 return 0;
4825
4826         return chip->manufacturer.desc->ops->init(chip);
4827 }
4828
4829 /*
4830  * Manufacturer cleanup. This function is called for all NANDs including
4831  * ONFI and JEDEC compliant ones.
4832  * Manufacturer drivers should put all their specific cleanup code in their
4833  * ->cleanup() hook.
4834  */
4835 static void nand_manufacturer_cleanup(struct nand_chip *chip)
4836 {
4837         /* Release manufacturer private data */
4838         if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4839             chip->manufacturer.desc->ops->cleanup)
4840                 chip->manufacturer.desc->ops->cleanup(chip);
4841 }
4842
4843 static const char *
4844 nand_manufacturer_name(const struct nand_manufacturer_desc *manufacturer_desc)
4845 {
4846         return manufacturer_desc ? manufacturer_desc->name : "Unknown";
4847 }
4848
4849 /*
4850  * Get the flash and manufacturer id and lookup if the type is supported.
4851  */
4852 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
4853 {
4854         const struct nand_manufacturer_desc *manufacturer_desc;
4855         struct mtd_info *mtd = nand_to_mtd(chip);
4856         struct nand_memory_organization *memorg;
4857         int busw, ret;
4858         u8 *id_data = chip->id.data;
4859         u8 maf_id, dev_id;
4860         u64 targetsize;
4861
4862         /*
4863          * Let's start by initializing memorg fields that might be left
4864          * unassigned by the ID-based detection logic.
4865          */
4866         memorg = nanddev_get_memorg(&chip->base);
4867         memorg->planes_per_lun = 1;
4868         memorg->luns_per_target = 1;
4869
4870         /*
4871          * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4872          * after power-up.
4873          */
4874         ret = nand_reset(chip, 0);
4875         if (ret)
4876                 return ret;
4877
4878         /* Select the device */
4879         nand_select_target(chip, 0);
4880
4881         /* Send the command for reading device ID */
4882         ret = nand_readid_op(chip, 0, id_data, 2);
4883         if (ret)
4884                 return ret;
4885
4886         /* Read manufacturer and device IDs */
4887         maf_id = id_data[0];
4888         dev_id = id_data[1];
4889
4890         /*
4891          * Try again to make sure, as some systems the bus-hold or other
4892          * interface concerns can cause random data which looks like a
4893          * possibly credible NAND flash to appear. If the two results do
4894          * not match, ignore the device completely.
4895          */
4896
4897         /* Read entire ID string */
4898         ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
4899         if (ret)
4900                 return ret;
4901
4902         if (id_data[0] != maf_id || id_data[1] != dev_id) {
4903                 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4904                         maf_id, dev_id, id_data[0], id_data[1]);
4905                 return -ENODEV;
4906         }
4907
4908         chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
4909
4910         /* Try to identify manufacturer */
4911         manufacturer_desc = nand_get_manufacturer_desc(maf_id);
4912         chip->manufacturer.desc = manufacturer_desc;
4913
4914         if (!type)
4915                 type = nand_flash_ids;
4916
4917         /*
4918          * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
4919          * override it.
4920          * This is required to make sure initial NAND bus width set by the
4921          * NAND controller driver is coherent with the real NAND bus width
4922          * (extracted by auto-detection code).
4923          */
4924         busw = chip->options & NAND_BUSWIDTH_16;
4925
4926         /*
4927          * The flag is only set (never cleared), reset it to its default value
4928          * before starting auto-detection.
4929          */
4930         chip->options &= ~NAND_BUSWIDTH_16;
4931
4932         for (; type->name != NULL; type++) {
4933                 if (is_full_id_nand(type)) {
4934                         if (find_full_id_nand(chip, type))
4935                                 goto ident_done;
4936                 } else if (dev_id == type->dev_id) {
4937                         break;
4938                 }
4939         }
4940
4941         if (!type->name || !type->pagesize) {
4942                 /* Check if the chip is ONFI compliant */
4943                 ret = nand_onfi_detect(chip);
4944                 if (ret < 0)
4945                         return ret;
4946                 else if (ret)
4947                         goto ident_done;
4948
4949                 /* Check if the chip is JEDEC compliant */
4950                 ret = nand_jedec_detect(chip);
4951                 if (ret < 0)
4952                         return ret;
4953                 else if (ret)
4954                         goto ident_done;
4955         }
4956
4957         if (!type->name)
4958                 return -ENODEV;
4959
4960         chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4961         if (!chip->parameters.model)
4962                 return -ENOMEM;
4963
4964         if (!type->pagesize)
4965                 nand_manufacturer_detect(chip);
4966         else
4967                 nand_decode_id(chip, type);
4968
4969         /* Get chip options */
4970         chip->options |= type->options;
4971
4972         memorg->eraseblocks_per_lun =
4973                         DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4974                                            memorg->pagesize *
4975                                            memorg->pages_per_eraseblock);
4976
4977 ident_done:
4978         if (!mtd->name)
4979                 mtd->name = chip->parameters.model;
4980
4981         if (chip->options & NAND_BUSWIDTH_AUTO) {
4982                 WARN_ON(busw & NAND_BUSWIDTH_16);
4983                 nand_set_defaults(chip);
4984         } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4985                 /*
4986                  * Check, if buswidth is correct. Hardware drivers should set
4987                  * chip correct!
4988                  */
4989                 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4990                         maf_id, dev_id);
4991                 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
4992                         mtd->name);
4993                 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
4994                         (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
4995                 ret = -EINVAL;
4996
4997                 goto free_detect_allocation;
4998         }
4999
5000         nand_decode_bbm_options(chip);
5001
5002         /* Calculate the address shift from the page size */
5003         chip->page_shift = ffs(mtd->writesize) - 1;
5004         /* Convert chipsize to number of pages per chip -1 */
5005         targetsize = nanddev_target_size(&chip->base);
5006         chip->pagemask = (targetsize >> chip->page_shift) - 1;
5007
5008         chip->bbt_erase_shift = chip->phys_erase_shift =
5009                 ffs(mtd->erasesize) - 1;
5010         if (targetsize & 0xffffffff)
5011                 chip->chip_shift = ffs((unsigned)targetsize) - 1;
5012         else {
5013                 chip->chip_shift = ffs((unsigned)(targetsize >> 32));
5014                 chip->chip_shift += 32 - 1;
5015         }
5016
5017         if (chip->chip_shift - chip->page_shift > 16)
5018                 chip->options |= NAND_ROW_ADDR_3;
5019
5020         chip->badblockbits = 8;
5021
5022         nand_legacy_adjust_cmdfunc(chip);
5023
5024         pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5025                 maf_id, dev_id);
5026         pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
5027                 chip->parameters.model);
5028         pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
5029                 (int)(targetsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
5030                 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
5031         return 0;
5032
5033 free_detect_allocation:
5034         kfree(chip->parameters.model);
5035
5036         return ret;
5037 }
5038
5039 static const char * const nand_ecc_modes[] = {
5040         [NAND_ECC_NONE]         = "none",
5041         [NAND_ECC_SOFT]         = "soft",
5042         [NAND_ECC_HW]           = "hw",
5043         [NAND_ECC_HW_SYNDROME]  = "hw_syndrome",
5044         [NAND_ECC_ON_DIE]       = "on-die",
5045 };
5046
5047 static enum nand_ecc_engine_type
5048 of_get_nand_ecc_engine_type(struct device_node *np)
5049 {
5050         enum nand_ecc_mode eng_type;
5051         const char *pm;
5052         int err;
5053
5054         err = of_property_read_string(np, "nand-ecc-mode", &pm);
5055         if (err)
5056                 return NAND_ECC_ENGINE_TYPE_INVALID;
5057
5058         for (eng_type = NAND_ECC_NONE;
5059              eng_type < ARRAY_SIZE(nand_ecc_modes); eng_type++) {
5060                 if (!strcasecmp(pm, nand_ecc_modes[eng_type])) {
5061                         switch (eng_type) {
5062                         case NAND_ECC_NONE:
5063                                 return NAND_ECC_ENGINE_TYPE_NONE;
5064                         case NAND_ECC_SOFT:
5065                                 return NAND_ECC_ENGINE_TYPE_SOFT;
5066                         case NAND_ECC_HW:
5067                         case NAND_ECC_HW_SYNDROME:
5068                                 return NAND_ECC_ENGINE_TYPE_ON_HOST;
5069                         case NAND_ECC_ON_DIE:
5070                                 return NAND_ECC_ENGINE_TYPE_ON_DIE;
5071                         default:
5072                                 break;
5073                         }
5074                 }
5075         }
5076
5077         /*
5078          * For backward compatibility we support few obsoleted values that don't
5079          * have their mappings into the nand_ecc_engine_providers enum anymore
5080          * (they were merged with other enums).
5081          */
5082         if (!strcasecmp(pm, "soft_bch"))
5083                 return NAND_ECC_ENGINE_TYPE_SOFT;
5084
5085         return NAND_ECC_ENGINE_TYPE_INVALID;
5086 }
5087
5088 static const char * const nand_ecc_algos[] = {
5089         [NAND_ECC_ALGO_HAMMING] = "hamming",
5090         [NAND_ECC_ALGO_BCH]     = "bch",
5091         [NAND_ECC_ALGO_RS]      = "rs",
5092 };
5093
5094 static enum nand_ecc_algo of_get_nand_ecc_algo(struct device_node *np)
5095 {
5096         enum nand_ecc_algo ecc_algo;
5097         const char *pm;
5098         int err;
5099
5100         err = of_property_read_string(np, "nand-ecc-algo", &pm);
5101         if (!err) {
5102                 for (ecc_algo = NAND_ECC_ALGO_HAMMING;
5103                      ecc_algo < ARRAY_SIZE(nand_ecc_algos);
5104                      ecc_algo++) {
5105                         if (!strcasecmp(pm, nand_ecc_algos[ecc_algo]))
5106                                 return ecc_algo;
5107                 }
5108         }
5109
5110         /*
5111          * For backward compatibility we also read "nand-ecc-mode" checking
5112          * for some obsoleted values that were specifying ECC algorithm.
5113          */
5114         err = of_property_read_string(np, "nand-ecc-mode", &pm);
5115         if (!err) {
5116                 if (!strcasecmp(pm, "soft"))
5117                         return NAND_ECC_ALGO_HAMMING;
5118                 else if (!strcasecmp(pm, "soft_bch"))
5119                         return NAND_ECC_ALGO_BCH;
5120         }
5121
5122         return NAND_ECC_ALGO_UNKNOWN;
5123 }
5124
5125 static int of_get_nand_ecc_step_size(struct device_node *np)
5126 {
5127         int ret;
5128         u32 val;
5129
5130         ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
5131         return ret ? ret : val;
5132 }
5133
5134 static int of_get_nand_ecc_strength(struct device_node *np)
5135 {
5136         int ret;
5137         u32 val;
5138
5139         ret = of_property_read_u32(np, "nand-ecc-strength", &val);
5140         return ret ? ret : val;
5141 }
5142
5143 static int of_get_nand_bus_width(struct device_node *np)
5144 {
5145         u32 val;
5146
5147         if (of_property_read_u32(np, "nand-bus-width", &val))
5148                 return 8;
5149
5150         switch (val) {
5151         case 8:
5152         case 16:
5153                 return val;
5154         default:
5155                 return -EIO;
5156         }
5157 }
5158
5159 static bool of_get_nand_on_flash_bbt(struct device_node *np)
5160 {
5161         return of_property_read_bool(np, "nand-on-flash-bbt");
5162 }
5163
5164 static int nand_dt_init(struct nand_chip *chip)
5165 {
5166         struct device_node *dn = nand_get_flash_node(chip);
5167         enum nand_ecc_engine_type ecc_type;
5168         enum nand_ecc_algo ecc_algo;
5169         int ecc_strength, ecc_step;
5170
5171         if (!dn)
5172                 return 0;
5173
5174         if (of_get_nand_bus_width(dn) == 16)
5175                 chip->options |= NAND_BUSWIDTH_16;
5176
5177         if (of_property_read_bool(dn, "nand-is-boot-medium"))
5178                 chip->options |= NAND_IS_BOOT_MEDIUM;
5179
5180         if (of_get_nand_on_flash_bbt(dn))
5181                 chip->bbt_options |= NAND_BBT_USE_FLASH;
5182
5183         ecc_type = of_get_nand_ecc_engine_type(dn);
5184         ecc_algo = of_get_nand_ecc_algo(dn);
5185         ecc_strength = of_get_nand_ecc_strength(dn);
5186         ecc_step = of_get_nand_ecc_step_size(dn);
5187
5188         if (ecc_type != NAND_ECC_ENGINE_TYPE_INVALID)
5189                 chip->ecc.engine_type = ecc_type;
5190
5191         if (ecc_algo != NAND_ECC_ALGO_UNKNOWN)
5192                 chip->ecc.algo = ecc_algo;
5193
5194         if (ecc_strength >= 0)
5195                 chip->ecc.strength = ecc_strength;
5196
5197         if (ecc_step > 0)
5198                 chip->ecc.size = ecc_step;
5199
5200         if (of_property_read_bool(dn, "nand-ecc-maximize"))
5201                 chip->ecc.options |= NAND_ECC_MAXIMIZE;
5202
5203         return 0;
5204 }
5205
5206 /**
5207  * nand_scan_ident - Scan for the NAND device
5208  * @chip: NAND chip object
5209  * @maxchips: number of chips to scan for
5210  * @table: alternative NAND ID table
5211  *
5212  * This is the first phase of the normal nand_scan() function. It reads the
5213  * flash ID and sets up MTD fields accordingly.
5214  *
5215  * This helper used to be called directly from controller drivers that needed
5216  * to tweak some ECC-related parameters before nand_scan_tail(). This separation
5217  * prevented dynamic allocations during this phase which was unconvenient and
5218  * as been banned for the benefit of the ->init_ecc()/cleanup_ecc() hooks.
5219  */
5220 static int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips,
5221                            struct nand_flash_dev *table)
5222 {
5223         struct mtd_info *mtd = nand_to_mtd(chip);
5224         struct nand_memory_organization *memorg;
5225         int nand_maf_id, nand_dev_id;
5226         unsigned int i;
5227         int ret;
5228
5229         memorg = nanddev_get_memorg(&chip->base);
5230
5231         /* Assume all dies are deselected when we enter nand_scan_ident(). */
5232         chip->cur_cs = -1;
5233
5234         mutex_init(&chip->lock);
5235
5236         /* Enforce the right timings for reset/detection */
5237         chip->current_interface_config = nand_get_reset_interface_config();
5238
5239         ret = nand_dt_init(chip);
5240         if (ret)
5241                 return ret;
5242
5243         if (!mtd->name && mtd->dev.parent)
5244                 mtd->name = dev_name(mtd->dev.parent);
5245
5246         /* Set the default functions */
5247         nand_set_defaults(chip);
5248
5249         ret = nand_legacy_check_hooks(chip);
5250         if (ret)
5251                 return ret;
5252
5253         memorg->ntargets = maxchips;
5254
5255         /* Read the flash type */
5256         ret = nand_detect(chip, table);
5257         if (ret) {
5258                 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
5259                         pr_warn("No NAND device found\n");
5260                 nand_deselect_target(chip);
5261                 return ret;
5262         }
5263
5264         nand_maf_id = chip->id.data[0];
5265         nand_dev_id = chip->id.data[1];
5266
5267         nand_deselect_target(chip);
5268
5269         /* Check for a chip array */
5270         for (i = 1; i < maxchips; i++) {
5271                 u8 id[2];
5272
5273                 /* See comment in nand_get_flash_type for reset */
5274                 ret = nand_reset(chip, i);
5275                 if (ret)
5276                         break;
5277
5278                 nand_select_target(chip, i);
5279                 /* Send the command for reading device ID */
5280                 ret = nand_readid_op(chip, 0, id, sizeof(id));
5281                 if (ret)
5282                         break;
5283                 /* Read manufacturer and device IDs */
5284                 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
5285                         nand_deselect_target(chip);
5286                         break;
5287                 }
5288                 nand_deselect_target(chip);
5289         }
5290         if (i > 1)
5291                 pr_info("%d chips detected\n", i);
5292
5293         /* Store the number of chips and calc total size for mtd */
5294         memorg->ntargets = i;
5295         mtd->size = i * nanddev_target_size(&chip->base);
5296
5297         return 0;
5298 }
5299
5300 static void nand_scan_ident_cleanup(struct nand_chip *chip)
5301 {
5302         kfree(chip->parameters.model);
5303         kfree(chip->parameters.onfi);
5304 }
5305
5306 static int nand_set_ecc_soft_ops(struct nand_chip *chip)
5307 {
5308         struct mtd_info *mtd = nand_to_mtd(chip);
5309         struct nand_ecc_ctrl *ecc = &chip->ecc;
5310
5311         if (WARN_ON(ecc->engine_type != NAND_ECC_ENGINE_TYPE_SOFT))
5312                 return -EINVAL;
5313
5314         switch (ecc->algo) {
5315         case NAND_ECC_ALGO_HAMMING:
5316                 ecc->calculate = nand_calculate_ecc;
5317                 ecc->correct = nand_correct_data;
5318                 ecc->read_page = nand_read_page_swecc;
5319                 ecc->read_subpage = nand_read_subpage;
5320                 ecc->write_page = nand_write_page_swecc;
5321                 if (!ecc->read_page_raw)
5322                         ecc->read_page_raw = nand_read_page_raw;
5323                 if (!ecc->write_page_raw)
5324                         ecc->write_page_raw = nand_write_page_raw;
5325                 ecc->read_oob = nand_read_oob_std;
5326                 ecc->write_oob = nand_write_oob_std;
5327                 if (!ecc->size)
5328                         ecc->size = 256;
5329                 ecc->bytes = 3;
5330                 ecc->strength = 1;
5331
5332                 if (IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_HAMMING_SMC))
5333                         ecc->options |= NAND_ECC_SOFT_HAMMING_SM_ORDER;
5334
5335                 return 0;
5336         case NAND_ECC_ALGO_BCH:
5337                 if (!mtd_nand_has_bch()) {
5338                         WARN(1, "CONFIG_MTD_NAND_ECC_SW_BCH not enabled\n");
5339                         return -EINVAL;
5340                 }
5341                 ecc->calculate = nand_bch_calculate_ecc;
5342                 ecc->correct = nand_bch_correct_data;
5343                 ecc->read_page = nand_read_page_swecc;
5344                 ecc->read_subpage = nand_read_subpage;
5345                 ecc->write_page = nand_write_page_swecc;
5346                 if (!ecc->read_page_raw)
5347                         ecc->read_page_raw = nand_read_page_raw;
5348                 if (!ecc->write_page_raw)
5349                         ecc->write_page_raw = nand_write_page_raw;
5350                 ecc->read_oob = nand_read_oob_std;
5351                 ecc->write_oob = nand_write_oob_std;
5352
5353                 /*
5354                 * Board driver should supply ecc.size and ecc.strength
5355                 * values to select how many bits are correctable.
5356                 * Otherwise, default to 4 bits for large page devices.
5357                 */
5358                 if (!ecc->size && (mtd->oobsize >= 64)) {
5359                         ecc->size = 512;
5360                         ecc->strength = 4;
5361                 }
5362
5363                 /*
5364                  * if no ecc placement scheme was provided pickup the default
5365                  * large page one.
5366                  */
5367                 if (!mtd->ooblayout) {
5368                         /* handle large page devices only */
5369                         if (mtd->oobsize < 64) {
5370                                 WARN(1, "OOB layout is required when using software BCH on small pages\n");
5371                                 return -EINVAL;
5372                         }
5373
5374                         mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
5375
5376                 }
5377
5378                 /*
5379                  * We can only maximize ECC config when the default layout is
5380                  * used, otherwise we don't know how many bytes can really be
5381                  * used.
5382                  */
5383                 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
5384                     ecc->options & NAND_ECC_MAXIMIZE) {
5385                         int steps, bytes;
5386
5387                         /* Always prefer 1k blocks over 512bytes ones */
5388                         ecc->size = 1024;
5389                         steps = mtd->writesize / ecc->size;
5390
5391                         /* Reserve 2 bytes for the BBM */
5392                         bytes = (mtd->oobsize - 2) / steps;
5393                         ecc->strength = bytes * 8 / fls(8 * ecc->size);
5394                 }
5395
5396                 /* See nand_bch_init() for details. */
5397                 ecc->bytes = 0;
5398                 ecc->priv = nand_bch_init(mtd);
5399                 if (!ecc->priv) {
5400                         WARN(1, "BCH ECC initialization failed!\n");
5401                         return -EINVAL;
5402                 }
5403                 return 0;
5404         default:
5405                 WARN(1, "Unsupported ECC algorithm!\n");
5406                 return -EINVAL;
5407         }
5408 }
5409
5410 /**
5411  * nand_check_ecc_caps - check the sanity of preset ECC settings
5412  * @chip: nand chip info structure
5413  * @caps: ECC caps info structure
5414  * @oobavail: OOB size that the ECC engine can use
5415  *
5416  * When ECC step size and strength are already set, check if they are supported
5417  * by the controller and the calculated ECC bytes fit within the chip's OOB.
5418  * On success, the calculated ECC bytes is set.
5419  */
5420 static int
5421 nand_check_ecc_caps(struct nand_chip *chip,
5422                     const struct nand_ecc_caps *caps, int oobavail)
5423 {
5424         struct mtd_info *mtd = nand_to_mtd(chip);
5425         const struct nand_ecc_step_info *stepinfo;
5426         int preset_step = chip->ecc.size;
5427         int preset_strength = chip->ecc.strength;
5428         int ecc_bytes, nsteps = mtd->writesize / preset_step;
5429         int i, j;
5430
5431         for (i = 0; i < caps->nstepinfos; i++) {
5432                 stepinfo = &caps->stepinfos[i];
5433
5434                 if (stepinfo->stepsize != preset_step)
5435                         continue;
5436
5437                 for (j = 0; j < stepinfo->nstrengths; j++) {
5438                         if (stepinfo->strengths[j] != preset_strength)
5439                                 continue;
5440
5441                         ecc_bytes = caps->calc_ecc_bytes(preset_step,
5442                                                          preset_strength);
5443                         if (WARN_ON_ONCE(ecc_bytes < 0))
5444                                 return ecc_bytes;
5445
5446                         if (ecc_bytes * nsteps > oobavail) {
5447                                 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
5448                                        preset_step, preset_strength);
5449                                 return -ENOSPC;
5450                         }
5451
5452                         chip->ecc.bytes = ecc_bytes;
5453
5454                         return 0;
5455                 }
5456         }
5457
5458         pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
5459                preset_step, preset_strength);
5460
5461         return -ENOTSUPP;
5462 }
5463
5464 /**
5465  * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
5466  * @chip: nand chip info structure
5467  * @caps: ECC engine caps info structure
5468  * @oobavail: OOB size that the ECC engine can use
5469  *
5470  * If a chip's ECC requirement is provided, try to meet it with the least
5471  * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
5472  * On success, the chosen ECC settings are set.
5473  */
5474 static int
5475 nand_match_ecc_req(struct nand_chip *chip,
5476                    const struct nand_ecc_caps *caps, int oobavail)
5477 {
5478         const struct nand_ecc_props *requirements =
5479                 nanddev_get_ecc_requirements(&chip->base);
5480         struct mtd_info *mtd = nand_to_mtd(chip);
5481         const struct nand_ecc_step_info *stepinfo;
5482         int req_step = requirements->step_size;
5483         int req_strength = requirements->strength;
5484         int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
5485         int best_step, best_strength, best_ecc_bytes;
5486         int best_ecc_bytes_total = INT_MAX;
5487         int i, j;
5488
5489         /* No information provided by the NAND chip */
5490         if (!req_step || !req_strength)
5491                 return -ENOTSUPP;
5492
5493         /* number of correctable bits the chip requires in a page */
5494         req_corr = mtd->writesize / req_step * req_strength;
5495
5496         for (i = 0; i < caps->nstepinfos; i++) {
5497                 stepinfo = &caps->stepinfos[i];
5498                 step_size = stepinfo->stepsize;
5499
5500                 for (j = 0; j < stepinfo->nstrengths; j++) {
5501                         strength = stepinfo->strengths[j];
5502
5503                         /*
5504                          * If both step size and strength are smaller than the
5505                          * chip's requirement, it is not easy to compare the
5506                          * resulted reliability.
5507                          */
5508                         if (step_size < req_step && strength < req_strength)
5509                                 continue;
5510
5511                         if (mtd->writesize % step_size)
5512                                 continue;
5513
5514                         nsteps = mtd->writesize / step_size;
5515
5516                         ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5517                         if (WARN_ON_ONCE(ecc_bytes < 0))
5518                                 continue;
5519                         ecc_bytes_total = ecc_bytes * nsteps;
5520
5521                         if (ecc_bytes_total > oobavail ||
5522                             strength * nsteps < req_corr)
5523                                 continue;
5524
5525                         /*
5526                          * We assume the best is to meet the chip's requrement
5527                          * with the least number of ECC bytes.
5528                          */
5529                         if (ecc_bytes_total < best_ecc_bytes_total) {
5530                                 best_ecc_bytes_total = ecc_bytes_total;
5531                                 best_step = step_size;
5532                                 best_strength = strength;
5533                                 best_ecc_bytes = ecc_bytes;
5534                         }
5535                 }
5536         }
5537
5538         if (best_ecc_bytes_total == INT_MAX)
5539                 return -ENOTSUPP;
5540
5541         chip->ecc.size = best_step;
5542         chip->ecc.strength = best_strength;
5543         chip->ecc.bytes = best_ecc_bytes;
5544
5545         return 0;
5546 }
5547
5548 /**
5549  * nand_maximize_ecc - choose the max ECC strength available
5550  * @chip: nand chip info structure
5551  * @caps: ECC engine caps info structure
5552  * @oobavail: OOB size that the ECC engine can use
5553  *
5554  * Choose the max ECC strength that is supported on the controller, and can fit
5555  * within the chip's OOB.  On success, the chosen ECC settings are set.
5556  */
5557 static int
5558 nand_maximize_ecc(struct nand_chip *chip,
5559                   const struct nand_ecc_caps *caps, int oobavail)
5560 {
5561         struct mtd_info *mtd = nand_to_mtd(chip);
5562         const struct nand_ecc_step_info *stepinfo;
5563         int step_size, strength, nsteps, ecc_bytes, corr;
5564         int best_corr = 0;
5565         int best_step = 0;
5566         int best_strength, best_ecc_bytes;
5567         int i, j;
5568
5569         for (i = 0; i < caps->nstepinfos; i++) {
5570                 stepinfo = &caps->stepinfos[i];
5571                 step_size = stepinfo->stepsize;
5572
5573                 /* If chip->ecc.size is already set, respect it */
5574                 if (chip->ecc.size && step_size != chip->ecc.size)
5575                         continue;
5576
5577                 for (j = 0; j < stepinfo->nstrengths; j++) {
5578                         strength = stepinfo->strengths[j];
5579
5580                         if (mtd->writesize % step_size)
5581                                 continue;
5582
5583                         nsteps = mtd->writesize / step_size;
5584
5585                         ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5586                         if (WARN_ON_ONCE(ecc_bytes < 0))
5587                                 continue;
5588
5589                         if (ecc_bytes * nsteps > oobavail)
5590                                 continue;
5591
5592                         corr = strength * nsteps;
5593
5594                         /*
5595                          * If the number of correctable bits is the same,
5596                          * bigger step_size has more reliability.
5597                          */
5598                         if (corr > best_corr ||
5599                             (corr == best_corr && step_size > best_step)) {
5600                                 best_corr = corr;
5601                                 best_step = step_size;
5602                                 best_strength = strength;
5603                                 best_ecc_bytes = ecc_bytes;
5604                         }
5605                 }
5606         }
5607
5608         if (!best_corr)
5609                 return -ENOTSUPP;
5610
5611         chip->ecc.size = best_step;
5612         chip->ecc.strength = best_strength;
5613         chip->ecc.bytes = best_ecc_bytes;
5614
5615         return 0;
5616 }
5617
5618 /**
5619  * nand_ecc_choose_conf - Set the ECC strength and ECC step size
5620  * @chip: nand chip info structure
5621  * @caps: ECC engine caps info structure
5622  * @oobavail: OOB size that the ECC engine can use
5623  *
5624  * Choose the ECC configuration according to following logic
5625  *
5626  * 1. If both ECC step size and ECC strength are already set (usually by DT)
5627  *    then check if it is supported by this controller.
5628  * 2. If NAND_ECC_MAXIMIZE is set, then select maximum ECC strength.
5629  * 3. Otherwise, try to match the ECC step size and ECC strength closest
5630  *    to the chip's requirement. If available OOB size can't fit the chip
5631  *    requirement then fallback to the maximum ECC step size and ECC strength.
5632  *
5633  * On success, the chosen ECC settings are set.
5634  */
5635 int nand_ecc_choose_conf(struct nand_chip *chip,
5636                          const struct nand_ecc_caps *caps, int oobavail)
5637 {
5638         struct mtd_info *mtd = nand_to_mtd(chip);
5639
5640         if (WARN_ON(oobavail < 0 || oobavail > mtd->oobsize))
5641                 return -EINVAL;
5642
5643         if (chip->ecc.size && chip->ecc.strength)
5644                 return nand_check_ecc_caps(chip, caps, oobavail);
5645
5646         if (chip->ecc.options & NAND_ECC_MAXIMIZE)
5647                 return nand_maximize_ecc(chip, caps, oobavail);
5648
5649         if (!nand_match_ecc_req(chip, caps, oobavail))
5650                 return 0;
5651
5652         return nand_maximize_ecc(chip, caps, oobavail);
5653 }
5654 EXPORT_SYMBOL_GPL(nand_ecc_choose_conf);
5655
5656 /*
5657  * Check if the chip configuration meet the datasheet requirements.
5658
5659  * If our configuration corrects A bits per B bytes and the minimum
5660  * required correction level is X bits per Y bytes, then we must ensure
5661  * both of the following are true:
5662  *
5663  * (1) A / B >= X / Y
5664  * (2) A >= X
5665  *
5666  * Requirement (1) ensures we can correct for the required bitflip density.
5667  * Requirement (2) ensures we can correct even when all bitflips are clumped
5668  * in the same sector.
5669  */
5670 static bool nand_ecc_strength_good(struct nand_chip *chip)
5671 {
5672         struct mtd_info *mtd = nand_to_mtd(chip);
5673         struct nand_ecc_ctrl *ecc = &chip->ecc;
5674         const struct nand_ecc_props *requirements =
5675                 nanddev_get_ecc_requirements(&chip->base);
5676         int corr, ds_corr;
5677
5678         if (ecc->size == 0 || requirements->step_size == 0)
5679                 /* Not enough information */
5680                 return true;
5681
5682         /*
5683          * We get the number of corrected bits per page to compare
5684          * the correction density.
5685          */
5686         corr = (mtd->writesize * ecc->strength) / ecc->size;
5687         ds_corr = (mtd->writesize * requirements->strength) /
5688                   requirements->step_size;
5689
5690         return corr >= ds_corr && ecc->strength >= requirements->strength;
5691 }
5692
5693 static int rawnand_erase(struct nand_device *nand, const struct nand_pos *pos)
5694 {
5695         struct nand_chip *chip = container_of(nand, struct nand_chip,
5696                                               base);
5697         unsigned int eb = nanddev_pos_to_row(nand, pos);
5698         int ret;
5699
5700         eb >>= nand->rowconv.eraseblock_addr_shift;
5701
5702         nand_select_target(chip, pos->target);
5703         ret = nand_erase_op(chip, eb);
5704         nand_deselect_target(chip);
5705
5706         return ret;
5707 }
5708
5709 static int rawnand_markbad(struct nand_device *nand,
5710                            const struct nand_pos *pos)
5711 {
5712         struct nand_chip *chip = container_of(nand, struct nand_chip,
5713                                               base);
5714
5715         return nand_markbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5716 }
5717
5718 static bool rawnand_isbad(struct nand_device *nand, const struct nand_pos *pos)
5719 {
5720         struct nand_chip *chip = container_of(nand, struct nand_chip,
5721                                               base);
5722         int ret;
5723
5724         nand_select_target(chip, pos->target);
5725         ret = nand_isbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5726         nand_deselect_target(chip);
5727
5728         return ret;
5729 }
5730
5731 static const struct nand_ops rawnand_ops = {
5732         .erase = rawnand_erase,
5733         .markbad = rawnand_markbad,
5734         .isbad = rawnand_isbad,
5735 };
5736
5737 /**
5738  * nand_scan_tail - Scan for the NAND device
5739  * @chip: NAND chip object
5740  *
5741  * This is the second phase of the normal nand_scan() function. It fills out
5742  * all the uninitialized function pointers with the defaults and scans for a
5743  * bad block table if appropriate.
5744  */
5745 static int nand_scan_tail(struct nand_chip *chip)
5746 {
5747         struct mtd_info *mtd = nand_to_mtd(chip);
5748         struct nand_ecc_ctrl *ecc = &chip->ecc;
5749         int ret, i;
5750
5751         /* New bad blocks should be marked in OOB, flash-based BBT, or both */
5752         if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
5753                    !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
5754                 return -EINVAL;
5755         }
5756
5757         chip->data_buf = kmalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
5758         if (!chip->data_buf)
5759                 return -ENOMEM;
5760
5761         /*
5762          * FIXME: some NAND manufacturer drivers expect the first die to be
5763          * selected when manufacturer->init() is called. They should be fixed
5764          * to explictly select the relevant die when interacting with the NAND
5765          * chip.
5766          */
5767         nand_select_target(chip, 0);
5768         ret = nand_manufacturer_init(chip);
5769         nand_deselect_target(chip);
5770         if (ret)
5771                 goto err_free_buf;
5772
5773         /* Set the internal oob buffer location, just after the page data */
5774         chip->oob_poi = chip->data_buf + mtd->writesize;
5775
5776         /*
5777          * If no default placement scheme is given, select an appropriate one.
5778          */
5779         if (!mtd->ooblayout &&
5780             !(ecc->engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
5781               ecc->algo == NAND_ECC_ALGO_BCH)) {
5782                 switch (mtd->oobsize) {
5783                 case 8:
5784                 case 16:
5785                         mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
5786                         break;
5787                 case 64:
5788                 case 128:
5789                         mtd_set_ooblayout(mtd, &nand_ooblayout_lp_hamming_ops);
5790                         break;
5791                 default:
5792                         /*
5793                          * Expose the whole OOB area to users if ECC_NONE
5794                          * is passed. We could do that for all kind of
5795                          * ->oobsize, but we must keep the old large/small
5796                          * page with ECC layout when ->oobsize <= 128 for
5797                          * compatibility reasons.
5798                          */
5799                         if (ecc->engine_type == NAND_ECC_ENGINE_TYPE_NONE) {
5800                                 mtd_set_ooblayout(mtd,
5801                                                 &nand_ooblayout_lp_ops);
5802                                 break;
5803                         }
5804
5805                         WARN(1, "No oob scheme defined for oobsize %d\n",
5806                                 mtd->oobsize);
5807                         ret = -EINVAL;
5808                         goto err_nand_manuf_cleanup;
5809                 }
5810         }
5811
5812         /*
5813          * Check ECC mode, default to software if 3byte/512byte hardware ECC is
5814          * selected and we have 256 byte pagesize fallback to software ECC
5815          */
5816
5817         switch (ecc->engine_type) {
5818         case NAND_ECC_ENGINE_TYPE_ON_HOST:
5819
5820                 switch (ecc->placement) {
5821                 case NAND_ECC_PLACEMENT_UNKNOWN:
5822                 case NAND_ECC_PLACEMENT_OOB:
5823                         /* Use standard hwecc read page function? */
5824                         if (!ecc->read_page)
5825                                 ecc->read_page = nand_read_page_hwecc;
5826                         if (!ecc->write_page)
5827                                 ecc->write_page = nand_write_page_hwecc;
5828                         if (!ecc->read_page_raw)
5829                                 ecc->read_page_raw = nand_read_page_raw;
5830                         if (!ecc->write_page_raw)
5831                                 ecc->write_page_raw = nand_write_page_raw;
5832                         if (!ecc->read_oob)
5833                                 ecc->read_oob = nand_read_oob_std;
5834                         if (!ecc->write_oob)
5835                                 ecc->write_oob = nand_write_oob_std;
5836                         if (!ecc->read_subpage)
5837                                 ecc->read_subpage = nand_read_subpage;
5838                         if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5839                                 ecc->write_subpage = nand_write_subpage_hwecc;
5840                         fallthrough;
5841
5842                 case NAND_ECC_PLACEMENT_INTERLEAVED:
5843                         if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5844                             (!ecc->read_page ||
5845                              ecc->read_page == nand_read_page_hwecc ||
5846                              !ecc->write_page ||
5847                              ecc->write_page == nand_write_page_hwecc)) {
5848                                 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5849                                 ret = -EINVAL;
5850                                 goto err_nand_manuf_cleanup;
5851                         }
5852                         /* Use standard syndrome read/write page function? */
5853                         if (!ecc->read_page)
5854                                 ecc->read_page = nand_read_page_syndrome;
5855                         if (!ecc->write_page)
5856                                 ecc->write_page = nand_write_page_syndrome;
5857                         if (!ecc->read_page_raw)
5858                                 ecc->read_page_raw = nand_read_page_raw_syndrome;
5859                         if (!ecc->write_page_raw)
5860                                 ecc->write_page_raw = nand_write_page_raw_syndrome;
5861                         if (!ecc->read_oob)
5862                                 ecc->read_oob = nand_read_oob_syndrome;
5863                         if (!ecc->write_oob)
5864                                 ecc->write_oob = nand_write_oob_syndrome;
5865                         break;
5866
5867                 default:
5868                         pr_warn("Invalid NAND_ECC_PLACEMENT %d\n",
5869                                 ecc->placement);
5870                         ret = -EINVAL;
5871                         goto err_nand_manuf_cleanup;
5872                 }
5873
5874                 if (mtd->writesize >= ecc->size) {
5875                         if (!ecc->strength) {
5876                                 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
5877                                 ret = -EINVAL;
5878                                 goto err_nand_manuf_cleanup;
5879                         }
5880                         break;
5881                 }
5882                 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
5883                         ecc->size, mtd->writesize);
5884                 ecc->engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5885                 ecc->algo = NAND_ECC_ALGO_HAMMING;
5886                 fallthrough;
5887
5888         case NAND_ECC_ENGINE_TYPE_SOFT:
5889                 ret = nand_set_ecc_soft_ops(chip);
5890                 if (ret) {
5891                         ret = -EINVAL;
5892                         goto err_nand_manuf_cleanup;
5893                 }
5894                 break;
5895
5896         case NAND_ECC_ENGINE_TYPE_ON_DIE:
5897                 if (!ecc->read_page || !ecc->write_page) {
5898                         WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
5899                         ret = -EINVAL;
5900                         goto err_nand_manuf_cleanup;
5901                 }
5902                 if (!ecc->read_oob)
5903                         ecc->read_oob = nand_read_oob_std;
5904                 if (!ecc->write_oob)
5905                         ecc->write_oob = nand_write_oob_std;
5906                 break;
5907
5908         case NAND_ECC_ENGINE_TYPE_NONE:
5909                 pr_warn("NAND_ECC_ENGINE_TYPE_NONE selected by board driver. This is not recommended!\n");
5910                 ecc->read_page = nand_read_page_raw;
5911                 ecc->write_page = nand_write_page_raw;
5912                 ecc->read_oob = nand_read_oob_std;
5913                 ecc->read_page_raw = nand_read_page_raw;
5914                 ecc->write_page_raw = nand_write_page_raw;
5915                 ecc->write_oob = nand_write_oob_std;
5916                 ecc->size = mtd->writesize;
5917                 ecc->bytes = 0;
5918                 ecc->strength = 0;
5919                 break;
5920
5921         default:
5922                 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->engine_type);
5923                 ret = -EINVAL;
5924                 goto err_nand_manuf_cleanup;
5925         }
5926
5927         if (ecc->correct || ecc->calculate) {
5928                 ecc->calc_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
5929                 ecc->code_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
5930                 if (!ecc->calc_buf || !ecc->code_buf) {
5931                         ret = -ENOMEM;
5932                         goto err_nand_manuf_cleanup;
5933                 }
5934         }
5935
5936         /* For many systems, the standard OOB write also works for raw */
5937         if (!ecc->read_oob_raw)
5938                 ecc->read_oob_raw = ecc->read_oob;
5939         if (!ecc->write_oob_raw)
5940                 ecc->write_oob_raw = ecc->write_oob;
5941
5942         /* propagate ecc info to mtd_info */
5943         mtd->ecc_strength = ecc->strength;
5944         mtd->ecc_step_size = ecc->size;
5945
5946         /*
5947          * Set the number of read / write steps for one page depending on ECC
5948          * mode.
5949          */
5950         ecc->steps = mtd->writesize / ecc->size;
5951         if (ecc->steps * ecc->size != mtd->writesize) {
5952                 WARN(1, "Invalid ECC parameters\n");
5953                 ret = -EINVAL;
5954                 goto err_nand_manuf_cleanup;
5955         }
5956         ecc->total = ecc->steps * ecc->bytes;
5957         if (ecc->total > mtd->oobsize) {
5958                 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
5959                 ret = -EINVAL;
5960                 goto err_nand_manuf_cleanup;
5961         }
5962
5963         /*
5964          * The number of bytes available for a client to place data into
5965          * the out of band area.
5966          */
5967         ret = mtd_ooblayout_count_freebytes(mtd);
5968         if (ret < 0)
5969                 ret = 0;
5970
5971         mtd->oobavail = ret;
5972
5973         /* ECC sanity check: warn if it's too weak */
5974         if (!nand_ecc_strength_good(chip))
5975                 pr_warn("WARNING: %s: the ECC used on your system (%db/%dB) is too weak compared to the one required by the NAND chip (%db/%dB)\n",
5976                         mtd->name, chip->ecc.strength, chip->ecc.size,
5977                         nanddev_get_ecc_requirements(&chip->base)->strength,
5978                         nanddev_get_ecc_requirements(&chip->base)->step_size);
5979
5980         /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
5981         if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
5982                 switch (ecc->steps) {
5983                 case 2:
5984                         mtd->subpage_sft = 1;
5985                         break;
5986                 case 4:
5987                 case 8:
5988                 case 16:
5989                         mtd->subpage_sft = 2;
5990                         break;
5991                 }
5992         }
5993         chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
5994
5995         /* Invalidate the pagebuffer reference */
5996         chip->pagecache.page = -1;
5997
5998         /* Large page NAND with SOFT_ECC should support subpage reads */
5999         switch (ecc->engine_type) {
6000         case NAND_ECC_ENGINE_TYPE_SOFT:
6001                 if (chip->page_shift > 9)
6002                         chip->options |= NAND_SUBPAGE_READ;
6003                 break;
6004
6005         default:
6006                 break;
6007         }
6008
6009         ret = nanddev_init(&chip->base, &rawnand_ops, mtd->owner);
6010         if (ret)
6011                 goto err_nand_manuf_cleanup;
6012
6013         /* Adjust the MTD_CAP_ flags when NAND_ROM is set. */
6014         if (chip->options & NAND_ROM)
6015                 mtd->flags = MTD_CAP_ROM;
6016
6017         /* Fill in remaining MTD driver data */
6018         mtd->_erase = nand_erase;
6019         mtd->_point = NULL;
6020         mtd->_unpoint = NULL;
6021         mtd->_panic_write = panic_nand_write;
6022         mtd->_read_oob = nand_read_oob;
6023         mtd->_write_oob = nand_write_oob;
6024         mtd->_sync = nand_sync;
6025         mtd->_lock = nand_lock;
6026         mtd->_unlock = nand_unlock;
6027         mtd->_suspend = nand_suspend;
6028         mtd->_resume = nand_resume;
6029         mtd->_reboot = nand_shutdown;
6030         mtd->_block_isreserved = nand_block_isreserved;
6031         mtd->_block_isbad = nand_block_isbad;
6032         mtd->_block_markbad = nand_block_markbad;
6033         mtd->_max_bad_blocks = nanddev_mtd_max_bad_blocks;
6034
6035         /*
6036          * Initialize bitflip_threshold to its default prior scan_bbt() call.
6037          * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
6038          * properly set.
6039          */
6040         if (!mtd->bitflip_threshold)
6041                 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
6042
6043         /* Find the fastest data interface for this chip */
6044         ret = nand_choose_interface_config(chip);
6045         if (ret)
6046                 goto err_nanddev_cleanup;
6047
6048         /* Enter fastest possible mode on all dies. */
6049         for (i = 0; i < nanddev_ntargets(&chip->base); i++) {
6050                 ret = nand_setup_interface(chip, i);
6051                 if (ret)
6052                         goto err_free_interface_config;
6053         }
6054
6055         /* Check, if we should skip the bad block table scan */
6056         if (chip->options & NAND_SKIP_BBTSCAN)
6057                 return 0;
6058
6059         /* Build bad block table */
6060         ret = nand_create_bbt(chip);
6061         if (ret)
6062                 goto err_free_interface_config;
6063
6064         return 0;
6065
6066 err_free_interface_config:
6067         kfree(chip->best_interface_config);
6068
6069 err_nanddev_cleanup:
6070         nanddev_cleanup(&chip->base);
6071
6072 err_nand_manuf_cleanup:
6073         nand_manufacturer_cleanup(chip);
6074
6075 err_free_buf:
6076         kfree(chip->data_buf);
6077         kfree(ecc->code_buf);
6078         kfree(ecc->calc_buf);
6079
6080         return ret;
6081 }
6082
6083 static int nand_attach(struct nand_chip *chip)
6084 {
6085         if (chip->controller->ops && chip->controller->ops->attach_chip)
6086                 return chip->controller->ops->attach_chip(chip);
6087
6088         return 0;
6089 }
6090
6091 static void nand_detach(struct nand_chip *chip)
6092 {
6093         if (chip->controller->ops && chip->controller->ops->detach_chip)
6094                 chip->controller->ops->detach_chip(chip);
6095 }
6096
6097 /**
6098  * nand_scan_with_ids - [NAND Interface] Scan for the NAND device
6099  * @chip: NAND chip object
6100  * @maxchips: number of chips to scan for.
6101  * @ids: optional flash IDs table
6102  *
6103  * This fills out all the uninitialized function pointers with the defaults.
6104  * The flash ID is read and the mtd/chip structures are filled with the
6105  * appropriate values.
6106  */
6107 int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips,
6108                        struct nand_flash_dev *ids)
6109 {
6110         int ret;
6111
6112         if (!maxchips)
6113                 return -EINVAL;
6114
6115         ret = nand_scan_ident(chip, maxchips, ids);
6116         if (ret)
6117                 return ret;
6118
6119         ret = nand_attach(chip);
6120         if (ret)
6121                 goto cleanup_ident;
6122
6123         ret = nand_scan_tail(chip);
6124         if (ret)
6125                 goto detach_chip;
6126
6127         return 0;
6128
6129 detach_chip:
6130         nand_detach(chip);
6131 cleanup_ident:
6132         nand_scan_ident_cleanup(chip);
6133
6134         return ret;
6135 }
6136 EXPORT_SYMBOL(nand_scan_with_ids);
6137
6138 /**
6139  * nand_cleanup - [NAND Interface] Free resources held by the NAND device
6140  * @chip: NAND chip object
6141  */
6142 void nand_cleanup(struct nand_chip *chip)
6143 {
6144         if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
6145             chip->ecc.algo == NAND_ECC_ALGO_BCH)
6146                 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
6147
6148         nanddev_cleanup(&chip->base);
6149
6150         /* Free bad block table memory */
6151         kfree(chip->bbt);
6152         kfree(chip->data_buf);
6153         kfree(chip->ecc.code_buf);
6154         kfree(chip->ecc.calc_buf);
6155
6156         /* Free bad block descriptor memory */
6157         if (chip->badblock_pattern && chip->badblock_pattern->options
6158                         & NAND_BBT_DYNAMICSTRUCT)
6159                 kfree(chip->badblock_pattern);
6160
6161         /* Free the data interface */
6162         kfree(chip->best_interface_config);
6163
6164         /* Free manufacturer priv data. */
6165         nand_manufacturer_cleanup(chip);
6166
6167         /* Free controller specific allocations after chip identification */
6168         nand_detach(chip);
6169
6170         /* Free identification phase allocations */
6171         nand_scan_ident_cleanup(chip);
6172 }
6173
6174 EXPORT_SYMBOL_GPL(nand_cleanup);
6175
6176 MODULE_LICENSE("GPL");
6177 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
6178 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
6179 MODULE_DESCRIPTION("Generic NAND flash driver code");