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