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);
1212 * nand_read_page_op - Do a READ PAGE operation
1213 * @chip: The NAND chip
1214 * @page: page to read
1215 * @offset_in_page: offset within the page
1216 * @buf: buffer used to store the data
1217 * @len: length of the buffer
1219 * This function issues a READ PAGE operation.
1220 * This function does not select/unselect the CS line.
1222 * Returns 0 on success, a negative error code otherwise.
1224 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1225 unsigned int offset_in_page, void *buf, unsigned int len)
1227 struct mtd_info *mtd = nand_to_mtd(chip);
1232 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1235 if (nand_has_exec_op(chip)) {
1236 if (mtd->writesize > 512)
1237 return nand_lp_exec_read_page_op(chip, page,
1238 offset_in_page, buf,
1241 return nand_sp_exec_read_page_op(chip, page, offset_in_page,
1245 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, offset_in_page, page);
1247 chip->legacy.read_buf(chip, buf, len);
1251 EXPORT_SYMBOL_GPL(nand_read_page_op);
1254 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1255 * @chip: The NAND chip
1256 * @page: parameter page to read
1257 * @buf: buffer used to store the data
1258 * @len: length of the buffer
1260 * This function issues a READ PARAMETER PAGE operation.
1261 * This function does not select/unselect the CS line.
1263 * Returns 0 on success, a negative error code otherwise.
1265 int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1274 if (nand_has_exec_op(chip)) {
1275 const struct nand_interface_config *conf =
1276 nand_get_interface_config(chip);
1277 struct nand_op_instr instrs[] = {
1278 NAND_OP_CMD(NAND_CMD_PARAM, 0),
1279 NAND_OP_ADDR(1, &page,
1280 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1281 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1282 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1283 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1285 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1287 /* Drop the DATA_IN instruction if len is set to 0. */
1291 return nand_exec_op(chip, &op);
1294 chip->legacy.cmdfunc(chip, NAND_CMD_PARAM, page, -1);
1295 for (i = 0; i < len; i++)
1296 p[i] = chip->legacy.read_byte(chip);
1302 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1303 * @chip: The NAND chip
1304 * @offset_in_page: offset within the page
1305 * @buf: buffer used to store the data
1306 * @len: length of the buffer
1307 * @force_8bit: force 8-bit bus access
1309 * This function issues a CHANGE READ COLUMN operation.
1310 * This function does not select/unselect the CS line.
1312 * Returns 0 on success, a negative error code otherwise.
1314 int nand_change_read_column_op(struct nand_chip *chip,
1315 unsigned int offset_in_page, void *buf,
1316 unsigned int len, bool force_8bit)
1318 struct mtd_info *mtd = nand_to_mtd(chip);
1323 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1326 /* Small page NANDs do not support column change. */
1327 if (mtd->writesize <= 512)
1330 if (nand_has_exec_op(chip)) {
1331 const struct nand_interface_config *conf =
1332 nand_get_interface_config(chip);
1334 struct nand_op_instr instrs[] = {
1335 NAND_OP_CMD(NAND_CMD_RNDOUT, 0),
1336 NAND_OP_ADDR(2, addrs, 0),
1337 NAND_OP_CMD(NAND_CMD_RNDOUTSTART,
1338 NAND_COMMON_TIMING_NS(conf, tCCS_min)),
1339 NAND_OP_DATA_IN(len, buf, 0),
1341 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1344 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1348 /* Drop the DATA_IN instruction if len is set to 0. */
1352 instrs[3].ctx.data.force_8bit = force_8bit;
1354 return nand_exec_op(chip, &op);
1357 chip->legacy.cmdfunc(chip, NAND_CMD_RNDOUT, offset_in_page, -1);
1359 chip->legacy.read_buf(chip, buf, len);
1363 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1366 * nand_read_oob_op - Do a READ OOB operation
1367 * @chip: The NAND chip
1368 * @page: page to read
1369 * @offset_in_oob: offset within the OOB area
1370 * @buf: buffer used to store the data
1371 * @len: length of the buffer
1373 * This function issues a READ OOB operation.
1374 * This function does not select/unselect the CS line.
1376 * Returns 0 on success, a negative error code otherwise.
1378 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1379 unsigned int offset_in_oob, void *buf, unsigned int len)
1381 struct mtd_info *mtd = nand_to_mtd(chip);
1386 if (offset_in_oob + len > mtd->oobsize)
1389 if (nand_has_exec_op(chip))
1390 return nand_read_page_op(chip, page,
1391 mtd->writesize + offset_in_oob,
1394 chip->legacy.cmdfunc(chip, NAND_CMD_READOOB, offset_in_oob, page);
1396 chip->legacy.read_buf(chip, buf, len);
1400 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1402 static int nand_exec_prog_page_op(struct nand_chip *chip, unsigned int page,
1403 unsigned int offset_in_page, const void *buf,
1404 unsigned int len, bool prog)
1406 const struct nand_interface_config *conf =
1407 nand_get_interface_config(chip);
1408 struct mtd_info *mtd = nand_to_mtd(chip);
1410 struct nand_op_instr instrs[] = {
1412 * The first instruction will be dropped if we're dealing
1413 * with a large page NAND and adjusted if we're dealing
1414 * with a small page NAND and the page offset is > 255.
1416 NAND_OP_CMD(NAND_CMD_READ0, 0),
1417 NAND_OP_CMD(NAND_CMD_SEQIN, 0),
1418 NAND_OP_ADDR(0, addrs, NAND_COMMON_TIMING_NS(conf, tADL_min)),
1419 NAND_OP_DATA_OUT(len, buf, 0),
1420 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1421 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1422 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tPROG_max), 0),
1424 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1425 int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
1430 addrs[naddrs++] = page;
1431 addrs[naddrs++] = page >> 8;
1432 if (chip->options & NAND_ROW_ADDR_3)
1433 addrs[naddrs++] = page >> 16;
1435 instrs[2].ctx.addr.naddrs = naddrs;
1437 /* Drop the last two instructions if we're not programming the page. */
1440 /* Also drop the DATA_OUT instruction if empty. */
1445 if (mtd->writesize <= 512) {
1447 * Small pages need some more tweaking: we have to adjust the
1448 * first instruction depending on the page offset we're trying
1451 if (offset_in_page >= mtd->writesize)
1452 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1453 else if (offset_in_page >= 256 &&
1454 !(chip->options & NAND_BUSWIDTH_16))
1455 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1458 * Drop the first command if we're dealing with a large page
1465 return nand_exec_op(chip, &op);
1469 * nand_prog_page_begin_op - starts a PROG PAGE operation
1470 * @chip: The NAND chip
1471 * @page: page to write
1472 * @offset_in_page: offset within the page
1473 * @buf: buffer containing the data to write to the page
1474 * @len: length of the buffer
1476 * This function issues the first half of a PROG PAGE operation.
1477 * This function does not select/unselect the CS line.
1479 * Returns 0 on success, a negative error code otherwise.
1481 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1482 unsigned int offset_in_page, const void *buf,
1485 struct mtd_info *mtd = nand_to_mtd(chip);
1490 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1493 if (nand_has_exec_op(chip))
1494 return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1497 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page, page);
1500 chip->legacy.write_buf(chip, buf, len);
1504 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1507 * nand_prog_page_end_op - ends a PROG PAGE operation
1508 * @chip: The NAND chip
1510 * This function issues the second half of a PROG PAGE operation.
1511 * This function does not select/unselect the CS line.
1513 * Returns 0 on success, a negative error code otherwise.
1515 int nand_prog_page_end_op(struct nand_chip *chip)
1520 if (nand_has_exec_op(chip)) {
1521 const struct nand_interface_config *conf =
1522 nand_get_interface_config(chip);
1523 struct nand_op_instr instrs[] = {
1524 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1525 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1526 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tPROG_max),
1529 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1531 ret = nand_exec_op(chip, &op);
1535 ret = nand_status_op(chip, &status);
1539 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1540 ret = chip->legacy.waitfunc(chip);
1547 if (status & NAND_STATUS_FAIL)
1552 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1555 * nand_prog_page_op - Do a full PROG PAGE operation
1556 * @chip: The NAND chip
1557 * @page: page to write
1558 * @offset_in_page: offset within the page
1559 * @buf: buffer containing the data to write to the page
1560 * @len: length of the buffer
1562 * This function issues a full PROG PAGE operation.
1563 * This function does not select/unselect the CS line.
1565 * Returns 0 on success, a negative error code otherwise.
1567 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1568 unsigned int offset_in_page, const void *buf,
1571 struct mtd_info *mtd = nand_to_mtd(chip);
1578 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1581 if (nand_has_exec_op(chip)) {
1582 ret = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1587 ret = nand_status_op(chip, &status);
1591 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page,
1593 chip->legacy.write_buf(chip, buf, len);
1594 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1595 ret = chip->legacy.waitfunc(chip);
1602 if (status & NAND_STATUS_FAIL)
1607 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1610 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1611 * @chip: The NAND chip
1612 * @offset_in_page: offset within the page
1613 * @buf: buffer containing the data to send to the NAND
1614 * @len: length of the buffer
1615 * @force_8bit: force 8-bit bus access
1617 * This function issues a CHANGE WRITE COLUMN operation.
1618 * This function does not select/unselect the CS line.
1620 * Returns 0 on success, a negative error code otherwise.
1622 int nand_change_write_column_op(struct nand_chip *chip,
1623 unsigned int offset_in_page,
1624 const void *buf, unsigned int len,
1627 struct mtd_info *mtd = nand_to_mtd(chip);
1632 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1635 /* Small page NANDs do not support column change. */
1636 if (mtd->writesize <= 512)
1639 if (nand_has_exec_op(chip)) {
1640 const struct nand_interface_config *conf =
1641 nand_get_interface_config(chip);
1643 struct nand_op_instr instrs[] = {
1644 NAND_OP_CMD(NAND_CMD_RNDIN, 0),
1645 NAND_OP_ADDR(2, addrs, NAND_COMMON_TIMING_NS(conf, tCCS_min)),
1646 NAND_OP_DATA_OUT(len, buf, 0),
1648 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1651 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1655 instrs[2].ctx.data.force_8bit = force_8bit;
1657 /* Drop the DATA_OUT instruction if len is set to 0. */
1661 return nand_exec_op(chip, &op);
1664 chip->legacy.cmdfunc(chip, NAND_CMD_RNDIN, offset_in_page, -1);
1666 chip->legacy.write_buf(chip, buf, len);
1670 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1673 * nand_readid_op - Do a READID operation
1674 * @chip: The NAND chip
1675 * @addr: address cycle to pass after the READID command
1676 * @buf: buffer used to store the ID
1677 * @len: length of the buffer
1679 * This function sends a READID command and reads back the ID returned by the
1681 * This function does not select/unselect the CS line.
1683 * Returns 0 on success, a negative error code otherwise.
1685 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1689 u8 *id = buf, *ddrbuf = NULL;
1694 if (nand_has_exec_op(chip)) {
1695 const struct nand_interface_config *conf =
1696 nand_get_interface_config(chip);
1697 struct nand_op_instr instrs[] = {
1698 NAND_OP_CMD(NAND_CMD_READID, 0),
1699 NAND_OP_ADDR(1, &addr,
1700 NAND_COMMON_TIMING_NS(conf, tADL_min)),
1701 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1703 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1706 /* READ_ID data bytes are received twice in NV-DDR mode */
1707 if (len && nand_interface_is_nvddr(conf)) {
1708 ddrbuf = kzalloc(len * 2, GFP_KERNEL);
1712 instrs[2].ctx.data.len *= 2;
1713 instrs[2].ctx.data.buf.in = ddrbuf;
1716 /* Drop the DATA_IN instruction if len is set to 0. */
1720 ret = nand_exec_op(chip, &op);
1721 if (!ret && len && nand_interface_is_nvddr(conf)) {
1722 for (i = 0; i < len; i++)
1723 id[i] = ddrbuf[i * 2];
1731 chip->legacy.cmdfunc(chip, NAND_CMD_READID, addr, -1);
1733 for (i = 0; i < len; i++)
1734 id[i] = chip->legacy.read_byte(chip);
1738 EXPORT_SYMBOL_GPL(nand_readid_op);
1741 * nand_status_op - Do a STATUS operation
1742 * @chip: The NAND chip
1743 * @status: out variable to store the NAND status
1745 * This function sends a STATUS command and reads back the status returned by
1747 * This function does not select/unselect the CS line.
1749 * Returns 0 on success, a negative error code otherwise.
1751 int nand_status_op(struct nand_chip *chip, u8 *status)
1753 if (nand_has_exec_op(chip)) {
1754 const struct nand_interface_config *conf =
1755 nand_get_interface_config(chip);
1757 struct nand_op_instr instrs[] = {
1758 NAND_OP_CMD(NAND_CMD_STATUS,
1759 NAND_COMMON_TIMING_NS(conf, tADL_min)),
1760 NAND_OP_8BIT_DATA_IN(1, status, 0),
1762 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1765 /* The status data byte will be received twice in NV-DDR mode */
1766 if (status && nand_interface_is_nvddr(conf)) {
1767 instrs[1].ctx.data.len *= 2;
1768 instrs[1].ctx.data.buf.in = ddrstatus;
1774 ret = nand_exec_op(chip, &op);
1775 if (!ret && status && nand_interface_is_nvddr(conf))
1776 *status = ddrstatus[0];
1781 chip->legacy.cmdfunc(chip, NAND_CMD_STATUS, -1, -1);
1783 *status = chip->legacy.read_byte(chip);
1787 EXPORT_SYMBOL_GPL(nand_status_op);
1790 * nand_exit_status_op - Exit a STATUS operation
1791 * @chip: The NAND chip
1793 * This function sends a READ0 command to cancel the effect of the STATUS
1794 * command to avoid reading only the status until a new read command is sent.
1796 * This function does not select/unselect the CS line.
1798 * Returns 0 on success, a negative error code otherwise.
1800 int nand_exit_status_op(struct nand_chip *chip)
1802 if (nand_has_exec_op(chip)) {
1803 struct nand_op_instr instrs[] = {
1804 NAND_OP_CMD(NAND_CMD_READ0, 0),
1806 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1808 return nand_exec_op(chip, &op);
1811 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, -1, -1);
1817 * nand_erase_op - Do an erase operation
1818 * @chip: The NAND chip
1819 * @eraseblock: block to erase
1821 * This function sends an ERASE command and waits for the NAND to be ready
1823 * This function does not select/unselect the CS line.
1825 * Returns 0 on success, a negative error code otherwise.
1827 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1829 unsigned int page = eraseblock <<
1830 (chip->phys_erase_shift - chip->page_shift);
1834 if (nand_has_exec_op(chip)) {
1835 const struct nand_interface_config *conf =
1836 nand_get_interface_config(chip);
1837 u8 addrs[3] = { page, page >> 8, page >> 16 };
1838 struct nand_op_instr instrs[] = {
1839 NAND_OP_CMD(NAND_CMD_ERASE1, 0),
1840 NAND_OP_ADDR(2, addrs, 0),
1841 NAND_OP_CMD(NAND_CMD_ERASE2,
1842 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1843 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tBERS_max),
1846 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1848 if (chip->options & NAND_ROW_ADDR_3)
1849 instrs[1].ctx.addr.naddrs++;
1851 ret = nand_exec_op(chip, &op);
1855 ret = nand_status_op(chip, &status);
1859 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE1, -1, page);
1860 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE2, -1, -1);
1862 ret = chip->legacy.waitfunc(chip);
1869 if (status & NAND_STATUS_FAIL)
1874 EXPORT_SYMBOL_GPL(nand_erase_op);
1877 * nand_set_features_op - Do a SET FEATURES operation
1878 * @chip: The NAND chip
1879 * @feature: feature id
1880 * @data: 4 bytes of data
1882 * This function sends a SET FEATURES command and waits for the NAND to be
1883 * ready before returning.
1884 * This function does not select/unselect the CS line.
1886 * Returns 0 on success, a negative error code otherwise.
1888 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1891 const u8 *params = data;
1894 if (nand_has_exec_op(chip)) {
1895 const struct nand_interface_config *conf =
1896 nand_get_interface_config(chip);
1897 struct nand_op_instr instrs[] = {
1898 NAND_OP_CMD(NAND_CMD_SET_FEATURES, 0),
1899 NAND_OP_ADDR(1, &feature, NAND_COMMON_TIMING_NS(conf,
1901 NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
1902 NAND_COMMON_TIMING_NS(conf,
1904 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tFEAT_max),
1907 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1909 return nand_exec_op(chip, &op);
1912 chip->legacy.cmdfunc(chip, NAND_CMD_SET_FEATURES, feature, -1);
1913 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1914 chip->legacy.write_byte(chip, params[i]);
1916 ret = chip->legacy.waitfunc(chip);
1920 if (ret & NAND_STATUS_FAIL)
1927 * nand_get_features_op - Do a GET FEATURES operation
1928 * @chip: The NAND chip
1929 * @feature: feature id
1930 * @data: 4 bytes of data
1932 * This function sends a GET FEATURES command and waits for the NAND to be
1933 * ready before returning.
1934 * This function does not select/unselect the CS line.
1936 * Returns 0 on success, a negative error code otherwise.
1938 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1941 u8 *params = data, ddrbuf[ONFI_SUBFEATURE_PARAM_LEN * 2];
1944 if (nand_has_exec_op(chip)) {
1945 const struct nand_interface_config *conf =
1946 nand_get_interface_config(chip);
1947 struct nand_op_instr instrs[] = {
1948 NAND_OP_CMD(NAND_CMD_GET_FEATURES, 0),
1949 NAND_OP_ADDR(1, &feature,
1950 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1951 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tFEAT_max),
1952 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1953 NAND_OP_8BIT_DATA_IN(ONFI_SUBFEATURE_PARAM_LEN,
1956 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1959 /* GET_FEATURE data bytes are received twice in NV-DDR mode */
1960 if (nand_interface_is_nvddr(conf)) {
1961 instrs[3].ctx.data.len *= 2;
1962 instrs[3].ctx.data.buf.in = ddrbuf;
1965 ret = nand_exec_op(chip, &op);
1966 if (nand_interface_is_nvddr(conf)) {
1967 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; i++)
1968 params[i] = ddrbuf[i * 2];
1974 chip->legacy.cmdfunc(chip, NAND_CMD_GET_FEATURES, feature, -1);
1975 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1976 params[i] = chip->legacy.read_byte(chip);
1981 static int nand_wait_rdy_op(struct nand_chip *chip, unsigned int timeout_ms,
1982 unsigned int delay_ns)
1984 if (nand_has_exec_op(chip)) {
1985 struct nand_op_instr instrs[] = {
1986 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(timeout_ms),
1987 PSEC_TO_NSEC(delay_ns)),
1989 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1991 return nand_exec_op(chip, &op);
1994 /* Apply delay or wait for ready/busy pin */
1995 if (!chip->legacy.dev_ready)
1996 udelay(chip->legacy.chip_delay);
1998 nand_wait_ready(chip);
2004 * nand_reset_op - Do a reset operation
2005 * @chip: The NAND chip
2007 * This function sends a RESET command and waits for the NAND to be ready
2009 * This function does not select/unselect the CS line.
2011 * Returns 0 on success, a negative error code otherwise.
2013 int nand_reset_op(struct nand_chip *chip)
2015 if (nand_has_exec_op(chip)) {
2016 const struct nand_interface_config *conf =
2017 nand_get_interface_config(chip);
2018 struct nand_op_instr instrs[] = {
2019 NAND_OP_CMD(NAND_CMD_RESET,
2020 NAND_COMMON_TIMING_NS(conf, tWB_max)),
2021 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tRST_max),
2024 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2026 return nand_exec_op(chip, &op);
2029 chip->legacy.cmdfunc(chip, NAND_CMD_RESET, -1, -1);
2033 EXPORT_SYMBOL_GPL(nand_reset_op);
2036 * nand_read_data_op - Read data from the NAND
2037 * @chip: The NAND chip
2038 * @buf: buffer used to store the data
2039 * @len: length of the buffer
2040 * @force_8bit: force 8-bit bus access
2041 * @check_only: do not actually run the command, only checks if the
2042 * controller driver supports it
2044 * This function does a raw data read on the bus. Usually used after launching
2045 * another NAND operation like nand_read_page_op().
2046 * This function does not select/unselect the CS line.
2048 * Returns 0 on success, a negative error code otherwise.
2050 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
2051 bool force_8bit, bool check_only)
2056 if (nand_has_exec_op(chip)) {
2057 const struct nand_interface_config *conf =
2058 nand_get_interface_config(chip);
2059 struct nand_op_instr instrs[] = {
2060 NAND_OP_DATA_IN(len, buf, 0),
2062 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2066 instrs[0].ctx.data.force_8bit = force_8bit;
2069 * Parameter payloads (ID, status, features, etc) do not go
2070 * through the same pipeline as regular data, hence the
2071 * force_8bit flag must be set and this also indicates that in
2072 * case NV-DDR timings are being used the data will be received
2075 if (force_8bit && nand_interface_is_nvddr(conf)) {
2076 ddrbuf = kzalloc(len * 2, GFP_KERNEL);
2080 instrs[0].ctx.data.len *= 2;
2081 instrs[0].ctx.data.buf.in = ddrbuf;
2085 ret = nand_check_op(chip, &op);
2090 ret = nand_exec_op(chip, &op);
2091 if (!ret && force_8bit && nand_interface_is_nvddr(conf)) {
2094 for (i = 0; i < len; i++)
2095 dst[i] = ddrbuf[i * 2];
2110 for (i = 0; i < len; i++)
2111 p[i] = chip->legacy.read_byte(chip);
2113 chip->legacy.read_buf(chip, buf, len);
2118 EXPORT_SYMBOL_GPL(nand_read_data_op);
2121 * nand_write_data_op - Write data from the NAND
2122 * @chip: The NAND chip
2123 * @buf: buffer containing the data to send on the bus
2124 * @len: length of the buffer
2125 * @force_8bit: force 8-bit bus access
2127 * This function does a raw data write on the bus. Usually used after launching
2128 * another NAND operation like nand_write_page_begin_op().
2129 * This function does not select/unselect the CS line.
2131 * Returns 0 on success, a negative error code otherwise.
2133 int nand_write_data_op(struct nand_chip *chip, const void *buf,
2134 unsigned int len, bool force_8bit)
2139 if (nand_has_exec_op(chip)) {
2140 struct nand_op_instr instrs[] = {
2141 NAND_OP_DATA_OUT(len, buf, 0),
2143 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2145 instrs[0].ctx.data.force_8bit = force_8bit;
2147 return nand_exec_op(chip, &op);
2154 for (i = 0; i < len; i++)
2155 chip->legacy.write_byte(chip, p[i]);
2157 chip->legacy.write_buf(chip, buf, len);
2162 EXPORT_SYMBOL_GPL(nand_write_data_op);
2165 * struct nand_op_parser_ctx - Context used by the parser
2166 * @instrs: array of all the instructions that must be addressed
2167 * @ninstrs: length of the @instrs array
2168 * @subop: Sub-operation to be passed to the NAND controller
2170 * This structure is used by the core to split NAND operations into
2171 * sub-operations that can be handled by the NAND controller.
2173 struct nand_op_parser_ctx {
2174 const struct nand_op_instr *instrs;
2175 unsigned int ninstrs;
2176 struct nand_subop subop;
2180 * nand_op_parser_must_split_instr - Checks if an instruction must be split
2181 * @pat: the parser pattern element that matches @instr
2182 * @instr: pointer to the instruction to check
2183 * @start_offset: this is an in/out parameter. If @instr has already been
2184 * split, then @start_offset is the offset from which to start
2185 * (either an address cycle or an offset in the data buffer).
2186 * Conversely, if the function returns true (ie. instr must be
2187 * split), this parameter is updated to point to the first
2188 * data/address cycle that has not been taken care of.
2190 * Some NAND controllers are limited and cannot send X address cycles with a
2191 * unique operation, or cannot read/write more than Y bytes at the same time.
2192 * In this case, split the instruction that does not fit in a single
2193 * controller-operation into two or more chunks.
2195 * Returns true if the instruction must be split, false otherwise.
2196 * The @start_offset parameter is also updated to the offset at which the next
2197 * bundle of instruction must start (if an address or a data instruction).
2200 nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat,
2201 const struct nand_op_instr *instr,
2202 unsigned int *start_offset)
2204 switch (pat->type) {
2205 case NAND_OP_ADDR_INSTR:
2206 if (!pat->ctx.addr.maxcycles)
2209 if (instr->ctx.addr.naddrs - *start_offset >
2210 pat->ctx.addr.maxcycles) {
2211 *start_offset += pat->ctx.addr.maxcycles;
2216 case NAND_OP_DATA_IN_INSTR:
2217 case NAND_OP_DATA_OUT_INSTR:
2218 if (!pat->ctx.data.maxlen)
2221 if (instr->ctx.data.len - *start_offset >
2222 pat->ctx.data.maxlen) {
2223 *start_offset += pat->ctx.data.maxlen;
2236 * nand_op_parser_match_pat - Checks if a pattern matches the instructions
2237 * remaining in the parser context
2238 * @pat: the pattern to test
2239 * @ctx: the parser context structure to match with the pattern @pat
2241 * Check if @pat matches the set or a sub-set of instructions remaining in @ctx.
2242 * Returns true if this is the case, false ortherwise. When true is returned,
2243 * @ctx->subop is updated with the set of instructions to be passed to the
2244 * controller driver.
2247 nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
2248 struct nand_op_parser_ctx *ctx)
2250 unsigned int instr_offset = ctx->subop.first_instr_start_off;
2251 const struct nand_op_instr *end = ctx->instrs + ctx->ninstrs;
2252 const struct nand_op_instr *instr = ctx->subop.instrs;
2253 unsigned int i, ninstrs;
2255 for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
2257 * The pattern instruction does not match the operation
2258 * instruction. If the instruction is marked optional in the
2259 * pattern definition, we skip the pattern element and continue
2260 * to the next one. If the element is mandatory, there's no
2261 * match and we can return false directly.
2263 if (instr->type != pat->elems[i].type) {
2264 if (!pat->elems[i].optional)
2271 * Now check the pattern element constraints. If the pattern is
2272 * not able to handle the whole instruction in a single step,
2273 * we have to split it.
2274 * The last_instr_end_off value comes back updated to point to
2275 * the position where we have to split the instruction (the
2276 * start of the next subop chunk).
2278 if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
2291 * This can happen if all instructions of a pattern are optional.
2292 * Still, if there's not at least one instruction handled by this
2293 * pattern, this is not a match, and we should try the next one (if
2300 * We had a match on the pattern head, but the pattern may be longer
2301 * than the instructions we're asked to execute. We need to make sure
2302 * there's no mandatory elements in the pattern tail.
2304 for (; i < pat->nelems; i++) {
2305 if (!pat->elems[i].optional)
2310 * We have a match: update the subop structure accordingly and return
2313 ctx->subop.ninstrs = ninstrs;
2314 ctx->subop.last_instr_end_off = instr_offset;
2319 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
2320 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2322 const struct nand_op_instr *instr;
2326 pr_debug("executing subop (CS%d):\n", ctx->subop.cs);
2328 for (i = 0; i < ctx->ninstrs; i++) {
2329 instr = &ctx->instrs[i];
2331 if (instr == &ctx->subop.instrs[0])
2334 nand_op_trace(prefix, instr);
2336 if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
2341 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2347 static int nand_op_parser_cmp_ctx(const struct nand_op_parser_ctx *a,
2348 const struct nand_op_parser_ctx *b)
2350 if (a->subop.ninstrs < b->subop.ninstrs)
2352 else if (a->subop.ninstrs > b->subop.ninstrs)
2355 if (a->subop.last_instr_end_off < b->subop.last_instr_end_off)
2357 else if (a->subop.last_instr_end_off > b->subop.last_instr_end_off)
2364 * nand_op_parser_exec_op - exec_op parser
2365 * @chip: the NAND chip
2366 * @parser: patterns description provided by the controller driver
2367 * @op: the NAND operation to address
2368 * @check_only: when true, the function only checks if @op can be handled but
2369 * does not execute the operation
2371 * Helper function designed to ease integration of NAND controller drivers that
2372 * only support a limited set of instruction sequences. The supported sequences
2373 * are described in @parser, and the framework takes care of splitting @op into
2374 * multiple sub-operations (if required) and pass them back to the ->exec()
2375 * callback of the matching pattern if @check_only is set to false.
2377 * NAND controller drivers should call this function from their own ->exec_op()
2380 * Returns 0 on success, a negative error code otherwise. A failure can be
2381 * caused by an unsupported operation (none of the supported patterns is able
2382 * to handle the requested operation), or an error returned by one of the
2383 * matching pattern->exec() hook.
2385 int nand_op_parser_exec_op(struct nand_chip *chip,
2386 const struct nand_op_parser *parser,
2387 const struct nand_operation *op, bool check_only)
2389 struct nand_op_parser_ctx ctx = {
2391 .subop.instrs = op->instrs,
2392 .instrs = op->instrs,
2393 .ninstrs = op->ninstrs,
2397 while (ctx.subop.instrs < op->instrs + op->ninstrs) {
2398 const struct nand_op_parser_pattern *pattern;
2399 struct nand_op_parser_ctx best_ctx;
2400 int ret, best_pattern = -1;
2402 for (i = 0; i < parser->npatterns; i++) {
2403 struct nand_op_parser_ctx test_ctx = ctx;
2405 pattern = &parser->patterns[i];
2406 if (!nand_op_parser_match_pat(pattern, &test_ctx))
2409 if (best_pattern >= 0 &&
2410 nand_op_parser_cmp_ctx(&test_ctx, &best_ctx) <= 0)
2414 best_ctx = test_ctx;
2417 if (best_pattern < 0) {
2418 pr_debug("->exec_op() parser: pattern not found!\n");
2423 nand_op_parser_trace(&ctx);
2426 pattern = &parser->patterns[best_pattern];
2427 ret = pattern->exec(chip, &ctx.subop);
2433 * Update the context structure by pointing to the start of the
2436 ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
2437 if (ctx.subop.last_instr_end_off)
2438 ctx.subop.instrs -= 1;
2440 ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
2445 EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
2447 static bool nand_instr_is_data(const struct nand_op_instr *instr)
2449 return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
2450 instr->type == NAND_OP_DATA_OUT_INSTR);
2453 static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
2454 unsigned int instr_idx)
2456 return subop && instr_idx < subop->ninstrs;
2459 static unsigned int nand_subop_get_start_off(const struct nand_subop *subop,
2460 unsigned int instr_idx)
2465 return subop->first_instr_start_off;
2469 * nand_subop_get_addr_start_off - Get the start offset in an address array
2470 * @subop: The entire sub-operation
2471 * @instr_idx: Index of the instruction inside the sub-operation
2473 * During driver development, one could be tempted to directly use the
2474 * ->addr.addrs field of address instructions. This is wrong as address
2475 * instructions might be split.
2477 * Given an address instruction, returns the offset of the first cycle to issue.
2479 unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
2480 unsigned int instr_idx)
2482 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2483 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2486 return nand_subop_get_start_off(subop, instr_idx);
2488 EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
2491 * nand_subop_get_num_addr_cyc - Get the remaining address cycles to assert
2492 * @subop: The entire sub-operation
2493 * @instr_idx: Index of the instruction inside the sub-operation
2495 * During driver development, one could be tempted to directly use the
2496 * ->addr->naddrs field of a data instruction. This is wrong as instructions
2499 * Given an address instruction, returns the number of address cycle to issue.
2501 unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
2502 unsigned int instr_idx)
2504 int start_off, end_off;
2506 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2507 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2510 start_off = nand_subop_get_addr_start_off(subop, instr_idx);
2512 if (instr_idx == subop->ninstrs - 1 &&
2513 subop->last_instr_end_off)
2514 end_off = subop->last_instr_end_off;
2516 end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
2518 return end_off - start_off;
2520 EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
2523 * nand_subop_get_data_start_off - Get the start offset in a data array
2524 * @subop: The entire sub-operation
2525 * @instr_idx: Index of the instruction inside the sub-operation
2527 * During driver development, one could be tempted to directly use the
2528 * ->data->buf.{in,out} field of data instructions. This is wrong as data
2529 * instructions might be split.
2531 * Given a data instruction, returns the offset to start from.
2533 unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
2534 unsigned int instr_idx)
2536 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2537 !nand_instr_is_data(&subop->instrs[instr_idx])))
2540 return nand_subop_get_start_off(subop, instr_idx);
2542 EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
2545 * nand_subop_get_data_len - Get the number of bytes to retrieve
2546 * @subop: The entire sub-operation
2547 * @instr_idx: Index of the instruction inside the sub-operation
2549 * During driver development, one could be tempted to directly use the
2550 * ->data->len field of a data instruction. This is wrong as data instructions
2553 * Returns the length of the chunk of data to send/receive.
2555 unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
2556 unsigned int instr_idx)
2558 int start_off = 0, end_off;
2560 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2561 !nand_instr_is_data(&subop->instrs[instr_idx])))
2564 start_off = nand_subop_get_data_start_off(subop, instr_idx);
2566 if (instr_idx == subop->ninstrs - 1 &&
2567 subop->last_instr_end_off)
2568 end_off = subop->last_instr_end_off;
2570 end_off = subop->instrs[instr_idx].ctx.data.len;
2572 return end_off - start_off;
2574 EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
2577 * nand_reset - Reset and initialize a NAND device
2578 * @chip: The NAND chip
2579 * @chipnr: Internal die id
2581 * Save the timings data structure, then apply SDR timings mode 0 (see
2582 * nand_reset_interface for details), do the reset operation, and apply
2583 * back the previous timings.
2585 * Returns 0 on success, a negative error code otherwise.
2587 int nand_reset(struct nand_chip *chip, int chipnr)
2591 ret = nand_reset_interface(chip, chipnr);
2596 * The CS line has to be released before we can apply the new NAND
2597 * interface settings, hence this weird nand_select_target()
2598 * nand_deselect_target() dance.
2600 nand_select_target(chip, chipnr);
2601 ret = nand_reset_op(chip);
2602 nand_deselect_target(chip);
2606 ret = nand_setup_interface(chip, chipnr);
2612 EXPORT_SYMBOL_GPL(nand_reset);
2615 * nand_get_features - wrapper to perform a GET_FEATURE
2616 * @chip: NAND chip info structure
2617 * @addr: feature address
2618 * @subfeature_param: the subfeature parameters, a four bytes array
2620 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2621 * operation cannot be handled.
2623 int nand_get_features(struct nand_chip *chip, int addr,
2624 u8 *subfeature_param)
2626 if (!nand_supports_get_features(chip, addr))
2629 if (chip->legacy.get_features)
2630 return chip->legacy.get_features(chip, addr, subfeature_param);
2632 return nand_get_features_op(chip, addr, subfeature_param);
2636 * nand_set_features - wrapper to perform a SET_FEATURE
2637 * @chip: NAND chip info structure
2638 * @addr: feature address
2639 * @subfeature_param: the subfeature parameters, a four bytes array
2641 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2642 * operation cannot be handled.
2644 int nand_set_features(struct nand_chip *chip, int addr,
2645 u8 *subfeature_param)
2647 if (!nand_supports_set_features(chip, addr))
2650 if (chip->legacy.set_features)
2651 return chip->legacy.set_features(chip, addr, subfeature_param);
2653 return nand_set_features_op(chip, addr, subfeature_param);
2657 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
2658 * @buf: buffer to test
2659 * @len: buffer length
2660 * @bitflips_threshold: maximum number of bitflips
2662 * Check if a buffer contains only 0xff, which means the underlying region
2663 * has been erased and is ready to be programmed.
2664 * The bitflips_threshold specify the maximum number of bitflips before
2665 * considering the region is not erased.
2666 * Note: The logic of this function has been extracted from the memweight
2667 * implementation, except that nand_check_erased_buf function exit before
2668 * testing the whole buffer if the number of bitflips exceed the
2669 * bitflips_threshold value.
2671 * Returns a positive number of bitflips less than or equal to
2672 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2675 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
2677 const unsigned char *bitmap = buf;
2681 for (; len && ((uintptr_t)bitmap) % sizeof(long);
2683 weight = hweight8(*bitmap);
2684 bitflips += BITS_PER_BYTE - weight;
2685 if (unlikely(bitflips > bitflips_threshold))
2689 for (; len >= sizeof(long);
2690 len -= sizeof(long), bitmap += sizeof(long)) {
2691 unsigned long d = *((unsigned long *)bitmap);
2694 weight = hweight_long(d);
2695 bitflips += BITS_PER_LONG - weight;
2696 if (unlikely(bitflips > bitflips_threshold))
2700 for (; len > 0; len--, bitmap++) {
2701 weight = hweight8(*bitmap);
2702 bitflips += BITS_PER_BYTE - weight;
2703 if (unlikely(bitflips > bitflips_threshold))
2711 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
2713 * @data: data buffer to test
2714 * @datalen: data length
2716 * @ecclen: ECC length
2717 * @extraoob: extra OOB buffer
2718 * @extraooblen: extra OOB length
2719 * @bitflips_threshold: maximum number of bitflips
2721 * Check if a data buffer and its associated ECC and OOB data contains only
2722 * 0xff pattern, which means the underlying region has been erased and is
2723 * ready to be programmed.
2724 * The bitflips_threshold specify the maximum number of bitflips before
2725 * considering the region as not erased.
2728 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
2729 * different from the NAND page size. When fixing bitflips, ECC engines will
2730 * report the number of errors per chunk, and the NAND core infrastructure
2731 * expect you to return the maximum number of bitflips for the whole page.
2732 * This is why you should always use this function on a single chunk and
2733 * not on the whole page. After checking each chunk you should update your
2734 * max_bitflips value accordingly.
2735 * 2/ When checking for bitflips in erased pages you should not only check
2736 * the payload data but also their associated ECC data, because a user might
2737 * have programmed almost all bits to 1 but a few. In this case, we
2738 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
2740 * 3/ The extraoob argument is optional, and should be used if some of your OOB
2741 * data are protected by the ECC engine.
2742 * It could also be used if you support subpages and want to attach some
2743 * extra OOB data to an ECC chunk.
2745 * Returns a positive number of bitflips less than or equal to
2746 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2747 * threshold. In case of success, the passed buffers are filled with 0xff.
2749 int nand_check_erased_ecc_chunk(void *data, int datalen,
2750 void *ecc, int ecclen,
2751 void *extraoob, int extraooblen,
2752 int bitflips_threshold)
2754 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
2756 data_bitflips = nand_check_erased_buf(data, datalen,
2757 bitflips_threshold);
2758 if (data_bitflips < 0)
2759 return data_bitflips;
2761 bitflips_threshold -= data_bitflips;
2763 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
2764 if (ecc_bitflips < 0)
2765 return ecc_bitflips;
2767 bitflips_threshold -= ecc_bitflips;
2769 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
2770 bitflips_threshold);
2771 if (extraoob_bitflips < 0)
2772 return extraoob_bitflips;
2775 memset(data, 0xff, datalen);
2778 memset(ecc, 0xff, ecclen);
2780 if (extraoob_bitflips)
2781 memset(extraoob, 0xff, extraooblen);
2783 return data_bitflips + ecc_bitflips + extraoob_bitflips;
2785 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
2788 * nand_read_page_raw_notsupp - dummy read raw page function
2789 * @chip: nand chip info structure
2790 * @buf: buffer to store read data
2791 * @oob_required: caller requires OOB data read to chip->oob_poi
2792 * @page: page number to read
2794 * Returns -ENOTSUPP unconditionally.
2796 int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf,
2797 int oob_required, int page)
2803 * nand_read_page_raw - [INTERN] read raw page data without ecc
2804 * @chip: nand chip info structure
2805 * @buf: buffer to store read data
2806 * @oob_required: caller requires OOB data read to chip->oob_poi
2807 * @page: page number to read
2809 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2811 int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
2814 struct mtd_info *mtd = nand_to_mtd(chip);
2817 ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
2822 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
2830 EXPORT_SYMBOL(nand_read_page_raw);
2833 * nand_monolithic_read_page_raw - Monolithic page read in raw mode
2834 * @chip: NAND chip info structure
2835 * @buf: buffer to store read data
2836 * @oob_required: caller requires OOB data read to chip->oob_poi
2837 * @page: page number to read
2839 * This is a raw page read, ie. without any error detection/correction.
2840 * Monolithic means we are requesting all the relevant data (main plus
2841 * eventually OOB) to be loaded in the NAND cache and sent over the
2842 * bus (from the NAND chip to the NAND controller) in a single
2843 * operation. This is an alternative to nand_read_page_raw(), which
2844 * first reads the main data, and if the OOB data is requested too,
2845 * then reads more data on the bus.
2847 int nand_monolithic_read_page_raw(struct nand_chip *chip, u8 *buf,
2848 int oob_required, int page)
2850 struct mtd_info *mtd = nand_to_mtd(chip);
2851 unsigned int size = mtd->writesize;
2856 size += mtd->oobsize;
2858 if (buf != chip->data_buf)
2859 read_buf = nand_get_data_buf(chip);
2862 ret = nand_read_page_op(chip, page, 0, read_buf, size);
2866 if (buf != chip->data_buf)
2867 memcpy(buf, read_buf, mtd->writesize);
2871 EXPORT_SYMBOL(nand_monolithic_read_page_raw);
2874 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
2875 * @chip: nand chip info structure
2876 * @buf: buffer to store read data
2877 * @oob_required: caller requires OOB data read to chip->oob_poi
2878 * @page: page number to read
2880 * We need a special oob layout and handling even when OOB isn't used.
2882 static int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf,
2883 int oob_required, int page)
2885 struct mtd_info *mtd = nand_to_mtd(chip);
2886 int eccsize = chip->ecc.size;
2887 int eccbytes = chip->ecc.bytes;
2888 uint8_t *oob = chip->oob_poi;
2889 int steps, size, ret;
2891 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2895 for (steps = chip->ecc.steps; steps > 0; steps--) {
2896 ret = nand_read_data_op(chip, buf, eccsize, false, false);
2902 if (chip->ecc.prepad) {
2903 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2908 oob += chip->ecc.prepad;
2911 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
2917 if (chip->ecc.postpad) {
2918 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2923 oob += chip->ecc.postpad;
2927 size = mtd->oobsize - (oob - chip->oob_poi);
2929 ret = nand_read_data_op(chip, oob, size, false, false);
2938 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
2939 * @chip: nand chip info structure
2940 * @buf: buffer to store read data
2941 * @oob_required: caller requires OOB data read to chip->oob_poi
2942 * @page: page number to read
2944 static int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf,
2945 int oob_required, int page)
2947 struct mtd_info *mtd = nand_to_mtd(chip);
2948 int i, eccsize = chip->ecc.size, ret;
2949 int eccbytes = chip->ecc.bytes;
2950 int eccsteps = chip->ecc.steps;
2952 uint8_t *ecc_calc = chip->ecc.calc_buf;
2953 uint8_t *ecc_code = chip->ecc.code_buf;
2954 unsigned int max_bitflips = 0;
2956 chip->ecc.read_page_raw(chip, buf, 1, page);
2958 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2959 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2961 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2966 eccsteps = chip->ecc.steps;
2969 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2972 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
2974 mtd->ecc_stats.failed++;
2976 mtd->ecc_stats.corrected += stat;
2977 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2980 return max_bitflips;
2984 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
2985 * @chip: nand chip info structure
2986 * @data_offs: offset of requested data within the page
2987 * @readlen: data length
2988 * @bufpoi: buffer to store read data
2989 * @page: page number to read
2991 static int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs,
2992 uint32_t readlen, uint8_t *bufpoi, int page)
2994 struct mtd_info *mtd = nand_to_mtd(chip);
2995 int start_step, end_step, num_steps, ret;
2997 int data_col_addr, i, gaps = 0;
2998 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
2999 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
3000 int index, section = 0;
3001 unsigned int max_bitflips = 0;
3002 struct mtd_oob_region oobregion = { };
3004 /* Column address within the page aligned to ECC size (256bytes) */
3005 start_step = data_offs / chip->ecc.size;
3006 end_step = (data_offs + readlen - 1) / chip->ecc.size;
3007 num_steps = end_step - start_step + 1;
3008 index = start_step * chip->ecc.bytes;
3010 /* Data size aligned to ECC ecc.size */
3011 datafrag_len = num_steps * chip->ecc.size;
3012 eccfrag_len = num_steps * chip->ecc.bytes;
3014 data_col_addr = start_step * chip->ecc.size;
3015 /* If we read not a page aligned data */
3016 p = bufpoi + data_col_addr;
3017 ret = nand_read_page_op(chip, page, data_col_addr, p, datafrag_len);
3022 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
3023 chip->ecc.calculate(chip, p, &chip->ecc.calc_buf[i]);
3026 * The performance is faster if we position offsets according to
3027 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
3029 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
3033 if (oobregion.length < eccfrag_len)
3037 ret = nand_change_read_column_op(chip, mtd->writesize,
3038 chip->oob_poi, mtd->oobsize,
3044 * Send the command to read the particular ECC bytes take care
3045 * about buswidth alignment in read_buf.
3047 aligned_pos = oobregion.offset & ~(busw - 1);
3048 aligned_len = eccfrag_len;
3049 if (oobregion.offset & (busw - 1))
3051 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
3055 ret = nand_change_read_column_op(chip,
3056 mtd->writesize + aligned_pos,
3057 &chip->oob_poi[aligned_pos],
3058 aligned_len, false);
3063 ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
3064 chip->oob_poi, index, eccfrag_len);
3068 p = bufpoi + data_col_addr;
3069 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
3072 stat = chip->ecc.correct(chip, p, &chip->ecc.code_buf[i],
3073 &chip->ecc.calc_buf[i]);
3074 if (stat == -EBADMSG &&
3075 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3076 /* check for empty pages with bitflips */
3077 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3078 &chip->ecc.code_buf[i],
3081 chip->ecc.strength);
3085 mtd->ecc_stats.failed++;
3087 mtd->ecc_stats.corrected += stat;
3088 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3091 return max_bitflips;
3095 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
3096 * @chip: nand chip info structure
3097 * @buf: buffer to store read data
3098 * @oob_required: caller requires OOB data read to chip->oob_poi
3099 * @page: page number to read
3101 * Not for syndrome calculating ECC controllers which need a special oob layout.
3103 static int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf,
3104 int oob_required, int page)
3106 struct mtd_info *mtd = nand_to_mtd(chip);
3107 int i, eccsize = chip->ecc.size, ret;
3108 int eccbytes = chip->ecc.bytes;
3109 int eccsteps = chip->ecc.steps;
3111 uint8_t *ecc_calc = chip->ecc.calc_buf;
3112 uint8_t *ecc_code = chip->ecc.code_buf;
3113 unsigned int max_bitflips = 0;
3115 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3119 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3120 chip->ecc.hwctl(chip, NAND_ECC_READ);
3122 ret = nand_read_data_op(chip, p, eccsize, false, false);
3126 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3129 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false,
3134 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3139 eccsteps = chip->ecc.steps;
3142 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3145 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
3146 if (stat == -EBADMSG &&
3147 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3148 /* check for empty pages with bitflips */
3149 stat = nand_check_erased_ecc_chunk(p, eccsize,
3150 &ecc_code[i], eccbytes,
3152 chip->ecc.strength);
3156 mtd->ecc_stats.failed++;
3158 mtd->ecc_stats.corrected += stat;
3159 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3162 return max_bitflips;
3166 * nand_read_page_hwecc_oob_first - Hardware ECC page read with ECC
3167 * data read from OOB area
3168 * @chip: nand chip info structure
3169 * @buf: buffer to store read data
3170 * @oob_required: caller requires OOB data read to chip->oob_poi
3171 * @page: page number to read
3173 * Hardware ECC for large page chips, which requires the ECC data to be
3174 * extracted from the OOB before the actual data is read.
3176 int nand_read_page_hwecc_oob_first(struct nand_chip *chip, uint8_t *buf,
3177 int oob_required, int page)
3179 struct mtd_info *mtd = nand_to_mtd(chip);
3180 int i, eccsize = chip->ecc.size, ret;
3181 int eccbytes = chip->ecc.bytes;
3182 int eccsteps = chip->ecc.steps;
3184 uint8_t *ecc_code = chip->ecc.code_buf;
3185 unsigned int max_bitflips = 0;
3187 /* Read the OOB area first */
3188 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3192 /* Move read cursor to start of page */
3193 ret = nand_change_read_column_op(chip, 0, NULL, 0, false);
3197 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3202 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3205 chip->ecc.hwctl(chip, NAND_ECC_READ);
3207 ret = nand_read_data_op(chip, p, eccsize, false, false);
3211 stat = chip->ecc.correct(chip, p, &ecc_code[i], NULL);
3212 if (stat == -EBADMSG &&
3213 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3214 /* check for empty pages with bitflips */
3215 stat = nand_check_erased_ecc_chunk(p, eccsize,
3218 chip->ecc.strength);
3222 mtd->ecc_stats.failed++;
3224 mtd->ecc_stats.corrected += stat;
3225 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3228 return max_bitflips;
3230 EXPORT_SYMBOL_GPL(nand_read_page_hwecc_oob_first);
3233 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
3234 * @chip: nand chip info structure
3235 * @buf: buffer to store read data
3236 * @oob_required: caller requires OOB data read to chip->oob_poi
3237 * @page: page number to read
3239 * The hw generator calculates the error syndrome automatically. Therefore we
3240 * need a special oob layout and handling.
3242 static int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf,
3243 int oob_required, int page)
3245 struct mtd_info *mtd = nand_to_mtd(chip);
3246 int ret, i, eccsize = chip->ecc.size;
3247 int eccbytes = chip->ecc.bytes;
3248 int eccsteps = chip->ecc.steps;
3249 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
3251 uint8_t *oob = chip->oob_poi;
3252 unsigned int max_bitflips = 0;
3254 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3258 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3261 chip->ecc.hwctl(chip, NAND_ECC_READ);
3263 ret = nand_read_data_op(chip, p, eccsize, false, false);
3267 if (chip->ecc.prepad) {
3268 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3273 oob += chip->ecc.prepad;
3276 chip->ecc.hwctl(chip, NAND_ECC_READSYN);
3278 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
3282 stat = chip->ecc.correct(chip, p, oob, NULL);
3286 if (chip->ecc.postpad) {
3287 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3292 oob += chip->ecc.postpad;
3295 if (stat == -EBADMSG &&
3296 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3297 /* check for empty pages with bitflips */
3298 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3302 chip->ecc.strength);
3306 mtd->ecc_stats.failed++;
3308 mtd->ecc_stats.corrected += stat;
3309 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3313 /* Calculate remaining oob bytes */
3314 i = mtd->oobsize - (oob - chip->oob_poi);
3316 ret = nand_read_data_op(chip, oob, i, false, false);
3321 return max_bitflips;
3325 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
3326 * @chip: NAND chip object
3327 * @oob: oob destination address
3328 * @ops: oob ops structure
3329 * @len: size of oob to transfer
3331 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
3332 struct mtd_oob_ops *ops, size_t len)
3334 struct mtd_info *mtd = nand_to_mtd(chip);
3337 switch (ops->mode) {
3339 case MTD_OPS_PLACE_OOB:
3341 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
3344 case MTD_OPS_AUTO_OOB:
3345 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
3357 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
3358 * @chip: NAND chip object
3359 * @retry_mode: the retry mode to use
3361 * Some vendors supply a special command to shift the Vt threshold, to be used
3362 * when there are too many bitflips in a page (i.e., ECC error). After setting
3363 * a new threshold, the host should retry reading the page.
3365 static int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
3367 pr_debug("setting READ RETRY mode %d\n", retry_mode);
3369 if (retry_mode >= chip->read_retries)
3372 if (!chip->ops.setup_read_retry)
3375 return chip->ops.setup_read_retry(chip, retry_mode);
3378 static void nand_wait_readrdy(struct nand_chip *chip)
3380 const struct nand_interface_config *conf;
3382 if (!(chip->options & NAND_NEED_READRDY))
3385 conf = nand_get_interface_config(chip);
3386 WARN_ON(nand_wait_rdy_op(chip, NAND_COMMON_TIMING_MS(conf, tR_max), 0));
3390 * nand_do_read_ops - [INTERN] Read data with ECC
3391 * @chip: NAND chip object
3392 * @from: offset to read from
3393 * @ops: oob ops structure
3395 * Internal function. Called with chip held.
3397 static int nand_do_read_ops(struct nand_chip *chip, loff_t from,
3398 struct mtd_oob_ops *ops)
3400 int chipnr, page, realpage, col, bytes, aligned, oob_required;
3401 struct mtd_info *mtd = nand_to_mtd(chip);
3403 uint32_t readlen = ops->len;
3404 uint32_t oobreadlen = ops->ooblen;
3405 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
3407 uint8_t *bufpoi, *oob, *buf;
3409 unsigned int max_bitflips = 0;
3411 bool ecc_fail = false;
3413 /* Check if the region is secured */
3414 if (nand_region_is_secured(chip, from, readlen))
3417 chipnr = (int)(from >> chip->chip_shift);
3418 nand_select_target(chip, chipnr);
3420 realpage = (int)(from >> chip->page_shift);
3421 page = realpage & chip->pagemask;
3423 col = (int)(from & (mtd->writesize - 1));
3427 oob_required = oob ? 1 : 0;
3430 struct mtd_ecc_stats ecc_stats = mtd->ecc_stats;
3432 bytes = min(mtd->writesize - col, readlen);
3433 aligned = (bytes == mtd->writesize);
3437 else if (chip->options & NAND_USES_DMA)
3438 use_bounce_buf = !virt_addr_valid(buf) ||
3439 !IS_ALIGNED((unsigned long)buf,
3444 /* Is the current page in the buffer? */
3445 if (realpage != chip->pagecache.page || oob) {
3446 bufpoi = use_bounce_buf ? chip->data_buf : buf;
3448 if (use_bounce_buf && aligned)
3449 pr_debug("%s: using read bounce buffer for buf@%p\n",
3454 * Now read the page into the buffer. Absent an error,
3455 * the read methods return max bitflips per ecc step.
3457 if (unlikely(ops->mode == MTD_OPS_RAW))
3458 ret = chip->ecc.read_page_raw(chip, bufpoi,
3461 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
3463 ret = chip->ecc.read_subpage(chip, col, bytes,
3466 ret = chip->ecc.read_page(chip, bufpoi,
3467 oob_required, page);
3470 /* Invalidate page cache */
3471 chip->pagecache.page = -1;
3476 * Copy back the data in the initial buffer when reading
3477 * partial pages or when a bounce buffer is required.
3479 if (use_bounce_buf) {
3480 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
3481 !(mtd->ecc_stats.failed - ecc_stats.failed) &&
3482 (ops->mode != MTD_OPS_RAW)) {
3483 chip->pagecache.page = realpage;
3484 chip->pagecache.bitflips = ret;
3486 /* Invalidate page cache */
3487 chip->pagecache.page = -1;
3489 memcpy(buf, bufpoi + col, bytes);
3492 if (unlikely(oob)) {
3493 int toread = min(oobreadlen, max_oobsize);
3496 oob = nand_transfer_oob(chip, oob, ops,
3498 oobreadlen -= toread;
3502 nand_wait_readrdy(chip);
3504 if (mtd->ecc_stats.failed - ecc_stats.failed) {
3505 if (retry_mode + 1 < chip->read_retries) {
3507 ret = nand_setup_read_retry(chip,
3512 /* Reset ecc_stats; retry */
3513 mtd->ecc_stats = ecc_stats;
3516 /* No more retry modes; real failure */
3522 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3524 memcpy(buf, chip->data_buf + col, bytes);
3526 max_bitflips = max_t(unsigned int, max_bitflips,
3527 chip->pagecache.bitflips);
3532 /* Reset to retry mode 0 */
3534 ret = nand_setup_read_retry(chip, 0);
3543 /* For subsequent reads align to page boundary */
3545 /* Increment page address */
3548 page = realpage & chip->pagemask;
3549 /* Check, if we cross a chip boundary */
3552 nand_deselect_target(chip);
3553 nand_select_target(chip, chipnr);
3556 nand_deselect_target(chip);
3558 ops->retlen = ops->len - (size_t) readlen;
3560 ops->oobretlen = ops->ooblen - oobreadlen;
3568 return max_bitflips;
3572 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
3573 * @chip: nand chip info structure
3574 * @page: page number to read
3576 int nand_read_oob_std(struct nand_chip *chip, int page)
3578 struct mtd_info *mtd = nand_to_mtd(chip);
3580 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3582 EXPORT_SYMBOL(nand_read_oob_std);
3585 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
3587 * @chip: nand chip info structure
3588 * @page: page number to read
3590 static int nand_read_oob_syndrome(struct nand_chip *chip, int page)
3592 struct mtd_info *mtd = nand_to_mtd(chip);
3593 int length = mtd->oobsize;
3594 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3595 int eccsize = chip->ecc.size;
3596 uint8_t *bufpoi = chip->oob_poi;
3597 int i, toread, sndrnd = 0, pos, ret;
3599 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
3603 for (i = 0; i < chip->ecc.steps; i++) {
3607 pos = eccsize + i * (eccsize + chunk);
3608 if (mtd->writesize > 512)
3609 ret = nand_change_read_column_op(chip, pos,
3613 ret = nand_read_page_op(chip, page, pos, NULL,
3620 toread = min_t(int, length, chunk);
3622 ret = nand_read_data_op(chip, bufpoi, toread, false, false);
3630 ret = nand_read_data_op(chip, bufpoi, length, false, false);
3639 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
3640 * @chip: nand chip info structure
3641 * @page: page number to write
3643 int nand_write_oob_std(struct nand_chip *chip, int page)
3645 struct mtd_info *mtd = nand_to_mtd(chip);
3647 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
3650 EXPORT_SYMBOL(nand_write_oob_std);
3653 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
3654 * with syndrome - only for large page flash
3655 * @chip: nand chip info structure
3656 * @page: page number to write
3658 static int nand_write_oob_syndrome(struct nand_chip *chip, int page)
3660 struct mtd_info *mtd = nand_to_mtd(chip);
3661 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3662 int eccsize = chip->ecc.size, length = mtd->oobsize;
3663 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
3664 const uint8_t *bufpoi = chip->oob_poi;
3667 * data-ecc-data-ecc ... ecc-oob
3669 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
3671 if (!chip->ecc.prepad && !chip->ecc.postpad) {
3672 pos = steps * (eccsize + chunk);
3677 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
3681 for (i = 0; i < steps; i++) {
3683 if (mtd->writesize <= 512) {
3684 uint32_t fill = 0xFFFFFFFF;
3688 int num = min_t(int, len, 4);
3690 ret = nand_write_data_op(chip, &fill,
3698 pos = eccsize + i * (eccsize + chunk);
3699 ret = nand_change_write_column_op(chip, pos,
3707 len = min_t(int, length, chunk);
3709 ret = nand_write_data_op(chip, bufpoi, len, false);
3717 ret = nand_write_data_op(chip, bufpoi, length, false);
3722 return nand_prog_page_end_op(chip);
3726 * nand_do_read_oob - [INTERN] NAND read out-of-band
3727 * @chip: NAND chip object
3728 * @from: offset to read from
3729 * @ops: oob operations description structure
3731 * NAND read out-of-band data from the spare area.
3733 static int nand_do_read_oob(struct nand_chip *chip, loff_t from,
3734 struct mtd_oob_ops *ops)
3736 struct mtd_info *mtd = nand_to_mtd(chip);
3737 unsigned int max_bitflips = 0;
3738 int page, realpage, chipnr;
3739 struct mtd_ecc_stats stats;
3740 int readlen = ops->ooblen;
3742 uint8_t *buf = ops->oobbuf;
3745 pr_debug("%s: from = 0x%08Lx, len = %i\n",
3746 __func__, (unsigned long long)from, readlen);
3748 /* Check if the region is secured */
3749 if (nand_region_is_secured(chip, from, readlen))
3752 stats = mtd->ecc_stats;
3754 len = mtd_oobavail(mtd, ops);
3756 chipnr = (int)(from >> chip->chip_shift);
3757 nand_select_target(chip, chipnr);
3759 /* Shift to get page */
3760 realpage = (int)(from >> chip->page_shift);
3761 page = realpage & chip->pagemask;
3764 if (ops->mode == MTD_OPS_RAW)
3765 ret = chip->ecc.read_oob_raw(chip, page);
3767 ret = chip->ecc.read_oob(chip, page);
3772 len = min(len, readlen);
3773 buf = nand_transfer_oob(chip, buf, ops, len);
3775 nand_wait_readrdy(chip);
3777 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3783 /* Increment page address */
3786 page = realpage & chip->pagemask;
3787 /* Check, if we cross a chip boundary */
3790 nand_deselect_target(chip);
3791 nand_select_target(chip, chipnr);
3794 nand_deselect_target(chip);
3796 ops->oobretlen = ops->ooblen - readlen;
3801 if (mtd->ecc_stats.failed - stats.failed)
3804 return max_bitflips;
3808 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
3809 * @mtd: MTD device structure
3810 * @from: offset to read from
3811 * @ops: oob operation description structure
3813 * NAND read data and/or out-of-band data.
3815 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
3816 struct mtd_oob_ops *ops)
3818 struct nand_chip *chip = mtd_to_nand(mtd);
3819 struct mtd_ecc_stats old_stats;
3824 if (ops->mode != MTD_OPS_PLACE_OOB &&
3825 ops->mode != MTD_OPS_AUTO_OOB &&
3826 ops->mode != MTD_OPS_RAW)
3829 nand_get_device(chip);
3831 old_stats = mtd->ecc_stats;
3834 ret = nand_do_read_oob(chip, from, ops);
3836 ret = nand_do_read_ops(chip, from, ops);
3839 ops->stats->uncorrectable_errors +=
3840 mtd->ecc_stats.failed - old_stats.failed;
3841 ops->stats->corrected_bitflips +=
3842 mtd->ecc_stats.corrected - old_stats.corrected;
3845 nand_release_device(chip);
3850 * nand_write_page_raw_notsupp - dummy raw page write function
3851 * @chip: nand chip info structure
3853 * @oob_required: must write chip->oob_poi to OOB
3854 * @page: page number to write
3856 * Returns -ENOTSUPP unconditionally.
3858 int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf,
3859 int oob_required, int page)
3865 * nand_write_page_raw - [INTERN] raw page write function
3866 * @chip: nand chip info structure
3868 * @oob_required: must write chip->oob_poi to OOB
3869 * @page: page number to write
3871 * Not for syndrome calculating ECC controllers, which use a special oob layout.
3873 int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
3874 int oob_required, int page)
3876 struct mtd_info *mtd = nand_to_mtd(chip);
3879 ret = nand_prog_page_begin_op(chip, page, 0, buf, mtd->writesize);
3884 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
3890 return nand_prog_page_end_op(chip);
3892 EXPORT_SYMBOL(nand_write_page_raw);
3895 * nand_monolithic_write_page_raw - Monolithic page write in raw mode
3896 * @chip: NAND chip info structure
3897 * @buf: data buffer to write
3898 * @oob_required: must write chip->oob_poi to OOB
3899 * @page: page number to write
3901 * This is a raw page write, ie. without any error detection/correction.
3902 * Monolithic means we are requesting all the relevant data (main plus
3903 * eventually OOB) to be sent over the bus and effectively programmed
3904 * into the NAND chip arrays in a single operation. This is an
3905 * alternative to nand_write_page_raw(), which first sends the main
3906 * data, then eventually send the OOB data by latching more data
3907 * cycles on the NAND bus, and finally sends the program command to
3908 * synchronyze the NAND chip cache.
3910 int nand_monolithic_write_page_raw(struct nand_chip *chip, const u8 *buf,
3911 int oob_required, int page)
3913 struct mtd_info *mtd = nand_to_mtd(chip);
3914 unsigned int size = mtd->writesize;
3915 u8 *write_buf = (u8 *)buf;
3918 size += mtd->oobsize;
3920 if (buf != chip->data_buf) {
3921 write_buf = nand_get_data_buf(chip);
3922 memcpy(write_buf, buf, mtd->writesize);
3926 return nand_prog_page_op(chip, page, 0, write_buf, size);
3928 EXPORT_SYMBOL(nand_monolithic_write_page_raw);
3931 * nand_write_page_raw_syndrome - [INTERN] raw page write function
3932 * @chip: nand chip info structure
3934 * @oob_required: must write chip->oob_poi to OOB
3935 * @page: page number to write
3937 * We need a special oob layout and handling even when ECC isn't checked.
3939 static int nand_write_page_raw_syndrome(struct nand_chip *chip,
3940 const uint8_t *buf, int oob_required,
3943 struct mtd_info *mtd = nand_to_mtd(chip);
3944 int eccsize = chip->ecc.size;
3945 int eccbytes = chip->ecc.bytes;
3946 uint8_t *oob = chip->oob_poi;
3947 int steps, size, ret;
3949 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3953 for (steps = chip->ecc.steps; steps > 0; steps--) {
3954 ret = nand_write_data_op(chip, buf, eccsize, false);
3960 if (chip->ecc.prepad) {
3961 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3966 oob += chip->ecc.prepad;
3969 ret = nand_write_data_op(chip, oob, eccbytes, false);
3975 if (chip->ecc.postpad) {
3976 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3981 oob += chip->ecc.postpad;
3985 size = mtd->oobsize - (oob - chip->oob_poi);
3987 ret = nand_write_data_op(chip, oob, size, false);
3992 return nand_prog_page_end_op(chip);
3995 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
3996 * @chip: nand chip info structure
3998 * @oob_required: must write chip->oob_poi to OOB
3999 * @page: page number to write
4001 static int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf,
4002 int oob_required, int page)
4004 struct mtd_info *mtd = nand_to_mtd(chip);
4005 int i, eccsize = chip->ecc.size, ret;
4006 int eccbytes = chip->ecc.bytes;
4007 int eccsteps = chip->ecc.steps;
4008 uint8_t *ecc_calc = chip->ecc.calc_buf;
4009 const uint8_t *p = buf;
4011 /* Software ECC calculation */
4012 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
4013 chip->ecc.calculate(chip, p, &ecc_calc[i]);
4015 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4020 return chip->ecc.write_page_raw(chip, buf, 1, page);
4024 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
4025 * @chip: nand chip info structure
4027 * @oob_required: must write chip->oob_poi to OOB
4028 * @page: page number to write
4030 static int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf,
4031 int oob_required, int page)
4033 struct mtd_info *mtd = nand_to_mtd(chip);
4034 int i, eccsize = chip->ecc.size, ret;
4035 int eccbytes = chip->ecc.bytes;
4036 int eccsteps = chip->ecc.steps;
4037 uint8_t *ecc_calc = chip->ecc.calc_buf;
4038 const uint8_t *p = buf;
4040 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4044 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4045 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4047 ret = nand_write_data_op(chip, p, eccsize, false);
4051 chip->ecc.calculate(chip, p, &ecc_calc[i]);
4054 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4059 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
4063 return nand_prog_page_end_op(chip);
4068 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
4069 * @chip: nand chip info structure
4070 * @offset: column address of subpage within the page
4071 * @data_len: data length
4073 * @oob_required: must write chip->oob_poi to OOB
4074 * @page: page number to write
4076 static int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset,
4077 uint32_t data_len, const uint8_t *buf,
4078 int oob_required, int page)
4080 struct mtd_info *mtd = nand_to_mtd(chip);
4081 uint8_t *oob_buf = chip->oob_poi;
4082 uint8_t *ecc_calc = chip->ecc.calc_buf;
4083 int ecc_size = chip->ecc.size;
4084 int ecc_bytes = chip->ecc.bytes;
4085 int ecc_steps = chip->ecc.steps;
4086 uint32_t start_step = offset / ecc_size;
4087 uint32_t end_step = (offset + data_len - 1) / ecc_size;
4088 int oob_bytes = mtd->oobsize / ecc_steps;
4091 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4095 for (step = 0; step < ecc_steps; step++) {
4096 /* configure controller for WRITE access */
4097 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4099 /* write data (untouched subpages already masked by 0xFF) */
4100 ret = nand_write_data_op(chip, buf, ecc_size, false);
4104 /* mask ECC of un-touched subpages by padding 0xFF */
4105 if ((step < start_step) || (step > end_step))
4106 memset(ecc_calc, 0xff, ecc_bytes);
4108 chip->ecc.calculate(chip, buf, ecc_calc);
4110 /* mask OOB of un-touched subpages by padding 0xFF */
4111 /* if oob_required, preserve OOB metadata of written subpage */
4112 if (!oob_required || (step < start_step) || (step > end_step))
4113 memset(oob_buf, 0xff, oob_bytes);
4116 ecc_calc += ecc_bytes;
4117 oob_buf += oob_bytes;
4120 /* copy calculated ECC for whole page to chip->buffer->oob */
4121 /* this include masked-value(0xFF) for unwritten subpages */
4122 ecc_calc = chip->ecc.calc_buf;
4123 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4128 /* write OOB buffer to NAND device */
4129 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
4133 return nand_prog_page_end_op(chip);
4138 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
4139 * @chip: nand chip info structure
4141 * @oob_required: must write chip->oob_poi to OOB
4142 * @page: page number to write
4144 * The hw generator calculates the error syndrome automatically. Therefore we
4145 * need a special oob layout and handling.
4147 static int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf,
4148 int oob_required, int page)
4150 struct mtd_info *mtd = nand_to_mtd(chip);
4151 int i, eccsize = chip->ecc.size;
4152 int eccbytes = chip->ecc.bytes;
4153 int eccsteps = chip->ecc.steps;
4154 const uint8_t *p = buf;
4155 uint8_t *oob = chip->oob_poi;
4158 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4162 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4163 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4165 ret = nand_write_data_op(chip, p, eccsize, false);
4169 if (chip->ecc.prepad) {
4170 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4175 oob += chip->ecc.prepad;
4178 chip->ecc.calculate(chip, p, oob);
4180 ret = nand_write_data_op(chip, oob, eccbytes, false);
4186 if (chip->ecc.postpad) {
4187 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4192 oob += chip->ecc.postpad;
4196 /* Calculate remaining oob bytes */
4197 i = mtd->oobsize - (oob - chip->oob_poi);
4199 ret = nand_write_data_op(chip, oob, i, false);
4204 return nand_prog_page_end_op(chip);
4208 * nand_write_page - write one page
4209 * @chip: NAND chip descriptor
4210 * @offset: address offset within the page
4211 * @data_len: length of actual data to be written
4212 * @buf: the data to write
4213 * @oob_required: must write chip->oob_poi to OOB
4214 * @page: page number to write
4215 * @raw: use _raw version of write_page
4217 static int nand_write_page(struct nand_chip *chip, uint32_t offset,
4218 int data_len, const uint8_t *buf, int oob_required,
4221 struct mtd_info *mtd = nand_to_mtd(chip);
4222 int status, subpage;
4224 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
4225 chip->ecc.write_subpage)
4226 subpage = offset || (data_len < mtd->writesize);
4231 status = chip->ecc.write_page_raw(chip, buf, oob_required,
4234 status = chip->ecc.write_subpage(chip, offset, data_len, buf,
4235 oob_required, page);
4237 status = chip->ecc.write_page(chip, buf, oob_required, page);
4245 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
4248 * nand_do_write_ops - [INTERN] NAND write with ECC
4249 * @chip: NAND chip object
4250 * @to: offset to write to
4251 * @ops: oob operations description structure
4253 * NAND write with ECC.
4255 static int nand_do_write_ops(struct nand_chip *chip, loff_t to,
4256 struct mtd_oob_ops *ops)
4258 struct mtd_info *mtd = nand_to_mtd(chip);
4259 int chipnr, realpage, page, column;
4260 uint32_t writelen = ops->len;
4262 uint32_t oobwritelen = ops->ooblen;
4263 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
4265 uint8_t *oob = ops->oobbuf;
4266 uint8_t *buf = ops->datbuf;
4268 int oob_required = oob ? 1 : 0;
4274 /* Reject writes, which are not page aligned */
4275 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
4276 pr_notice("%s: attempt to write non page aligned data\n",
4281 /* Check if the region is secured */
4282 if (nand_region_is_secured(chip, to, writelen))
4285 column = to & (mtd->writesize - 1);
4287 chipnr = (int)(to >> chip->chip_shift);
4288 nand_select_target(chip, chipnr);
4290 /* Check, if it is write protected */
4291 if (nand_check_wp(chip)) {
4296 realpage = (int)(to >> chip->page_shift);
4297 page = realpage & chip->pagemask;
4299 /* Invalidate the page cache, when we write to the cached page */
4300 if (to <= ((loff_t)chip->pagecache.page << chip->page_shift) &&
4301 ((loff_t)chip->pagecache.page << chip->page_shift) < (to + ops->len))
4302 chip->pagecache.page = -1;
4304 /* Don't allow multipage oob writes with offset */
4305 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
4311 int bytes = mtd->writesize;
4312 uint8_t *wbuf = buf;
4314 int part_pagewr = (column || writelen < mtd->writesize);
4318 else if (chip->options & NAND_USES_DMA)
4319 use_bounce_buf = !virt_addr_valid(buf) ||
4320 !IS_ALIGNED((unsigned long)buf,
4326 * Copy the data from the initial buffer when doing partial page
4327 * writes or when a bounce buffer is required.
4329 if (use_bounce_buf) {
4330 pr_debug("%s: using write bounce buffer for buf@%p\n",
4333 bytes = min_t(int, bytes - column, writelen);
4334 wbuf = nand_get_data_buf(chip);
4335 memset(wbuf, 0xff, mtd->writesize);
4336 memcpy(&wbuf[column], buf, bytes);
4339 if (unlikely(oob)) {
4340 size_t len = min(oobwritelen, oobmaxlen);
4341 oob = nand_fill_oob(chip, oob, len, ops);
4344 /* We still need to erase leftover OOB data */
4345 memset(chip->oob_poi, 0xff, mtd->oobsize);
4348 ret = nand_write_page(chip, column, bytes, wbuf,
4350 (ops->mode == MTD_OPS_RAW));
4362 page = realpage & chip->pagemask;
4363 /* Check, if we cross a chip boundary */
4366 nand_deselect_target(chip);
4367 nand_select_target(chip, chipnr);
4371 ops->retlen = ops->len - writelen;
4373 ops->oobretlen = ops->ooblen;
4376 nand_deselect_target(chip);
4381 * panic_nand_write - [MTD Interface] NAND write with ECC
4382 * @mtd: MTD device structure
4383 * @to: offset to write to
4384 * @len: number of bytes to write
4385 * @retlen: pointer to variable to store the number of written bytes
4386 * @buf: the data to write
4388 * NAND write with ECC. Used when performing writes in interrupt context, this
4389 * may for example be called by mtdoops when writing an oops while in panic.
4391 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
4392 size_t *retlen, const uint8_t *buf)
4394 struct nand_chip *chip = mtd_to_nand(mtd);
4395 int chipnr = (int)(to >> chip->chip_shift);
4396 struct mtd_oob_ops ops;
4399 nand_select_target(chip, chipnr);
4401 /* Wait for the device to get ready */
4402 panic_nand_wait(chip, 400);
4404 memset(&ops, 0, sizeof(ops));
4406 ops.datbuf = (uint8_t *)buf;
4407 ops.mode = MTD_OPS_PLACE_OOB;
4409 ret = nand_do_write_ops(chip, to, &ops);
4411 *retlen = ops.retlen;
4416 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
4417 * @mtd: MTD device structure
4418 * @to: offset to write to
4419 * @ops: oob operation description structure
4421 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
4422 struct mtd_oob_ops *ops)
4424 struct nand_chip *chip = mtd_to_nand(mtd);
4429 nand_get_device(chip);
4431 switch (ops->mode) {
4432 case MTD_OPS_PLACE_OOB:
4433 case MTD_OPS_AUTO_OOB:
4442 ret = nand_do_write_oob(chip, to, ops);
4444 ret = nand_do_write_ops(chip, to, ops);
4447 nand_release_device(chip);
4452 * nand_erase - [MTD Interface] erase block(s)
4453 * @mtd: MTD device structure
4454 * @instr: erase instruction
4456 * Erase one ore more blocks.
4458 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
4460 return nand_erase_nand(mtd_to_nand(mtd), instr, 0);
4464 * nand_erase_nand - [INTERN] erase block(s)
4465 * @chip: NAND chip object
4466 * @instr: erase instruction
4467 * @allowbbt: allow erasing the bbt area
4469 * Erase one ore more blocks.
4471 int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr,
4474 int page, pages_per_block, ret, chipnr;
4477 pr_debug("%s: start = 0x%012llx, len = %llu\n",
4478 __func__, (unsigned long long)instr->addr,
4479 (unsigned long long)instr->len);
4481 if (check_offs_len(chip, instr->addr, instr->len))
4484 /* Check if the region is secured */
4485 if (nand_region_is_secured(chip, instr->addr, instr->len))
4488 /* Grab the lock and see if the device is available */
4489 nand_get_device(chip);
4491 /* Shift to get first page */
4492 page = (int)(instr->addr >> chip->page_shift);
4493 chipnr = (int)(instr->addr >> chip->chip_shift);
4495 /* Calculate pages in each block */
4496 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
4498 /* Select the NAND device */
4499 nand_select_target(chip, chipnr);
4501 /* Check, if it is write protected */
4502 if (nand_check_wp(chip)) {
4503 pr_debug("%s: device is write protected!\n",
4509 /* Loop through the pages */
4513 loff_t ofs = (loff_t)page << chip->page_shift;
4515 /* Check if we have a bad block, we do not erase bad blocks! */
4516 if (nand_block_checkbad(chip, ((loff_t) page) <<
4517 chip->page_shift, allowbbt)) {
4518 pr_warn("%s: attempt to erase a bad block at 0x%08llx\n",
4519 __func__, (unsigned long long)ofs);
4525 * Invalidate the page cache, if we erase the block which
4526 * contains the current cached page.
4528 if (page <= chip->pagecache.page && chip->pagecache.page <
4529 (page + pages_per_block))
4530 chip->pagecache.page = -1;
4532 ret = nand_erase_op(chip, (page & chip->pagemask) >>
4533 (chip->phys_erase_shift - chip->page_shift));
4535 pr_debug("%s: failed erase, page 0x%08x\n",
4537 instr->fail_addr = ofs;
4541 /* Increment page address and decrement length */
4542 len -= (1ULL << chip->phys_erase_shift);
4543 page += pages_per_block;
4545 /* Check, if we cross a chip boundary */
4546 if (len && !(page & chip->pagemask)) {
4548 nand_deselect_target(chip);
4549 nand_select_target(chip, chipnr);
4556 /* Deselect and wake up anyone waiting on the device */
4557 nand_deselect_target(chip);
4558 nand_release_device(chip);
4560 /* Return more or less happy */
4565 * nand_sync - [MTD Interface] sync
4566 * @mtd: MTD device structure
4568 * Sync is actually a wait for chip ready function.
4570 static void nand_sync(struct mtd_info *mtd)
4572 struct nand_chip *chip = mtd_to_nand(mtd);
4574 pr_debug("%s: called\n", __func__);
4576 /* Grab the lock and see if the device is available */
4577 nand_get_device(chip);
4578 /* Release it and go back */
4579 nand_release_device(chip);
4583 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
4584 * @mtd: MTD device structure
4585 * @offs: offset relative to mtd start
4587 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
4589 struct nand_chip *chip = mtd_to_nand(mtd);
4590 int chipnr = (int)(offs >> chip->chip_shift);
4593 /* Select the NAND device */
4594 nand_get_device(chip);
4596 nand_select_target(chip, chipnr);
4598 ret = nand_block_checkbad(chip, offs, 0);
4600 nand_deselect_target(chip);
4601 nand_release_device(chip);
4607 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
4608 * @mtd: MTD device structure
4609 * @ofs: offset relative to mtd start
4611 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
4615 ret = nand_block_isbad(mtd, ofs);
4617 /* If it was bad already, return success and do nothing */
4623 return nand_block_markbad_lowlevel(mtd_to_nand(mtd), ofs);
4627 * nand_suspend - [MTD Interface] Suspend the NAND flash
4628 * @mtd: MTD device structure
4630 * Returns 0 for success or negative error code otherwise.
4632 static int nand_suspend(struct mtd_info *mtd)
4634 struct nand_chip *chip = mtd_to_nand(mtd);
4637 mutex_lock(&chip->lock);
4638 if (chip->ops.suspend)
4639 ret = chip->ops.suspend(chip);
4641 chip->suspended = 1;
4642 mutex_unlock(&chip->lock);
4648 * nand_resume - [MTD Interface] Resume the NAND flash
4649 * @mtd: MTD device structure
4651 static void nand_resume(struct mtd_info *mtd)
4653 struct nand_chip *chip = mtd_to_nand(mtd);
4655 mutex_lock(&chip->lock);
4656 if (chip->suspended) {
4657 if (chip->ops.resume)
4658 chip->ops.resume(chip);
4659 chip->suspended = 0;
4661 pr_err("%s called for a chip which is not in suspended state\n",
4664 mutex_unlock(&chip->lock);
4666 wake_up_all(&chip->resume_wq);
4670 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
4671 * prevent further operations
4672 * @mtd: MTD device structure
4674 static void nand_shutdown(struct mtd_info *mtd)
4680 * nand_lock - [MTD Interface] Lock the NAND flash
4681 * @mtd: MTD device structure
4682 * @ofs: offset byte address
4683 * @len: number of bytes to lock (must be a multiple of block/page size)
4685 static int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4687 struct nand_chip *chip = mtd_to_nand(mtd);
4689 if (!chip->ops.lock_area)
4692 return chip->ops.lock_area(chip, ofs, len);
4696 * nand_unlock - [MTD Interface] Unlock the NAND flash
4697 * @mtd: MTD device structure
4698 * @ofs: offset byte address
4699 * @len: number of bytes to unlock (must be a multiple of block/page size)
4701 static int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4703 struct nand_chip *chip = mtd_to_nand(mtd);
4705 if (!chip->ops.unlock_area)
4708 return chip->ops.unlock_area(chip, ofs, len);
4711 /* Set default functions */
4712 static void nand_set_defaults(struct nand_chip *chip)
4714 /* If no controller is provided, use the dummy, legacy one. */
4715 if (!chip->controller) {
4716 chip->controller = &chip->legacy.dummy_controller;
4717 nand_controller_init(chip->controller);
4720 nand_legacy_set_defaults(chip);
4722 if (!chip->buf_align)
4723 chip->buf_align = 1;
4726 /* Sanitize ONFI strings so we can safely print them */
4727 void sanitize_string(uint8_t *s, size_t len)
4731 /* Null terminate */
4734 /* Remove non printable chars */
4735 for (i = 0; i < len - 1; i++) {
4736 if (s[i] < ' ' || s[i] > 127)
4740 /* Remove trailing spaces */
4745 * nand_id_has_period - Check if an ID string has a given wraparound period
4746 * @id_data: the ID string
4747 * @arrlen: the length of the @id_data array
4748 * @period: the period of repitition
4750 * Check if an ID string is repeated within a given sequence of bytes at
4751 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4752 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4753 * if the repetition has a period of @period; otherwise, returns zero.
4755 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4758 for (i = 0; i < period; i++)
4759 for (j = i + period; j < arrlen; j += period)
4760 if (id_data[i] != id_data[j])
4766 * nand_id_len - Get the length of an ID string returned by CMD_READID
4767 * @id_data: the ID string
4768 * @arrlen: the length of the @id_data array
4770 * Returns the length of the ID string, according to known wraparound/trailing
4771 * zero patterns. If no pattern exists, returns the length of the array.
4773 static int nand_id_len(u8 *id_data, int arrlen)
4775 int last_nonzero, period;
4777 /* Find last non-zero byte */
4778 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4779 if (id_data[last_nonzero])
4783 if (last_nonzero < 0)
4786 /* Calculate wraparound period */
4787 for (period = 1; period < arrlen; period++)
4788 if (nand_id_has_period(id_data, arrlen, period))
4791 /* There's a repeated pattern */
4792 if (period < arrlen)
4795 /* There are trailing zeros */
4796 if (last_nonzero < arrlen - 1)
4797 return last_nonzero + 1;
4799 /* No pattern detected */
4803 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4804 static int nand_get_bits_per_cell(u8 cellinfo)
4808 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4809 bits >>= NAND_CI_CELLTYPE_SHIFT;
4814 * Many new NAND share similar device ID codes, which represent the size of the
4815 * chip. The rest of the parameters must be decoded according to generic or
4816 * manufacturer-specific "extended ID" decoding patterns.
4818 void nand_decode_ext_id(struct nand_chip *chip)
4820 struct nand_memory_organization *memorg;
4821 struct mtd_info *mtd = nand_to_mtd(chip);
4823 u8 *id_data = chip->id.data;
4825 memorg = nanddev_get_memorg(&chip->base);
4827 /* The 3rd id byte holds MLC / multichip data */
4828 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4829 /* The 4th id byte is the important one */
4833 memorg->pagesize = 1024 << (extid & 0x03);
4834 mtd->writesize = memorg->pagesize;
4837 memorg->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
4838 mtd->oobsize = memorg->oobsize;
4840 /* Calc blocksize. Blocksize is multiples of 64KiB */
4841 memorg->pages_per_eraseblock = ((64 * 1024) << (extid & 0x03)) /
4843 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4845 /* Get buswidth information */
4847 chip->options |= NAND_BUSWIDTH_16;
4849 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
4852 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4853 * decodes a matching ID table entry and assigns the MTD size parameters for
4856 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
4858 struct mtd_info *mtd = nand_to_mtd(chip);
4859 struct nand_memory_organization *memorg;
4861 memorg = nanddev_get_memorg(&chip->base);
4863 memorg->pages_per_eraseblock = type->erasesize / type->pagesize;
4864 mtd->erasesize = type->erasesize;
4865 memorg->pagesize = type->pagesize;
4866 mtd->writesize = memorg->pagesize;
4867 memorg->oobsize = memorg->pagesize / 32;
4868 mtd->oobsize = memorg->oobsize;
4870 /* All legacy ID NAND are small-page, SLC */
4871 memorg->bits_per_cell = 1;
4875 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4876 * heuristic patterns using various detected parameters (e.g., manufacturer,
4877 * page size, cell-type information).
4879 static void nand_decode_bbm_options(struct nand_chip *chip)
4881 struct mtd_info *mtd = nand_to_mtd(chip);
4883 /* Set the bad block position */
4884 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4885 chip->badblockpos = NAND_BBM_POS_LARGE;
4887 chip->badblockpos = NAND_BBM_POS_SMALL;
4890 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4892 return type->id_len;
4895 static bool find_full_id_nand(struct nand_chip *chip,
4896 struct nand_flash_dev *type)
4898 struct nand_device *base = &chip->base;
4899 struct nand_ecc_props requirements;
4900 struct mtd_info *mtd = nand_to_mtd(chip);
4901 struct nand_memory_organization *memorg;
4902 u8 *id_data = chip->id.data;
4904 memorg = nanddev_get_memorg(&chip->base);
4906 if (!strncmp(type->id, id_data, type->id_len)) {
4907 memorg->pagesize = type->pagesize;
4908 mtd->writesize = memorg->pagesize;
4909 memorg->pages_per_eraseblock = type->erasesize /
4911 mtd->erasesize = type->erasesize;
4912 memorg->oobsize = type->oobsize;
4913 mtd->oobsize = memorg->oobsize;
4915 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4916 memorg->eraseblocks_per_lun =
4917 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4919 memorg->pages_per_eraseblock);
4920 chip->options |= type->options;
4921 requirements.strength = NAND_ECC_STRENGTH(type);
4922 requirements.step_size = NAND_ECC_STEP(type);
4923 nanddev_set_ecc_requirements(base, &requirements);
4925 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4926 if (!chip->parameters.model)
4935 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
4936 * compliant and does not have a full-id or legacy-id entry in the nand_ids
4939 static void nand_manufacturer_detect(struct nand_chip *chip)
4942 * Try manufacturer detection if available and use
4943 * nand_decode_ext_id() otherwise.
4945 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4946 chip->manufacturer.desc->ops->detect) {
4947 struct nand_memory_organization *memorg;
4949 memorg = nanddev_get_memorg(&chip->base);
4951 /* The 3rd id byte holds MLC / multichip data */
4952 memorg->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
4953 chip->manufacturer.desc->ops->detect(chip);
4955 nand_decode_ext_id(chip);
4960 * Manufacturer initialization. This function is called for all NANDs including
4961 * ONFI and JEDEC compliant ones.
4962 * Manufacturer drivers should put all their specific initialization code in
4963 * their ->init() hook.
4965 static int nand_manufacturer_init(struct nand_chip *chip)
4967 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
4968 !chip->manufacturer.desc->ops->init)
4971 return chip->manufacturer.desc->ops->init(chip);
4975 * Manufacturer cleanup. This function is called for all NANDs including
4976 * ONFI and JEDEC compliant ones.
4977 * Manufacturer drivers should put all their specific cleanup code in their
4980 static void nand_manufacturer_cleanup(struct nand_chip *chip)
4982 /* Release manufacturer private data */
4983 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4984 chip->manufacturer.desc->ops->cleanup)
4985 chip->manufacturer.desc->ops->cleanup(chip);
4989 nand_manufacturer_name(const struct nand_manufacturer_desc *manufacturer_desc)
4991 return manufacturer_desc ? manufacturer_desc->name : "Unknown";
4995 * Get the flash and manufacturer id and lookup if the type is supported.
4997 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
4999 const struct nand_manufacturer_desc *manufacturer_desc;
5000 struct mtd_info *mtd = nand_to_mtd(chip);
5001 struct nand_memory_organization *memorg;
5003 u8 *id_data = chip->id.data;
5008 * Let's start by initializing memorg fields that might be left
5009 * unassigned by the ID-based detection logic.
5011 memorg = nanddev_get_memorg(&chip->base);
5012 memorg->planes_per_lun = 1;
5013 memorg->luns_per_target = 1;
5016 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
5019 ret = nand_reset(chip, 0);
5023 /* Select the device */
5024 nand_select_target(chip, 0);
5026 /* Send the command for reading device ID */
5027 ret = nand_readid_op(chip, 0, id_data, 2);
5031 /* Read manufacturer and device IDs */
5032 maf_id = id_data[0];
5033 dev_id = id_data[1];
5036 * Try again to make sure, as some systems the bus-hold or other
5037 * interface concerns can cause random data which looks like a
5038 * possibly credible NAND flash to appear. If the two results do
5039 * not match, ignore the device completely.
5042 /* Read entire ID string */
5043 ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
5047 if (id_data[0] != maf_id || id_data[1] != dev_id) {
5048 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
5049 maf_id, dev_id, id_data[0], id_data[1]);
5053 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
5055 /* Try to identify manufacturer */
5056 manufacturer_desc = nand_get_manufacturer_desc(maf_id);
5057 chip->manufacturer.desc = manufacturer_desc;
5060 type = nand_flash_ids;
5063 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
5065 * This is required to make sure initial NAND bus width set by the
5066 * NAND controller driver is coherent with the real NAND bus width
5067 * (extracted by auto-detection code).
5069 busw = chip->options & NAND_BUSWIDTH_16;
5072 * The flag is only set (never cleared), reset it to its default value
5073 * before starting auto-detection.
5075 chip->options &= ~NAND_BUSWIDTH_16;
5077 for (; type->name != NULL; type++) {
5078 if (is_full_id_nand(type)) {
5079 if (find_full_id_nand(chip, type))
5081 } else if (dev_id == type->dev_id) {
5086 if (!type->name || !type->pagesize) {
5087 /* Check if the chip is ONFI compliant */
5088 ret = nand_onfi_detect(chip);
5094 /* Check if the chip is JEDEC compliant */
5095 ret = nand_jedec_detect(chip);
5105 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
5106 if (!chip->parameters.model)
5109 if (!type->pagesize)
5110 nand_manufacturer_detect(chip);
5112 nand_decode_id(chip, type);
5114 /* Get chip options */
5115 chip->options |= type->options;
5117 memorg->eraseblocks_per_lun =
5118 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
5120 memorg->pages_per_eraseblock);
5124 mtd->name = chip->parameters.model;
5126 if (chip->options & NAND_BUSWIDTH_AUTO) {
5127 WARN_ON(busw & NAND_BUSWIDTH_16);
5128 nand_set_defaults(chip);
5129 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
5131 * Check, if buswidth is correct. Hardware drivers should set
5134 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5136 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
5138 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
5139 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
5142 goto free_detect_allocation;
5145 nand_decode_bbm_options(chip);
5147 /* Calculate the address shift from the page size */
5148 chip->page_shift = ffs(mtd->writesize) - 1;
5149 /* Convert chipsize to number of pages per chip -1 */
5150 targetsize = nanddev_target_size(&chip->base);
5151 chip->pagemask = (targetsize >> chip->page_shift) - 1;
5153 chip->bbt_erase_shift = chip->phys_erase_shift =
5154 ffs(mtd->erasesize) - 1;
5155 if (targetsize & 0xffffffff)
5156 chip->chip_shift = ffs((unsigned)targetsize) - 1;
5158 chip->chip_shift = ffs((unsigned)(targetsize >> 32));
5159 chip->chip_shift += 32 - 1;
5162 if (chip->chip_shift - chip->page_shift > 16)
5163 chip->options |= NAND_ROW_ADDR_3;
5165 chip->badblockbits = 8;
5167 nand_legacy_adjust_cmdfunc(chip);
5169 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5171 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
5172 chip->parameters.model);
5173 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
5174 (int)(targetsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
5175 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
5178 free_detect_allocation:
5179 kfree(chip->parameters.model);
5184 static enum nand_ecc_engine_type
5185 of_get_rawnand_ecc_engine_type_legacy(struct device_node *np)
5187 enum nand_ecc_legacy_mode {
5193 NAND_ECC_HW_SYNDROME,
5196 const char * const nand_ecc_legacy_modes[] = {
5197 [NAND_ECC_NONE] = "none",
5198 [NAND_ECC_SOFT] = "soft",
5199 [NAND_ECC_SOFT_BCH] = "soft_bch",
5200 [NAND_ECC_HW] = "hw",
5201 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
5202 [NAND_ECC_ON_DIE] = "on-die",
5204 enum nand_ecc_legacy_mode eng_type;
5208 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5210 return NAND_ECC_ENGINE_TYPE_INVALID;
5212 for (eng_type = NAND_ECC_NONE;
5213 eng_type < ARRAY_SIZE(nand_ecc_legacy_modes); eng_type++) {
5214 if (!strcasecmp(pm, nand_ecc_legacy_modes[eng_type])) {
5217 return NAND_ECC_ENGINE_TYPE_NONE;
5219 case NAND_ECC_SOFT_BCH:
5220 return NAND_ECC_ENGINE_TYPE_SOFT;
5222 case NAND_ECC_HW_SYNDROME:
5223 return NAND_ECC_ENGINE_TYPE_ON_HOST;
5224 case NAND_ECC_ON_DIE:
5225 return NAND_ECC_ENGINE_TYPE_ON_DIE;
5232 return NAND_ECC_ENGINE_TYPE_INVALID;
5235 static enum nand_ecc_placement
5236 of_get_rawnand_ecc_placement_legacy(struct device_node *np)
5241 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5243 if (!strcasecmp(pm, "hw_syndrome"))
5244 return NAND_ECC_PLACEMENT_INTERLEAVED;
5247 return NAND_ECC_PLACEMENT_UNKNOWN;
5250 static enum nand_ecc_algo of_get_rawnand_ecc_algo_legacy(struct device_node *np)
5255 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5257 if (!strcasecmp(pm, "soft"))
5258 return NAND_ECC_ALGO_HAMMING;
5259 else if (!strcasecmp(pm, "soft_bch"))
5260 return NAND_ECC_ALGO_BCH;
5263 return NAND_ECC_ALGO_UNKNOWN;
5266 static void of_get_nand_ecc_legacy_user_config(struct nand_chip *chip)
5268 struct device_node *dn = nand_get_flash_node(chip);
5269 struct nand_ecc_props *user_conf = &chip->base.ecc.user_conf;
5271 if (user_conf->engine_type == NAND_ECC_ENGINE_TYPE_INVALID)
5272 user_conf->engine_type = of_get_rawnand_ecc_engine_type_legacy(dn);
5274 if (user_conf->algo == NAND_ECC_ALGO_UNKNOWN)
5275 user_conf->algo = of_get_rawnand_ecc_algo_legacy(dn);
5277 if (user_conf->placement == NAND_ECC_PLACEMENT_UNKNOWN)
5278 user_conf->placement = of_get_rawnand_ecc_placement_legacy(dn);
5281 static int of_get_nand_bus_width(struct nand_chip *chip)
5283 struct device_node *dn = nand_get_flash_node(chip);
5287 ret = of_property_read_u32(dn, "nand-bus-width", &val);
5289 /* Buswidth defaults to 8 if the property does not exist .*/
5295 chip->options |= NAND_BUSWIDTH_16;
5301 static int of_get_nand_secure_regions(struct nand_chip *chip)
5303 struct device_node *dn = nand_get_flash_node(chip);
5304 struct property *prop;
5307 /* Only proceed if the "secure-regions" property is present in DT */
5308 prop = of_find_property(dn, "secure-regions", NULL);
5312 nr_elem = of_property_count_elems_of_size(dn, "secure-regions", sizeof(u64));
5316 chip->nr_secure_regions = nr_elem / 2;
5317 chip->secure_regions = kcalloc(chip->nr_secure_regions, sizeof(*chip->secure_regions),
5319 if (!chip->secure_regions)
5322 for (i = 0, j = 0; i < chip->nr_secure_regions; i++, j += 2) {
5323 of_property_read_u64_index(dn, "secure-regions", j,
5324 &chip->secure_regions[i].offset);
5325 of_property_read_u64_index(dn, "secure-regions", j + 1,
5326 &chip->secure_regions[i].size);
5333 * rawnand_dt_parse_gpio_cs - Parse the gpio-cs property of a controller
5334 * @dev: Device that will be parsed. Also used for managed allocations.
5335 * @cs_array: Array of GPIO desc pointers allocated on success
5336 * @ncs_array: Number of entries in @cs_array updated on success.
5337 * @return 0 on success, an error otherwise.
5339 int rawnand_dt_parse_gpio_cs(struct device *dev, struct gpio_desc ***cs_array,
5340 unsigned int *ncs_array)
5342 struct gpio_desc **descs;
5345 ndescs = gpiod_count(dev, "cs");
5347 dev_dbg(dev, "No valid cs-gpios property\n");
5351 descs = devm_kcalloc(dev, ndescs, sizeof(*descs), GFP_KERNEL);
5355 for (i = 0; i < ndescs; i++) {
5356 descs[i] = gpiod_get_index_optional(dev, "cs", i,
5358 if (IS_ERR(descs[i]))
5359 return PTR_ERR(descs[i]);
5362 *ncs_array = ndescs;
5367 EXPORT_SYMBOL(rawnand_dt_parse_gpio_cs);
5369 static int rawnand_dt_init(struct nand_chip *chip)
5371 struct nand_device *nand = mtd_to_nanddev(nand_to_mtd(chip));
5372 struct device_node *dn = nand_get_flash_node(chip);
5378 ret = of_get_nand_bus_width(chip);
5382 if (of_property_read_bool(dn, "nand-is-boot-medium"))
5383 chip->options |= NAND_IS_BOOT_MEDIUM;
5385 if (of_property_read_bool(dn, "nand-on-flash-bbt"))
5386 chip->bbt_options |= NAND_BBT_USE_FLASH;
5388 of_get_nand_ecc_user_config(nand);
5389 of_get_nand_ecc_legacy_user_config(chip);
5392 * If neither the user nor the NAND controller have requested a specific
5393 * ECC engine type, we will default to NAND_ECC_ENGINE_TYPE_ON_HOST.
5395 nand->ecc.defaults.engine_type = NAND_ECC_ENGINE_TYPE_ON_HOST;
5398 * Use the user requested engine type, unless there is none, in this
5399 * case default to the NAND controller choice, otherwise fallback to
5400 * the raw NAND default one.
5402 if (nand->ecc.user_conf.engine_type != NAND_ECC_ENGINE_TYPE_INVALID)
5403 chip->ecc.engine_type = nand->ecc.user_conf.engine_type;
5404 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_INVALID)
5405 chip->ecc.engine_type = nand->ecc.defaults.engine_type;
5407 chip->ecc.placement = nand->ecc.user_conf.placement;
5408 chip->ecc.algo = nand->ecc.user_conf.algo;
5409 chip->ecc.strength = nand->ecc.user_conf.strength;
5410 chip->ecc.size = nand->ecc.user_conf.step_size;
5416 * nand_scan_ident - Scan for the NAND device
5417 * @chip: NAND chip object
5418 * @maxchips: number of chips to scan for
5419 * @table: alternative NAND ID table
5421 * This is the first phase of the normal nand_scan() function. It reads the
5422 * flash ID and sets up MTD fields accordingly.
5424 * This helper used to be called directly from controller drivers that needed
5425 * to tweak some ECC-related parameters before nand_scan_tail(). This separation
5426 * prevented dynamic allocations during this phase which was unconvenient and
5427 * as been banned for the benefit of the ->init_ecc()/cleanup_ecc() hooks.
5429 static int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips,
5430 struct nand_flash_dev *table)
5432 struct mtd_info *mtd = nand_to_mtd(chip);
5433 struct nand_memory_organization *memorg;
5434 int nand_maf_id, nand_dev_id;
5438 memorg = nanddev_get_memorg(&chip->base);
5440 /* Assume all dies are deselected when we enter nand_scan_ident(). */
5443 mutex_init(&chip->lock);
5444 init_waitqueue_head(&chip->resume_wq);
5446 /* Enforce the right timings for reset/detection */
5447 chip->current_interface_config = nand_get_reset_interface_config();
5449 ret = rawnand_dt_init(chip);
5453 if (!mtd->name && mtd->dev.parent)
5454 mtd->name = dev_name(mtd->dev.parent);
5456 /* Set the default functions */
5457 nand_set_defaults(chip);
5459 ret = nand_legacy_check_hooks(chip);
5463 memorg->ntargets = maxchips;
5465 /* Read the flash type */
5466 ret = nand_detect(chip, table);
5468 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
5469 pr_warn("No NAND device found\n");
5470 nand_deselect_target(chip);
5474 nand_maf_id = chip->id.data[0];
5475 nand_dev_id = chip->id.data[1];
5477 nand_deselect_target(chip);
5479 /* Check for a chip array */
5480 for (i = 1; i < maxchips; i++) {
5483 /* See comment in nand_get_flash_type for reset */
5484 ret = nand_reset(chip, i);
5488 nand_select_target(chip, i);
5489 /* Send the command for reading device ID */
5490 ret = nand_readid_op(chip, 0, id, sizeof(id));
5493 /* Read manufacturer and device IDs */
5494 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
5495 nand_deselect_target(chip);
5498 nand_deselect_target(chip);
5501 pr_info("%d chips detected\n", i);
5503 /* Store the number of chips and calc total size for mtd */
5504 memorg->ntargets = i;
5505 mtd->size = i * nanddev_target_size(&chip->base);
5510 static void nand_scan_ident_cleanup(struct nand_chip *chip)
5512 kfree(chip->parameters.model);
5513 kfree(chip->parameters.onfi);
5516 int rawnand_sw_hamming_init(struct nand_chip *chip)
5518 struct nand_ecc_sw_hamming_conf *engine_conf;
5519 struct nand_device *base = &chip->base;
5522 base->ecc.user_conf.engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5523 base->ecc.user_conf.algo = NAND_ECC_ALGO_HAMMING;
5524 base->ecc.user_conf.strength = chip->ecc.strength;
5525 base->ecc.user_conf.step_size = chip->ecc.size;
5527 ret = nand_ecc_sw_hamming_init_ctx(base);
5531 engine_conf = base->ecc.ctx.priv;
5533 if (chip->ecc.options & NAND_ECC_SOFT_HAMMING_SM_ORDER)
5534 engine_conf->sm_order = true;
5536 chip->ecc.size = base->ecc.ctx.conf.step_size;
5537 chip->ecc.strength = base->ecc.ctx.conf.strength;
5538 chip->ecc.total = base->ecc.ctx.total;
5539 chip->ecc.steps = nanddev_get_ecc_nsteps(base);
5540 chip->ecc.bytes = base->ecc.ctx.total / nanddev_get_ecc_nsteps(base);
5544 EXPORT_SYMBOL(rawnand_sw_hamming_init);
5546 int rawnand_sw_hamming_calculate(struct nand_chip *chip,
5547 const unsigned char *buf,
5548 unsigned char *code)
5550 struct nand_device *base = &chip->base;
5552 return nand_ecc_sw_hamming_calculate(base, buf, code);
5554 EXPORT_SYMBOL(rawnand_sw_hamming_calculate);
5556 int rawnand_sw_hamming_correct(struct nand_chip *chip,
5558 unsigned char *read_ecc,
5559 unsigned char *calc_ecc)
5561 struct nand_device *base = &chip->base;
5563 return nand_ecc_sw_hamming_correct(base, buf, read_ecc, calc_ecc);
5565 EXPORT_SYMBOL(rawnand_sw_hamming_correct);
5567 void rawnand_sw_hamming_cleanup(struct nand_chip *chip)
5569 struct nand_device *base = &chip->base;
5571 nand_ecc_sw_hamming_cleanup_ctx(base);
5573 EXPORT_SYMBOL(rawnand_sw_hamming_cleanup);
5575 int rawnand_sw_bch_init(struct nand_chip *chip)
5577 struct nand_device *base = &chip->base;
5578 const struct nand_ecc_props *ecc_conf = nanddev_get_ecc_conf(base);
5581 base->ecc.user_conf.engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5582 base->ecc.user_conf.algo = NAND_ECC_ALGO_BCH;
5583 base->ecc.user_conf.step_size = chip->ecc.size;
5584 base->ecc.user_conf.strength = chip->ecc.strength;
5586 ret = nand_ecc_sw_bch_init_ctx(base);
5590 chip->ecc.size = ecc_conf->step_size;
5591 chip->ecc.strength = ecc_conf->strength;
5592 chip->ecc.total = base->ecc.ctx.total;
5593 chip->ecc.steps = nanddev_get_ecc_nsteps(base);
5594 chip->ecc.bytes = base->ecc.ctx.total / nanddev_get_ecc_nsteps(base);
5598 EXPORT_SYMBOL(rawnand_sw_bch_init);
5600 static int rawnand_sw_bch_calculate(struct nand_chip *chip,
5601 const unsigned char *buf,
5602 unsigned char *code)
5604 struct nand_device *base = &chip->base;
5606 return nand_ecc_sw_bch_calculate(base, buf, code);
5609 int rawnand_sw_bch_correct(struct nand_chip *chip, unsigned char *buf,
5610 unsigned char *read_ecc, unsigned char *calc_ecc)
5612 struct nand_device *base = &chip->base;
5614 return nand_ecc_sw_bch_correct(base, buf, read_ecc, calc_ecc);
5616 EXPORT_SYMBOL(rawnand_sw_bch_correct);
5618 void rawnand_sw_bch_cleanup(struct nand_chip *chip)
5620 struct nand_device *base = &chip->base;
5622 nand_ecc_sw_bch_cleanup_ctx(base);
5624 EXPORT_SYMBOL(rawnand_sw_bch_cleanup);
5626 static int nand_set_ecc_on_host_ops(struct nand_chip *chip)
5628 struct nand_ecc_ctrl *ecc = &chip->ecc;
5630 switch (ecc->placement) {
5631 case NAND_ECC_PLACEMENT_UNKNOWN:
5632 case NAND_ECC_PLACEMENT_OOB:
5633 /* Use standard hwecc read page function? */
5634 if (!ecc->read_page)
5635 ecc->read_page = nand_read_page_hwecc;
5636 if (!ecc->write_page)
5637 ecc->write_page = nand_write_page_hwecc;
5638 if (!ecc->read_page_raw)
5639 ecc->read_page_raw = nand_read_page_raw;
5640 if (!ecc->write_page_raw)
5641 ecc->write_page_raw = nand_write_page_raw;
5643 ecc->read_oob = nand_read_oob_std;
5644 if (!ecc->write_oob)
5645 ecc->write_oob = nand_write_oob_std;
5646 if (!ecc->read_subpage)
5647 ecc->read_subpage = nand_read_subpage;
5648 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5649 ecc->write_subpage = nand_write_subpage_hwecc;
5652 case NAND_ECC_PLACEMENT_INTERLEAVED:
5653 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5655 ecc->read_page == nand_read_page_hwecc ||
5657 ecc->write_page == nand_write_page_hwecc)) {
5658 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5661 /* Use standard syndrome read/write page function? */
5662 if (!ecc->read_page)
5663 ecc->read_page = nand_read_page_syndrome;
5664 if (!ecc->write_page)
5665 ecc->write_page = nand_write_page_syndrome;
5666 if (!ecc->read_page_raw)
5667 ecc->read_page_raw = nand_read_page_raw_syndrome;
5668 if (!ecc->write_page_raw)
5669 ecc->write_page_raw = nand_write_page_raw_syndrome;
5671 ecc->read_oob = nand_read_oob_syndrome;
5672 if (!ecc->write_oob)
5673 ecc->write_oob = nand_write_oob_syndrome;
5677 pr_warn("Invalid NAND_ECC_PLACEMENT %d\n",
5685 static int nand_set_ecc_soft_ops(struct nand_chip *chip)
5687 struct mtd_info *mtd = nand_to_mtd(chip);
5688 struct nand_device *nanddev = mtd_to_nanddev(mtd);
5689 struct nand_ecc_ctrl *ecc = &chip->ecc;
5692 if (WARN_ON(ecc->engine_type != NAND_ECC_ENGINE_TYPE_SOFT))
5695 switch (ecc->algo) {
5696 case NAND_ECC_ALGO_HAMMING:
5697 ecc->calculate = rawnand_sw_hamming_calculate;
5698 ecc->correct = rawnand_sw_hamming_correct;
5699 ecc->read_page = nand_read_page_swecc;
5700 ecc->read_subpage = nand_read_subpage;
5701 ecc->write_page = nand_write_page_swecc;
5702 if (!ecc->read_page_raw)
5703 ecc->read_page_raw = nand_read_page_raw;
5704 if (!ecc->write_page_raw)
5705 ecc->write_page_raw = nand_write_page_raw;
5706 ecc->read_oob = nand_read_oob_std;
5707 ecc->write_oob = nand_write_oob_std;
5713 if (IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_HAMMING_SMC))
5714 ecc->options |= NAND_ECC_SOFT_HAMMING_SM_ORDER;
5716 ret = rawnand_sw_hamming_init(chip);
5718 WARN(1, "Hamming ECC initialization failed!\n");
5723 case NAND_ECC_ALGO_BCH:
5724 if (!IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_BCH)) {
5725 WARN(1, "CONFIG_MTD_NAND_ECC_SW_BCH not enabled\n");
5728 ecc->calculate = rawnand_sw_bch_calculate;
5729 ecc->correct = rawnand_sw_bch_correct;
5730 ecc->read_page = nand_read_page_swecc;
5731 ecc->read_subpage = nand_read_subpage;
5732 ecc->write_page = nand_write_page_swecc;
5733 if (!ecc->read_page_raw)
5734 ecc->read_page_raw = nand_read_page_raw;
5735 if (!ecc->write_page_raw)
5736 ecc->write_page_raw = nand_write_page_raw;
5737 ecc->read_oob = nand_read_oob_std;
5738 ecc->write_oob = nand_write_oob_std;
5741 * We can only maximize ECC config when the default layout is
5742 * used, otherwise we don't know how many bytes can really be
5745 if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH &&
5746 mtd->ooblayout != nand_get_large_page_ooblayout())
5747 nanddev->ecc.user_conf.flags &= ~NAND_ECC_MAXIMIZE_STRENGTH;
5749 ret = rawnand_sw_bch_init(chip);
5751 WARN(1, "BCH ECC initialization failed!\n");
5757 WARN(1, "Unsupported ECC algorithm!\n");
5763 * nand_check_ecc_caps - check the sanity of preset ECC settings
5764 * @chip: nand chip info structure
5765 * @caps: ECC caps info structure
5766 * @oobavail: OOB size that the ECC engine can use
5768 * When ECC step size and strength are already set, check if they are supported
5769 * by the controller and the calculated ECC bytes fit within the chip's OOB.
5770 * On success, the calculated ECC bytes is set.
5773 nand_check_ecc_caps(struct nand_chip *chip,
5774 const struct nand_ecc_caps *caps, int oobavail)
5776 struct mtd_info *mtd = nand_to_mtd(chip);
5777 const struct nand_ecc_step_info *stepinfo;
5778 int preset_step = chip->ecc.size;
5779 int preset_strength = chip->ecc.strength;
5780 int ecc_bytes, nsteps = mtd->writesize / preset_step;
5783 for (i = 0; i < caps->nstepinfos; i++) {
5784 stepinfo = &caps->stepinfos[i];
5786 if (stepinfo->stepsize != preset_step)
5789 for (j = 0; j < stepinfo->nstrengths; j++) {
5790 if (stepinfo->strengths[j] != preset_strength)
5793 ecc_bytes = caps->calc_ecc_bytes(preset_step,
5795 if (WARN_ON_ONCE(ecc_bytes < 0))
5798 if (ecc_bytes * nsteps > oobavail) {
5799 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
5800 preset_step, preset_strength);
5804 chip->ecc.bytes = ecc_bytes;
5810 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
5811 preset_step, preset_strength);
5817 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
5818 * @chip: nand chip info structure
5819 * @caps: ECC engine caps info structure
5820 * @oobavail: OOB size that the ECC engine can use
5822 * If a chip's ECC requirement is provided, try to meet it with the least
5823 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
5824 * On success, the chosen ECC settings are set.
5827 nand_match_ecc_req(struct nand_chip *chip,
5828 const struct nand_ecc_caps *caps, int oobavail)
5830 const struct nand_ecc_props *requirements =
5831 nanddev_get_ecc_requirements(&chip->base);
5832 struct mtd_info *mtd = nand_to_mtd(chip);
5833 const struct nand_ecc_step_info *stepinfo;
5834 int req_step = requirements->step_size;
5835 int req_strength = requirements->strength;
5836 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
5837 int best_step, best_strength, best_ecc_bytes;
5838 int best_ecc_bytes_total = INT_MAX;
5841 /* No information provided by the NAND chip */
5842 if (!req_step || !req_strength)
5845 /* number of correctable bits the chip requires in a page */
5846 req_corr = mtd->writesize / req_step * req_strength;
5848 for (i = 0; i < caps->nstepinfos; i++) {
5849 stepinfo = &caps->stepinfos[i];
5850 step_size = stepinfo->stepsize;
5852 for (j = 0; j < stepinfo->nstrengths; j++) {
5853 strength = stepinfo->strengths[j];
5856 * If both step size and strength are smaller than the
5857 * chip's requirement, it is not easy to compare the
5858 * resulted reliability.
5860 if (step_size < req_step && strength < req_strength)
5863 if (mtd->writesize % step_size)
5866 nsteps = mtd->writesize / step_size;
5868 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5869 if (WARN_ON_ONCE(ecc_bytes < 0))
5871 ecc_bytes_total = ecc_bytes * nsteps;
5873 if (ecc_bytes_total > oobavail ||
5874 strength * nsteps < req_corr)
5878 * We assume the best is to meet the chip's requrement
5879 * with the least number of ECC bytes.
5881 if (ecc_bytes_total < best_ecc_bytes_total) {
5882 best_ecc_bytes_total = ecc_bytes_total;
5883 best_step = step_size;
5884 best_strength = strength;
5885 best_ecc_bytes = ecc_bytes;
5890 if (best_ecc_bytes_total == INT_MAX)
5893 chip->ecc.size = best_step;
5894 chip->ecc.strength = best_strength;
5895 chip->ecc.bytes = best_ecc_bytes;
5901 * nand_maximize_ecc - choose the max ECC strength available
5902 * @chip: nand chip info structure
5903 * @caps: ECC engine caps info structure
5904 * @oobavail: OOB size that the ECC engine can use
5906 * Choose the max ECC strength that is supported on the controller, and can fit
5907 * within the chip's OOB. On success, the chosen ECC settings are set.
5910 nand_maximize_ecc(struct nand_chip *chip,
5911 const struct nand_ecc_caps *caps, int oobavail)
5913 struct mtd_info *mtd = nand_to_mtd(chip);
5914 const struct nand_ecc_step_info *stepinfo;
5915 int step_size, strength, nsteps, ecc_bytes, corr;
5918 int best_strength, best_ecc_bytes;
5921 for (i = 0; i < caps->nstepinfos; i++) {
5922 stepinfo = &caps->stepinfos[i];
5923 step_size = stepinfo->stepsize;
5925 /* If chip->ecc.size is already set, respect it */
5926 if (chip->ecc.size && step_size != chip->ecc.size)
5929 for (j = 0; j < stepinfo->nstrengths; j++) {
5930 strength = stepinfo->strengths[j];
5932 if (mtd->writesize % step_size)
5935 nsteps = mtd->writesize / step_size;
5937 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5938 if (WARN_ON_ONCE(ecc_bytes < 0))
5941 if (ecc_bytes * nsteps > oobavail)
5944 corr = strength * nsteps;
5947 * If the number of correctable bits is the same,
5948 * bigger step_size has more reliability.
5950 if (corr > best_corr ||
5951 (corr == best_corr && step_size > best_step)) {
5953 best_step = step_size;
5954 best_strength = strength;
5955 best_ecc_bytes = ecc_bytes;
5963 chip->ecc.size = best_step;
5964 chip->ecc.strength = best_strength;
5965 chip->ecc.bytes = best_ecc_bytes;
5971 * nand_ecc_choose_conf - Set the ECC strength and ECC step size
5972 * @chip: nand chip info structure
5973 * @caps: ECC engine caps info structure
5974 * @oobavail: OOB size that the ECC engine can use
5976 * Choose the ECC configuration according to following logic.
5978 * 1. If both ECC step size and ECC strength are already set (usually by DT)
5979 * then check if it is supported by this controller.
5980 * 2. If the user provided the nand-ecc-maximize property, then select maximum
5982 * 3. Otherwise, try to match the ECC step size and ECC strength closest
5983 * to the chip's requirement. If available OOB size can't fit the chip
5984 * requirement then fallback to the maximum ECC step size and ECC strength.
5986 * On success, the chosen ECC settings are set.
5988 int nand_ecc_choose_conf(struct nand_chip *chip,
5989 const struct nand_ecc_caps *caps, int oobavail)
5991 struct mtd_info *mtd = nand_to_mtd(chip);
5992 struct nand_device *nanddev = mtd_to_nanddev(mtd);
5994 if (WARN_ON(oobavail < 0 || oobavail > mtd->oobsize))
5997 if (chip->ecc.size && chip->ecc.strength)
5998 return nand_check_ecc_caps(chip, caps, oobavail);
6000 if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH)
6001 return nand_maximize_ecc(chip, caps, oobavail);
6003 if (!nand_match_ecc_req(chip, caps, oobavail))
6006 return nand_maximize_ecc(chip, caps, oobavail);
6008 EXPORT_SYMBOL_GPL(nand_ecc_choose_conf);
6010 static int rawnand_erase(struct nand_device *nand, const struct nand_pos *pos)
6012 struct nand_chip *chip = container_of(nand, struct nand_chip,
6014 unsigned int eb = nanddev_pos_to_row(nand, pos);
6017 eb >>= nand->rowconv.eraseblock_addr_shift;
6019 nand_select_target(chip, pos->target);
6020 ret = nand_erase_op(chip, eb);
6021 nand_deselect_target(chip);
6026 static int rawnand_markbad(struct nand_device *nand,
6027 const struct nand_pos *pos)
6029 struct nand_chip *chip = container_of(nand, struct nand_chip,
6032 return nand_markbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
6035 static bool rawnand_isbad(struct nand_device *nand, const struct nand_pos *pos)
6037 struct nand_chip *chip = container_of(nand, struct nand_chip,
6041 nand_select_target(chip, pos->target);
6042 ret = nand_isbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
6043 nand_deselect_target(chip);
6048 static const struct nand_ops rawnand_ops = {
6049 .erase = rawnand_erase,
6050 .markbad = rawnand_markbad,
6051 .isbad = rawnand_isbad,
6055 * nand_scan_tail - Scan for the NAND device
6056 * @chip: NAND chip object
6058 * This is the second phase of the normal nand_scan() function. It fills out
6059 * all the uninitialized function pointers with the defaults and scans for a
6060 * bad block table if appropriate.
6062 static int nand_scan_tail(struct nand_chip *chip)
6064 struct mtd_info *mtd = nand_to_mtd(chip);
6065 struct nand_ecc_ctrl *ecc = &chip->ecc;
6068 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
6069 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
6070 !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
6074 chip->data_buf = kmalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
6075 if (!chip->data_buf)
6079 * FIXME: some NAND manufacturer drivers expect the first die to be
6080 * selected when manufacturer->init() is called. They should be fixed
6081 * to explictly select the relevant die when interacting with the NAND
6084 nand_select_target(chip, 0);
6085 ret = nand_manufacturer_init(chip);
6086 nand_deselect_target(chip);
6090 /* Set the internal oob buffer location, just after the page data */
6091 chip->oob_poi = chip->data_buf + mtd->writesize;
6094 * If no default placement scheme is given, select an appropriate one.
6096 if (!mtd->ooblayout &&
6097 !(ecc->engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
6098 ecc->algo == NAND_ECC_ALGO_BCH) &&
6099 !(ecc->engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
6100 ecc->algo == NAND_ECC_ALGO_HAMMING)) {
6101 switch (mtd->oobsize) {
6104 mtd_set_ooblayout(mtd, nand_get_small_page_ooblayout());
6108 mtd_set_ooblayout(mtd,
6109 nand_get_large_page_hamming_ooblayout());
6113 * Expose the whole OOB area to users if ECC_NONE
6114 * is passed. We could do that for all kind of
6115 * ->oobsize, but we must keep the old large/small
6116 * page with ECC layout when ->oobsize <= 128 for
6117 * compatibility reasons.
6119 if (ecc->engine_type == NAND_ECC_ENGINE_TYPE_NONE) {
6120 mtd_set_ooblayout(mtd,
6121 nand_get_large_page_ooblayout());
6125 WARN(1, "No oob scheme defined for oobsize %d\n",
6128 goto err_nand_manuf_cleanup;
6133 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
6134 * selected and we have 256 byte pagesize fallback to software ECC
6137 switch (ecc->engine_type) {
6138 case NAND_ECC_ENGINE_TYPE_ON_HOST:
6139 ret = nand_set_ecc_on_host_ops(chip);
6141 goto err_nand_manuf_cleanup;
6143 if (mtd->writesize >= ecc->size) {
6144 if (!ecc->strength) {
6145 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
6147 goto err_nand_manuf_cleanup;
6151 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
6152 ecc->size, mtd->writesize);
6153 ecc->engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
6154 ecc->algo = NAND_ECC_ALGO_HAMMING;
6157 case NAND_ECC_ENGINE_TYPE_SOFT:
6158 ret = nand_set_ecc_soft_ops(chip);
6160 goto err_nand_manuf_cleanup;
6163 case NAND_ECC_ENGINE_TYPE_ON_DIE:
6164 if (!ecc->read_page || !ecc->write_page) {
6165 WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
6167 goto err_nand_manuf_cleanup;
6170 ecc->read_oob = nand_read_oob_std;
6171 if (!ecc->write_oob)
6172 ecc->write_oob = nand_write_oob_std;
6175 case NAND_ECC_ENGINE_TYPE_NONE:
6176 pr_warn("NAND_ECC_ENGINE_TYPE_NONE selected by board driver. This is not recommended!\n");
6177 ecc->read_page = nand_read_page_raw;
6178 ecc->write_page = nand_write_page_raw;
6179 ecc->read_oob = nand_read_oob_std;
6180 ecc->read_page_raw = nand_read_page_raw;
6181 ecc->write_page_raw = nand_write_page_raw;
6182 ecc->write_oob = nand_write_oob_std;
6183 ecc->size = mtd->writesize;
6189 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->engine_type);
6191 goto err_nand_manuf_cleanup;
6194 if (ecc->correct || ecc->calculate) {
6195 ecc->calc_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
6196 ecc->code_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
6197 if (!ecc->calc_buf || !ecc->code_buf) {
6199 goto err_nand_manuf_cleanup;
6203 /* For many systems, the standard OOB write also works for raw */
6204 if (!ecc->read_oob_raw)
6205 ecc->read_oob_raw = ecc->read_oob;
6206 if (!ecc->write_oob_raw)
6207 ecc->write_oob_raw = ecc->write_oob;
6209 /* propagate ecc info to mtd_info */
6210 mtd->ecc_strength = ecc->strength;
6211 mtd->ecc_step_size = ecc->size;
6214 * Set the number of read / write steps for one page depending on ECC
6218 ecc->steps = mtd->writesize / ecc->size;
6219 if (ecc->steps * ecc->size != mtd->writesize) {
6220 WARN(1, "Invalid ECC parameters\n");
6222 goto err_nand_manuf_cleanup;
6226 ecc->total = ecc->steps * ecc->bytes;
6227 chip->base.ecc.ctx.total = ecc->total;
6230 if (ecc->total > mtd->oobsize) {
6231 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
6233 goto err_nand_manuf_cleanup;
6237 * The number of bytes available for a client to place data into
6238 * the out of band area.
6240 ret = mtd_ooblayout_count_freebytes(mtd);
6244 mtd->oobavail = ret;
6246 /* ECC sanity check: warn if it's too weak */
6247 if (!nand_ecc_is_strong_enough(&chip->base))
6248 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",
6249 mtd->name, chip->ecc.strength, chip->ecc.size,
6250 nanddev_get_ecc_requirements(&chip->base)->strength,
6251 nanddev_get_ecc_requirements(&chip->base)->step_size);
6253 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
6254 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
6255 switch (ecc->steps) {
6257 mtd->subpage_sft = 1;
6262 mtd->subpage_sft = 2;
6266 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
6268 /* Invalidate the pagebuffer reference */
6269 chip->pagecache.page = -1;
6271 /* Large page NAND with SOFT_ECC should support subpage reads */
6272 switch (ecc->engine_type) {
6273 case NAND_ECC_ENGINE_TYPE_SOFT:
6274 if (chip->page_shift > 9)
6275 chip->options |= NAND_SUBPAGE_READ;
6282 ret = nanddev_init(&chip->base, &rawnand_ops, mtd->owner);
6284 goto err_nand_manuf_cleanup;
6286 /* Adjust the MTD_CAP_ flags when NAND_ROM is set. */
6287 if (chip->options & NAND_ROM)
6288 mtd->flags = MTD_CAP_ROM;
6290 /* Fill in remaining MTD driver data */
6291 mtd->_erase = nand_erase;
6293 mtd->_unpoint = NULL;
6294 mtd->_panic_write = panic_nand_write;
6295 mtd->_read_oob = nand_read_oob;
6296 mtd->_write_oob = nand_write_oob;
6297 mtd->_sync = nand_sync;
6298 mtd->_lock = nand_lock;
6299 mtd->_unlock = nand_unlock;
6300 mtd->_suspend = nand_suspend;
6301 mtd->_resume = nand_resume;
6302 mtd->_reboot = nand_shutdown;
6303 mtd->_block_isreserved = nand_block_isreserved;
6304 mtd->_block_isbad = nand_block_isbad;
6305 mtd->_block_markbad = nand_block_markbad;
6306 mtd->_max_bad_blocks = nanddev_mtd_max_bad_blocks;
6309 * Initialize bitflip_threshold to its default prior scan_bbt() call.
6310 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
6313 if (!mtd->bitflip_threshold)
6314 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
6316 /* Find the fastest data interface for this chip */
6317 ret = nand_choose_interface_config(chip);
6319 goto err_nanddev_cleanup;
6321 /* Enter fastest possible mode on all dies. */
6322 for (i = 0; i < nanddev_ntargets(&chip->base); i++) {
6323 ret = nand_setup_interface(chip, i);
6325 goto err_free_interface_config;
6329 * Look for secure regions in the NAND chip. These regions are supposed
6330 * to be protected by a secure element like Trustzone. So the read/write
6331 * accesses to these regions will be blocked in the runtime by this
6334 ret = of_get_nand_secure_regions(chip);
6336 goto err_free_interface_config;
6338 /* Check, if we should skip the bad block table scan */
6339 if (chip->options & NAND_SKIP_BBTSCAN)
6342 /* Build bad block table */
6343 ret = nand_create_bbt(chip);
6345 goto err_free_secure_regions;
6349 err_free_secure_regions:
6350 kfree(chip->secure_regions);
6352 err_free_interface_config:
6353 kfree(chip->best_interface_config);
6355 err_nanddev_cleanup:
6356 nanddev_cleanup(&chip->base);
6358 err_nand_manuf_cleanup:
6359 nand_manufacturer_cleanup(chip);
6362 kfree(chip->data_buf);
6363 kfree(ecc->code_buf);
6364 kfree(ecc->calc_buf);
6369 static int nand_attach(struct nand_chip *chip)
6371 if (chip->controller->ops && chip->controller->ops->attach_chip)
6372 return chip->controller->ops->attach_chip(chip);
6377 static void nand_detach(struct nand_chip *chip)
6379 if (chip->controller->ops && chip->controller->ops->detach_chip)
6380 chip->controller->ops->detach_chip(chip);
6384 * nand_scan_with_ids - [NAND Interface] Scan for the NAND device
6385 * @chip: NAND chip object
6386 * @maxchips: number of chips to scan for.
6387 * @ids: optional flash IDs table
6389 * This fills out all the uninitialized function pointers with the defaults.
6390 * The flash ID is read and the mtd/chip structures are filled with the
6391 * appropriate values.
6393 int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips,
6394 struct nand_flash_dev *ids)
6401 ret = nand_scan_ident(chip, maxchips, ids);
6405 ret = nand_attach(chip);
6409 ret = nand_scan_tail(chip);
6418 nand_scan_ident_cleanup(chip);
6422 EXPORT_SYMBOL(nand_scan_with_ids);
6425 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
6426 * @chip: NAND chip object
6428 void nand_cleanup(struct nand_chip *chip)
6430 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_SOFT) {
6431 if (chip->ecc.algo == NAND_ECC_ALGO_HAMMING)
6432 rawnand_sw_hamming_cleanup(chip);
6433 else if (chip->ecc.algo == NAND_ECC_ALGO_BCH)
6434 rawnand_sw_bch_cleanup(chip);
6437 nanddev_cleanup(&chip->base);
6439 /* Free secure regions data */
6440 kfree(chip->secure_regions);
6442 /* Free bad block table memory */
6444 kfree(chip->data_buf);
6445 kfree(chip->ecc.code_buf);
6446 kfree(chip->ecc.calc_buf);
6448 /* Free bad block descriptor memory */
6449 if (chip->badblock_pattern && chip->badblock_pattern->options
6450 & NAND_BBT_DYNAMICSTRUCT)
6451 kfree(chip->badblock_pattern);
6453 /* Free the data interface */
6454 kfree(chip->best_interface_config);
6456 /* Free manufacturer priv data. */
6457 nand_manufacturer_cleanup(chip);
6459 /* Free controller specific allocations after chip identification */
6462 /* Free identification phase allocations */
6463 nand_scan_ident_cleanup(chip);
6466 EXPORT_SYMBOL_GPL(nand_cleanup);
6468 MODULE_LICENSE("GPL");
6469 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
6470 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
6471 MODULE_DESCRIPTION("Generic NAND flash driver code");