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