xref: /linux/drivers/mtd/nand/spi/core.c (revision 6093a688a07da07808f0122f9aa2a3eed250d853)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2016-2017 Micron Technology, Inc.
4  *
5  * Authors:
6  *	Peter Pan <peterpandong@micron.com>
7  *	Boris Brezillon <boris.brezillon@bootlin.com>
8  */
9 
10 #define pr_fmt(fmt)	"spi-nand: " fmt
11 
12 #include <linux/device.h>
13 #include <linux/jiffies.h>
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/mtd/spinand.h>
17 #include <linux/of.h>
18 #include <linux/slab.h>
19 #include <linux/string.h>
20 #include <linux/spi/spi.h>
21 #include <linux/spi/spi-mem.h>
22 
23 int spinand_read_reg_op(struct spinand_device *spinand, u8 reg, u8 *val)
24 {
25 	struct spi_mem_op op = SPINAND_GET_FEATURE_1S_1S_1S_OP(reg,
26 						      spinand->scratchbuf);
27 	int ret;
28 
29 	ret = spi_mem_exec_op(spinand->spimem, &op);
30 	if (ret)
31 		return ret;
32 
33 	*val = *spinand->scratchbuf;
34 	return 0;
35 }
36 
37 int spinand_write_reg_op(struct spinand_device *spinand, u8 reg, u8 val)
38 {
39 	struct spi_mem_op op = SPINAND_SET_FEATURE_1S_1S_1S_OP(reg,
40 						      spinand->scratchbuf);
41 
42 	*spinand->scratchbuf = val;
43 	return spi_mem_exec_op(spinand->spimem, &op);
44 }
45 
46 static int spinand_read_status(struct spinand_device *spinand, u8 *status)
47 {
48 	return spinand_read_reg_op(spinand, REG_STATUS, status);
49 }
50 
51 static int spinand_get_cfg(struct spinand_device *spinand, u8 *cfg)
52 {
53 	struct nand_device *nand = spinand_to_nand(spinand);
54 
55 	if (WARN_ON(spinand->cur_target < 0 ||
56 		    spinand->cur_target >= nand->memorg.ntargets))
57 		return -EINVAL;
58 
59 	*cfg = spinand->cfg_cache[spinand->cur_target];
60 	return 0;
61 }
62 
63 static int spinand_set_cfg(struct spinand_device *spinand, u8 cfg)
64 {
65 	struct nand_device *nand = spinand_to_nand(spinand);
66 	int ret;
67 
68 	if (WARN_ON(spinand->cur_target < 0 ||
69 		    spinand->cur_target >= nand->memorg.ntargets))
70 		return -EINVAL;
71 
72 	if (spinand->cfg_cache[spinand->cur_target] == cfg)
73 		return 0;
74 
75 	ret = spinand_write_reg_op(spinand, REG_CFG, cfg);
76 	if (ret)
77 		return ret;
78 
79 	spinand->cfg_cache[spinand->cur_target] = cfg;
80 	return 0;
81 }
82 
83 /**
84  * spinand_upd_cfg() - Update the configuration register
85  * @spinand: the spinand device
86  * @mask: the mask encoding the bits to update in the config reg
87  * @val: the new value to apply
88  *
89  * Update the configuration register.
90  *
91  * Return: 0 on success, a negative error code otherwise.
92  */
93 int spinand_upd_cfg(struct spinand_device *spinand, u8 mask, u8 val)
94 {
95 	int ret;
96 	u8 cfg;
97 
98 	ret = spinand_get_cfg(spinand, &cfg);
99 	if (ret)
100 		return ret;
101 
102 	cfg &= ~mask;
103 	cfg |= val;
104 
105 	return spinand_set_cfg(spinand, cfg);
106 }
107 
108 /**
109  * spinand_select_target() - Select a specific NAND target/die
110  * @spinand: the spinand device
111  * @target: the target/die to select
112  *
113  * Select a new target/die. If chip only has one die, this function is a NOOP.
114  *
115  * Return: 0 on success, a negative error code otherwise.
116  */
117 int spinand_select_target(struct spinand_device *spinand, unsigned int target)
118 {
119 	struct nand_device *nand = spinand_to_nand(spinand);
120 	int ret;
121 
122 	if (WARN_ON(target >= nand->memorg.ntargets))
123 		return -EINVAL;
124 
125 	if (spinand->cur_target == target)
126 		return 0;
127 
128 	if (nand->memorg.ntargets == 1) {
129 		spinand->cur_target = target;
130 		return 0;
131 	}
132 
133 	ret = spinand->select_target(spinand, target);
134 	if (ret)
135 		return ret;
136 
137 	spinand->cur_target = target;
138 	return 0;
139 }
140 
141 static int spinand_read_cfg(struct spinand_device *spinand)
142 {
143 	struct nand_device *nand = spinand_to_nand(spinand);
144 	unsigned int target;
145 	int ret;
146 
147 	for (target = 0; target < nand->memorg.ntargets; target++) {
148 		ret = spinand_select_target(spinand, target);
149 		if (ret)
150 			return ret;
151 
152 		/*
153 		 * We use spinand_read_reg_op() instead of spinand_get_cfg()
154 		 * here to bypass the config cache.
155 		 */
156 		ret = spinand_read_reg_op(spinand, REG_CFG,
157 					  &spinand->cfg_cache[target]);
158 		if (ret)
159 			return ret;
160 	}
161 
162 	return 0;
163 }
164 
165 static int spinand_init_cfg_cache(struct spinand_device *spinand)
166 {
167 	struct nand_device *nand = spinand_to_nand(spinand);
168 	struct device *dev = &spinand->spimem->spi->dev;
169 
170 	spinand->cfg_cache = devm_kcalloc(dev,
171 					  nand->memorg.ntargets,
172 					  sizeof(*spinand->cfg_cache),
173 					  GFP_KERNEL);
174 	if (!spinand->cfg_cache)
175 		return -ENOMEM;
176 
177 	return 0;
178 }
179 
180 static int spinand_init_quad_enable(struct spinand_device *spinand)
181 {
182 	bool enable = false;
183 
184 	if (!(spinand->flags & SPINAND_HAS_QE_BIT))
185 		return 0;
186 
187 	if (spinand->op_templates.read_cache->data.buswidth == 4 ||
188 	    spinand->op_templates.write_cache->data.buswidth == 4 ||
189 	    spinand->op_templates.update_cache->data.buswidth == 4)
190 		enable = true;
191 
192 	return spinand_upd_cfg(spinand, CFG_QUAD_ENABLE,
193 			       enable ? CFG_QUAD_ENABLE : 0);
194 }
195 
196 static int spinand_ecc_enable(struct spinand_device *spinand,
197 			      bool enable)
198 {
199 	return spinand_upd_cfg(spinand, CFG_ECC_ENABLE,
200 			       enable ? CFG_ECC_ENABLE : 0);
201 }
202 
203 static int spinand_cont_read_enable(struct spinand_device *spinand,
204 				    bool enable)
205 {
206 	return spinand->set_cont_read(spinand, enable);
207 }
208 
209 static int spinand_check_ecc_status(struct spinand_device *spinand, u8 status)
210 {
211 	struct nand_device *nand = spinand_to_nand(spinand);
212 
213 	if (spinand->eccinfo.get_status)
214 		return spinand->eccinfo.get_status(spinand, status);
215 
216 	switch (status & STATUS_ECC_MASK) {
217 	case STATUS_ECC_NO_BITFLIPS:
218 		return 0;
219 
220 	case STATUS_ECC_HAS_BITFLIPS:
221 		/*
222 		 * We have no way to know exactly how many bitflips have been
223 		 * fixed, so let's return the maximum possible value so that
224 		 * wear-leveling layers move the data immediately.
225 		 */
226 		return nanddev_get_ecc_conf(nand)->strength;
227 
228 	case STATUS_ECC_UNCOR_ERROR:
229 		return -EBADMSG;
230 
231 	default:
232 		break;
233 	}
234 
235 	return -EINVAL;
236 }
237 
238 static int spinand_noecc_ooblayout_ecc(struct mtd_info *mtd, int section,
239 				       struct mtd_oob_region *region)
240 {
241 	return -ERANGE;
242 }
243 
244 static int spinand_noecc_ooblayout_free(struct mtd_info *mtd, int section,
245 					struct mtd_oob_region *region)
246 {
247 	if (section)
248 		return -ERANGE;
249 
250 	/* Reserve 2 bytes for the BBM. */
251 	region->offset = 2;
252 	region->length = 62;
253 
254 	return 0;
255 }
256 
257 static const struct mtd_ooblayout_ops spinand_noecc_ooblayout = {
258 	.ecc = spinand_noecc_ooblayout_ecc,
259 	.free = spinand_noecc_ooblayout_free,
260 };
261 
262 static int spinand_ondie_ecc_init_ctx(struct nand_device *nand)
263 {
264 	struct spinand_device *spinand = nand_to_spinand(nand);
265 	struct mtd_info *mtd = nanddev_to_mtd(nand);
266 	struct spinand_ondie_ecc_conf *engine_conf;
267 
268 	nand->ecc.ctx.conf.engine_type = NAND_ECC_ENGINE_TYPE_ON_DIE;
269 	nand->ecc.ctx.conf.step_size = nand->ecc.requirements.step_size;
270 	nand->ecc.ctx.conf.strength = nand->ecc.requirements.strength;
271 
272 	engine_conf = kzalloc(sizeof(*engine_conf), GFP_KERNEL);
273 	if (!engine_conf)
274 		return -ENOMEM;
275 
276 	nand->ecc.ctx.priv = engine_conf;
277 
278 	if (spinand->eccinfo.ooblayout)
279 		mtd_set_ooblayout(mtd, spinand->eccinfo.ooblayout);
280 	else
281 		mtd_set_ooblayout(mtd, &spinand_noecc_ooblayout);
282 
283 	return 0;
284 }
285 
286 static void spinand_ondie_ecc_cleanup_ctx(struct nand_device *nand)
287 {
288 	kfree(nand->ecc.ctx.priv);
289 }
290 
291 static int spinand_ondie_ecc_prepare_io_req(struct nand_device *nand,
292 					    struct nand_page_io_req *req)
293 {
294 	struct spinand_device *spinand = nand_to_spinand(nand);
295 	bool enable = (req->mode != MTD_OPS_RAW);
296 
297 	if (!enable && spinand->flags & SPINAND_NO_RAW_ACCESS)
298 		return -EOPNOTSUPP;
299 
300 	memset(spinand->oobbuf, 0xff, nanddev_per_page_oobsize(nand));
301 
302 	/* Only enable or disable the engine */
303 	return spinand_ecc_enable(spinand, enable);
304 }
305 
306 static int spinand_ondie_ecc_finish_io_req(struct nand_device *nand,
307 					   struct nand_page_io_req *req)
308 {
309 	struct spinand_ondie_ecc_conf *engine_conf = nand->ecc.ctx.priv;
310 	struct spinand_device *spinand = nand_to_spinand(nand);
311 	struct mtd_info *mtd = spinand_to_mtd(spinand);
312 	int ret;
313 
314 	if (req->mode == MTD_OPS_RAW)
315 		return 0;
316 
317 	/* Nothing to do when finishing a page write */
318 	if (req->type == NAND_PAGE_WRITE)
319 		return 0;
320 
321 	/* Finish a page read: check the status, report errors/bitflips */
322 	ret = spinand_check_ecc_status(spinand, engine_conf->status);
323 	if (ret == -EBADMSG) {
324 		mtd->ecc_stats.failed++;
325 	} else if (ret > 0) {
326 		unsigned int pages;
327 
328 		/*
329 		 * Continuous reads don't allow us to get the detail,
330 		 * so we may exagerate the actual number of corrected bitflips.
331 		 */
332 		if (!req->continuous)
333 			pages = 1;
334 		else
335 			pages = req->datalen / nanddev_page_size(nand);
336 
337 		mtd->ecc_stats.corrected += ret * pages;
338 	}
339 
340 	return ret;
341 }
342 
343 static const struct nand_ecc_engine_ops spinand_ondie_ecc_engine_ops = {
344 	.init_ctx = spinand_ondie_ecc_init_ctx,
345 	.cleanup_ctx = spinand_ondie_ecc_cleanup_ctx,
346 	.prepare_io_req = spinand_ondie_ecc_prepare_io_req,
347 	.finish_io_req = spinand_ondie_ecc_finish_io_req,
348 };
349 
350 static struct nand_ecc_engine spinand_ondie_ecc_engine = {
351 	.ops = &spinand_ondie_ecc_engine_ops,
352 };
353 
354 static void spinand_ondie_ecc_save_status(struct nand_device *nand, u8 status)
355 {
356 	struct spinand_ondie_ecc_conf *engine_conf = nand->ecc.ctx.priv;
357 
358 	if (nand->ecc.ctx.conf.engine_type == NAND_ECC_ENGINE_TYPE_ON_DIE &&
359 	    engine_conf)
360 		engine_conf->status = status;
361 }
362 
363 int spinand_write_enable_op(struct spinand_device *spinand)
364 {
365 	struct spi_mem_op op = SPINAND_WR_EN_DIS_1S_0_0_OP(true);
366 
367 	return spi_mem_exec_op(spinand->spimem, &op);
368 }
369 
370 static int spinand_load_page_op(struct spinand_device *spinand,
371 				const struct nand_page_io_req *req)
372 {
373 	struct nand_device *nand = spinand_to_nand(spinand);
374 	unsigned int row = nanddev_pos_to_row(nand, &req->pos);
375 	struct spi_mem_op op = SPINAND_PAGE_READ_1S_1S_0_OP(row);
376 
377 	return spi_mem_exec_op(spinand->spimem, &op);
378 }
379 
380 static int spinand_read_from_cache_op(struct spinand_device *spinand,
381 				      const struct nand_page_io_req *req)
382 {
383 	struct nand_device *nand = spinand_to_nand(spinand);
384 	struct mtd_info *mtd = spinand_to_mtd(spinand);
385 	struct spi_mem_dirmap_desc *rdesc;
386 	unsigned int nbytes = 0;
387 	void *buf = NULL;
388 	u16 column = 0;
389 	ssize_t ret;
390 
391 	if (req->datalen) {
392 		buf = spinand->databuf;
393 		if (!req->continuous)
394 			nbytes = nanddev_page_size(nand);
395 		else
396 			nbytes = round_up(req->dataoffs + req->datalen,
397 					  nanddev_page_size(nand));
398 		column = 0;
399 	}
400 
401 	if (req->ooblen) {
402 		nbytes += nanddev_per_page_oobsize(nand);
403 		if (!buf) {
404 			buf = spinand->oobbuf;
405 			column = nanddev_page_size(nand);
406 		}
407 	}
408 
409 	if (req->mode == MTD_OPS_RAW)
410 		rdesc = spinand->dirmaps[req->pos.plane].rdesc;
411 	else
412 		rdesc = spinand->dirmaps[req->pos.plane].rdesc_ecc;
413 
414 	if (spinand->flags & SPINAND_HAS_READ_PLANE_SELECT_BIT)
415 		column |= req->pos.plane << fls(nanddev_page_size(nand));
416 
417 	while (nbytes) {
418 		ret = spi_mem_dirmap_read(rdesc, column, nbytes, buf);
419 		if (ret < 0)
420 			return ret;
421 
422 		if (!ret || ret > nbytes)
423 			return -EIO;
424 
425 		nbytes -= ret;
426 		column += ret;
427 		buf += ret;
428 
429 		/*
430 		 * Dirmap accesses are allowed to toggle the CS.
431 		 * Toggling the CS during a continuous read is forbidden.
432 		 */
433 		if (nbytes && req->continuous) {
434 			/*
435 			 * Spi controller with broken support of continuous
436 			 * reading was detected. Disable future use of
437 			 * continuous reading and return -EAGAIN to retry
438 			 * reading within regular mode.
439 			 */
440 			spinand->cont_read_possible = false;
441 			return -EAGAIN;
442 		}
443 	}
444 
445 	if (req->datalen)
446 		memcpy(req->databuf.in, spinand->databuf + req->dataoffs,
447 		       req->datalen);
448 
449 	if (req->ooblen) {
450 		if (req->mode == MTD_OPS_AUTO_OOB)
451 			mtd_ooblayout_get_databytes(mtd, req->oobbuf.in,
452 						    spinand->oobbuf,
453 						    req->ooboffs,
454 						    req->ooblen);
455 		else
456 			memcpy(req->oobbuf.in, spinand->oobbuf + req->ooboffs,
457 			       req->ooblen);
458 	}
459 
460 	return 0;
461 }
462 
463 static int spinand_write_to_cache_op(struct spinand_device *spinand,
464 				     const struct nand_page_io_req *req)
465 {
466 	struct nand_device *nand = spinand_to_nand(spinand);
467 	struct mtd_info *mtd = spinand_to_mtd(spinand);
468 	struct spi_mem_dirmap_desc *wdesc;
469 	unsigned int nbytes, column = 0;
470 	void *buf = spinand->databuf;
471 	ssize_t ret;
472 
473 	/*
474 	 * Looks like PROGRAM LOAD (AKA write cache) does not necessarily reset
475 	 * the cache content to 0xFF (depends on vendor implementation), so we
476 	 * must fill the page cache entirely even if we only want to program
477 	 * the data portion of the page, otherwise we might corrupt the BBM or
478 	 * user data previously programmed in OOB area.
479 	 *
480 	 * Only reset the data buffer manually, the OOB buffer is prepared by
481 	 * ECC engines ->prepare_io_req() callback.
482 	 */
483 	nbytes = nanddev_page_size(nand) + nanddev_per_page_oobsize(nand);
484 	memset(spinand->databuf, 0xff, nanddev_page_size(nand));
485 
486 	if (req->datalen)
487 		memcpy(spinand->databuf + req->dataoffs, req->databuf.out,
488 		       req->datalen);
489 
490 	if (req->ooblen) {
491 		if (req->mode == MTD_OPS_AUTO_OOB)
492 			mtd_ooblayout_set_databytes(mtd, req->oobbuf.out,
493 						    spinand->oobbuf,
494 						    req->ooboffs,
495 						    req->ooblen);
496 		else
497 			memcpy(spinand->oobbuf + req->ooboffs, req->oobbuf.out,
498 			       req->ooblen);
499 	}
500 
501 	if (req->mode == MTD_OPS_RAW)
502 		wdesc = spinand->dirmaps[req->pos.plane].wdesc;
503 	else
504 		wdesc = spinand->dirmaps[req->pos.plane].wdesc_ecc;
505 
506 	if (spinand->flags & SPINAND_HAS_PROG_PLANE_SELECT_BIT)
507 		column |= req->pos.plane << fls(nanddev_page_size(nand));
508 
509 	while (nbytes) {
510 		ret = spi_mem_dirmap_write(wdesc, column, nbytes, buf);
511 		if (ret < 0)
512 			return ret;
513 
514 		if (!ret || ret > nbytes)
515 			return -EIO;
516 
517 		nbytes -= ret;
518 		column += ret;
519 		buf += ret;
520 	}
521 
522 	return 0;
523 }
524 
525 static int spinand_program_op(struct spinand_device *spinand,
526 			      const struct nand_page_io_req *req)
527 {
528 	struct nand_device *nand = spinand_to_nand(spinand);
529 	unsigned int row = nanddev_pos_to_row(nand, &req->pos);
530 	struct spi_mem_op op = SPINAND_PROG_EXEC_1S_1S_0_OP(row);
531 
532 	return spi_mem_exec_op(spinand->spimem, &op);
533 }
534 
535 static int spinand_erase_op(struct spinand_device *spinand,
536 			    const struct nand_pos *pos)
537 {
538 	struct nand_device *nand = spinand_to_nand(spinand);
539 	unsigned int row = nanddev_pos_to_row(nand, pos);
540 	struct spi_mem_op op = SPINAND_BLK_ERASE_1S_1S_0_OP(row);
541 
542 	return spi_mem_exec_op(spinand->spimem, &op);
543 }
544 
545 /**
546  * spinand_wait() - Poll memory device status
547  * @spinand: the spinand device
548  * @initial_delay_us: delay in us before starting to poll
549  * @poll_delay_us: time to sleep between reads in us
550  * @s: the pointer to variable to store the value of REG_STATUS
551  *
552  * This function polls a status register (REG_STATUS) and returns when
553  * the STATUS_READY bit is 0 or when the timeout has expired.
554  *
555  * Return: 0 on success, a negative error code otherwise.
556  */
557 int spinand_wait(struct spinand_device *spinand, unsigned long initial_delay_us,
558 		 unsigned long poll_delay_us, u8 *s)
559 {
560 	struct spi_mem_op op = SPINAND_GET_FEATURE_1S_1S_1S_OP(REG_STATUS,
561 							       spinand->scratchbuf);
562 	u8 status;
563 	int ret;
564 
565 	ret = spi_mem_poll_status(spinand->spimem, &op, STATUS_BUSY, 0,
566 				  initial_delay_us,
567 				  poll_delay_us,
568 				  SPINAND_WAITRDY_TIMEOUT_MS);
569 	if (ret)
570 		return ret;
571 
572 	status = *spinand->scratchbuf;
573 	if (!(status & STATUS_BUSY))
574 		goto out;
575 
576 	/*
577 	 * Extra read, just in case the STATUS_READY bit has changed
578 	 * since our last check
579 	 */
580 	ret = spinand_read_status(spinand, &status);
581 	if (ret)
582 		return ret;
583 
584 out:
585 	if (s)
586 		*s = status;
587 
588 	return status & STATUS_BUSY ? -ETIMEDOUT : 0;
589 }
590 
591 static int spinand_read_id_op(struct spinand_device *spinand, u8 naddr,
592 			      u8 ndummy, u8 *buf)
593 {
594 	struct spi_mem_op op = SPINAND_READID_1S_1S_1S_OP(
595 		naddr, ndummy, spinand->scratchbuf, SPINAND_MAX_ID_LEN);
596 	int ret;
597 
598 	ret = spi_mem_exec_op(spinand->spimem, &op);
599 	if (!ret)
600 		memcpy(buf, spinand->scratchbuf, SPINAND_MAX_ID_LEN);
601 
602 	return ret;
603 }
604 
605 static int spinand_reset_op(struct spinand_device *spinand)
606 {
607 	struct spi_mem_op op = SPINAND_RESET_1S_0_0_OP;
608 	int ret;
609 
610 	ret = spi_mem_exec_op(spinand->spimem, &op);
611 	if (ret)
612 		return ret;
613 
614 	return spinand_wait(spinand,
615 			    SPINAND_RESET_INITIAL_DELAY_US,
616 			    SPINAND_RESET_POLL_DELAY_US,
617 			    NULL);
618 }
619 
620 static int spinand_lock_block(struct spinand_device *spinand, u8 lock)
621 {
622 	return spinand_write_reg_op(spinand, REG_BLOCK_LOCK, lock);
623 }
624 
625 /**
626  * spinand_read_page() - Read a page
627  * @spinand: the spinand device
628  * @req: the I/O request
629  *
630  * Return: 0 or a positive number of bitflips corrected on success.
631  * A negative error code otherwise.
632  */
633 int spinand_read_page(struct spinand_device *spinand,
634 		      const struct nand_page_io_req *req)
635 {
636 	struct nand_device *nand = spinand_to_nand(spinand);
637 	u8 status;
638 	int ret;
639 
640 	ret = nand_ecc_prepare_io_req(nand, (struct nand_page_io_req *)req);
641 	if (ret)
642 		return ret;
643 
644 	ret = spinand_load_page_op(spinand, req);
645 	if (ret)
646 		return ret;
647 
648 	ret = spinand_wait(spinand,
649 			   SPINAND_READ_INITIAL_DELAY_US,
650 			   SPINAND_READ_POLL_DELAY_US,
651 			   &status);
652 	if (ret < 0)
653 		return ret;
654 
655 	spinand_ondie_ecc_save_status(nand, status);
656 
657 	ret = spinand_read_from_cache_op(spinand, req);
658 	if (ret)
659 		return ret;
660 
661 	return nand_ecc_finish_io_req(nand, (struct nand_page_io_req *)req);
662 }
663 
664 /**
665  * spinand_write_page() - Write a page
666  * @spinand: the spinand device
667  * @req: the I/O request
668  *
669  * Return: 0 or a positive number of bitflips corrected on success.
670  * A negative error code otherwise.
671  */
672 int spinand_write_page(struct spinand_device *spinand,
673 		       const struct nand_page_io_req *req)
674 {
675 	struct nand_device *nand = spinand_to_nand(spinand);
676 	u8 status;
677 	int ret;
678 
679 	ret = nand_ecc_prepare_io_req(nand, (struct nand_page_io_req *)req);
680 	if (ret)
681 		return ret;
682 
683 	ret = spinand_write_enable_op(spinand);
684 	if (ret)
685 		return ret;
686 
687 	ret = spinand_write_to_cache_op(spinand, req);
688 	if (ret)
689 		return ret;
690 
691 	ret = spinand_program_op(spinand, req);
692 	if (ret)
693 		return ret;
694 
695 	ret = spinand_wait(spinand,
696 			   SPINAND_WRITE_INITIAL_DELAY_US,
697 			   SPINAND_WRITE_POLL_DELAY_US,
698 			   &status);
699 	if (ret)
700 		return ret;
701 
702 	if (status & STATUS_PROG_FAILED)
703 		return -EIO;
704 
705 	return nand_ecc_finish_io_req(nand, (struct nand_page_io_req *)req);
706 }
707 
708 static int spinand_mtd_regular_page_read(struct mtd_info *mtd, loff_t from,
709 					 struct mtd_oob_ops *ops,
710 					 unsigned int *max_bitflips)
711 {
712 	struct spinand_device *spinand = mtd_to_spinand(mtd);
713 	struct nand_device *nand = mtd_to_nanddev(mtd);
714 	struct mtd_ecc_stats old_stats;
715 	struct nand_io_iter iter;
716 	bool disable_ecc = false;
717 	bool ecc_failed = false;
718 	unsigned int retry_mode = 0;
719 	int ret;
720 
721 	old_stats = mtd->ecc_stats;
722 
723 	if (ops->mode == MTD_OPS_RAW || !mtd->ooblayout)
724 		disable_ecc = true;
725 
726 	nanddev_io_for_each_page(nand, NAND_PAGE_READ, from, ops, &iter) {
727 		if (disable_ecc)
728 			iter.req.mode = MTD_OPS_RAW;
729 
730 		ret = spinand_select_target(spinand, iter.req.pos.target);
731 		if (ret)
732 			break;
733 
734 read_retry:
735 		ret = spinand_read_page(spinand, &iter.req);
736 		if (ret < 0 && ret != -EBADMSG)
737 			break;
738 
739 		if (ret == -EBADMSG && spinand->set_read_retry) {
740 			if (spinand->read_retries && (++retry_mode <= spinand->read_retries)) {
741 				ret = spinand->set_read_retry(spinand, retry_mode);
742 				if (ret < 0) {
743 					spinand->set_read_retry(spinand, 0);
744 					return ret;
745 				}
746 
747 				/* Reset ecc_stats; retry */
748 				mtd->ecc_stats = old_stats;
749 				goto read_retry;
750 			} else {
751 				/* No more retry modes; real failure */
752 				ecc_failed = true;
753 			}
754 		} else if (ret == -EBADMSG) {
755 			ecc_failed = true;
756 		} else {
757 			*max_bitflips = max_t(unsigned int, *max_bitflips, ret);
758 		}
759 
760 		ret = 0;
761 		ops->retlen += iter.req.datalen;
762 		ops->oobretlen += iter.req.ooblen;
763 
764 		/* Reset to retry mode 0 */
765 		if (retry_mode) {
766 			retry_mode = 0;
767 			ret = spinand->set_read_retry(spinand, retry_mode);
768 			if (ret < 0)
769 				return ret;
770 		}
771 	}
772 
773 	if (ecc_failed && !ret)
774 		ret = -EBADMSG;
775 
776 	return ret;
777 }
778 
779 static int spinand_mtd_continuous_page_read(struct mtd_info *mtd, loff_t from,
780 					    struct mtd_oob_ops *ops,
781 					    unsigned int *max_bitflips)
782 {
783 	struct spinand_device *spinand = mtd_to_spinand(mtd);
784 	struct nand_device *nand = mtd_to_nanddev(mtd);
785 	struct nand_io_iter iter;
786 	u8 status;
787 	int ret;
788 
789 	ret = spinand_cont_read_enable(spinand, true);
790 	if (ret)
791 		return ret;
792 
793 	/*
794 	 * The cache is divided into two halves. While one half of the cache has
795 	 * the requested data, the other half is loaded with the next chunk of data.
796 	 * Therefore, the host can read out the data continuously from page to page.
797 	 * Each data read must be a multiple of 4-bytes and full pages should be read;
798 	 * otherwise, the data output might get out of sequence from one read command
799 	 * to another.
800 	 */
801 	nanddev_io_for_each_block(nand, NAND_PAGE_READ, from, ops, &iter) {
802 		ret = spinand_select_target(spinand, iter.req.pos.target);
803 		if (ret)
804 			goto end_cont_read;
805 
806 		ret = nand_ecc_prepare_io_req(nand, &iter.req);
807 		if (ret)
808 			goto end_cont_read;
809 
810 		ret = spinand_load_page_op(spinand, &iter.req);
811 		if (ret)
812 			goto end_cont_read;
813 
814 		ret = spinand_wait(spinand, SPINAND_READ_INITIAL_DELAY_US,
815 				   SPINAND_READ_POLL_DELAY_US, NULL);
816 		if (ret < 0)
817 			goto end_cont_read;
818 
819 		ret = spinand_read_from_cache_op(spinand, &iter.req);
820 		if (ret)
821 			goto end_cont_read;
822 
823 		ops->retlen += iter.req.datalen;
824 
825 		ret = spinand_read_status(spinand, &status);
826 		if (ret)
827 			goto end_cont_read;
828 
829 		spinand_ondie_ecc_save_status(nand, status);
830 
831 		ret = nand_ecc_finish_io_req(nand, &iter.req);
832 		if (ret < 0)
833 			goto end_cont_read;
834 
835 		*max_bitflips = max_t(unsigned int, *max_bitflips, ret);
836 		ret = 0;
837 	}
838 
839 end_cont_read:
840 	/*
841 	 * Once all the data has been read out, the host can either pull CS#
842 	 * high and wait for tRST or manually clear the bit in the configuration
843 	 * register to terminate the continuous read operation. We have no
844 	 * guarantee the SPI controller drivers will effectively deassert the CS
845 	 * when we expect them to, so take the register based approach.
846 	 */
847 	spinand_cont_read_enable(spinand, false);
848 
849 	return ret;
850 }
851 
852 static void spinand_cont_read_init(struct spinand_device *spinand)
853 {
854 	struct nand_device *nand = spinand_to_nand(spinand);
855 	enum nand_ecc_engine_type engine_type = nand->ecc.ctx.conf.engine_type;
856 
857 	/* OOBs cannot be retrieved so external/on-host ECC engine won't work */
858 	if (spinand->set_cont_read &&
859 	    (engine_type == NAND_ECC_ENGINE_TYPE_ON_DIE ||
860 	     engine_type == NAND_ECC_ENGINE_TYPE_NONE)) {
861 		spinand->cont_read_possible = true;
862 	}
863 }
864 
865 static bool spinand_use_cont_read(struct mtd_info *mtd, loff_t from,
866 				  struct mtd_oob_ops *ops)
867 {
868 	struct nand_device *nand = mtd_to_nanddev(mtd);
869 	struct spinand_device *spinand = nand_to_spinand(nand);
870 	struct nand_pos start_pos, end_pos;
871 
872 	if (!spinand->cont_read_possible)
873 		return false;
874 
875 	/* OOBs won't be retrieved */
876 	if (ops->ooblen || ops->oobbuf)
877 		return false;
878 
879 	nanddev_offs_to_pos(nand, from, &start_pos);
880 	nanddev_offs_to_pos(nand, from + ops->len - 1, &end_pos);
881 
882 	/*
883 	 * Continuous reads never cross LUN boundaries. Some devices don't
884 	 * support crossing planes boundaries. Some devices don't even support
885 	 * crossing blocks boundaries. The common case being to read through UBI,
886 	 * we will very rarely read two consequent blocks or more, so it is safer
887 	 * and easier (can be improved) to only enable continuous reads when
888 	 * reading within the same erase block.
889 	 */
890 	if (start_pos.target != end_pos.target ||
891 	    start_pos.plane != end_pos.plane ||
892 	    start_pos.eraseblock != end_pos.eraseblock)
893 		return false;
894 
895 	return start_pos.page < end_pos.page;
896 }
897 
898 static int spinand_mtd_read(struct mtd_info *mtd, loff_t from,
899 			    struct mtd_oob_ops *ops)
900 {
901 	struct spinand_device *spinand = mtd_to_spinand(mtd);
902 	struct mtd_ecc_stats old_stats;
903 	unsigned int max_bitflips = 0;
904 	int ret;
905 
906 	mutex_lock(&spinand->lock);
907 
908 	old_stats = mtd->ecc_stats;
909 
910 	if (spinand_use_cont_read(mtd, from, ops)) {
911 		ret = spinand_mtd_continuous_page_read(mtd, from, ops, &max_bitflips);
912 		if (ret == -EAGAIN && !spinand->cont_read_possible) {
913 			/*
914 			 * Spi controller with broken support of continuous
915 			 * reading was detected (see spinand_read_from_cache_op()),
916 			 * repeat reading in regular mode.
917 			 */
918 			ret = spinand_mtd_regular_page_read(mtd, from, ops, &max_bitflips);
919 		}
920 	} else {
921 		ret = spinand_mtd_regular_page_read(mtd, from, ops, &max_bitflips);
922 	}
923 
924 	if (ops->stats) {
925 		ops->stats->uncorrectable_errors +=
926 			mtd->ecc_stats.failed - old_stats.failed;
927 		ops->stats->corrected_bitflips +=
928 			mtd->ecc_stats.corrected - old_stats.corrected;
929 	}
930 
931 	mutex_unlock(&spinand->lock);
932 
933 	return ret ? ret : max_bitflips;
934 }
935 
936 static int spinand_mtd_write(struct mtd_info *mtd, loff_t to,
937 			     struct mtd_oob_ops *ops)
938 {
939 	struct spinand_device *spinand = mtd_to_spinand(mtd);
940 	struct nand_device *nand = mtd_to_nanddev(mtd);
941 	struct nand_io_iter iter;
942 	bool disable_ecc = false;
943 	int ret = 0;
944 
945 	if (ops->mode == MTD_OPS_RAW || !mtd->ooblayout)
946 		disable_ecc = true;
947 
948 	mutex_lock(&spinand->lock);
949 
950 	nanddev_io_for_each_page(nand, NAND_PAGE_WRITE, to, ops, &iter) {
951 		if (disable_ecc)
952 			iter.req.mode = MTD_OPS_RAW;
953 
954 		ret = spinand_select_target(spinand, iter.req.pos.target);
955 		if (ret)
956 			break;
957 
958 		ret = spinand_write_page(spinand, &iter.req);
959 		if (ret)
960 			break;
961 
962 		ops->retlen += iter.req.datalen;
963 		ops->oobretlen += iter.req.ooblen;
964 	}
965 
966 	mutex_unlock(&spinand->lock);
967 
968 	return ret;
969 }
970 
971 static bool spinand_isbad(struct nand_device *nand, const struct nand_pos *pos)
972 {
973 	struct spinand_device *spinand = nand_to_spinand(nand);
974 	u8 marker[2] = { };
975 	struct nand_page_io_req req = {
976 		.pos = *pos,
977 		.ooblen = sizeof(marker),
978 		.ooboffs = 0,
979 		.oobbuf.in = marker,
980 		.mode = MTD_OPS_RAW,
981 	};
982 	int ret;
983 
984 	spinand_select_target(spinand, pos->target);
985 
986 	ret = spinand_read_page(spinand, &req);
987 	if (ret == -EOPNOTSUPP) {
988 		/* Retry with ECC in case raw access is not supported */
989 		req.mode = MTD_OPS_PLACE_OOB;
990 		spinand_read_page(spinand, &req);
991 	}
992 
993 	if (marker[0] != 0xff || marker[1] != 0xff)
994 		return true;
995 
996 	return false;
997 }
998 
999 static int spinand_mtd_block_isbad(struct mtd_info *mtd, loff_t offs)
1000 {
1001 	struct nand_device *nand = mtd_to_nanddev(mtd);
1002 	struct spinand_device *spinand = nand_to_spinand(nand);
1003 	struct nand_pos pos;
1004 	int ret;
1005 
1006 	nanddev_offs_to_pos(nand, offs, &pos);
1007 	mutex_lock(&spinand->lock);
1008 	ret = nanddev_isbad(nand, &pos);
1009 	mutex_unlock(&spinand->lock);
1010 
1011 	return ret;
1012 }
1013 
1014 static int spinand_markbad(struct nand_device *nand, const struct nand_pos *pos)
1015 {
1016 	struct spinand_device *spinand = nand_to_spinand(nand);
1017 	u8 marker[2] = { };
1018 	struct nand_page_io_req req = {
1019 		.pos = *pos,
1020 		.ooboffs = 0,
1021 		.ooblen = sizeof(marker),
1022 		.oobbuf.out = marker,
1023 		.mode = MTD_OPS_RAW,
1024 	};
1025 	int ret;
1026 
1027 	ret = spinand_select_target(spinand, pos->target);
1028 	if (ret)
1029 		return ret;
1030 
1031 	ret = spinand_write_page(spinand, &req);
1032 	if (ret == -EOPNOTSUPP) {
1033 		/* Retry with ECC in case raw access is not supported */
1034 		req.mode = MTD_OPS_PLACE_OOB;
1035 		ret = spinand_write_page(spinand, &req);
1036 	}
1037 
1038 	return ret;
1039 }
1040 
1041 static int spinand_mtd_block_markbad(struct mtd_info *mtd, loff_t offs)
1042 {
1043 	struct nand_device *nand = mtd_to_nanddev(mtd);
1044 	struct spinand_device *spinand = nand_to_spinand(nand);
1045 	struct nand_pos pos;
1046 	int ret;
1047 
1048 	nanddev_offs_to_pos(nand, offs, &pos);
1049 	mutex_lock(&spinand->lock);
1050 	ret = nanddev_markbad(nand, &pos);
1051 	mutex_unlock(&spinand->lock);
1052 
1053 	return ret;
1054 }
1055 
1056 static int spinand_erase(struct nand_device *nand, const struct nand_pos *pos)
1057 {
1058 	struct spinand_device *spinand = nand_to_spinand(nand);
1059 	u8 status;
1060 	int ret;
1061 
1062 	ret = spinand_select_target(spinand, pos->target);
1063 	if (ret)
1064 		return ret;
1065 
1066 	ret = spinand_write_enable_op(spinand);
1067 	if (ret)
1068 		return ret;
1069 
1070 	ret = spinand_erase_op(spinand, pos);
1071 	if (ret)
1072 		return ret;
1073 
1074 	ret = spinand_wait(spinand,
1075 			   SPINAND_ERASE_INITIAL_DELAY_US,
1076 			   SPINAND_ERASE_POLL_DELAY_US,
1077 			   &status);
1078 
1079 	if (!ret && (status & STATUS_ERASE_FAILED))
1080 		ret = -EIO;
1081 
1082 	return ret;
1083 }
1084 
1085 static int spinand_mtd_erase(struct mtd_info *mtd,
1086 			     struct erase_info *einfo)
1087 {
1088 	struct spinand_device *spinand = mtd_to_spinand(mtd);
1089 	int ret;
1090 
1091 	mutex_lock(&spinand->lock);
1092 	ret = nanddev_mtd_erase(mtd, einfo);
1093 	mutex_unlock(&spinand->lock);
1094 
1095 	return ret;
1096 }
1097 
1098 static int spinand_mtd_block_isreserved(struct mtd_info *mtd, loff_t offs)
1099 {
1100 	struct spinand_device *spinand = mtd_to_spinand(mtd);
1101 	struct nand_device *nand = mtd_to_nanddev(mtd);
1102 	struct nand_pos pos;
1103 	int ret;
1104 
1105 	nanddev_offs_to_pos(nand, offs, &pos);
1106 	mutex_lock(&spinand->lock);
1107 	ret = nanddev_isreserved(nand, &pos);
1108 	mutex_unlock(&spinand->lock);
1109 
1110 	return ret;
1111 }
1112 
1113 static struct spi_mem_dirmap_desc *spinand_create_rdesc(
1114 					struct spinand_device *spinand,
1115 					struct spi_mem_dirmap_info *info)
1116 {
1117 	struct nand_device *nand = spinand_to_nand(spinand);
1118 	struct spi_mem_dirmap_desc *desc = NULL;
1119 
1120 	if (spinand->cont_read_possible) {
1121 		/*
1122 		 * spi controller may return an error if info->length is
1123 		 * too large
1124 		 */
1125 		info->length = nanddev_eraseblock_size(nand);
1126 		desc = devm_spi_mem_dirmap_create(&spinand->spimem->spi->dev,
1127 						  spinand->spimem, info);
1128 	}
1129 
1130 	if (IS_ERR_OR_NULL(desc)) {
1131 		/*
1132 		 * continuous reading is not supported by flash or
1133 		 * its spi controller, use regular reading
1134 		 */
1135 		spinand->cont_read_possible = false;
1136 
1137 		info->length = nanddev_page_size(nand) +
1138 			       nanddev_per_page_oobsize(nand);
1139 		desc = devm_spi_mem_dirmap_create(&spinand->spimem->spi->dev,
1140 						  spinand->spimem, info);
1141 	}
1142 
1143 	return desc;
1144 }
1145 
1146 static int spinand_create_dirmap(struct spinand_device *spinand,
1147 				 unsigned int plane)
1148 {
1149 	struct nand_device *nand = spinand_to_nand(spinand);
1150 	struct spi_mem_dirmap_info info = { 0 };
1151 	struct spi_mem_dirmap_desc *desc;
1152 
1153 	/* The plane number is passed in MSB just above the column address */
1154 	info.offset = plane << fls(nand->memorg.pagesize);
1155 
1156 	info.length = nanddev_page_size(nand) + nanddev_per_page_oobsize(nand);
1157 	info.op_tmpl = *spinand->op_templates.update_cache;
1158 	desc = devm_spi_mem_dirmap_create(&spinand->spimem->spi->dev,
1159 					  spinand->spimem, &info);
1160 	if (IS_ERR(desc))
1161 		return PTR_ERR(desc);
1162 
1163 	spinand->dirmaps[plane].wdesc = desc;
1164 
1165 	info.op_tmpl = *spinand->op_templates.read_cache;
1166 	desc = spinand_create_rdesc(spinand, &info);
1167 	if (IS_ERR(desc))
1168 		return PTR_ERR(desc);
1169 
1170 	spinand->dirmaps[plane].rdesc = desc;
1171 
1172 	if (nand->ecc.engine->integration != NAND_ECC_ENGINE_INTEGRATION_PIPELINED) {
1173 		spinand->dirmaps[plane].wdesc_ecc = spinand->dirmaps[plane].wdesc;
1174 		spinand->dirmaps[plane].rdesc_ecc = spinand->dirmaps[plane].rdesc;
1175 
1176 		return 0;
1177 	}
1178 
1179 	info.length = nanddev_page_size(nand) + nanddev_per_page_oobsize(nand);
1180 	info.op_tmpl = *spinand->op_templates.update_cache;
1181 	info.op_tmpl.data.ecc = true;
1182 	desc = devm_spi_mem_dirmap_create(&spinand->spimem->spi->dev,
1183 					  spinand->spimem, &info);
1184 	if (IS_ERR(desc))
1185 		return PTR_ERR(desc);
1186 
1187 	spinand->dirmaps[plane].wdesc_ecc = desc;
1188 
1189 	info.op_tmpl = *spinand->op_templates.read_cache;
1190 	info.op_tmpl.data.ecc = true;
1191 	desc = spinand_create_rdesc(spinand, &info);
1192 	if (IS_ERR(desc))
1193 		return PTR_ERR(desc);
1194 
1195 	spinand->dirmaps[plane].rdesc_ecc = desc;
1196 
1197 	return 0;
1198 }
1199 
1200 static int spinand_create_dirmaps(struct spinand_device *spinand)
1201 {
1202 	struct nand_device *nand = spinand_to_nand(spinand);
1203 	int i, ret;
1204 
1205 	spinand->dirmaps = devm_kzalloc(&spinand->spimem->spi->dev,
1206 					sizeof(*spinand->dirmaps) *
1207 					nand->memorg.planes_per_lun,
1208 					GFP_KERNEL);
1209 	if (!spinand->dirmaps)
1210 		return -ENOMEM;
1211 
1212 	for (i = 0; i < nand->memorg.planes_per_lun; i++) {
1213 		ret = spinand_create_dirmap(spinand, i);
1214 		if (ret)
1215 			return ret;
1216 	}
1217 
1218 	return 0;
1219 }
1220 
1221 static const struct nand_ops spinand_ops = {
1222 	.erase = spinand_erase,
1223 	.markbad = spinand_markbad,
1224 	.isbad = spinand_isbad,
1225 };
1226 
1227 static const struct spinand_manufacturer *spinand_manufacturers[] = {
1228 	&alliancememory_spinand_manufacturer,
1229 	&ato_spinand_manufacturer,
1230 	&esmt_c8_spinand_manufacturer,
1231 	&fmsh_spinand_manufacturer,
1232 	&foresee_spinand_manufacturer,
1233 	&gigadevice_spinand_manufacturer,
1234 	&macronix_spinand_manufacturer,
1235 	&micron_spinand_manufacturer,
1236 	&paragon_spinand_manufacturer,
1237 	&skyhigh_spinand_manufacturer,
1238 	&toshiba_spinand_manufacturer,
1239 	&winbond_spinand_manufacturer,
1240 	&xtx_spinand_manufacturer,
1241 };
1242 
1243 static int spinand_manufacturer_match(struct spinand_device *spinand,
1244 				      enum spinand_readid_method rdid_method)
1245 {
1246 	u8 *id = spinand->id.data;
1247 	unsigned int i;
1248 	int ret;
1249 
1250 	for (i = 0; i < ARRAY_SIZE(spinand_manufacturers); i++) {
1251 		const struct spinand_manufacturer *manufacturer =
1252 			spinand_manufacturers[i];
1253 
1254 		if (id[0] != manufacturer->id)
1255 			continue;
1256 
1257 		ret = spinand_match_and_init(spinand,
1258 					     manufacturer->chips,
1259 					     manufacturer->nchips,
1260 					     rdid_method);
1261 		if (ret < 0)
1262 			continue;
1263 
1264 		spinand->manufacturer = manufacturer;
1265 		return 0;
1266 	}
1267 	return -EOPNOTSUPP;
1268 }
1269 
1270 static int spinand_id_detect(struct spinand_device *spinand)
1271 {
1272 	u8 *id = spinand->id.data;
1273 	int ret;
1274 
1275 	ret = spinand_read_id_op(spinand, 0, 0, id);
1276 	if (ret)
1277 		return ret;
1278 	ret = spinand_manufacturer_match(spinand, SPINAND_READID_METHOD_OPCODE);
1279 	if (!ret)
1280 		return 0;
1281 
1282 	ret = spinand_read_id_op(spinand, 1, 0, id);
1283 	if (ret)
1284 		return ret;
1285 	ret = spinand_manufacturer_match(spinand,
1286 					 SPINAND_READID_METHOD_OPCODE_ADDR);
1287 	if (!ret)
1288 		return 0;
1289 
1290 	ret = spinand_read_id_op(spinand, 0, 1, id);
1291 	if (ret)
1292 		return ret;
1293 	ret = spinand_manufacturer_match(spinand,
1294 					 SPINAND_READID_METHOD_OPCODE_DUMMY);
1295 
1296 	return ret;
1297 }
1298 
1299 static int spinand_manufacturer_init(struct spinand_device *spinand)
1300 {
1301 	int ret;
1302 
1303 	if (spinand->manufacturer->ops->init) {
1304 		ret = spinand->manufacturer->ops->init(spinand);
1305 		if (ret)
1306 			return ret;
1307 	}
1308 
1309 	if (spinand->configure_chip) {
1310 		ret = spinand->configure_chip(spinand);
1311 		if (ret)
1312 			return ret;
1313 	}
1314 
1315 	return 0;
1316 }
1317 
1318 static void spinand_manufacturer_cleanup(struct spinand_device *spinand)
1319 {
1320 	/* Release manufacturer private data */
1321 	if (spinand->manufacturer->ops->cleanup)
1322 		return spinand->manufacturer->ops->cleanup(spinand);
1323 }
1324 
1325 static const struct spi_mem_op *
1326 spinand_select_op_variant(struct spinand_device *spinand,
1327 			  const struct spinand_op_variants *variants)
1328 {
1329 	struct nand_device *nand = spinand_to_nand(spinand);
1330 	const struct spi_mem_op *best_variant = NULL;
1331 	u64 best_op_duration_ns = ULLONG_MAX;
1332 	unsigned int i;
1333 
1334 	for (i = 0; i < variants->nops; i++) {
1335 		struct spi_mem_op op = variants->ops[i];
1336 		u64 op_duration_ns = 0;
1337 		unsigned int nbytes;
1338 		int ret;
1339 
1340 		nbytes = nanddev_per_page_oobsize(nand) +
1341 			 nanddev_page_size(nand);
1342 
1343 		while (nbytes) {
1344 			op.data.nbytes = nbytes;
1345 			ret = spi_mem_adjust_op_size(spinand->spimem, &op);
1346 			if (ret)
1347 				break;
1348 
1349 			spi_mem_adjust_op_freq(spinand->spimem, &op);
1350 
1351 			if (!spi_mem_supports_op(spinand->spimem, &op))
1352 				break;
1353 
1354 			nbytes -= op.data.nbytes;
1355 
1356 			op_duration_ns += spi_mem_calc_op_duration(spinand->spimem, &op);
1357 		}
1358 
1359 		if (!nbytes && op_duration_ns < best_op_duration_ns) {
1360 			best_op_duration_ns = op_duration_ns;
1361 			best_variant = &variants->ops[i];
1362 		}
1363 	}
1364 
1365 	return best_variant;
1366 }
1367 
1368 /**
1369  * spinand_match_and_init() - Try to find a match between a device ID and an
1370  *			      entry in a spinand_info table
1371  * @spinand: SPI NAND object
1372  * @table: SPI NAND device description table
1373  * @table_size: size of the device description table
1374  * @rdid_method: read id method to match
1375  *
1376  * Match between a device ID retrieved through the READ_ID command and an
1377  * entry in the SPI NAND description table. If a match is found, the spinand
1378  * object will be initialized with information provided by the matching
1379  * spinand_info entry.
1380  *
1381  * Return: 0 on success, a negative error code otherwise.
1382  */
1383 int spinand_match_and_init(struct spinand_device *spinand,
1384 			   const struct spinand_info *table,
1385 			   unsigned int table_size,
1386 			   enum spinand_readid_method rdid_method)
1387 {
1388 	u8 *id = spinand->id.data;
1389 	struct nand_device *nand = spinand_to_nand(spinand);
1390 	unsigned int i;
1391 
1392 	for (i = 0; i < table_size; i++) {
1393 		const struct spinand_info *info = &table[i];
1394 		const struct spi_mem_op *op;
1395 
1396 		if (rdid_method != info->devid.method)
1397 			continue;
1398 
1399 		if (memcmp(id + 1, info->devid.id, info->devid.len))
1400 			continue;
1401 
1402 		nand->memorg = table[i].memorg;
1403 		nanddev_set_ecc_requirements(nand, &table[i].eccreq);
1404 		spinand->eccinfo = table[i].eccinfo;
1405 		spinand->flags = table[i].flags;
1406 		spinand->id.len = 1 + table[i].devid.len;
1407 		spinand->select_target = table[i].select_target;
1408 		spinand->configure_chip = table[i].configure_chip;
1409 		spinand->set_cont_read = table[i].set_cont_read;
1410 		spinand->fact_otp = &table[i].fact_otp;
1411 		spinand->user_otp = &table[i].user_otp;
1412 		spinand->read_retries = table[i].read_retries;
1413 		spinand->set_read_retry = table[i].set_read_retry;
1414 
1415 		op = spinand_select_op_variant(spinand,
1416 					       info->op_variants.read_cache);
1417 		if (!op)
1418 			return -ENOTSUPP;
1419 
1420 		spinand->op_templates.read_cache = op;
1421 
1422 		op = spinand_select_op_variant(spinand,
1423 					       info->op_variants.write_cache);
1424 		if (!op)
1425 			return -ENOTSUPP;
1426 
1427 		spinand->op_templates.write_cache = op;
1428 
1429 		op = spinand_select_op_variant(spinand,
1430 					       info->op_variants.update_cache);
1431 		spinand->op_templates.update_cache = op;
1432 
1433 		return 0;
1434 	}
1435 
1436 	return -ENOTSUPP;
1437 }
1438 
1439 static int spinand_detect(struct spinand_device *spinand)
1440 {
1441 	struct device *dev = &spinand->spimem->spi->dev;
1442 	struct nand_device *nand = spinand_to_nand(spinand);
1443 	int ret;
1444 
1445 	ret = spinand_reset_op(spinand);
1446 	if (ret)
1447 		return ret;
1448 
1449 	ret = spinand_id_detect(spinand);
1450 	if (ret) {
1451 		dev_err(dev, "unknown raw ID %*phN\n", SPINAND_MAX_ID_LEN,
1452 			spinand->id.data);
1453 		return ret;
1454 	}
1455 
1456 	if (nand->memorg.ntargets > 1 && !spinand->select_target) {
1457 		dev_err(dev,
1458 			"SPI NANDs with more than one die must implement ->select_target()\n");
1459 		return -EINVAL;
1460 	}
1461 
1462 	dev_info(&spinand->spimem->spi->dev,
1463 		 "%s SPI NAND was found.\n", spinand->manufacturer->name);
1464 	dev_info(&spinand->spimem->spi->dev,
1465 		 "%llu MiB, block size: %zu KiB, page size: %zu, OOB size: %u\n",
1466 		 nanddev_size(nand) >> 20, nanddev_eraseblock_size(nand) >> 10,
1467 		 nanddev_page_size(nand), nanddev_per_page_oobsize(nand));
1468 
1469 	return 0;
1470 }
1471 
1472 static int spinand_init_flash(struct spinand_device *spinand)
1473 {
1474 	struct device *dev = &spinand->spimem->spi->dev;
1475 	struct nand_device *nand = spinand_to_nand(spinand);
1476 	int ret, i;
1477 
1478 	ret = spinand_read_cfg(spinand);
1479 	if (ret)
1480 		return ret;
1481 
1482 	ret = spinand_init_quad_enable(spinand);
1483 	if (ret)
1484 		return ret;
1485 
1486 	ret = spinand_upd_cfg(spinand, CFG_OTP_ENABLE, 0);
1487 	if (ret)
1488 		return ret;
1489 
1490 	ret = spinand_manufacturer_init(spinand);
1491 	if (ret) {
1492 		dev_err(dev,
1493 		"Failed to initialize the SPI NAND chip (err = %d)\n",
1494 		ret);
1495 		return ret;
1496 	}
1497 
1498 	/* After power up, all blocks are locked, so unlock them here. */
1499 	for (i = 0; i < nand->memorg.ntargets; i++) {
1500 		ret = spinand_select_target(spinand, i);
1501 		if (ret)
1502 			break;
1503 
1504 		ret = spinand_lock_block(spinand, BL_ALL_UNLOCKED);
1505 		if (ret)
1506 			break;
1507 	}
1508 
1509 	if (ret)
1510 		spinand_manufacturer_cleanup(spinand);
1511 
1512 	return ret;
1513 }
1514 
1515 static void spinand_mtd_resume(struct mtd_info *mtd)
1516 {
1517 	struct spinand_device *spinand = mtd_to_spinand(mtd);
1518 	int ret;
1519 
1520 	ret = spinand_reset_op(spinand);
1521 	if (ret)
1522 		return;
1523 
1524 	ret = spinand_init_flash(spinand);
1525 	if (ret)
1526 		return;
1527 
1528 	spinand_ecc_enable(spinand, false);
1529 }
1530 
1531 static int spinand_init(struct spinand_device *spinand)
1532 {
1533 	struct device *dev = &spinand->spimem->spi->dev;
1534 	struct mtd_info *mtd = spinand_to_mtd(spinand);
1535 	struct nand_device *nand = mtd_to_nanddev(mtd);
1536 	int ret;
1537 
1538 	/*
1539 	 * We need a scratch buffer because the spi_mem interface requires that
1540 	 * buf passed in spi_mem_op->data.buf be DMA-able.
1541 	 */
1542 	spinand->scratchbuf = kzalloc(SPINAND_MAX_ID_LEN, GFP_KERNEL);
1543 	if (!spinand->scratchbuf)
1544 		return -ENOMEM;
1545 
1546 	ret = spinand_detect(spinand);
1547 	if (ret)
1548 		goto err_free_bufs;
1549 
1550 	/*
1551 	 * Use kzalloc() instead of devm_kzalloc() here, because some drivers
1552 	 * may use this buffer for DMA access.
1553 	 * Memory allocated by devm_ does not guarantee DMA-safe alignment.
1554 	 */
1555 	spinand->databuf = kzalloc(nanddev_eraseblock_size(nand),
1556 				   GFP_KERNEL);
1557 	if (!spinand->databuf) {
1558 		ret = -ENOMEM;
1559 		goto err_free_bufs;
1560 	}
1561 
1562 	spinand->oobbuf = spinand->databuf + nanddev_page_size(nand);
1563 
1564 	ret = spinand_init_cfg_cache(spinand);
1565 	if (ret)
1566 		goto err_free_bufs;
1567 
1568 	ret = spinand_init_flash(spinand);
1569 	if (ret)
1570 		goto err_free_bufs;
1571 
1572 	ret = nanddev_init(nand, &spinand_ops, THIS_MODULE);
1573 	if (ret)
1574 		goto err_manuf_cleanup;
1575 
1576 	/* SPI-NAND default ECC engine is on-die */
1577 	nand->ecc.defaults.engine_type = NAND_ECC_ENGINE_TYPE_ON_DIE;
1578 	nand->ecc.ondie_engine = &spinand_ondie_ecc_engine;
1579 
1580 	spinand_ecc_enable(spinand, false);
1581 	ret = nanddev_ecc_engine_init(nand);
1582 	if (ret)
1583 		goto err_cleanup_nanddev;
1584 
1585 	/*
1586 	 * Continuous read can only be enabled with an on-die ECC engine, so the
1587 	 * ECC initialization must have happened previously.
1588 	 */
1589 	spinand_cont_read_init(spinand);
1590 
1591 	mtd->_read_oob = spinand_mtd_read;
1592 	mtd->_write_oob = spinand_mtd_write;
1593 	mtd->_block_isbad = spinand_mtd_block_isbad;
1594 	mtd->_block_markbad = spinand_mtd_block_markbad;
1595 	mtd->_block_isreserved = spinand_mtd_block_isreserved;
1596 	mtd->_erase = spinand_mtd_erase;
1597 	mtd->_max_bad_blocks = nanddev_mtd_max_bad_blocks;
1598 	mtd->_resume = spinand_mtd_resume;
1599 
1600 	if (spinand_user_otp_size(spinand) || spinand_fact_otp_size(spinand)) {
1601 		ret = spinand_set_mtd_otp_ops(spinand);
1602 		if (ret)
1603 			goto err_cleanup_ecc_engine;
1604 	}
1605 
1606 	if (nand->ecc.engine) {
1607 		ret = mtd_ooblayout_count_freebytes(mtd);
1608 		if (ret < 0)
1609 			goto err_cleanup_ecc_engine;
1610 	}
1611 
1612 	mtd->oobavail = ret;
1613 
1614 	/* Propagate ECC information to mtd_info */
1615 	mtd->ecc_strength = nanddev_get_ecc_conf(nand)->strength;
1616 	mtd->ecc_step_size = nanddev_get_ecc_conf(nand)->step_size;
1617 	mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
1618 
1619 	ret = spinand_create_dirmaps(spinand);
1620 	if (ret) {
1621 		dev_err(dev,
1622 			"Failed to create direct mappings for read/write operations (err = %d)\n",
1623 			ret);
1624 		goto err_cleanup_ecc_engine;
1625 	}
1626 
1627 	return 0;
1628 
1629 err_cleanup_ecc_engine:
1630 	nanddev_ecc_engine_cleanup(nand);
1631 
1632 err_cleanup_nanddev:
1633 	nanddev_cleanup(nand);
1634 
1635 err_manuf_cleanup:
1636 	spinand_manufacturer_cleanup(spinand);
1637 
1638 err_free_bufs:
1639 	kfree(spinand->databuf);
1640 	kfree(spinand->scratchbuf);
1641 	return ret;
1642 }
1643 
1644 static void spinand_cleanup(struct spinand_device *spinand)
1645 {
1646 	struct nand_device *nand = spinand_to_nand(spinand);
1647 
1648 	nanddev_ecc_engine_cleanup(nand);
1649 	nanddev_cleanup(nand);
1650 	spinand_manufacturer_cleanup(spinand);
1651 	kfree(spinand->databuf);
1652 	kfree(spinand->scratchbuf);
1653 }
1654 
1655 static int spinand_probe(struct spi_mem *mem)
1656 {
1657 	struct spinand_device *spinand;
1658 	struct mtd_info *mtd;
1659 	int ret;
1660 
1661 	spinand = devm_kzalloc(&mem->spi->dev, sizeof(*spinand),
1662 			       GFP_KERNEL);
1663 	if (!spinand)
1664 		return -ENOMEM;
1665 
1666 	spinand->spimem = mem;
1667 	spi_mem_set_drvdata(mem, spinand);
1668 	spinand_set_of_node(spinand, mem->spi->dev.of_node);
1669 	mutex_init(&spinand->lock);
1670 	mtd = spinand_to_mtd(spinand);
1671 	mtd->dev.parent = &mem->spi->dev;
1672 
1673 	ret = spinand_init(spinand);
1674 	if (ret)
1675 		return ret;
1676 
1677 	ret = mtd_device_register(mtd, NULL, 0);
1678 	if (ret)
1679 		goto err_spinand_cleanup;
1680 
1681 	return 0;
1682 
1683 err_spinand_cleanup:
1684 	spinand_cleanup(spinand);
1685 
1686 	return ret;
1687 }
1688 
1689 static int spinand_remove(struct spi_mem *mem)
1690 {
1691 	struct spinand_device *spinand;
1692 	struct mtd_info *mtd;
1693 	int ret;
1694 
1695 	spinand = spi_mem_get_drvdata(mem);
1696 	mtd = spinand_to_mtd(spinand);
1697 
1698 	ret = mtd_device_unregister(mtd);
1699 	if (ret)
1700 		return ret;
1701 
1702 	spinand_cleanup(spinand);
1703 
1704 	return 0;
1705 }
1706 
1707 static const struct spi_device_id spinand_ids[] = {
1708 	{ .name = "spi-nand" },
1709 	{ /* sentinel */ },
1710 };
1711 MODULE_DEVICE_TABLE(spi, spinand_ids);
1712 
1713 #ifdef CONFIG_OF
1714 static const struct of_device_id spinand_of_ids[] = {
1715 	{ .compatible = "spi-nand" },
1716 	{ /* sentinel */ },
1717 };
1718 MODULE_DEVICE_TABLE(of, spinand_of_ids);
1719 #endif
1720 
1721 static struct spi_mem_driver spinand_drv = {
1722 	.spidrv = {
1723 		.id_table = spinand_ids,
1724 		.driver = {
1725 			.name = "spi-nand",
1726 			.of_match_table = of_match_ptr(spinand_of_ids),
1727 		},
1728 	},
1729 	.probe = spinand_probe,
1730 	.remove = spinand_remove,
1731 };
1732 module_spi_mem_driver(spinand_drv);
1733 
1734 MODULE_DESCRIPTION("SPI NAND framework");
1735 MODULE_AUTHOR("Peter Pan<peterpandong@micron.com>");
1736 MODULE_LICENSE("GPL v2");
1737