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