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