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