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