1 // SPDX-License-Identifier: GPL-2.0-only
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.
7 * Additional technical information is available on
8 * http://www.linux-mtd.infradead.org/doc/nand.html
10 * Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
11 * 2002-2006 Thomas Gleixner (tglx@linutronix.de)
14 * David Woodhouse for adding multichip support
16 * Aleph One Ltd. and Toby Churchill Ltd. for supporting the
17 * rework for 2K page size chips
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
26 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
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>
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>
43 #include <linux/mtd/partitions.h>
45 #include <linux/of_gpio.h>
46 #include <linux/gpio/consumer.h>
48 #include "internals.h"
50 static int nand_pairing_dist3_get_info(struct mtd_info *mtd, int page,
51 struct mtd_pairing_info *info)
53 int lastpage = (mtd->erasesize / mtd->writesize) - 1;
59 if (!page || (page & 1)) {
61 info->pair = (page + 1) / 2;
64 info->pair = (page + 1 - dist) / 2;
70 static int nand_pairing_dist3_get_wunit(struct mtd_info *mtd,
71 const struct mtd_pairing_info *info)
73 int lastpair = ((mtd->erasesize / mtd->writesize) - 1) / 2;
74 int page = info->pair * 2;
77 if (!info->group && !info->pair)
80 if (info->pair == lastpair && info->group)
88 if (page >= mtd->erasesize / mtd->writesize)
94 const struct mtd_pairing_scheme dist3_pairing_scheme = {
96 .get_info = nand_pairing_dist3_get_info,
97 .get_wunit = nand_pairing_dist3_get_wunit,
100 static int check_offs_len(struct nand_chip *chip, loff_t ofs, uint64_t len)
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__);
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__);
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
127 * Copy bits from one memory region to another (overlap authorized).
129 void nand_extract_bits(u8 *dst, unsigned int dst_off, const u8 *src,
130 unsigned int src_off, unsigned int nbits)
140 n = min3(8 - dst_off, 8 - src_off, nbits);
142 tmp = (*src >> src_off) & GENMASK(n - 1, 0);
143 *dst &= ~GENMASK(n - 1 + dst_off, dst_off);
144 *dst |= tmp << dst_off;
161 EXPORT_SYMBOL_GPL(nand_extract_bits);
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
169 * Select a NAND target so that further operations executed on @chip go to the
170 * selected NAND target.
172 void nand_select_target(struct nand_chip *chip, unsigned int cs)
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.
178 if (WARN_ON(cs > nanddev_ntargets(&chip->base)))
183 if (chip->legacy.select_chip)
184 chip->legacy.select_chip(chip, cs);
186 EXPORT_SYMBOL_GPL(nand_select_target);
189 * nand_deselect_target() - Deselect the currently selected target
190 * @chip: NAND chip object
192 * Deselect the currently selected NAND target. The result of operations
193 * executed on @chip after the target has been deselected is undefined.
195 void nand_deselect_target(struct nand_chip *chip)
197 if (chip->legacy.select_chip)
198 chip->legacy.select_chip(chip, -1);
202 EXPORT_SYMBOL_GPL(nand_deselect_target);
205 * nand_release_device - [GENERIC] release chip
206 * @chip: NAND chip object
208 * Release chip lock and wake up anyone waiting on the device.
210 static void nand_release_device(struct nand_chip *chip)
212 /* Release the controller and the chip */
213 mutex_unlock(&chip->controller->lock);
214 mutex_unlock(&chip->lock);
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
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.
226 int nand_bbm_get_next_page(struct nand_chip *chip, int page)
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
234 if (page == 0 && !(chip->options & bbm_flags))
236 if (page == 0 && chip->options & NAND_BBM_FIRSTPAGE)
238 if (page <= 1 && chip->options & NAND_BBM_SECONDPAGE)
240 if (page <= last_page && chip->options & NAND_BBM_LASTPAGE)
247 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
248 * @chip: NAND chip object
249 * @ofs: offset from device start
251 * Check, if the block is bad.
253 static int nand_block_bad(struct nand_chip *chip, loff_t ofs)
255 int first_page, page_offset;
259 first_page = (int)(ofs >> chip->page_shift) & chip->pagemask;
260 page_offset = nand_bbm_get_next_page(chip, 0);
262 while (page_offset >= 0) {
263 res = chip->ecc.read_oob(chip, first_page + page_offset);
267 bad = chip->oob_poi[chip->badblockpos];
269 if (likely(chip->badblockbits == 8))
272 res = hweight8(bad) < chip->badblockbits;
276 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
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
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.
292 static bool nand_region_is_secured(struct nand_chip *chip, loff_t offset, u64 size)
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];
300 if (offset + size <= region->offset ||
301 offset >= region->offset + region->size)
304 pr_debug("%s: Region 0x%llx - 0x%llx is secured!",
305 __func__, offset, offset + size);
313 static int nand_isbad_bbm(struct nand_chip *chip, loff_t ofs)
315 struct mtd_info *mtd = nand_to_mtd(chip);
317 if (chip->options & NAND_NO_BBM_QUIRK)
320 /* Check if the region is secured */
321 if (nand_region_is_secured(chip, ofs, mtd->erasesize))
324 if (mtd_check_expert_analysis_mode())
327 if (chip->legacy.block_bad)
328 return chip->legacy.block_bad(chip, ofs);
330 return nand_block_bad(chip, ofs);
334 * nand_get_device - [GENERIC] Get chip for selected access
335 * @chip: NAND chip structure
337 * Lock the device and its controller for exclusive access
339 static void nand_get_device(struct nand_chip *chip)
341 /* Wait until the device is resumed. */
343 mutex_lock(&chip->lock);
344 if (!chip->suspended) {
345 mutex_lock(&chip->controller->lock);
348 mutex_unlock(&chip->lock);
350 wait_event(chip->resume_wq, !chip->suspended);
355 * nand_check_wp - [GENERIC] check if the chip is write protected
356 * @chip: NAND chip object
358 * Check, if the device is write protected. The function expects, that the
359 * device is already selected.
361 static int nand_check_wp(struct nand_chip *chip)
366 /* Broken xD cards report WP despite being writable */
367 if (chip->options & NAND_BROKEN_XD)
370 /* Check the WP bit */
371 ret = nand_status_op(chip, &status);
375 return status & NAND_STATUS_WP ? 0 : 1;
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
385 static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len,
386 struct mtd_oob_ops *ops)
388 struct mtd_info *mtd = nand_to_mtd(chip);
392 * Initialise to all 0xFF, to avoid the possibility of left over OOB
393 * data from a previous OOB read.
395 memset(chip->oob_poi, 0xff, mtd->oobsize);
399 case MTD_OPS_PLACE_OOB:
401 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
404 case MTD_OPS_AUTO_OOB:
405 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
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
422 * NAND write out-of-band.
424 static int nand_do_write_oob(struct nand_chip *chip, loff_t to,
425 struct mtd_oob_ops *ops)
427 struct mtd_info *mtd = nand_to_mtd(chip);
428 int chipnr, page, status, len, ret;
430 pr_debug("%s: to = 0x%08x, len = %i\n",
431 __func__, (unsigned int)to, (int)ops->ooblen);
433 len = mtd_oobavail(mtd, ops);
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",
442 /* Check if the region is secured */
443 if (nand_region_is_secured(chip, to, ops->ooblen))
446 chipnr = (int)(to >> chip->chip_shift);
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.
454 ret = nand_reset(chip, chipnr);
458 nand_select_target(chip, chipnr);
460 /* Shift to get page */
461 page = (int)(to >> chip->page_shift);
463 /* Check, if it is write protected */
464 if (nand_check_wp(chip)) {
465 nand_deselect_target(chip);
469 /* Invalidate the page cache, if we write to the cached page */
470 if (page == chip->pagecache.page)
471 chip->pagecache.page = -1;
473 nand_fill_oob(chip, ops->oobbuf, ops->ooblen, ops);
475 if (ops->mode == MTD_OPS_RAW)
476 status = chip->ecc.write_oob_raw(chip, page & chip->pagemask);
478 status = chip->ecc.write_oob(chip, page & chip->pagemask);
480 nand_deselect_target(chip);
485 ops->oobretlen = ops->ooblen;
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
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
499 static int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
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;
506 memset(&ops, 0, sizeof(ops));
508 ops.ooboffs = chip->badblockpos;
509 if (chip->options & NAND_BUSWIDTH_16) {
510 ops.ooboffs &= ~0x01;
511 ops.len = ops.ooblen = 2;
513 ops.len = ops.ooblen = 1;
515 ops.mode = MTD_OPS_PLACE_OOB;
517 page_offset = nand_bbm_get_next_page(chip, 0);
519 while (page_offset >= 0) {
520 res = nand_do_write_oob(chip,
521 ofs + (page_offset * mtd->writesize),
527 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
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
538 int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
540 if (chip->legacy.block_markbad)
541 return chip->legacy.block_markbad(chip, ofs);
543 return nand_default_block_markbad(chip, ofs);
547 * nand_block_markbad_lowlevel - mark a block bad
548 * @chip: NAND chip object
549 * @ofs: offset from device start
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).
555 * We try operations in the following order:
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)
562 * Note that we retain the first error encountered in (2) or (3), finish the
563 * procedures, and dump the error in the end.
565 static int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
567 struct mtd_info *mtd = nand_to_mtd(chip);
570 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
571 struct erase_info einfo;
573 /* Attempt erase before marking OOB */
574 memset(&einfo, 0, sizeof(einfo));
576 einfo.len = 1ULL << chip->phys_erase_shift;
577 nand_erase_nand(chip, &einfo, 0);
579 /* Write bad block marker to OOB */
580 nand_get_device(chip);
582 ret = nand_markbad_bbm(chip, ofs);
583 nand_release_device(chip);
586 /* Mark block bad in BBT */
588 res = nand_markbad_bbt(chip, ofs);
594 mtd->ecc_stats.badblocks++;
600 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
601 * @mtd: MTD device structure
602 * @ofs: offset from device start
604 * Check if the block is marked as reserved.
606 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
608 struct nand_chip *chip = mtd_to_nand(mtd);
612 /* Return info from the table */
613 return nand_isreserved_bbt(chip, ofs);
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
622 * Check, if the block is bad. Either by reading the bad block table or
623 * calling of the scan function.
625 static int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
627 /* Return info from the table */
629 return nand_isbad_bbt(chip, ofs, allowbbt);
631 return nand_isbad_bbm(chip, ofs);
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
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
643 * This helper is intended to be used when the controller does not have access
644 * to the NAND R/B pin.
646 * Be aware that calling this helper from an ->exec_op() implementation means
647 * ->exec_op() must be re-entrant.
649 * Return 0 if the NAND chip is ready, a negative error otherwise.
651 int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
653 const struct nand_interface_config *conf;
657 if (!nand_has_exec_op(chip))
660 /* Wait tWB before polling the STATUS reg. */
661 conf = nand_get_interface_config(chip);
662 ndelay(NAND_COMMON_TIMING_NS(conf, tWB_max));
664 ret = nand_status_op(chip, NULL);
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
673 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
675 ret = nand_read_data_op(chip, &status, sizeof(status), true,
680 if (status & NAND_STATUS_READY)
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).
689 } while (time_before(jiffies, timeout_ms));
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
696 nand_exit_status_op(chip);
701 return status & NAND_STATUS_READY ? 0 : -ETIMEDOUT;
703 EXPORT_SYMBOL_GPL(nand_soft_waitrdy);
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
711 * Poll the R/B GPIO pin until it becomes ready. If that does not happen
712 * whitin the specified timeout, -ETIMEDOUT is returned.
714 * This helper is intended to be used when the controller has access to the
715 * NAND R/B pin over GPIO.
717 * Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.
719 int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
720 unsigned long timeout_ms)
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.
729 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
731 if (gpiod_get_value_cansleep(gpiod))
735 } while (time_before(jiffies, timeout_ms));
737 return gpiod_get_value_cansleep(gpiod) ? 0 : -ETIMEDOUT;
739 EXPORT_SYMBOL_GPL(nand_gpio_waitrdy);
742 * panic_nand_wait - [GENERIC] wait until the command is done
743 * @chip: NAND chip structure
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.
750 void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
753 for (i = 0; i < timeo; i++) {
754 if (chip->legacy.dev_ready) {
755 if (chip->legacy.dev_ready(chip))
761 ret = nand_read_data_op(chip, &status, sizeof(status),
766 if (status & NAND_STATUS_READY)
773 static bool nand_supports_get_features(struct nand_chip *chip, int addr)
775 return (chip->parameters.supports_set_get_features &&
776 test_bit(addr, chip->parameters.get_feature_list));
779 static bool nand_supports_set_features(struct nand_chip *chip, int addr)
781 return (chip->parameters.supports_set_get_features &&
782 test_bit(addr, chip->parameters.set_feature_list));
786 * nand_reset_interface - Reset data interface and timings
787 * @chip: The NAND chip
788 * @chipnr: Internal die id
790 * Reset the Data interface and timings to ONFI mode 0.
792 * Returns 0 for success or negative error code otherwise.
794 static int nand_reset_interface(struct nand_chip *chip, int chipnr)
796 const struct nand_controller_ops *ops = chip->controller->ops;
799 if (!nand_controller_can_setup_interface(chip))
803 * The ONFI specification says:
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
812 * Configure the data interface in SDR mode and set the
813 * timings to timing mode 0.
816 chip->current_interface_config = nand_get_reset_interface_config();
817 ret = ops->setup_interface(chip, chipnr,
818 chip->current_interface_config);
820 pr_err("Failed to configure data interface to SDR timing mode 0\n");
826 * nand_setup_interface - Setup the best data interface and timings
827 * @chip: The NAND chip
828 * @chipnr: Internal die id
830 * Configure what has been reported to be the best data interface and NAND
831 * timings supported by the chip and the driver.
833 * Returns 0 for success or negative error code otherwise.
835 static int nand_setup_interface(struct nand_chip *chip, int chipnr)
837 const struct nand_controller_ops *ops = chip->controller->ops;
838 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = { }, request;
841 if (!nand_controller_can_setup_interface(chip))
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.
851 if (!chip->best_interface_config)
854 request = chip->best_interface_config->timings.mode;
855 if (nand_interface_is_sdr(chip->best_interface_config))
856 request |= ONFI_DATA_INTERFACE_SDR;
858 request |= ONFI_DATA_INTERFACE_NVDDR;
859 tmode_param[0] = request;
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,
866 nand_deselect_target(chip);
871 /* Change the mode on the controller side */
872 ret = ops->setup_interface(chip, chipnr, chip->best_interface_config);
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;
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,
884 nand_deselect_target(chip);
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]));
898 update_interface_config:
899 chip->current_interface_config = chip->best_interface_config;
905 * Fallback to mode 0 if the chip explicitly did not ack the chosen
908 nand_reset_interface(chip, chipnr);
909 nand_select_target(chip, chipnr);
911 nand_deselect_target(chip);
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
923 * If specific timings are provided, use them. Otherwise, retrieve supported
924 * timing modes from ONFI information.
926 int nand_choose_best_sdr_timings(struct nand_chip *chip,
927 struct nand_interface_config *iface,
928 struct nand_sdr_timings *spec_timings)
930 const struct nand_controller_ops *ops = chip->controller->ops;
931 int best_mode = 0, mode, ret = -EOPNOTSUPP;
933 iface->type = NAND_SDR_IFACE;
936 iface->timings.sdr = *spec_timings;
937 iface->timings.mode = onfi_find_closest_sdr_mode(spec_timings);
939 /* Verify the controller supports the requested interface */
940 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
943 chip->best_interface_config = iface;
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;
953 for (mode = best_mode; mode >= 0; mode--) {
954 onfi_fill_interface_config(chip, iface, NAND_SDR_IFACE, mode);
956 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
959 chip->best_interface_config = iface;
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
974 * If specific timings are provided, use them. Otherwise, retrieve supported
975 * timing modes from ONFI information.
977 int nand_choose_best_nvddr_timings(struct nand_chip *chip,
978 struct nand_interface_config *iface,
979 struct nand_nvddr_timings *spec_timings)
981 const struct nand_controller_ops *ops = chip->controller->ops;
982 int best_mode = 0, mode, ret = -EOPNOTSUPP;
984 iface->type = NAND_NVDDR_IFACE;
987 iface->timings.nvddr = *spec_timings;
988 iface->timings.mode = onfi_find_closest_nvddr_mode(spec_timings);
990 /* Verify the controller supports the requested interface */
991 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
994 chip->best_interface_config = iface;
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;
1004 for (mode = best_mode; mode >= 0; mode--) {
1005 onfi_fill_interface_config(chip, iface, NAND_NVDDR_IFACE, mode);
1007 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
1010 chip->best_interface_config = iface;
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)
1024 * If specific timings are provided, use them. Otherwise, retrieve supported
1025 * timing modes from ONFI information.
1027 static int nand_choose_best_timings(struct nand_chip *chip,
1028 struct nand_interface_config *iface)
1032 /* Try the fastest timings: NV-DDR */
1033 ret = nand_choose_best_nvddr_timings(chip, iface, NULL);
1037 /* Fallback to SDR timings otherwise */
1038 return nand_choose_best_sdr_timings(chip, iface, NULL);
1042 * nand_choose_interface_config - find the best data interface and timings
1043 * @chip: The NAND chip
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
1049 * After this function nand_chip->interface_config is initialized with the best
1050 * timing mode available.
1052 * Returns 0 for success or negative error code otherwise.
1054 static int nand_choose_interface_config(struct nand_chip *chip)
1056 struct nand_interface_config *iface;
1059 if (!nand_controller_can_setup_interface(chip))
1062 iface = kzalloc(sizeof(*iface), GFP_KERNEL);
1066 if (chip->ops.choose_interface_config)
1067 ret = chip->ops.choose_interface_config(chip, iface);
1069 ret = nand_choose_best_timings(chip, iface);
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
1083 * Fills the first or the first two bytes of the @addrs field depending
1084 * on the NAND bus width and the page size.
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.
1089 static int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs,
1090 unsigned int offset_in_page)
1092 struct mtd_info *mtd = nand_to_mtd(chip);
1094 /* Make sure the offset is less than the actual page size. */
1095 if (offset_in_page > mtd->writesize + mtd->oobsize)
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.
1103 if (mtd->writesize <= 512 && offset_in_page >= mtd->writesize)
1104 offset_in_page -= mtd->writesize;
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.
1110 if (chip->options & NAND_BUSWIDTH_16) {
1111 if (WARN_ON(offset_in_page % 2))
1114 offset_in_page /= 2;
1117 addrs[0] = offset_in_page;
1120 * Small page NANDs use 1 cycle for the columns, while large page NANDs
1123 if (mtd->writesize <= 512)
1126 addrs[1] = offset_in_page >> 8;
1131 static int nand_sp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1132 unsigned int offset_in_page, void *buf,
1135 const struct nand_interface_config *conf =
1136 nand_get_interface_config(chip);
1137 struct mtd_info *mtd = nand_to_mtd(chip);
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),
1146 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1149 /* Drop the DATA_IN instruction if len is set to 0. */
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;
1159 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1164 addrs[2] = page >> 8;
1166 if (chip->options & NAND_ROW_ADDR_3) {
1167 addrs[3] = page >> 16;
1168 instrs[1].ctx.addr.naddrs++;
1171 return nand_exec_op(chip, &op);
1174 static int nand_lp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1175 unsigned int offset_in_page, void *buf,
1178 const struct nand_interface_config *conf =
1179 nand_get_interface_config(chip);
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),
1189 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1192 /* Drop the DATA_IN instruction if len is set to 0. */
1196 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1201 addrs[3] = page >> 8;
1203 if (chip->options & NAND_ROW_ADDR_3) {
1204 addrs[4] = page >> 16;
1205 instrs[1].ctx.addr.naddrs++;
1208 return nand_exec_op(chip, &op);
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)
1215 const struct nand_interface_config *conf =
1216 nand_get_interface_config(chip);
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),
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),
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);
1245 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1250 addrs[3] = page >> 8;
1252 if (chip->options & NAND_ROW_ADDR_3) {
1253 addrs[4] = page >> 16;
1254 start_instrs[1].ctx.addr.naddrs++;
1257 /* Check if cache reads are supported */
1259 if (nand_check_op(chip, &start_op) || nand_check_op(chip, &cont_op))
1265 if (page == chip->cont_read.first_page)
1266 return nand_exec_op(chip, &start_op);
1268 return nand_exec_op(chip, &cont_op);
1271 static bool rawnand_cont_read_ongoing(struct nand_chip *chip, unsigned int page)
1273 return chip->cont_read.ongoing &&
1274 page >= chip->cont_read.first_page &&
1275 page <= chip->cont_read.last_page;
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
1286 * This function issues a READ PAGE operation.
1287 * This function does not select/unselect the CS line.
1289 * Returns 0 on success, a negative error code otherwise.
1291 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1292 unsigned int offset_in_page, void *buf, unsigned int len)
1294 struct mtd_info *mtd = nand_to_mtd(chip);
1299 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
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,
1309 return nand_lp_exec_read_page_op(chip, page,
1310 offset_in_page, buf,
1314 return nand_sp_exec_read_page_op(chip, page, offset_in_page,
1318 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, offset_in_page, page);
1320 chip->legacy.read_buf(chip, buf, len);
1324 EXPORT_SYMBOL_GPL(nand_read_page_op);
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
1333 * This function issues a READ PARAMETER PAGE operation.
1334 * This function does not select/unselect the CS line.
1336 * Returns 0 on success, a negative error code otherwise.
1338 int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
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),
1358 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1360 /* Drop the DATA_IN instruction if len is set to 0. */
1364 return nand_exec_op(chip, &op);
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);
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
1382 * This function issues a CHANGE READ COLUMN operation.
1383 * This function does not select/unselect the CS line.
1385 * Returns 0 on success, a negative error code otherwise.
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)
1391 struct mtd_info *mtd = nand_to_mtd(chip);
1396 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1399 /* Small page NANDs do not support column change. */
1400 if (mtd->writesize <= 512)
1403 if (nand_has_exec_op(chip)) {
1404 const struct nand_interface_config *conf =
1405 nand_get_interface_config(chip);
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),
1414 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1417 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1421 /* Drop the DATA_IN instruction if len is set to 0. */
1425 instrs[3].ctx.data.force_8bit = force_8bit;
1427 return nand_exec_op(chip, &op);
1430 chip->legacy.cmdfunc(chip, NAND_CMD_RNDOUT, offset_in_page, -1);
1432 chip->legacy.read_buf(chip, buf, len);
1436 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
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
1446 * This function issues a READ OOB operation.
1447 * This function does not select/unselect the CS line.
1449 * Returns 0 on success, a negative error code otherwise.
1451 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1452 unsigned int offset_in_oob, void *buf, unsigned int len)
1454 struct mtd_info *mtd = nand_to_mtd(chip);
1459 if (offset_in_oob + len > mtd->oobsize)
1462 if (nand_has_exec_op(chip))
1463 return nand_read_page_op(chip, page,
1464 mtd->writesize + offset_in_oob,
1467 chip->legacy.cmdfunc(chip, NAND_CMD_READOOB, offset_in_oob, page);
1469 chip->legacy.read_buf(chip, buf, len);
1473 EXPORT_SYMBOL_GPL(nand_read_oob_op);
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)
1479 const struct nand_interface_config *conf =
1480 nand_get_interface_config(chip);
1481 struct mtd_info *mtd = nand_to_mtd(chip);
1483 struct nand_op_instr instrs[] = {
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.
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),
1497 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1498 int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
1503 addrs[naddrs++] = page;
1504 addrs[naddrs++] = page >> 8;
1505 if (chip->options & NAND_ROW_ADDR_3)
1506 addrs[naddrs++] = page >> 16;
1508 instrs[2].ctx.addr.naddrs = naddrs;
1510 /* Drop the last two instructions if we're not programming the page. */
1513 /* Also drop the DATA_OUT instruction if empty. */
1518 if (mtd->writesize <= 512) {
1520 * Small pages need some more tweaking: we have to adjust the
1521 * first instruction depending on the page offset we're trying
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;
1531 * Drop the first command if we're dealing with a large page
1538 return nand_exec_op(chip, &op);
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
1549 * This function issues the first half of a PROG PAGE operation.
1550 * This function does not select/unselect the CS line.
1552 * Returns 0 on success, a negative error code otherwise.
1554 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1555 unsigned int offset_in_page, const void *buf,
1558 struct mtd_info *mtd = nand_to_mtd(chip);
1563 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1566 if (nand_has_exec_op(chip))
1567 return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1570 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page, page);
1573 chip->legacy.write_buf(chip, buf, len);
1577 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1580 * nand_prog_page_end_op - ends a PROG PAGE operation
1581 * @chip: The NAND chip
1583 * This function issues the second half of a PROG PAGE operation.
1584 * This function does not select/unselect the CS line.
1586 * Returns 0 on success, a negative error code otherwise.
1588 int nand_prog_page_end_op(struct nand_chip *chip)
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),
1602 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1604 ret = nand_exec_op(chip, &op);
1608 ret = nand_status_op(chip, &status);
1612 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1613 ret = chip->legacy.waitfunc(chip);
1620 if (status & NAND_STATUS_FAIL)
1625 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
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
1635 * This function issues a full PROG PAGE operation.
1636 * This function does not select/unselect the CS line.
1638 * Returns 0 on success, a negative error code otherwise.
1640 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1641 unsigned int offset_in_page, const void *buf,
1644 struct mtd_info *mtd = nand_to_mtd(chip);
1651 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1654 if (nand_has_exec_op(chip)) {
1655 ret = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1660 ret = nand_status_op(chip, &status);
1664 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_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);
1675 if (status & NAND_STATUS_FAIL)
1680 EXPORT_SYMBOL_GPL(nand_prog_page_op);
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
1690 * This function issues a CHANGE WRITE COLUMN operation.
1691 * This function does not select/unselect the CS line.
1693 * Returns 0 on success, a negative error code otherwise.
1695 int nand_change_write_column_op(struct nand_chip *chip,
1696 unsigned int offset_in_page,
1697 const void *buf, unsigned int len,
1700 struct mtd_info *mtd = nand_to_mtd(chip);
1705 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1708 /* Small page NANDs do not support column change. */
1709 if (mtd->writesize <= 512)
1712 if (nand_has_exec_op(chip)) {
1713 const struct nand_interface_config *conf =
1714 nand_get_interface_config(chip);
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),
1721 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1724 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1728 instrs[2].ctx.data.force_8bit = force_8bit;
1730 /* Drop the DATA_OUT instruction if len is set to 0. */
1734 return nand_exec_op(chip, &op);
1737 chip->legacy.cmdfunc(chip, NAND_CMD_RNDIN, offset_in_page, -1);
1739 chip->legacy.write_buf(chip, buf, len);
1743 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
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
1752 * This function sends a READID command and reads back the ID returned by the
1754 * This function does not select/unselect the CS line.
1756 * Returns 0 on success, a negative error code otherwise.
1758 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1762 u8 *id = buf, *ddrbuf = NULL;
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),
1776 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
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);
1785 instrs[2].ctx.data.len *= 2;
1786 instrs[2].ctx.data.buf.in = ddrbuf;
1789 /* Drop the DATA_IN instruction if len is set to 0. */
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];
1804 chip->legacy.cmdfunc(chip, NAND_CMD_READID, addr, -1);
1806 for (i = 0; i < len; i++)
1807 id[i] = chip->legacy.read_byte(chip);
1811 EXPORT_SYMBOL_GPL(nand_readid_op);
1814 * nand_status_op - Do a STATUS operation
1815 * @chip: The NAND chip
1816 * @status: out variable to store the NAND status
1818 * This function sends a STATUS command and reads back the status returned by
1820 * This function does not select/unselect the CS line.
1822 * Returns 0 on success, a negative error code otherwise.
1824 int nand_status_op(struct nand_chip *chip, u8 *status)
1826 if (nand_has_exec_op(chip)) {
1827 const struct nand_interface_config *conf =
1828 nand_get_interface_config(chip);
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),
1835 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
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;
1847 ret = nand_exec_op(chip, &op);
1848 if (!ret && status && nand_interface_is_nvddr(conf))
1849 *status = ddrstatus[0];
1854 chip->legacy.cmdfunc(chip, NAND_CMD_STATUS, -1, -1);
1856 *status = chip->legacy.read_byte(chip);
1860 EXPORT_SYMBOL_GPL(nand_status_op);
1863 * nand_exit_status_op - Exit a STATUS operation
1864 * @chip: The NAND chip
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.
1869 * This function does not select/unselect the CS line.
1871 * Returns 0 on success, a negative error code otherwise.
1873 int nand_exit_status_op(struct nand_chip *chip)
1875 if (nand_has_exec_op(chip)) {
1876 struct nand_op_instr instrs[] = {
1877 NAND_OP_CMD(NAND_CMD_READ0, 0),
1879 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1881 return nand_exec_op(chip, &op);
1884 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, -1, -1);
1888 EXPORT_SYMBOL_GPL(nand_exit_status_op);
1891 * nand_erase_op - Do an erase operation
1892 * @chip: The NAND chip
1893 * @eraseblock: block to erase
1895 * This function sends an ERASE command and waits for the NAND to be ready
1897 * This function does not select/unselect the CS line.
1899 * Returns 0 on success, a negative error code otherwise.
1901 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1903 unsigned int page = eraseblock <<
1904 (chip->phys_erase_shift - chip->page_shift);
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),
1920 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1922 if (chip->options & NAND_ROW_ADDR_3)
1923 instrs[1].ctx.addr.naddrs++;
1925 ret = nand_exec_op(chip, &op);
1929 ret = nand_status_op(chip, &status);
1933 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE1, -1, page);
1934 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE2, -1, -1);
1936 ret = chip->legacy.waitfunc(chip);
1943 if (status & NAND_STATUS_FAIL)
1948 EXPORT_SYMBOL_GPL(nand_erase_op);
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
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.
1960 * Returns 0 on success, a negative error code otherwise.
1962 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1965 const u8 *params = data;
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,
1975 NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
1976 NAND_COMMON_TIMING_NS(conf,
1978 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tFEAT_max),
1981 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1983 return nand_exec_op(chip, &op);
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]);
1990 ret = chip->legacy.waitfunc(chip);
1994 if (ret & NAND_STATUS_FAIL)
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
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.
2010 * Returns 0 on success, a negative error code otherwise.
2012 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
2015 u8 *params = data, ddrbuf[ONFI_SUBFEATURE_PARAM_LEN * 2];
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,
2030 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
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;
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];
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);
2055 static int nand_wait_rdy_op(struct nand_chip *chip, unsigned int timeout_ms,
2056 unsigned int delay_ns)
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)),
2063 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2065 return nand_exec_op(chip, &op);
2068 /* Apply delay or wait for ready/busy pin */
2069 if (!chip->legacy.dev_ready)
2070 udelay(chip->legacy.chip_delay);
2072 nand_wait_ready(chip);
2078 * nand_reset_op - Do a reset operation
2079 * @chip: The NAND chip
2081 * This function sends a RESET command and waits for the NAND to be ready
2083 * This function does not select/unselect the CS line.
2085 * Returns 0 on success, a negative error code otherwise.
2087 int nand_reset_op(struct nand_chip *chip)
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),
2098 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2100 return nand_exec_op(chip, &op);
2103 chip->legacy.cmdfunc(chip, NAND_CMD_RESET, -1, -1);
2107 EXPORT_SYMBOL_GPL(nand_reset_op);
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
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.
2122 * Returns 0 on success, a negative error code otherwise.
2124 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
2125 bool force_8bit, bool check_only)
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),
2136 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2140 instrs[0].ctx.data.force_8bit = force_8bit;
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
2149 if (force_8bit && nand_interface_is_nvddr(conf)) {
2150 ddrbuf = kzalloc(len * 2, GFP_KERNEL);
2154 instrs[0].ctx.data.len *= 2;
2155 instrs[0].ctx.data.buf.in = ddrbuf;
2159 ret = nand_check_op(chip, &op);
2164 ret = nand_exec_op(chip, &op);
2165 if (!ret && force_8bit && nand_interface_is_nvddr(conf)) {
2168 for (i = 0; i < len; i++)
2169 dst[i] = ddrbuf[i * 2];
2184 for (i = 0; i < len; i++)
2185 p[i] = chip->legacy.read_byte(chip);
2187 chip->legacy.read_buf(chip, buf, len);
2192 EXPORT_SYMBOL_GPL(nand_read_data_op);
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
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.
2205 * Returns 0 on success, a negative error code otherwise.
2207 int nand_write_data_op(struct nand_chip *chip, const void *buf,
2208 unsigned int len, bool force_8bit)
2213 if (nand_has_exec_op(chip)) {
2214 struct nand_op_instr instrs[] = {
2215 NAND_OP_DATA_OUT(len, buf, 0),
2217 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2219 instrs[0].ctx.data.force_8bit = force_8bit;
2221 return nand_exec_op(chip, &op);
2228 for (i = 0; i < len; i++)
2229 chip->legacy.write_byte(chip, p[i]);
2231 chip->legacy.write_buf(chip, buf, len);
2236 EXPORT_SYMBOL_GPL(nand_write_data_op);
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
2244 * This structure is used by the core to split NAND operations into
2245 * sub-operations that can be handled by the NAND controller.
2247 struct nand_op_parser_ctx {
2248 const struct nand_op_instr *instrs;
2249 unsigned int ninstrs;
2250 struct nand_subop subop;
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.
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.
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).
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)
2278 switch (pat->type) {
2279 case NAND_OP_ADDR_INSTR:
2280 if (!pat->ctx.addr.maxcycles)
2283 if (instr->ctx.addr.naddrs - *start_offset >
2284 pat->ctx.addr.maxcycles) {
2285 *start_offset += pat->ctx.addr.maxcycles;
2290 case NAND_OP_DATA_IN_INSTR:
2291 case NAND_OP_DATA_OUT_INSTR:
2292 if (!pat->ctx.data.maxlen)
2295 if (instr->ctx.data.len - *start_offset >
2296 pat->ctx.data.maxlen) {
2297 *start_offset += pat->ctx.data.maxlen;
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
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.
2321 nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
2322 struct nand_op_parser_ctx *ctx)
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;
2329 for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
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.
2337 if (instr->type != pat->elems[i].type) {
2338 if (!pat->elems[i].optional)
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).
2352 if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
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
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.
2378 for (; i < pat->nelems; i++) {
2379 if (!pat->elems[i].optional)
2384 * We have a match: update the subop structure accordingly and return
2387 ctx->subop.ninstrs = ninstrs;
2388 ctx->subop.last_instr_end_off = instr_offset;
2393 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
2394 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2396 const struct nand_op_instr *instr;
2400 pr_debug("executing subop (CS%d):\n", ctx->subop.cs);
2402 for (i = 0; i < ctx->ninstrs; i++) {
2403 instr = &ctx->instrs[i];
2405 if (instr == &ctx->subop.instrs[0])
2408 nand_op_trace(prefix, instr);
2410 if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
2415 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2421 static int nand_op_parser_cmp_ctx(const struct nand_op_parser_ctx *a,
2422 const struct nand_op_parser_ctx *b)
2424 if (a->subop.ninstrs < b->subop.ninstrs)
2426 else if (a->subop.ninstrs > b->subop.ninstrs)
2429 if (a->subop.last_instr_end_off < b->subop.last_instr_end_off)
2431 else if (a->subop.last_instr_end_off > b->subop.last_instr_end_off)
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
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.
2451 * NAND controller drivers should call this function from their own ->exec_op()
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.
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)
2463 struct nand_op_parser_ctx ctx = {
2465 .subop.instrs = op->instrs,
2466 .instrs = op->instrs,
2467 .ninstrs = op->ninstrs,
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;
2476 for (i = 0; i < parser->npatterns; i++) {
2477 struct nand_op_parser_ctx test_ctx = ctx;
2479 pattern = &parser->patterns[i];
2480 if (!nand_op_parser_match_pat(pattern, &test_ctx))
2483 if (best_pattern >= 0 &&
2484 nand_op_parser_cmp_ctx(&test_ctx, &best_ctx) <= 0)
2488 best_ctx = test_ctx;
2491 if (best_pattern < 0) {
2492 pr_debug("->exec_op() parser: pattern not found!\n");
2497 nand_op_parser_trace(&ctx);
2500 pattern = &parser->patterns[best_pattern];
2501 ret = pattern->exec(chip, &ctx.subop);
2507 * Update the context structure by pointing to the start of the
2510 ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
2511 if (ctx.subop.last_instr_end_off)
2512 ctx.subop.instrs -= 1;
2514 ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
2519 EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
2521 static bool nand_instr_is_data(const struct nand_op_instr *instr)
2523 return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
2524 instr->type == NAND_OP_DATA_OUT_INSTR);
2527 static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
2528 unsigned int instr_idx)
2530 return subop && instr_idx < subop->ninstrs;
2533 static unsigned int nand_subop_get_start_off(const struct nand_subop *subop,
2534 unsigned int instr_idx)
2539 return subop->first_instr_start_off;
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
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.
2551 * Given an address instruction, returns the offset of the first cycle to issue.
2553 unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
2554 unsigned int instr_idx)
2556 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2557 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2560 return nand_subop_get_start_off(subop, instr_idx);
2562 EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
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
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
2573 * Given an address instruction, returns the number of address cycle to issue.
2575 unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
2576 unsigned int instr_idx)
2578 int start_off, end_off;
2580 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2581 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2584 start_off = nand_subop_get_addr_start_off(subop, instr_idx);
2586 if (instr_idx == subop->ninstrs - 1 &&
2587 subop->last_instr_end_off)
2588 end_off = subop->last_instr_end_off;
2590 end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
2592 return end_off - start_off;
2594 EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
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
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.
2605 * Given a data instruction, returns the offset to start from.
2607 unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
2608 unsigned int instr_idx)
2610 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2611 !nand_instr_is_data(&subop->instrs[instr_idx])))
2614 return nand_subop_get_start_off(subop, instr_idx);
2616 EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
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
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
2627 * Returns the length of the chunk of data to send/receive.
2629 unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
2630 unsigned int instr_idx)
2632 int start_off = 0, end_off;
2634 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2635 !nand_instr_is_data(&subop->instrs[instr_idx])))
2638 start_off = nand_subop_get_data_start_off(subop, instr_idx);
2640 if (instr_idx == subop->ninstrs - 1 &&
2641 subop->last_instr_end_off)
2642 end_off = subop->last_instr_end_off;
2644 end_off = subop->instrs[instr_idx].ctx.data.len;
2646 return end_off - start_off;
2648 EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
2651 * nand_reset - Reset and initialize a NAND device
2652 * @chip: The NAND chip
2653 * @chipnr: Internal die id
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.
2659 * Returns 0 on success, a negative error code otherwise.
2661 int nand_reset(struct nand_chip *chip, int chipnr)
2665 ret = nand_reset_interface(chip, chipnr);
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.
2674 nand_select_target(chip, chipnr);
2675 ret = nand_reset_op(chip);
2676 nand_deselect_target(chip);
2680 ret = nand_setup_interface(chip, chipnr);
2686 EXPORT_SYMBOL_GPL(nand_reset);
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
2694 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2695 * operation cannot be handled.
2697 int nand_get_features(struct nand_chip *chip, int addr,
2698 u8 *subfeature_param)
2700 if (!nand_supports_get_features(chip, addr))
2703 if (chip->legacy.get_features)
2704 return chip->legacy.get_features(chip, addr, subfeature_param);
2706 return nand_get_features_op(chip, addr, subfeature_param);
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
2715 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2716 * operation cannot be handled.
2718 int nand_set_features(struct nand_chip *chip, int addr,
2719 u8 *subfeature_param)
2721 if (!nand_supports_set_features(chip, addr))
2724 if (chip->legacy.set_features)
2725 return chip->legacy.set_features(chip, addr, subfeature_param);
2727 return nand_set_features_op(chip, addr, subfeature_param);
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
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.
2745 * Returns a positive number of bitflips less than or equal to
2746 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2749 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
2751 const unsigned char *bitmap = buf;
2755 for (; len && ((uintptr_t)bitmap) % sizeof(long);
2757 weight = hweight8(*bitmap);
2758 bitflips += BITS_PER_BYTE - weight;
2759 if (unlikely(bitflips > bitflips_threshold))
2763 for (; len >= sizeof(long);
2764 len -= sizeof(long), bitmap += sizeof(long)) {
2765 unsigned long d = *((unsigned long *)bitmap);
2768 weight = hweight_long(d);
2769 bitflips += BITS_PER_LONG - weight;
2770 if (unlikely(bitflips > bitflips_threshold))
2774 for (; len > 0; len--, bitmap++) {
2775 weight = hweight8(*bitmap);
2776 bitflips += BITS_PER_BYTE - weight;
2777 if (unlikely(bitflips > bitflips_threshold))
2785 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
2787 * @data: data buffer to test
2788 * @datalen: data length
2790 * @ecclen: ECC length
2791 * @extraoob: extra OOB buffer
2792 * @extraooblen: extra OOB length
2793 * @bitflips_threshold: maximum number of bitflips
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.
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
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.
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.
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)
2828 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
2830 data_bitflips = nand_check_erased_buf(data, datalen,
2831 bitflips_threshold);
2832 if (data_bitflips < 0)
2833 return data_bitflips;
2835 bitflips_threshold -= data_bitflips;
2837 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
2838 if (ecc_bitflips < 0)
2839 return ecc_bitflips;
2841 bitflips_threshold -= ecc_bitflips;
2843 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
2844 bitflips_threshold);
2845 if (extraoob_bitflips < 0)
2846 return extraoob_bitflips;
2849 memset(data, 0xff, datalen);
2852 memset(ecc, 0xff, ecclen);
2854 if (extraoob_bitflips)
2855 memset(extraoob, 0xff, extraooblen);
2857 return data_bitflips + ecc_bitflips + extraoob_bitflips;
2859 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
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
2868 * Returns -ENOTSUPP unconditionally.
2870 int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf,
2871 int oob_required, int page)
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
2883 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2885 int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
2888 struct mtd_info *mtd = nand_to_mtd(chip);
2891 ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
2896 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
2904 EXPORT_SYMBOL(nand_read_page_raw);
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
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.
2921 int nand_monolithic_read_page_raw(struct nand_chip *chip, u8 *buf,
2922 int oob_required, int page)
2924 struct mtd_info *mtd = nand_to_mtd(chip);
2925 unsigned int size = mtd->writesize;
2930 size += mtd->oobsize;
2932 if (buf != chip->data_buf)
2933 read_buf = nand_get_data_buf(chip);
2936 ret = nand_read_page_op(chip, page, 0, read_buf, size);
2940 if (buf != chip->data_buf)
2941 memcpy(buf, read_buf, mtd->writesize);
2945 EXPORT_SYMBOL(nand_monolithic_read_page_raw);
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
2954 * We need a special oob layout and handling even when OOB isn't used.
2956 static int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf,
2957 int oob_required, int page)
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;
2965 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2969 for (steps = chip->ecc.steps; steps > 0; steps--) {
2970 ret = nand_read_data_op(chip, buf, eccsize, false, false);
2976 if (chip->ecc.prepad) {
2977 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2982 oob += chip->ecc.prepad;
2985 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
2991 if (chip->ecc.postpad) {
2992 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2997 oob += chip->ecc.postpad;
3001 size = mtd->oobsize - (oob - chip->oob_poi);
3003 ret = nand_read_data_op(chip, oob, size, false, false);
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
3018 static int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf,
3019 int oob_required, int page)
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;
3026 uint8_t *ecc_calc = chip->ecc.calc_buf;
3027 uint8_t *ecc_code = chip->ecc.code_buf;
3028 unsigned int max_bitflips = 0;
3030 chip->ecc.read_page_raw(chip, buf, 1, page);
3032 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
3033 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3035 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3040 eccsteps = chip->ecc.steps;
3043 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3046 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
3048 mtd->ecc_stats.failed++;
3050 mtd->ecc_stats.corrected += stat;
3051 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3054 return max_bitflips;
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
3065 static int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs,
3066 uint32_t readlen, uint8_t *bufpoi, int page)
3068 struct mtd_info *mtd = nand_to_mtd(chip);
3069 int start_step, end_step, num_steps, ret;
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 = { };
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;
3084 /* Data size aligned to ECC ecc.size */
3085 datafrag_len = num_steps * chip->ecc.size;
3086 eccfrag_len = num_steps * chip->ecc.bytes;
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);
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]);
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.
3103 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
3107 if (oobregion.length < eccfrag_len)
3111 ret = nand_change_read_column_op(chip, mtd->writesize,
3112 chip->oob_poi, mtd->oobsize,
3118 * Send the command to read the particular ECC bytes take care
3119 * about buswidth alignment in read_buf.
3121 aligned_pos = oobregion.offset & ~(busw - 1);
3122 aligned_len = eccfrag_len;
3123 if (oobregion.offset & (busw - 1))
3125 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
3129 ret = nand_change_read_column_op(chip,
3130 mtd->writesize + aligned_pos,
3131 &chip->oob_poi[aligned_pos],
3132 aligned_len, false);
3137 ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
3138 chip->oob_poi, index, eccfrag_len);
3142 p = bufpoi + data_col_addr;
3143 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
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],
3155 chip->ecc.strength);
3159 mtd->ecc_stats.failed++;
3161 mtd->ecc_stats.corrected += stat;
3162 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3165 return max_bitflips;
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
3175 * Not for syndrome calculating ECC controllers which need a special oob layout.
3177 static int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf,
3178 int oob_required, int page)
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;
3185 uint8_t *ecc_calc = chip->ecc.calc_buf;
3186 uint8_t *ecc_code = chip->ecc.code_buf;
3187 unsigned int max_bitflips = 0;
3189 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3193 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3194 chip->ecc.hwctl(chip, NAND_ECC_READ);
3196 ret = nand_read_data_op(chip, p, eccsize, false, false);
3200 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3203 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false,
3208 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3213 eccsteps = chip->ecc.steps;
3216 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
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,
3226 chip->ecc.strength);
3230 mtd->ecc_stats.failed++;
3232 mtd->ecc_stats.corrected += stat;
3233 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3236 return max_bitflips;
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
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.
3250 int nand_read_page_hwecc_oob_first(struct nand_chip *chip, uint8_t *buf,
3251 int oob_required, int page)
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;
3258 uint8_t *ecc_code = chip->ecc.code_buf;
3259 unsigned int max_bitflips = 0;
3261 /* Read the OOB area first */
3262 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3266 /* Move read cursor to start of page */
3267 ret = nand_change_read_column_op(chip, 0, NULL, 0, false);
3271 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3276 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3279 chip->ecc.hwctl(chip, NAND_ECC_READ);
3281 ret = nand_read_data_op(chip, p, eccsize, false, false);
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,
3292 chip->ecc.strength);
3296 mtd->ecc_stats.failed++;
3298 mtd->ecc_stats.corrected += stat;
3299 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3302 return max_bitflips;
3304 EXPORT_SYMBOL_GPL(nand_read_page_hwecc_oob_first);
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
3313 * The hw generator calculates the error syndrome automatically. Therefore we
3314 * need a special oob layout and handling.
3316 static int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf,
3317 int oob_required, int page)
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;
3325 uint8_t *oob = chip->oob_poi;
3326 unsigned int max_bitflips = 0;
3328 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3332 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3335 chip->ecc.hwctl(chip, NAND_ECC_READ);
3337 ret = nand_read_data_op(chip, p, eccsize, false, false);
3341 if (chip->ecc.prepad) {
3342 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3347 oob += chip->ecc.prepad;
3350 chip->ecc.hwctl(chip, NAND_ECC_READSYN);
3352 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
3356 stat = chip->ecc.correct(chip, p, oob, NULL);
3360 if (chip->ecc.postpad) {
3361 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3366 oob += chip->ecc.postpad;
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,
3376 chip->ecc.strength);
3380 mtd->ecc_stats.failed++;
3382 mtd->ecc_stats.corrected += stat;
3383 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3387 /* Calculate remaining oob bytes */
3388 i = mtd->oobsize - (oob - chip->oob_poi);
3390 ret = nand_read_data_op(chip, oob, i, false, false);
3395 return max_bitflips;
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
3405 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
3406 struct mtd_oob_ops *ops, size_t len)
3408 struct mtd_info *mtd = nand_to_mtd(chip);
3411 switch (ops->mode) {
3413 case MTD_OPS_PLACE_OOB:
3415 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
3418 case MTD_OPS_AUTO_OOB:
3419 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
3430 static void rawnand_enable_cont_reads(struct nand_chip *chip, unsigned int page,
3431 u32 readlen, int col)
3433 struct mtd_info *mtd = nand_to_mtd(chip);
3435 if (!chip->controller->supported_op.cont_read)
3438 if ((col && col + readlen < (3 * mtd->writesize)) ||
3439 (!col && readlen < (2 * mtd->writesize))) {
3440 chip->cont_read.ongoing = false;
3444 chip->cont_read.ongoing = true;
3445 chip->cont_read.first_page = page;
3447 chip->cont_read.first_page++;
3448 chip->cont_read.last_page = page + ((readlen >> chip->page_shift) & chip->pagemask);
3452 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
3453 * @chip: NAND chip object
3454 * @retry_mode: the retry mode to use
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.
3460 static int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
3462 pr_debug("setting READ RETRY mode %d\n", retry_mode);
3464 if (retry_mode >= chip->read_retries)
3467 if (!chip->ops.setup_read_retry)
3470 return chip->ops.setup_read_retry(chip, retry_mode);
3473 static void nand_wait_readrdy(struct nand_chip *chip)
3475 const struct nand_interface_config *conf;
3477 if (!(chip->options & NAND_NEED_READRDY))
3480 conf = nand_get_interface_config(chip);
3481 WARN_ON(nand_wait_rdy_op(chip, NAND_COMMON_TIMING_MS(conf, tR_max), 0));
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
3490 * Internal function. Called with chip held.
3492 static int nand_do_read_ops(struct nand_chip *chip, loff_t from,
3493 struct mtd_oob_ops *ops)
3495 int chipnr, page, realpage, col, bytes, aligned, oob_required;
3496 struct mtd_info *mtd = nand_to_mtd(chip);
3498 uint32_t readlen = ops->len;
3499 uint32_t oobreadlen = ops->ooblen;
3500 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
3502 uint8_t *bufpoi, *oob, *buf;
3504 unsigned int max_bitflips = 0;
3506 bool ecc_fail = false;
3508 /* Check if the region is secured */
3509 if (nand_region_is_secured(chip, from, readlen))
3512 chipnr = (int)(from >> chip->chip_shift);
3513 nand_select_target(chip, chipnr);
3515 realpage = (int)(from >> chip->page_shift);
3516 page = realpage & chip->pagemask;
3518 col = (int)(from & (mtd->writesize - 1));
3522 oob_required = oob ? 1 : 0;
3524 rawnand_enable_cont_reads(chip, page, readlen, col);
3527 struct mtd_ecc_stats ecc_stats = mtd->ecc_stats;
3529 bytes = min(mtd->writesize - col, readlen);
3530 aligned = (bytes == mtd->writesize);
3534 else if (chip->options & NAND_USES_DMA)
3535 use_bounce_buf = !virt_addr_valid(buf) ||
3536 !IS_ALIGNED((unsigned long)buf,
3541 /* Is the current page in the buffer? */
3542 if (realpage != chip->pagecache.page || oob) {
3543 bufpoi = use_bounce_buf ? chip->data_buf : buf;
3545 if (use_bounce_buf && aligned)
3546 pr_debug("%s: using read bounce buffer for buf@%p\n",
3551 * Now read the page into the buffer. Absent an error,
3552 * the read methods return max bitflips per ecc step.
3554 if (unlikely(ops->mode == MTD_OPS_RAW))
3555 ret = chip->ecc.read_page_raw(chip, bufpoi,
3558 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
3560 ret = chip->ecc.read_subpage(chip, col, bytes,
3563 ret = chip->ecc.read_page(chip, bufpoi,
3564 oob_required, page);
3567 /* Invalidate page cache */
3568 chip->pagecache.page = -1;
3573 * Copy back the data in the initial buffer when reading
3574 * partial pages or when a bounce buffer is required.
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;
3583 /* Invalidate page cache */
3584 chip->pagecache.page = -1;
3586 memcpy(buf, bufpoi + col, bytes);
3589 if (unlikely(oob)) {
3590 int toread = min(oobreadlen, max_oobsize);
3593 oob = nand_transfer_oob(chip, oob, ops,
3595 oobreadlen -= toread;
3599 nand_wait_readrdy(chip);
3601 if (mtd->ecc_stats.failed - ecc_stats.failed) {
3602 if (retry_mode + 1 < chip->read_retries) {
3604 ret = nand_setup_read_retry(chip,
3609 /* Reset ecc_stats; retry */
3610 mtd->ecc_stats = ecc_stats;
3613 /* No more retry modes; real failure */
3619 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3621 memcpy(buf, chip->data_buf + col, bytes);
3623 max_bitflips = max_t(unsigned int, max_bitflips,
3624 chip->pagecache.bitflips);
3629 /* Reset to retry mode 0 */
3631 ret = nand_setup_read_retry(chip, 0);
3640 /* For subsequent reads align to page boundary */
3642 /* Increment page address */
3645 page = realpage & chip->pagemask;
3646 /* Check, if we cross a chip boundary */
3649 nand_deselect_target(chip);
3650 nand_select_target(chip, chipnr);
3653 nand_deselect_target(chip);
3655 ops->retlen = ops->len - (size_t) readlen;
3657 ops->oobretlen = ops->ooblen - oobreadlen;
3665 return max_bitflips;
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
3673 int nand_read_oob_std(struct nand_chip *chip, int page)
3675 struct mtd_info *mtd = nand_to_mtd(chip);
3677 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3679 EXPORT_SYMBOL(nand_read_oob_std);
3682 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
3684 * @chip: nand chip info structure
3685 * @page: page number to read
3687 static int nand_read_oob_syndrome(struct nand_chip *chip, int page)
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;
3696 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
3700 for (i = 0; i < chip->ecc.steps; i++) {
3704 pos = eccsize + i * (eccsize + chunk);
3705 if (mtd->writesize > 512)
3706 ret = nand_change_read_column_op(chip, pos,
3710 ret = nand_read_page_op(chip, page, pos, NULL,
3717 toread = min_t(int, length, chunk);
3719 ret = nand_read_data_op(chip, bufpoi, toread, false, false);
3727 ret = nand_read_data_op(chip, bufpoi, length, false, false);
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
3740 int nand_write_oob_std(struct nand_chip *chip, int page)
3742 struct mtd_info *mtd = nand_to_mtd(chip);
3744 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
3747 EXPORT_SYMBOL(nand_write_oob_std);
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
3755 static int nand_write_oob_syndrome(struct nand_chip *chip, int page)
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;
3764 * data-ecc-data-ecc ... ecc-oob
3766 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
3768 if (!chip->ecc.prepad && !chip->ecc.postpad) {
3769 pos = steps * (eccsize + chunk);
3774 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
3778 for (i = 0; i < steps; i++) {
3780 if (mtd->writesize <= 512) {
3781 uint32_t fill = 0xFFFFFFFF;
3785 int num = min_t(int, len, 4);
3787 ret = nand_write_data_op(chip, &fill,
3795 pos = eccsize + i * (eccsize + chunk);
3796 ret = nand_change_write_column_op(chip, pos,
3804 len = min_t(int, length, chunk);
3806 ret = nand_write_data_op(chip, bufpoi, len, false);
3814 ret = nand_write_data_op(chip, bufpoi, length, false);
3819 return nand_prog_page_end_op(chip);
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
3828 * NAND read out-of-band data from the spare area.
3830 static int nand_do_read_oob(struct nand_chip *chip, loff_t from,
3831 struct mtd_oob_ops *ops)
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;
3839 uint8_t *buf = ops->oobbuf;
3842 pr_debug("%s: from = 0x%08Lx, len = %i\n",
3843 __func__, (unsigned long long)from, readlen);
3845 /* Check if the region is secured */
3846 if (nand_region_is_secured(chip, from, readlen))
3849 stats = mtd->ecc_stats;
3851 len = mtd_oobavail(mtd, ops);
3853 chipnr = (int)(from >> chip->chip_shift);
3854 nand_select_target(chip, chipnr);
3856 /* Shift to get page */
3857 realpage = (int)(from >> chip->page_shift);
3858 page = realpage & chip->pagemask;
3861 if (ops->mode == MTD_OPS_RAW)
3862 ret = chip->ecc.read_oob_raw(chip, page);
3864 ret = chip->ecc.read_oob(chip, page);
3869 len = min(len, readlen);
3870 buf = nand_transfer_oob(chip, buf, ops, len);
3872 nand_wait_readrdy(chip);
3874 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3880 /* Increment page address */
3883 page = realpage & chip->pagemask;
3884 /* Check, if we cross a chip boundary */
3887 nand_deselect_target(chip);
3888 nand_select_target(chip, chipnr);
3891 nand_deselect_target(chip);
3893 ops->oobretlen = ops->ooblen - readlen;
3898 if (mtd->ecc_stats.failed - stats.failed)
3901 return max_bitflips;
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
3910 * NAND read data and/or out-of-band data.
3912 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
3913 struct mtd_oob_ops *ops)
3915 struct nand_chip *chip = mtd_to_nand(mtd);
3916 struct mtd_ecc_stats old_stats;
3921 if (ops->mode != MTD_OPS_PLACE_OOB &&
3922 ops->mode != MTD_OPS_AUTO_OOB &&
3923 ops->mode != MTD_OPS_RAW)
3926 nand_get_device(chip);
3928 old_stats = mtd->ecc_stats;
3931 ret = nand_do_read_oob(chip, from, ops);
3933 ret = nand_do_read_ops(chip, from, ops);
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;
3942 nand_release_device(chip);
3947 * nand_write_page_raw_notsupp - dummy raw page write function
3948 * @chip: nand chip info structure
3950 * @oob_required: must write chip->oob_poi to OOB
3951 * @page: page number to write
3953 * Returns -ENOTSUPP unconditionally.
3955 int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf,
3956 int oob_required, int page)
3962 * nand_write_page_raw - [INTERN] raw page write function
3963 * @chip: nand chip info structure
3965 * @oob_required: must write chip->oob_poi to OOB
3966 * @page: page number to write
3968 * Not for syndrome calculating ECC controllers, which use a special oob layout.
3970 int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
3971 int oob_required, int page)
3973 struct mtd_info *mtd = nand_to_mtd(chip);
3976 ret = nand_prog_page_begin_op(chip, page, 0, buf, mtd->writesize);
3981 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
3987 return nand_prog_page_end_op(chip);
3989 EXPORT_SYMBOL(nand_write_page_raw);
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
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.
4007 int nand_monolithic_write_page_raw(struct nand_chip *chip, const u8 *buf,
4008 int oob_required, int page)
4010 struct mtd_info *mtd = nand_to_mtd(chip);
4011 unsigned int size = mtd->writesize;
4012 u8 *write_buf = (u8 *)buf;
4015 size += mtd->oobsize;
4017 if (buf != chip->data_buf) {
4018 write_buf = nand_get_data_buf(chip);
4019 memcpy(write_buf, buf, mtd->writesize);
4023 return nand_prog_page_op(chip, page, 0, write_buf, size);
4025 EXPORT_SYMBOL(nand_monolithic_write_page_raw);
4028 * nand_write_page_raw_syndrome - [INTERN] raw page write function
4029 * @chip: nand chip info structure
4031 * @oob_required: must write chip->oob_poi to OOB
4032 * @page: page number to write
4034 * We need a special oob layout and handling even when ECC isn't checked.
4036 static int nand_write_page_raw_syndrome(struct nand_chip *chip,
4037 const uint8_t *buf, int oob_required,
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;
4046 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4050 for (steps = chip->ecc.steps; steps > 0; steps--) {
4051 ret = nand_write_data_op(chip, buf, eccsize, false);
4057 if (chip->ecc.prepad) {
4058 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4063 oob += chip->ecc.prepad;
4066 ret = nand_write_data_op(chip, oob, eccbytes, false);
4072 if (chip->ecc.postpad) {
4073 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4078 oob += chip->ecc.postpad;
4082 size = mtd->oobsize - (oob - chip->oob_poi);
4084 ret = nand_write_data_op(chip, oob, size, false);
4089 return nand_prog_page_end_op(chip);
4092 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
4093 * @chip: nand chip info structure
4095 * @oob_required: must write chip->oob_poi to OOB
4096 * @page: page number to write
4098 static int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf,
4099 int oob_required, int page)
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;
4108 /* Software ECC calculation */
4109 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
4110 chip->ecc.calculate(chip, p, &ecc_calc[i]);
4112 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4117 return chip->ecc.write_page_raw(chip, buf, 1, page);
4121 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
4122 * @chip: nand chip info structure
4124 * @oob_required: must write chip->oob_poi to OOB
4125 * @page: page number to write
4127 static int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf,
4128 int oob_required, int page)
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;
4137 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4141 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4142 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4144 ret = nand_write_data_op(chip, p, eccsize, false);
4148 chip->ecc.calculate(chip, p, &ecc_calc[i]);
4151 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4156 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
4160 return nand_prog_page_end_op(chip);
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
4170 * @oob_required: must write chip->oob_poi to OOB
4171 * @page: page number to write
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)
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;
4188 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4192 for (step = 0; step < ecc_steps; step++) {
4193 /* configure controller for WRITE access */
4194 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4196 /* write data (untouched subpages already masked by 0xFF) */
4197 ret = nand_write_data_op(chip, buf, ecc_size, false);
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);
4205 chip->ecc.calculate(chip, buf, ecc_calc);
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);
4213 ecc_calc += ecc_bytes;
4214 oob_buf += oob_bytes;
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,
4225 /* write OOB buffer to NAND device */
4226 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
4230 return nand_prog_page_end_op(chip);
4235 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
4236 * @chip: nand chip info structure
4238 * @oob_required: must write chip->oob_poi to OOB
4239 * @page: page number to write
4241 * The hw generator calculates the error syndrome automatically. Therefore we
4242 * need a special oob layout and handling.
4244 static int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf,
4245 int oob_required, int page)
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;
4255 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4259 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4260 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4262 ret = nand_write_data_op(chip, p, eccsize, false);
4266 if (chip->ecc.prepad) {
4267 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4272 oob += chip->ecc.prepad;
4275 chip->ecc.calculate(chip, p, oob);
4277 ret = nand_write_data_op(chip, oob, eccbytes, false);
4283 if (chip->ecc.postpad) {
4284 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4289 oob += chip->ecc.postpad;
4293 /* Calculate remaining oob bytes */
4294 i = mtd->oobsize - (oob - chip->oob_poi);
4296 ret = nand_write_data_op(chip, oob, i, false);
4301 return nand_prog_page_end_op(chip);
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
4314 static int nand_write_page(struct nand_chip *chip, uint32_t offset,
4315 int data_len, const uint8_t *buf, int oob_required,
4318 struct mtd_info *mtd = nand_to_mtd(chip);
4319 int status, subpage;
4321 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
4322 chip->ecc.write_subpage)
4323 subpage = offset || (data_len < mtd->writesize);
4328 status = chip->ecc.write_page_raw(chip, buf, oob_required,
4331 status = chip->ecc.write_subpage(chip, offset, data_len, buf,
4332 oob_required, page);
4334 status = chip->ecc.write_page(chip, buf, oob_required, page);
4342 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
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
4350 * NAND write with ECC.
4352 static int nand_do_write_ops(struct nand_chip *chip, loff_t to,
4353 struct mtd_oob_ops *ops)
4355 struct mtd_info *mtd = nand_to_mtd(chip);
4356 int chipnr, realpage, page, column;
4357 uint32_t writelen = ops->len;
4359 uint32_t oobwritelen = ops->ooblen;
4360 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
4362 uint8_t *oob = ops->oobbuf;
4363 uint8_t *buf = ops->datbuf;
4365 int oob_required = oob ? 1 : 0;
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",
4378 /* Check if the region is secured */
4379 if (nand_region_is_secured(chip, to, writelen))
4382 column = to & (mtd->writesize - 1);
4384 chipnr = (int)(to >> chip->chip_shift);
4385 nand_select_target(chip, chipnr);
4387 /* Check, if it is write protected */
4388 if (nand_check_wp(chip)) {
4393 realpage = (int)(to >> chip->page_shift);
4394 page = realpage & chip->pagemask;
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;
4401 /* Don't allow multipage oob writes with offset */
4402 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
4408 int bytes = mtd->writesize;
4409 uint8_t *wbuf = buf;
4411 int part_pagewr = (column || writelen < mtd->writesize);
4415 else if (chip->options & NAND_USES_DMA)
4416 use_bounce_buf = !virt_addr_valid(buf) ||
4417 !IS_ALIGNED((unsigned long)buf,
4423 * Copy the data from the initial buffer when doing partial page
4424 * writes or when a bounce buffer is required.
4426 if (use_bounce_buf) {
4427 pr_debug("%s: using write bounce buffer for buf@%p\n",
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);
4436 if (unlikely(oob)) {
4437 size_t len = min(oobwritelen, oobmaxlen);
4438 oob = nand_fill_oob(chip, oob, len, ops);
4441 /* We still need to erase leftover OOB data */
4442 memset(chip->oob_poi, 0xff, mtd->oobsize);
4445 ret = nand_write_page(chip, column, bytes, wbuf,
4447 (ops->mode == MTD_OPS_RAW));
4459 page = realpage & chip->pagemask;
4460 /* Check, if we cross a chip boundary */
4463 nand_deselect_target(chip);
4464 nand_select_target(chip, chipnr);
4468 ops->retlen = ops->len - writelen;
4470 ops->oobretlen = ops->ooblen;
4473 nand_deselect_target(chip);
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
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.
4488 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
4489 size_t *retlen, const uint8_t *buf)
4491 struct nand_chip *chip = mtd_to_nand(mtd);
4492 int chipnr = (int)(to >> chip->chip_shift);
4493 struct mtd_oob_ops ops;
4496 nand_select_target(chip, chipnr);
4498 /* Wait for the device to get ready */
4499 panic_nand_wait(chip, 400);
4501 memset(&ops, 0, sizeof(ops));
4503 ops.datbuf = (uint8_t *)buf;
4504 ops.mode = MTD_OPS_PLACE_OOB;
4506 ret = nand_do_write_ops(chip, to, &ops);
4508 *retlen = ops.retlen;
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
4518 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
4519 struct mtd_oob_ops *ops)
4521 struct nand_chip *chip = mtd_to_nand(mtd);
4526 nand_get_device(chip);
4528 switch (ops->mode) {
4529 case MTD_OPS_PLACE_OOB:
4530 case MTD_OPS_AUTO_OOB:
4539 ret = nand_do_write_oob(chip, to, ops);
4541 ret = nand_do_write_ops(chip, to, ops);
4544 nand_release_device(chip);
4549 * nand_erase - [MTD Interface] erase block(s)
4550 * @mtd: MTD device structure
4551 * @instr: erase instruction
4553 * Erase one ore more blocks.
4555 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
4557 return nand_erase_nand(mtd_to_nand(mtd), instr, 0);
4561 * nand_erase_nand - [INTERN] erase block(s)
4562 * @chip: NAND chip object
4563 * @instr: erase instruction
4564 * @allowbbt: allow erasing the bbt area
4566 * Erase one ore more blocks.
4568 int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr,
4571 int page, pages_per_block, ret, chipnr;
4574 pr_debug("%s: start = 0x%012llx, len = %llu\n",
4575 __func__, (unsigned long long)instr->addr,
4576 (unsigned long long)instr->len);
4578 if (check_offs_len(chip, instr->addr, instr->len))
4581 /* Check if the region is secured */
4582 if (nand_region_is_secured(chip, instr->addr, instr->len))
4585 /* Grab the lock and see if the device is available */
4586 nand_get_device(chip);
4588 /* Shift to get first page */
4589 page = (int)(instr->addr >> chip->page_shift);
4590 chipnr = (int)(instr->addr >> chip->chip_shift);
4592 /* Calculate pages in each block */
4593 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
4595 /* Select the NAND device */
4596 nand_select_target(chip, chipnr);
4598 /* Check, if it is write protected */
4599 if (nand_check_wp(chip)) {
4600 pr_debug("%s: device is write protected!\n",
4606 /* Loop through the pages */
4610 loff_t ofs = (loff_t)page << chip->page_shift;
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);
4622 * Invalidate the page cache, if we erase the block which
4623 * contains the current cached page.
4625 if (page <= chip->pagecache.page && chip->pagecache.page <
4626 (page + pages_per_block))
4627 chip->pagecache.page = -1;
4629 ret = nand_erase_op(chip, (page & chip->pagemask) >>
4630 (chip->phys_erase_shift - chip->page_shift));
4632 pr_debug("%s: failed erase, page 0x%08x\n",
4634 instr->fail_addr = ofs;
4638 /* Increment page address and decrement length */
4639 len -= (1ULL << chip->phys_erase_shift);
4640 page += pages_per_block;
4642 /* Check, if we cross a chip boundary */
4643 if (len && !(page & chip->pagemask)) {
4645 nand_deselect_target(chip);
4646 nand_select_target(chip, chipnr);
4653 /* Deselect and wake up anyone waiting on the device */
4654 nand_deselect_target(chip);
4655 nand_release_device(chip);
4657 /* Return more or less happy */
4662 * nand_sync - [MTD Interface] sync
4663 * @mtd: MTD device structure
4665 * Sync is actually a wait for chip ready function.
4667 static void nand_sync(struct mtd_info *mtd)
4669 struct nand_chip *chip = mtd_to_nand(mtd);
4671 pr_debug("%s: called\n", __func__);
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);
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
4684 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
4686 struct nand_chip *chip = mtd_to_nand(mtd);
4687 int chipnr = (int)(offs >> chip->chip_shift);
4690 /* Select the NAND device */
4691 nand_get_device(chip);
4693 nand_select_target(chip, chipnr);
4695 ret = nand_block_checkbad(chip, offs, 0);
4697 nand_deselect_target(chip);
4698 nand_release_device(chip);
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
4708 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
4712 ret = nand_block_isbad(mtd, ofs);
4714 /* If it was bad already, return success and do nothing */
4720 return nand_block_markbad_lowlevel(mtd_to_nand(mtd), ofs);
4724 * nand_suspend - [MTD Interface] Suspend the NAND flash
4725 * @mtd: MTD device structure
4727 * Returns 0 for success or negative error code otherwise.
4729 static int nand_suspend(struct mtd_info *mtd)
4731 struct nand_chip *chip = mtd_to_nand(mtd);
4734 mutex_lock(&chip->lock);
4735 if (chip->ops.suspend)
4736 ret = chip->ops.suspend(chip);
4738 chip->suspended = 1;
4739 mutex_unlock(&chip->lock);
4745 * nand_resume - [MTD Interface] Resume the NAND flash
4746 * @mtd: MTD device structure
4748 static void nand_resume(struct mtd_info *mtd)
4750 struct nand_chip *chip = mtd_to_nand(mtd);
4752 mutex_lock(&chip->lock);
4753 if (chip->suspended) {
4754 if (chip->ops.resume)
4755 chip->ops.resume(chip);
4756 chip->suspended = 0;
4758 pr_err("%s called for a chip which is not in suspended state\n",
4761 mutex_unlock(&chip->lock);
4763 wake_up_all(&chip->resume_wq);
4767 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
4768 * prevent further operations
4769 * @mtd: MTD device structure
4771 static void nand_shutdown(struct mtd_info *mtd)
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)
4782 static int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4784 struct nand_chip *chip = mtd_to_nand(mtd);
4786 if (!chip->ops.lock_area)
4789 return chip->ops.lock_area(chip, ofs, len);
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)
4798 static int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4800 struct nand_chip *chip = mtd_to_nand(mtd);
4802 if (!chip->ops.unlock_area)
4805 return chip->ops.unlock_area(chip, ofs, len);
4808 /* Set default functions */
4809 static void nand_set_defaults(struct nand_chip *chip)
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);
4817 nand_legacy_set_defaults(chip);
4819 if (!chip->buf_align)
4820 chip->buf_align = 1;
4823 /* Sanitize ONFI strings so we can safely print them */
4824 void sanitize_string(uint8_t *s, size_t len)
4828 /* Null terminate */
4831 /* Remove non printable chars */
4832 for (i = 0; i < len - 1; i++) {
4833 if (s[i] < ' ' || s[i] > 127)
4837 /* Remove trailing spaces */
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
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.
4852 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4855 for (i = 0; i < period; i++)
4856 for (j = i + period; j < arrlen; j += period)
4857 if (id_data[i] != id_data[j])
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
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.
4870 static int nand_id_len(u8 *id_data, int arrlen)
4872 int last_nonzero, period;
4874 /* Find last non-zero byte */
4875 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4876 if (id_data[last_nonzero])
4880 if (last_nonzero < 0)
4883 /* Calculate wraparound period */
4884 for (period = 1; period < arrlen; period++)
4885 if (nand_id_has_period(id_data, arrlen, period))
4888 /* There's a repeated pattern */
4889 if (period < arrlen)
4892 /* There are trailing zeros */
4893 if (last_nonzero < arrlen - 1)
4894 return last_nonzero + 1;
4896 /* No pattern detected */
4900 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4901 static int nand_get_bits_per_cell(u8 cellinfo)
4905 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4906 bits >>= NAND_CI_CELLTYPE_SHIFT;
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.
4915 void nand_decode_ext_id(struct nand_chip *chip)
4917 struct nand_memory_organization *memorg;
4918 struct mtd_info *mtd = nand_to_mtd(chip);
4920 u8 *id_data = chip->id.data;
4922 memorg = nanddev_get_memorg(&chip->base);
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 */
4930 memorg->pagesize = 1024 << (extid & 0x03);
4931 mtd->writesize = memorg->pagesize;
4934 memorg->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
4935 mtd->oobsize = memorg->oobsize;
4937 /* Calc blocksize. Blocksize is multiples of 64KiB */
4938 memorg->pages_per_eraseblock = ((64 * 1024) << (extid & 0x03)) /
4940 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4942 /* Get buswidth information */
4944 chip->options |= NAND_BUSWIDTH_16;
4946 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
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
4953 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
4955 struct mtd_info *mtd = nand_to_mtd(chip);
4956 struct nand_memory_organization *memorg;
4958 memorg = nanddev_get_memorg(&chip->base);
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;
4967 /* All legacy ID NAND are small-page, SLC */
4968 memorg->bits_per_cell = 1;
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).
4976 static void nand_decode_bbm_options(struct nand_chip *chip)
4978 struct mtd_info *mtd = nand_to_mtd(chip);
4980 /* Set the bad block position */
4981 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4982 chip->badblockpos = NAND_BBM_POS_LARGE;
4984 chip->badblockpos = NAND_BBM_POS_SMALL;
4987 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4989 return type->id_len;
4992 static bool find_full_id_nand(struct nand_chip *chip,
4993 struct nand_flash_dev *type)
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;
5001 memorg = nanddev_get_memorg(&chip->base);
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 /
5008 mtd->erasesize = type->erasesize;
5009 memorg->oobsize = type->oobsize;
5010 mtd->oobsize = memorg->oobsize;
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,
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);
5022 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
5023 if (!chip->parameters.model)
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
5036 static void nand_manufacturer_detect(struct nand_chip *chip)
5039 * Try manufacturer detection if available and use
5040 * nand_decode_ext_id() otherwise.
5042 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
5043 chip->manufacturer.desc->ops->detect) {
5044 struct nand_memory_organization *memorg;
5046 memorg = nanddev_get_memorg(&chip->base);
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);
5052 nand_decode_ext_id(chip);
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.
5062 static int nand_manufacturer_init(struct nand_chip *chip)
5064 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
5065 !chip->manufacturer.desc->ops->init)
5068 return chip->manufacturer.desc->ops->init(chip);
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
5077 static void nand_manufacturer_cleanup(struct nand_chip *chip)
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);
5086 nand_manufacturer_name(const struct nand_manufacturer_desc *manufacturer_desc)
5088 return manufacturer_desc ? manufacturer_desc->name : "Unknown";
5091 static void rawnand_check_data_only_read_support(struct nand_chip *chip)
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;
5098 static void rawnand_early_check_supported_ops(struct nand_chip *chip)
5100 /* The supported_op fields should not be set by individual drivers */
5101 WARN_ON_ONCE(chip->controller->supported_op.data_only_read);
5103 if (!nand_has_exec_op(chip))
5106 rawnand_check_data_only_read_support(chip);
5109 static void rawnand_check_cont_read_support(struct nand_chip *chip)
5111 struct mtd_info *mtd = nand_to_mtd(chip);
5113 if (!chip->parameters.supports_read_cache)
5116 if (chip->read_retries)
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;
5124 static void rawnand_late_check_supported_ops(struct nand_chip *chip)
5126 /* The supported_op fields should not be set by individual drivers */
5127 WARN_ON_ONCE(chip->controller->supported_op.cont_read);
5129 if (!nand_has_exec_op(chip))
5132 rawnand_check_cont_read_support(chip);
5136 * Get the flash and manufacturer id and lookup if the type is supported.
5138 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
5140 const struct nand_manufacturer_desc *manufacturer_desc;
5141 struct mtd_info *mtd = nand_to_mtd(chip);
5142 struct nand_memory_organization *memorg;
5144 u8 *id_data = chip->id.data;
5149 * Let's start by initializing memorg fields that might be left
5150 * unassigned by the ID-based detection logic.
5152 memorg = nanddev_get_memorg(&chip->base);
5153 memorg->planes_per_lun = 1;
5154 memorg->luns_per_target = 1;
5157 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
5160 ret = nand_reset(chip, 0);
5164 /* Select the device */
5165 nand_select_target(chip, 0);
5167 rawnand_early_check_supported_ops(chip);
5169 /* Send the command for reading device ID */
5170 ret = nand_readid_op(chip, 0, id_data, 2);
5174 /* Read manufacturer and device IDs */
5175 maf_id = id_data[0];
5176 dev_id = id_data[1];
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.
5185 /* Read entire ID string */
5186 ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
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]);
5196 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
5198 /* Try to identify manufacturer */
5199 manufacturer_desc = nand_get_manufacturer_desc(maf_id);
5200 chip->manufacturer.desc = manufacturer_desc;
5203 type = nand_flash_ids;
5206 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
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).
5212 busw = chip->options & NAND_BUSWIDTH_16;
5215 * The flag is only set (never cleared), reset it to its default value
5216 * before starting auto-detection.
5218 chip->options &= ~NAND_BUSWIDTH_16;
5220 for (; type->name != NULL; type++) {
5221 if (is_full_id_nand(type)) {
5222 if (find_full_id_nand(chip, type))
5224 } else if (dev_id == type->dev_id) {
5229 if (!type->name || !type->pagesize) {
5230 /* Check if the chip is ONFI compliant */
5231 ret = nand_onfi_detect(chip);
5237 /* Check if the chip is JEDEC compliant */
5238 ret = nand_jedec_detect(chip);
5248 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
5249 if (!chip->parameters.model)
5252 if (!type->pagesize)
5253 nand_manufacturer_detect(chip);
5255 nand_decode_id(chip, type);
5257 /* Get chip options */
5258 chip->options |= type->options;
5260 memorg->eraseblocks_per_lun =
5261 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
5263 memorg->pages_per_eraseblock);
5267 mtd->name = chip->parameters.model;
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)) {
5274 * Check, if buswidth is correct. Hardware drivers should set
5277 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5279 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
5281 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
5282 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
5285 goto free_detect_allocation;
5288 nand_decode_bbm_options(chip);
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;
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;
5301 chip->chip_shift = ffs((unsigned)(targetsize >> 32));
5302 chip->chip_shift += 32 - 1;
5305 if (chip->chip_shift - chip->page_shift > 16)
5306 chip->options |= NAND_ROW_ADDR_3;
5308 chip->badblockbits = 8;
5310 nand_legacy_adjust_cmdfunc(chip);
5312 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
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);
5321 free_detect_allocation:
5322 kfree(chip->parameters.model);
5327 static enum nand_ecc_engine_type
5328 of_get_rawnand_ecc_engine_type_legacy(struct device_node *np)
5330 enum nand_ecc_legacy_mode {
5336 NAND_ECC_HW_SYNDROME,
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",
5347 enum nand_ecc_legacy_mode eng_type;
5351 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5353 return NAND_ECC_ENGINE_TYPE_INVALID;
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])) {
5360 return NAND_ECC_ENGINE_TYPE_NONE;
5362 case NAND_ECC_SOFT_BCH:
5363 return NAND_ECC_ENGINE_TYPE_SOFT;
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;
5375 return NAND_ECC_ENGINE_TYPE_INVALID;
5378 static enum nand_ecc_placement
5379 of_get_rawnand_ecc_placement_legacy(struct device_node *np)
5384 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5386 if (!strcasecmp(pm, "hw_syndrome"))
5387 return NAND_ECC_PLACEMENT_INTERLEAVED;
5390 return NAND_ECC_PLACEMENT_UNKNOWN;
5393 static enum nand_ecc_algo of_get_rawnand_ecc_algo_legacy(struct device_node *np)
5398 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5400 if (!strcasecmp(pm, "soft"))
5401 return NAND_ECC_ALGO_HAMMING;
5402 else if (!strcasecmp(pm, "soft_bch"))
5403 return NAND_ECC_ALGO_BCH;
5406 return NAND_ECC_ALGO_UNKNOWN;
5409 static void of_get_nand_ecc_legacy_user_config(struct nand_chip *chip)
5411 struct device_node *dn = nand_get_flash_node(chip);
5412 struct nand_ecc_props *user_conf = &chip->base.ecc.user_conf;
5414 if (user_conf->engine_type == NAND_ECC_ENGINE_TYPE_INVALID)
5415 user_conf->engine_type = of_get_rawnand_ecc_engine_type_legacy(dn);
5417 if (user_conf->algo == NAND_ECC_ALGO_UNKNOWN)
5418 user_conf->algo = of_get_rawnand_ecc_algo_legacy(dn);
5420 if (user_conf->placement == NAND_ECC_PLACEMENT_UNKNOWN)
5421 user_conf->placement = of_get_rawnand_ecc_placement_legacy(dn);
5424 static int of_get_nand_bus_width(struct nand_chip *chip)
5426 struct device_node *dn = nand_get_flash_node(chip);
5430 ret = of_property_read_u32(dn, "nand-bus-width", &val);
5432 /* Buswidth defaults to 8 if the property does not exist .*/
5438 chip->options |= NAND_BUSWIDTH_16;
5444 static int of_get_nand_secure_regions(struct nand_chip *chip)
5446 struct device_node *dn = nand_get_flash_node(chip);
5447 struct property *prop;
5450 /* Only proceed if the "secure-regions" property is present in DT */
5451 prop = of_find_property(dn, "secure-regions", NULL);
5455 nr_elem = of_property_count_elems_of_size(dn, "secure-regions", sizeof(u64));
5459 chip->nr_secure_regions = nr_elem / 2;
5460 chip->secure_regions = kcalloc(chip->nr_secure_regions, sizeof(*chip->secure_regions),
5462 if (!chip->secure_regions)
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);
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.
5482 int rawnand_dt_parse_gpio_cs(struct device *dev, struct gpio_desc ***cs_array,
5483 unsigned int *ncs_array)
5485 struct gpio_desc **descs;
5488 ndescs = gpiod_count(dev, "cs");
5490 dev_dbg(dev, "No valid cs-gpios property\n");
5494 descs = devm_kcalloc(dev, ndescs, sizeof(*descs), GFP_KERNEL);
5498 for (i = 0; i < ndescs; i++) {
5499 descs[i] = gpiod_get_index_optional(dev, "cs", i,
5501 if (IS_ERR(descs[i]))
5502 return PTR_ERR(descs[i]);
5505 *ncs_array = ndescs;
5510 EXPORT_SYMBOL(rawnand_dt_parse_gpio_cs);
5512 static int rawnand_dt_init(struct nand_chip *chip)
5514 struct nand_device *nand = mtd_to_nanddev(nand_to_mtd(chip));
5515 struct device_node *dn = nand_get_flash_node(chip);
5521 ret = of_get_nand_bus_width(chip);
5525 if (of_property_read_bool(dn, "nand-is-boot-medium"))
5526 chip->options |= NAND_IS_BOOT_MEDIUM;
5528 if (of_property_read_bool(dn, "nand-on-flash-bbt"))
5529 chip->bbt_options |= NAND_BBT_USE_FLASH;
5531 of_get_nand_ecc_user_config(nand);
5532 of_get_nand_ecc_legacy_user_config(chip);
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.
5538 nand->ecc.defaults.engine_type = NAND_ECC_ENGINE_TYPE_ON_HOST;
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.
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;
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;
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
5564 * This is the first phase of the normal nand_scan() function. It reads the
5565 * flash ID and sets up MTD fields accordingly.
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.
5572 static int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips,
5573 struct nand_flash_dev *table)
5575 struct mtd_info *mtd = nand_to_mtd(chip);
5576 struct nand_memory_organization *memorg;
5577 int nand_maf_id, nand_dev_id;
5581 memorg = nanddev_get_memorg(&chip->base);
5583 /* Assume all dies are deselected when we enter nand_scan_ident(). */
5586 mutex_init(&chip->lock);
5587 init_waitqueue_head(&chip->resume_wq);
5589 /* Enforce the right timings for reset/detection */
5590 chip->current_interface_config = nand_get_reset_interface_config();
5592 ret = rawnand_dt_init(chip);
5596 if (!mtd->name && mtd->dev.parent)
5597 mtd->name = dev_name(mtd->dev.parent);
5599 /* Set the default functions */
5600 nand_set_defaults(chip);
5602 ret = nand_legacy_check_hooks(chip);
5606 memorg->ntargets = maxchips;
5608 /* Read the flash type */
5609 ret = nand_detect(chip, table);
5611 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
5612 pr_warn("No NAND device found\n");
5613 nand_deselect_target(chip);
5617 nand_maf_id = chip->id.data[0];
5618 nand_dev_id = chip->id.data[1];
5620 nand_deselect_target(chip);
5622 /* Check for a chip array */
5623 for (i = 1; i < maxchips; i++) {
5626 /* See comment in nand_get_flash_type for reset */
5627 ret = nand_reset(chip, i);
5631 nand_select_target(chip, i);
5632 /* Send the command for reading device ID */
5633 ret = nand_readid_op(chip, 0, id, sizeof(id));
5636 /* Read manufacturer and device IDs */
5637 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
5638 nand_deselect_target(chip);
5641 nand_deselect_target(chip);
5644 pr_info("%d chips detected\n", i);
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);
5653 static void nand_scan_ident_cleanup(struct nand_chip *chip)
5655 kfree(chip->parameters.model);
5656 kfree(chip->parameters.onfi);
5659 int rawnand_sw_hamming_init(struct nand_chip *chip)
5661 struct nand_ecc_sw_hamming_conf *engine_conf;
5662 struct nand_device *base = &chip->base;
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;
5670 ret = nand_ecc_sw_hamming_init_ctx(base);
5674 engine_conf = base->ecc.ctx.priv;
5676 if (chip->ecc.options & NAND_ECC_SOFT_HAMMING_SM_ORDER)
5677 engine_conf->sm_order = true;
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);
5687 EXPORT_SYMBOL(rawnand_sw_hamming_init);
5689 int rawnand_sw_hamming_calculate(struct nand_chip *chip,
5690 const unsigned char *buf,
5691 unsigned char *code)
5693 struct nand_device *base = &chip->base;
5695 return nand_ecc_sw_hamming_calculate(base, buf, code);
5697 EXPORT_SYMBOL(rawnand_sw_hamming_calculate);
5699 int rawnand_sw_hamming_correct(struct nand_chip *chip,
5701 unsigned char *read_ecc,
5702 unsigned char *calc_ecc)
5704 struct nand_device *base = &chip->base;
5706 return nand_ecc_sw_hamming_correct(base, buf, read_ecc, calc_ecc);
5708 EXPORT_SYMBOL(rawnand_sw_hamming_correct);
5710 void rawnand_sw_hamming_cleanup(struct nand_chip *chip)
5712 struct nand_device *base = &chip->base;
5714 nand_ecc_sw_hamming_cleanup_ctx(base);
5716 EXPORT_SYMBOL(rawnand_sw_hamming_cleanup);
5718 int rawnand_sw_bch_init(struct nand_chip *chip)
5720 struct nand_device *base = &chip->base;
5721 const struct nand_ecc_props *ecc_conf = nanddev_get_ecc_conf(base);
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;
5729 ret = nand_ecc_sw_bch_init_ctx(base);
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);
5741 EXPORT_SYMBOL(rawnand_sw_bch_init);
5743 static int rawnand_sw_bch_calculate(struct nand_chip *chip,
5744 const unsigned char *buf,
5745 unsigned char *code)
5747 struct nand_device *base = &chip->base;
5749 return nand_ecc_sw_bch_calculate(base, buf, code);
5752 int rawnand_sw_bch_correct(struct nand_chip *chip, unsigned char *buf,
5753 unsigned char *read_ecc, unsigned char *calc_ecc)
5755 struct nand_device *base = &chip->base;
5757 return nand_ecc_sw_bch_correct(base, buf, read_ecc, calc_ecc);
5759 EXPORT_SYMBOL(rawnand_sw_bch_correct);
5761 void rawnand_sw_bch_cleanup(struct nand_chip *chip)
5763 struct nand_device *base = &chip->base;
5765 nand_ecc_sw_bch_cleanup_ctx(base);
5767 EXPORT_SYMBOL(rawnand_sw_bch_cleanup);
5769 static int nand_set_ecc_on_host_ops(struct nand_chip *chip)
5771 struct nand_ecc_ctrl *ecc = &chip->ecc;
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;
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;
5795 case NAND_ECC_PLACEMENT_INTERLEAVED:
5796 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5798 ecc->read_page == nand_read_page_hwecc ||
5800 ecc->write_page == nand_write_page_hwecc)) {
5801 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
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;
5814 ecc->read_oob = nand_read_oob_syndrome;
5815 if (!ecc->write_oob)
5816 ecc->write_oob = nand_write_oob_syndrome;
5820 pr_warn("Invalid NAND_ECC_PLACEMENT %d\n",
5828 static int nand_set_ecc_soft_ops(struct nand_chip *chip)
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;
5835 if (WARN_ON(ecc->engine_type != NAND_ECC_ENGINE_TYPE_SOFT))
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;
5856 if (IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_HAMMING_SMC))
5857 ecc->options |= NAND_ECC_SOFT_HAMMING_SM_ORDER;
5859 ret = rawnand_sw_hamming_init(chip);
5861 WARN(1, "Hamming ECC initialization failed!\n");
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");
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;
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
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;
5892 ret = rawnand_sw_bch_init(chip);
5894 WARN(1, "BCH ECC initialization failed!\n");
5900 WARN(1, "Unsupported ECC algorithm!\n");
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
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.
5916 nand_check_ecc_caps(struct nand_chip *chip,
5917 const struct nand_ecc_caps *caps, int oobavail)
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;
5926 for (i = 0; i < caps->nstepinfos; i++) {
5927 stepinfo = &caps->stepinfos[i];
5929 if (stepinfo->stepsize != preset_step)
5932 for (j = 0; j < stepinfo->nstrengths; j++) {
5933 if (stepinfo->strengths[j] != preset_strength)
5936 ecc_bytes = caps->calc_ecc_bytes(preset_step,
5938 if (WARN_ON_ONCE(ecc_bytes < 0))
5941 if (ecc_bytes * nsteps > oobavail) {
5942 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
5943 preset_step, preset_strength);
5947 chip->ecc.bytes = ecc_bytes;
5953 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
5954 preset_step, preset_strength);
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
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.
5970 nand_match_ecc_req(struct nand_chip *chip,
5971 const struct nand_ecc_caps *caps, int oobavail)
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;
5984 /* No information provided by the NAND chip */
5985 if (!req_step || !req_strength)
5988 /* number of correctable bits the chip requires in a page */
5989 req_corr = mtd->writesize / req_step * req_strength;
5991 for (i = 0; i < caps->nstepinfos; i++) {
5992 stepinfo = &caps->stepinfos[i];
5993 step_size = stepinfo->stepsize;
5995 for (j = 0; j < stepinfo->nstrengths; j++) {
5996 strength = stepinfo->strengths[j];
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.
6003 if (step_size < req_step && strength < req_strength)
6006 if (mtd->writesize % step_size)
6009 nsteps = mtd->writesize / step_size;
6011 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
6012 if (WARN_ON_ONCE(ecc_bytes < 0))
6014 ecc_bytes_total = ecc_bytes * nsteps;
6016 if (ecc_bytes_total > oobavail ||
6017 strength * nsteps < req_corr)
6021 * We assume the best is to meet the chip's requrement
6022 * with the least number of ECC bytes.
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;
6033 if (best_ecc_bytes_total == INT_MAX)
6036 chip->ecc.size = best_step;
6037 chip->ecc.strength = best_strength;
6038 chip->ecc.bytes = best_ecc_bytes;
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
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.
6053 nand_maximize_ecc(struct nand_chip *chip,
6054 const struct nand_ecc_caps *caps, int oobavail)
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;
6061 int best_strength = 0, best_ecc_bytes = 0;
6064 for (i = 0; i < caps->nstepinfos; i++) {
6065 stepinfo = &caps->stepinfos[i];
6066 step_size = stepinfo->stepsize;
6068 /* If chip->ecc.size is already set, respect it */
6069 if (chip->ecc.size && step_size != chip->ecc.size)
6072 for (j = 0; j < stepinfo->nstrengths; j++) {
6073 strength = stepinfo->strengths[j];
6075 if (mtd->writesize % step_size)
6078 nsteps = mtd->writesize / step_size;
6080 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
6081 if (WARN_ON_ONCE(ecc_bytes < 0))
6084 if (ecc_bytes * nsteps > oobavail)
6087 corr = strength * nsteps;
6090 * If the number of correctable bits is the same,
6091 * bigger step_size has more reliability.
6093 if (corr > best_corr ||
6094 (corr == best_corr && step_size > best_step)) {
6096 best_step = step_size;
6097 best_strength = strength;
6098 best_ecc_bytes = ecc_bytes;
6106 chip->ecc.size = best_step;
6107 chip->ecc.strength = best_strength;
6108 chip->ecc.bytes = best_ecc_bytes;
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
6119 * Choose the ECC configuration according to following logic.
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
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.
6129 * On success, the chosen ECC settings are set.
6131 int nand_ecc_choose_conf(struct nand_chip *chip,
6132 const struct nand_ecc_caps *caps, int oobavail)
6134 struct mtd_info *mtd = nand_to_mtd(chip);
6135 struct nand_device *nanddev = mtd_to_nanddev(mtd);
6137 if (WARN_ON(oobavail < 0 || oobavail > mtd->oobsize))
6140 if (chip->ecc.size && chip->ecc.strength)
6141 return nand_check_ecc_caps(chip, caps, oobavail);
6143 if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH)
6144 return nand_maximize_ecc(chip, caps, oobavail);
6146 if (!nand_match_ecc_req(chip, caps, oobavail))
6149 return nand_maximize_ecc(chip, caps, oobavail);
6151 EXPORT_SYMBOL_GPL(nand_ecc_choose_conf);
6153 static int rawnand_erase(struct nand_device *nand, const struct nand_pos *pos)
6155 struct nand_chip *chip = container_of(nand, struct nand_chip,
6157 unsigned int eb = nanddev_pos_to_row(nand, pos);
6160 eb >>= nand->rowconv.eraseblock_addr_shift;
6162 nand_select_target(chip, pos->target);
6163 ret = nand_erase_op(chip, eb);
6164 nand_deselect_target(chip);
6169 static int rawnand_markbad(struct nand_device *nand,
6170 const struct nand_pos *pos)
6172 struct nand_chip *chip = container_of(nand, struct nand_chip,
6175 return nand_markbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
6178 static bool rawnand_isbad(struct nand_device *nand, const struct nand_pos *pos)
6180 struct nand_chip *chip = container_of(nand, struct nand_chip,
6184 nand_select_target(chip, pos->target);
6185 ret = nand_isbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
6186 nand_deselect_target(chip);
6191 static const struct nand_ops rawnand_ops = {
6192 .erase = rawnand_erase,
6193 .markbad = rawnand_markbad,
6194 .isbad = rawnand_isbad,
6198 * nand_scan_tail - Scan for the NAND device
6199 * @chip: NAND chip object
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.
6205 static int nand_scan_tail(struct nand_chip *chip)
6207 struct mtd_info *mtd = nand_to_mtd(chip);
6208 struct nand_ecc_ctrl *ecc = &chip->ecc;
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))) {
6217 chip->data_buf = kmalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
6218 if (!chip->data_buf)
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
6227 nand_select_target(chip, 0);
6228 ret = nand_manufacturer_init(chip);
6229 nand_deselect_target(chip);
6233 /* Set the internal oob buffer location, just after the page data */
6234 chip->oob_poi = chip->data_buf + mtd->writesize;
6237 * If no default placement scheme is given, select an appropriate one.
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) {
6247 mtd_set_ooblayout(mtd, nand_get_small_page_ooblayout());
6251 mtd_set_ooblayout(mtd,
6252 nand_get_large_page_hamming_ooblayout());
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.
6262 if (ecc->engine_type == NAND_ECC_ENGINE_TYPE_NONE) {
6263 mtd_set_ooblayout(mtd,
6264 nand_get_large_page_ooblayout());
6268 WARN(1, "No oob scheme defined for oobsize %d\n",
6271 goto err_nand_manuf_cleanup;
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
6280 switch (ecc->engine_type) {
6281 case NAND_ECC_ENGINE_TYPE_ON_HOST:
6282 ret = nand_set_ecc_on_host_ops(chip);
6284 goto err_nand_manuf_cleanup;
6286 if (mtd->writesize >= ecc->size) {
6287 if (!ecc->strength) {
6288 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
6290 goto err_nand_manuf_cleanup;
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;
6300 case NAND_ECC_ENGINE_TYPE_SOFT:
6301 ret = nand_set_ecc_soft_ops(chip);
6303 goto err_nand_manuf_cleanup;
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");
6310 goto err_nand_manuf_cleanup;
6313 ecc->read_oob = nand_read_oob_std;
6314 if (!ecc->write_oob)
6315 ecc->write_oob = nand_write_oob_std;
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;
6332 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->engine_type);
6334 goto err_nand_manuf_cleanup;
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) {
6342 goto err_nand_manuf_cleanup;
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;
6352 /* propagate ecc info to mtd_info */
6353 mtd->ecc_strength = ecc->strength;
6354 mtd->ecc_step_size = ecc->size;
6357 * Set the number of read / write steps for one page depending on ECC
6361 ecc->steps = mtd->writesize / ecc->size;
6362 if (ecc->steps * ecc->size != mtd->writesize) {
6363 WARN(1, "Invalid ECC parameters\n");
6365 goto err_nand_manuf_cleanup;
6369 ecc->total = ecc->steps * ecc->bytes;
6370 chip->base.ecc.ctx.total = ecc->total;
6373 if (ecc->total > mtd->oobsize) {
6374 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
6376 goto err_nand_manuf_cleanup;
6380 * The number of bytes available for a client to place data into
6381 * the out of band area.
6383 ret = mtd_ooblayout_count_freebytes(mtd);
6387 mtd->oobavail = ret;
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);
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) {
6400 mtd->subpage_sft = 1;
6405 mtd->subpage_sft = 2;
6409 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
6411 /* Invalidate the pagebuffer reference */
6412 chip->pagecache.page = -1;
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;
6425 ret = nanddev_init(&chip->base, &rawnand_ops, mtd->owner);
6427 goto err_nand_manuf_cleanup;
6429 /* Adjust the MTD_CAP_ flags when NAND_ROM is set. */
6430 if (chip->options & NAND_ROM)
6431 mtd->flags = MTD_CAP_ROM;
6433 /* Fill in remaining MTD driver data */
6434 mtd->_erase = nand_erase;
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;
6452 * Initialize bitflip_threshold to its default prior scan_bbt() call.
6453 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
6456 if (!mtd->bitflip_threshold)
6457 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
6459 /* Find the fastest data interface for this chip */
6460 ret = nand_choose_interface_config(chip);
6462 goto err_nanddev_cleanup;
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);
6468 goto err_free_interface_config;
6471 rawnand_late_check_supported_ops(chip);
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
6479 ret = of_get_nand_secure_regions(chip);
6481 goto err_free_interface_config;
6483 /* Check, if we should skip the bad block table scan */
6484 if (chip->options & NAND_SKIP_BBTSCAN)
6487 /* Build bad block table */
6488 ret = nand_create_bbt(chip);
6490 goto err_free_secure_regions;
6494 err_free_secure_regions:
6495 kfree(chip->secure_regions);
6497 err_free_interface_config:
6498 kfree(chip->best_interface_config);
6500 err_nanddev_cleanup:
6501 nanddev_cleanup(&chip->base);
6503 err_nand_manuf_cleanup:
6504 nand_manufacturer_cleanup(chip);
6507 kfree(chip->data_buf);
6508 kfree(ecc->code_buf);
6509 kfree(ecc->calc_buf);
6514 static int nand_attach(struct nand_chip *chip)
6516 if (chip->controller->ops && chip->controller->ops->attach_chip)
6517 return chip->controller->ops->attach_chip(chip);
6522 static void nand_detach(struct nand_chip *chip)
6524 if (chip->controller->ops && chip->controller->ops->detach_chip)
6525 chip->controller->ops->detach_chip(chip);
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
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.
6538 int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips,
6539 struct nand_flash_dev *ids)
6546 ret = nand_scan_ident(chip, maxchips, ids);
6550 ret = nand_attach(chip);
6554 ret = nand_scan_tail(chip);
6563 nand_scan_ident_cleanup(chip);
6567 EXPORT_SYMBOL(nand_scan_with_ids);
6570 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
6571 * @chip: NAND chip object
6573 void nand_cleanup(struct nand_chip *chip)
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);
6582 nanddev_cleanup(&chip->base);
6584 /* Free secure regions data */
6585 kfree(chip->secure_regions);
6587 /* Free bad block table memory */
6589 kfree(chip->data_buf);
6590 kfree(chip->ecc.code_buf);
6591 kfree(chip->ecc.calc_buf);
6593 /* Free bad block descriptor memory */
6594 if (chip->badblock_pattern && chip->badblock_pattern->options
6595 & NAND_BBT_DYNAMICSTRUCT)
6596 kfree(chip->badblock_pattern);
6598 /* Free the data interface */
6599 kfree(chip->best_interface_config);
6601 /* Free manufacturer priv data. */
6602 nand_manufacturer_cleanup(chip);
6604 /* Free controller specific allocations after chip identification */
6607 /* Free identification phase allocations */
6608 nand_scan_ident_cleanup(chip);
6611 EXPORT_SYMBOL_GPL(nand_cleanup);
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");