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 (chip->legacy.block_bad)
325 return chip->legacy.block_bad(chip, ofs);
327 return nand_block_bad(chip, ofs);
331 * nand_get_device - [GENERIC] Get chip for selected access
332 * @chip: NAND chip structure
334 * Lock the device and its controller for exclusive access
336 * Return: -EBUSY if the chip has been suspended, 0 otherwise
338 static int nand_get_device(struct nand_chip *chip)
340 mutex_lock(&chip->lock);
341 if (chip->suspended) {
342 mutex_unlock(&chip->lock);
345 mutex_lock(&chip->controller->lock);
351 * nand_check_wp - [GENERIC] check if the chip is write protected
352 * @chip: NAND chip object
354 * Check, if the device is write protected. The function expects, that the
355 * device is already selected.
357 static int nand_check_wp(struct nand_chip *chip)
362 /* Broken xD cards report WP despite being writable */
363 if (chip->options & NAND_BROKEN_XD)
366 /* Check the WP bit */
367 ret = nand_status_op(chip, &status);
371 return status & NAND_STATUS_WP ? 0 : 1;
375 * nand_fill_oob - [INTERN] Transfer client buffer to oob
376 * @chip: NAND chip object
377 * @oob: oob data buffer
378 * @len: oob data write length
379 * @ops: oob ops structure
381 static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len,
382 struct mtd_oob_ops *ops)
384 struct mtd_info *mtd = nand_to_mtd(chip);
388 * Initialise to all 0xFF, to avoid the possibility of left over OOB
389 * data from a previous OOB read.
391 memset(chip->oob_poi, 0xff, mtd->oobsize);
395 case MTD_OPS_PLACE_OOB:
397 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
400 case MTD_OPS_AUTO_OOB:
401 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
413 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
414 * @chip: NAND chip object
415 * @to: offset to write to
416 * @ops: oob operation description structure
418 * NAND write out-of-band.
420 static int nand_do_write_oob(struct nand_chip *chip, loff_t to,
421 struct mtd_oob_ops *ops)
423 struct mtd_info *mtd = nand_to_mtd(chip);
424 int chipnr, page, status, len, ret;
426 pr_debug("%s: to = 0x%08x, len = %i\n",
427 __func__, (unsigned int)to, (int)ops->ooblen);
429 len = mtd_oobavail(mtd, ops);
431 /* Do not allow write past end of page */
432 if ((ops->ooboffs + ops->ooblen) > len) {
433 pr_debug("%s: attempt to write past end of page\n",
438 /* Check if the region is secured */
439 if (nand_region_is_secured(chip, to, ops->ooblen))
442 chipnr = (int)(to >> chip->chip_shift);
445 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
446 * of my DiskOnChip 2000 test units) will clear the whole data page too
447 * if we don't do this. I have no clue why, but I seem to have 'fixed'
448 * it in the doc2000 driver in August 1999. dwmw2.
450 ret = nand_reset(chip, chipnr);
454 nand_select_target(chip, chipnr);
456 /* Shift to get page */
457 page = (int)(to >> chip->page_shift);
459 /* Check, if it is write protected */
460 if (nand_check_wp(chip)) {
461 nand_deselect_target(chip);
465 /* Invalidate the page cache, if we write to the cached page */
466 if (page == chip->pagecache.page)
467 chip->pagecache.page = -1;
469 nand_fill_oob(chip, ops->oobbuf, ops->ooblen, ops);
471 if (ops->mode == MTD_OPS_RAW)
472 status = chip->ecc.write_oob_raw(chip, page & chip->pagemask);
474 status = chip->ecc.write_oob(chip, page & chip->pagemask);
476 nand_deselect_target(chip);
481 ops->oobretlen = ops->ooblen;
487 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
488 * @chip: NAND chip object
489 * @ofs: offset from device start
491 * This is the default implementation, which can be overridden by a hardware
492 * specific driver. It provides the details for writing a bad block marker to a
495 static int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
497 struct mtd_info *mtd = nand_to_mtd(chip);
498 struct mtd_oob_ops ops;
499 uint8_t buf[2] = { 0, 0 };
500 int ret = 0, res, page_offset;
502 memset(&ops, 0, sizeof(ops));
504 ops.ooboffs = chip->badblockpos;
505 if (chip->options & NAND_BUSWIDTH_16) {
506 ops.ooboffs &= ~0x01;
507 ops.len = ops.ooblen = 2;
509 ops.len = ops.ooblen = 1;
511 ops.mode = MTD_OPS_PLACE_OOB;
513 page_offset = nand_bbm_get_next_page(chip, 0);
515 while (page_offset >= 0) {
516 res = nand_do_write_oob(chip,
517 ofs + (page_offset * mtd->writesize),
523 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
530 * nand_markbad_bbm - mark a block by updating the BBM
531 * @chip: NAND chip object
532 * @ofs: offset of the block to mark bad
534 int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
536 if (chip->legacy.block_markbad)
537 return chip->legacy.block_markbad(chip, ofs);
539 return nand_default_block_markbad(chip, ofs);
543 * nand_block_markbad_lowlevel - mark a block bad
544 * @chip: NAND chip object
545 * @ofs: offset from device start
547 * This function performs the generic NAND bad block marking steps (i.e., bad
548 * block table(s) and/or marker(s)). We only allow the hardware driver to
549 * specify how to write bad block markers to OOB (chip->legacy.block_markbad).
551 * We try operations in the following order:
553 * (1) erase the affected block, to allow OOB marker to be written cleanly
554 * (2) write bad block marker to OOB area of affected block (unless flag
555 * NAND_BBT_NO_OOB_BBM is present)
558 * Note that we retain the first error encountered in (2) or (3), finish the
559 * procedures, and dump the error in the end.
561 static int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
563 struct mtd_info *mtd = nand_to_mtd(chip);
566 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
567 struct erase_info einfo;
569 /* Attempt erase before marking OOB */
570 memset(&einfo, 0, sizeof(einfo));
572 einfo.len = 1ULL << chip->phys_erase_shift;
573 nand_erase_nand(chip, &einfo, 0);
575 /* Write bad block marker to OOB */
576 ret = nand_get_device(chip);
580 ret = nand_markbad_bbm(chip, ofs);
581 nand_release_device(chip);
584 /* Mark block bad in BBT */
586 res = nand_markbad_bbt(chip, ofs);
592 mtd->ecc_stats.badblocks++;
598 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
599 * @mtd: MTD device structure
600 * @ofs: offset from device start
602 * Check if the block is marked as reserved.
604 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
606 struct nand_chip *chip = mtd_to_nand(mtd);
610 /* Return info from the table */
611 return nand_isreserved_bbt(chip, ofs);
615 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
616 * @chip: NAND chip object
617 * @ofs: offset from device start
618 * @allowbbt: 1, if its allowed to access the bbt area
620 * Check, if the block is bad. Either by reading the bad block table or
621 * calling of the scan function.
623 static int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
625 /* Return info from the table */
627 return nand_isbad_bbt(chip, ofs, allowbbt);
629 return nand_isbad_bbm(chip, ofs);
633 * nand_soft_waitrdy - Poll STATUS reg until RDY bit is set to 1
634 * @chip: NAND chip structure
635 * @timeout_ms: Timeout in ms
637 * Poll the STATUS register using ->exec_op() until the RDY bit becomes 1.
638 * If that does not happen whitin the specified timeout, -ETIMEDOUT is
641 * This helper is intended to be used when the controller does not have access
642 * to the NAND R/B pin.
644 * Be aware that calling this helper from an ->exec_op() implementation means
645 * ->exec_op() must be re-entrant.
647 * Return 0 if the NAND chip is ready, a negative error otherwise.
649 int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
651 const struct nand_interface_config *conf;
655 if (!nand_has_exec_op(chip))
658 /* Wait tWB before polling the STATUS reg. */
659 conf = nand_get_interface_config(chip);
660 ndelay(NAND_COMMON_TIMING_NS(conf, tWB_max));
662 ret = nand_status_op(chip, NULL);
667 * +1 below is necessary because if we are now in the last fraction
668 * of jiffy and msecs_to_jiffies is 1 then we will wait only that
669 * small jiffy fraction - possibly leading to false timeout
671 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
673 ret = nand_read_data_op(chip, &status, sizeof(status), true,
678 if (status & NAND_STATUS_READY)
682 * Typical lowest execution time for a tR on most NANDs is 10us,
683 * use this as polling delay before doing something smarter (ie.
684 * deriving a delay from the timeout value, timeout_ms/ratio).
687 } while (time_before(jiffies, timeout_ms));
690 * We have to exit READ_STATUS mode in order to read real data on the
691 * bus in case the WAITRDY instruction is preceding a DATA_IN
694 nand_exit_status_op(chip);
699 return status & NAND_STATUS_READY ? 0 : -ETIMEDOUT;
701 EXPORT_SYMBOL_GPL(nand_soft_waitrdy);
704 * nand_gpio_waitrdy - Poll R/B GPIO pin until ready
705 * @chip: NAND chip structure
706 * @gpiod: GPIO descriptor of R/B pin
707 * @timeout_ms: Timeout in ms
709 * Poll the R/B GPIO pin until it becomes ready. If that does not happen
710 * whitin the specified timeout, -ETIMEDOUT is returned.
712 * This helper is intended to be used when the controller has access to the
713 * NAND R/B pin over GPIO.
715 * Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.
717 int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
718 unsigned long timeout_ms)
722 * Wait until R/B pin indicates chip is ready or timeout occurs.
723 * +1 below is necessary because if we are now in the last fraction
724 * of jiffy and msecs_to_jiffies is 1 then we will wait only that
725 * small jiffy fraction - possibly leading to false timeout.
727 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
729 if (gpiod_get_value_cansleep(gpiod))
733 } while (time_before(jiffies, timeout_ms));
735 return gpiod_get_value_cansleep(gpiod) ? 0 : -ETIMEDOUT;
737 EXPORT_SYMBOL_GPL(nand_gpio_waitrdy);
740 * panic_nand_wait - [GENERIC] wait until the command is done
741 * @chip: NAND chip structure
744 * Wait for command done. This is a helper function for nand_wait used when
745 * we are in interrupt context. May happen when in panic and trying to write
746 * an oops through mtdoops.
748 void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
751 for (i = 0; i < timeo; i++) {
752 if (chip->legacy.dev_ready) {
753 if (chip->legacy.dev_ready(chip))
759 ret = nand_read_data_op(chip, &status, sizeof(status),
764 if (status & NAND_STATUS_READY)
771 static bool nand_supports_get_features(struct nand_chip *chip, int addr)
773 return (chip->parameters.supports_set_get_features &&
774 test_bit(addr, chip->parameters.get_feature_list));
777 static bool nand_supports_set_features(struct nand_chip *chip, int addr)
779 return (chip->parameters.supports_set_get_features &&
780 test_bit(addr, chip->parameters.set_feature_list));
784 * nand_reset_interface - Reset data interface and timings
785 * @chip: The NAND chip
786 * @chipnr: Internal die id
788 * Reset the Data interface and timings to ONFI mode 0.
790 * Returns 0 for success or negative error code otherwise.
792 static int nand_reset_interface(struct nand_chip *chip, int chipnr)
794 const struct nand_controller_ops *ops = chip->controller->ops;
797 if (!nand_controller_can_setup_interface(chip))
801 * The ONFI specification says:
803 * To transition from NV-DDR or NV-DDR2 to the SDR data
804 * interface, the host shall use the Reset (FFh) command
805 * using SDR timing mode 0. A device in any timing mode is
806 * required to recognize Reset (FFh) command issued in SDR
810 * Configure the data interface in SDR mode and set the
811 * timings to timing mode 0.
814 chip->current_interface_config = nand_get_reset_interface_config();
815 ret = ops->setup_interface(chip, chipnr,
816 chip->current_interface_config);
818 pr_err("Failed to configure data interface to SDR timing mode 0\n");
824 * nand_setup_interface - Setup the best data interface and timings
825 * @chip: The NAND chip
826 * @chipnr: Internal die id
828 * Configure what has been reported to be the best data interface and NAND
829 * timings supported by the chip and the driver.
831 * Returns 0 for success or negative error code otherwise.
833 static int nand_setup_interface(struct nand_chip *chip, int chipnr)
835 const struct nand_controller_ops *ops = chip->controller->ops;
836 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = { }, request;
839 if (!nand_controller_can_setup_interface(chip))
843 * A nand_reset_interface() put both the NAND chip and the NAND
844 * controller in timings mode 0. If the default mode for this chip is
845 * also 0, no need to proceed to the change again. Plus, at probe time,
846 * nand_setup_interface() uses ->set/get_features() which would
847 * fail anyway as the parameter page is not available yet.
849 if (!chip->best_interface_config)
852 request = chip->best_interface_config->timings.mode;
853 if (nand_interface_is_sdr(chip->best_interface_config))
854 request |= ONFI_DATA_INTERFACE_SDR;
856 request |= ONFI_DATA_INTERFACE_NVDDR;
857 tmode_param[0] = request;
859 /* Change the mode on the chip side (if supported by the NAND chip) */
860 if (nand_supports_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE)) {
861 nand_select_target(chip, chipnr);
862 ret = nand_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
864 nand_deselect_target(chip);
869 /* Change the mode on the controller side */
870 ret = ops->setup_interface(chip, chipnr, chip->best_interface_config);
874 /* Check the mode has been accepted by the chip, if supported */
875 if (!nand_supports_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE))
876 goto update_interface_config;
878 memset(tmode_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
879 nand_select_target(chip, chipnr);
880 ret = nand_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
882 nand_deselect_target(chip);
886 if (request != tmode_param[0]) {
887 pr_warn("%s timing mode %d not acknowledged by the NAND chip\n",
888 nand_interface_is_nvddr(chip->best_interface_config) ? "NV-DDR" : "SDR",
889 chip->best_interface_config->timings.mode);
890 pr_debug("NAND chip would work in %s timing mode %d\n",
891 tmode_param[0] & ONFI_DATA_INTERFACE_NVDDR ? "NV-DDR" : "SDR",
892 (unsigned int)ONFI_TIMING_MODE_PARAM(tmode_param[0]));
896 update_interface_config:
897 chip->current_interface_config = chip->best_interface_config;
903 * Fallback to mode 0 if the chip explicitly did not ack the chosen
906 nand_reset_interface(chip, chipnr);
907 nand_select_target(chip, chipnr);
909 nand_deselect_target(chip);
915 * nand_choose_best_sdr_timings - Pick up the best SDR timings that both the
916 * NAND controller and the NAND chip support
917 * @chip: the NAND chip
918 * @iface: the interface configuration (can eventually be updated)
919 * @spec_timings: specific timings, when not fitting the ONFI specification
921 * If specific timings are provided, use them. Otherwise, retrieve supported
922 * timing modes from ONFI information.
924 int nand_choose_best_sdr_timings(struct nand_chip *chip,
925 struct nand_interface_config *iface,
926 struct nand_sdr_timings *spec_timings)
928 const struct nand_controller_ops *ops = chip->controller->ops;
929 int best_mode = 0, mode, ret = -EOPNOTSUPP;
931 iface->type = NAND_SDR_IFACE;
934 iface->timings.sdr = *spec_timings;
935 iface->timings.mode = onfi_find_closest_sdr_mode(spec_timings);
937 /* Verify the controller supports the requested interface */
938 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
941 chip->best_interface_config = iface;
945 /* Fallback to slower modes */
946 best_mode = iface->timings.mode;
947 } else if (chip->parameters.onfi) {
948 best_mode = fls(chip->parameters.onfi->sdr_timing_modes) - 1;
951 for (mode = best_mode; mode >= 0; mode--) {
952 onfi_fill_interface_config(chip, iface, NAND_SDR_IFACE, mode);
954 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
957 chip->best_interface_config = iface;
966 * nand_choose_best_nvddr_timings - Pick up the best NVDDR timings that both the
967 * NAND controller and the NAND chip support
968 * @chip: the NAND chip
969 * @iface: the interface configuration (can eventually be updated)
970 * @spec_timings: specific timings, when not fitting the ONFI specification
972 * If specific timings are provided, use them. Otherwise, retrieve supported
973 * timing modes from ONFI information.
975 int nand_choose_best_nvddr_timings(struct nand_chip *chip,
976 struct nand_interface_config *iface,
977 struct nand_nvddr_timings *spec_timings)
979 const struct nand_controller_ops *ops = chip->controller->ops;
980 int best_mode = 0, mode, ret = -EOPNOTSUPP;
982 iface->type = NAND_NVDDR_IFACE;
985 iface->timings.nvddr = *spec_timings;
986 iface->timings.mode = onfi_find_closest_nvddr_mode(spec_timings);
988 /* Verify the controller supports the requested interface */
989 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
992 chip->best_interface_config = iface;
996 /* Fallback to slower modes */
997 best_mode = iface->timings.mode;
998 } else if (chip->parameters.onfi) {
999 best_mode = fls(chip->parameters.onfi->nvddr_timing_modes) - 1;
1002 for (mode = best_mode; mode >= 0; mode--) {
1003 onfi_fill_interface_config(chip, iface, NAND_NVDDR_IFACE, mode);
1005 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
1008 chip->best_interface_config = iface;
1017 * nand_choose_best_timings - Pick up the best NVDDR or SDR timings that both
1018 * NAND controller and the NAND chip support
1019 * @chip: the NAND chip
1020 * @iface: the interface configuration (can eventually be updated)
1022 * If specific timings are provided, use them. Otherwise, retrieve supported
1023 * timing modes from ONFI information.
1025 static int nand_choose_best_timings(struct nand_chip *chip,
1026 struct nand_interface_config *iface)
1030 /* Try the fastest timings: NV-DDR */
1031 ret = nand_choose_best_nvddr_timings(chip, iface, NULL);
1035 /* Fallback to SDR timings otherwise */
1036 return nand_choose_best_sdr_timings(chip, iface, NULL);
1040 * nand_choose_interface_config - find the best data interface and timings
1041 * @chip: The NAND chip
1043 * Find the best data interface and NAND timings supported by the chip
1044 * and the driver. Eventually let the NAND manufacturer driver propose his own
1047 * After this function nand_chip->interface_config is initialized with the best
1048 * timing mode available.
1050 * Returns 0 for success or negative error code otherwise.
1052 static int nand_choose_interface_config(struct nand_chip *chip)
1054 struct nand_interface_config *iface;
1057 if (!nand_controller_can_setup_interface(chip))
1060 iface = kzalloc(sizeof(*iface), GFP_KERNEL);
1064 if (chip->ops.choose_interface_config)
1065 ret = chip->ops.choose_interface_config(chip, iface);
1067 ret = nand_choose_best_timings(chip, iface);
1076 * nand_fill_column_cycles - fill the column cycles of an address
1077 * @chip: The NAND chip
1078 * @addrs: Array of address cycles to fill
1079 * @offset_in_page: The offset in the page
1081 * Fills the first or the first two bytes of the @addrs field depending
1082 * on the NAND bus width and the page size.
1084 * Returns the number of cycles needed to encode the column, or a negative
1085 * error code in case one of the arguments is invalid.
1087 static int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs,
1088 unsigned int offset_in_page)
1090 struct mtd_info *mtd = nand_to_mtd(chip);
1092 /* Make sure the offset is less than the actual page size. */
1093 if (offset_in_page > mtd->writesize + mtd->oobsize)
1097 * On small page NANDs, there's a dedicated command to access the OOB
1098 * area, and the column address is relative to the start of the OOB
1099 * area, not the start of the page. Asjust the address accordingly.
1101 if (mtd->writesize <= 512 && offset_in_page >= mtd->writesize)
1102 offset_in_page -= mtd->writesize;
1105 * The offset in page is expressed in bytes, if the NAND bus is 16-bit
1106 * wide, then it must be divided by 2.
1108 if (chip->options & NAND_BUSWIDTH_16) {
1109 if (WARN_ON(offset_in_page % 2))
1112 offset_in_page /= 2;
1115 addrs[0] = offset_in_page;
1118 * Small page NANDs use 1 cycle for the columns, while large page NANDs
1121 if (mtd->writesize <= 512)
1124 addrs[1] = offset_in_page >> 8;
1129 static int nand_sp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1130 unsigned int offset_in_page, void *buf,
1133 const struct nand_interface_config *conf =
1134 nand_get_interface_config(chip);
1135 struct mtd_info *mtd = nand_to_mtd(chip);
1137 struct nand_op_instr instrs[] = {
1138 NAND_OP_CMD(NAND_CMD_READ0, 0),
1139 NAND_OP_ADDR(3, addrs, NAND_COMMON_TIMING_NS(conf, tWB_max)),
1140 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1141 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1142 NAND_OP_DATA_IN(len, buf, 0),
1144 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1147 /* Drop the DATA_IN instruction if len is set to 0. */
1151 if (offset_in_page >= mtd->writesize)
1152 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1153 else if (offset_in_page >= 256 &&
1154 !(chip->options & NAND_BUSWIDTH_16))
1155 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1157 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1162 addrs[2] = page >> 8;
1164 if (chip->options & NAND_ROW_ADDR_3) {
1165 addrs[3] = page >> 16;
1166 instrs[1].ctx.addr.naddrs++;
1169 return nand_exec_op(chip, &op);
1172 static int nand_lp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1173 unsigned int offset_in_page, void *buf,
1176 const struct nand_interface_config *conf =
1177 nand_get_interface_config(chip);
1179 struct nand_op_instr instrs[] = {
1180 NAND_OP_CMD(NAND_CMD_READ0, 0),
1181 NAND_OP_ADDR(4, addrs, 0),
1182 NAND_OP_CMD(NAND_CMD_READSTART, NAND_COMMON_TIMING_NS(conf, tWB_max)),
1183 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1184 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1185 NAND_OP_DATA_IN(len, buf, 0),
1187 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1190 /* Drop the DATA_IN instruction if len is set to 0. */
1194 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1199 addrs[3] = page >> 8;
1201 if (chip->options & NAND_ROW_ADDR_3) {
1202 addrs[4] = page >> 16;
1203 instrs[1].ctx.addr.naddrs++;
1206 return nand_exec_op(chip, &op);
1210 * nand_read_page_op - Do a READ PAGE operation
1211 * @chip: The NAND chip
1212 * @page: page to read
1213 * @offset_in_page: offset within the page
1214 * @buf: buffer used to store the data
1215 * @len: length of the buffer
1217 * This function issues a READ PAGE operation.
1218 * This function does not select/unselect the CS line.
1220 * Returns 0 on success, a negative error code otherwise.
1222 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1223 unsigned int offset_in_page, void *buf, unsigned int len)
1225 struct mtd_info *mtd = nand_to_mtd(chip);
1230 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1233 if (nand_has_exec_op(chip)) {
1234 if (mtd->writesize > 512)
1235 return nand_lp_exec_read_page_op(chip, page,
1236 offset_in_page, buf,
1239 return nand_sp_exec_read_page_op(chip, page, offset_in_page,
1243 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, offset_in_page, page);
1245 chip->legacy.read_buf(chip, buf, len);
1249 EXPORT_SYMBOL_GPL(nand_read_page_op);
1252 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1253 * @chip: The NAND chip
1254 * @page: parameter page to read
1255 * @buf: buffer used to store the data
1256 * @len: length of the buffer
1258 * This function issues a READ PARAMETER PAGE operation.
1259 * This function does not select/unselect the CS line.
1261 * Returns 0 on success, a negative error code otherwise.
1263 int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1272 if (nand_has_exec_op(chip)) {
1273 const struct nand_interface_config *conf =
1274 nand_get_interface_config(chip);
1275 struct nand_op_instr instrs[] = {
1276 NAND_OP_CMD(NAND_CMD_PARAM, 0),
1277 NAND_OP_ADDR(1, &page,
1278 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1279 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1280 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1281 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1283 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1285 /* Drop the DATA_IN instruction if len is set to 0. */
1289 return nand_exec_op(chip, &op);
1292 chip->legacy.cmdfunc(chip, NAND_CMD_PARAM, page, -1);
1293 for (i = 0; i < len; i++)
1294 p[i] = chip->legacy.read_byte(chip);
1300 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1301 * @chip: The NAND chip
1302 * @offset_in_page: offset within the page
1303 * @buf: buffer used to store the data
1304 * @len: length of the buffer
1305 * @force_8bit: force 8-bit bus access
1307 * This function issues a CHANGE READ COLUMN operation.
1308 * This function does not select/unselect the CS line.
1310 * Returns 0 on success, a negative error code otherwise.
1312 int nand_change_read_column_op(struct nand_chip *chip,
1313 unsigned int offset_in_page, void *buf,
1314 unsigned int len, bool force_8bit)
1316 struct mtd_info *mtd = nand_to_mtd(chip);
1321 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1324 /* Small page NANDs do not support column change. */
1325 if (mtd->writesize <= 512)
1328 if (nand_has_exec_op(chip)) {
1329 const struct nand_interface_config *conf =
1330 nand_get_interface_config(chip);
1332 struct nand_op_instr instrs[] = {
1333 NAND_OP_CMD(NAND_CMD_RNDOUT, 0),
1334 NAND_OP_ADDR(2, addrs, 0),
1335 NAND_OP_CMD(NAND_CMD_RNDOUTSTART,
1336 NAND_COMMON_TIMING_NS(conf, tCCS_min)),
1337 NAND_OP_DATA_IN(len, buf, 0),
1339 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1342 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1346 /* Drop the DATA_IN instruction if len is set to 0. */
1350 instrs[3].ctx.data.force_8bit = force_8bit;
1352 return nand_exec_op(chip, &op);
1355 chip->legacy.cmdfunc(chip, NAND_CMD_RNDOUT, offset_in_page, -1);
1357 chip->legacy.read_buf(chip, buf, len);
1361 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1364 * nand_read_oob_op - Do a READ OOB operation
1365 * @chip: The NAND chip
1366 * @page: page to read
1367 * @offset_in_oob: offset within the OOB area
1368 * @buf: buffer used to store the data
1369 * @len: length of the buffer
1371 * This function issues a READ OOB operation.
1372 * This function does not select/unselect the CS line.
1374 * Returns 0 on success, a negative error code otherwise.
1376 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1377 unsigned int offset_in_oob, void *buf, unsigned int len)
1379 struct mtd_info *mtd = nand_to_mtd(chip);
1384 if (offset_in_oob + len > mtd->oobsize)
1387 if (nand_has_exec_op(chip))
1388 return nand_read_page_op(chip, page,
1389 mtd->writesize + offset_in_oob,
1392 chip->legacy.cmdfunc(chip, NAND_CMD_READOOB, offset_in_oob, page);
1394 chip->legacy.read_buf(chip, buf, len);
1398 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1400 static int nand_exec_prog_page_op(struct nand_chip *chip, unsigned int page,
1401 unsigned int offset_in_page, const void *buf,
1402 unsigned int len, bool prog)
1404 const struct nand_interface_config *conf =
1405 nand_get_interface_config(chip);
1406 struct mtd_info *mtd = nand_to_mtd(chip);
1408 struct nand_op_instr instrs[] = {
1410 * The first instruction will be dropped if we're dealing
1411 * with a large page NAND and adjusted if we're dealing
1412 * with a small page NAND and the page offset is > 255.
1414 NAND_OP_CMD(NAND_CMD_READ0, 0),
1415 NAND_OP_CMD(NAND_CMD_SEQIN, 0),
1416 NAND_OP_ADDR(0, addrs, NAND_COMMON_TIMING_NS(conf, tADL_min)),
1417 NAND_OP_DATA_OUT(len, buf, 0),
1418 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1419 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1420 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tPROG_max), 0),
1422 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1423 int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
1428 addrs[naddrs++] = page;
1429 addrs[naddrs++] = page >> 8;
1430 if (chip->options & NAND_ROW_ADDR_3)
1431 addrs[naddrs++] = page >> 16;
1433 instrs[2].ctx.addr.naddrs = naddrs;
1435 /* Drop the last two instructions if we're not programming the page. */
1438 /* Also drop the DATA_OUT instruction if empty. */
1443 if (mtd->writesize <= 512) {
1445 * Small pages need some more tweaking: we have to adjust the
1446 * first instruction depending on the page offset we're trying
1449 if (offset_in_page >= mtd->writesize)
1450 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1451 else if (offset_in_page >= 256 &&
1452 !(chip->options & NAND_BUSWIDTH_16))
1453 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1456 * Drop the first command if we're dealing with a large page
1463 return nand_exec_op(chip, &op);
1467 * nand_prog_page_begin_op - starts a PROG PAGE operation
1468 * @chip: The NAND chip
1469 * @page: page to write
1470 * @offset_in_page: offset within the page
1471 * @buf: buffer containing the data to write to the page
1472 * @len: length of the buffer
1474 * This function issues the first half of a PROG PAGE operation.
1475 * This function does not select/unselect the CS line.
1477 * Returns 0 on success, a negative error code otherwise.
1479 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1480 unsigned int offset_in_page, const void *buf,
1483 struct mtd_info *mtd = nand_to_mtd(chip);
1488 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1491 if (nand_has_exec_op(chip))
1492 return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1495 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page, page);
1498 chip->legacy.write_buf(chip, buf, len);
1502 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1505 * nand_prog_page_end_op - ends a PROG PAGE operation
1506 * @chip: The NAND chip
1508 * This function issues the second half of a PROG PAGE operation.
1509 * This function does not select/unselect the CS line.
1511 * Returns 0 on success, a negative error code otherwise.
1513 int nand_prog_page_end_op(struct nand_chip *chip)
1518 if (nand_has_exec_op(chip)) {
1519 const struct nand_interface_config *conf =
1520 nand_get_interface_config(chip);
1521 struct nand_op_instr instrs[] = {
1522 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1523 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1524 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tPROG_max),
1527 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1529 ret = nand_exec_op(chip, &op);
1533 ret = nand_status_op(chip, &status);
1537 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1538 ret = chip->legacy.waitfunc(chip);
1545 if (status & NAND_STATUS_FAIL)
1550 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1553 * nand_prog_page_op - Do a full PROG PAGE operation
1554 * @chip: The NAND chip
1555 * @page: page to write
1556 * @offset_in_page: offset within the page
1557 * @buf: buffer containing the data to write to the page
1558 * @len: length of the buffer
1560 * This function issues a full PROG PAGE operation.
1561 * This function does not select/unselect the CS line.
1563 * Returns 0 on success, a negative error code otherwise.
1565 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1566 unsigned int offset_in_page, const void *buf,
1569 struct mtd_info *mtd = nand_to_mtd(chip);
1576 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1579 if (nand_has_exec_op(chip)) {
1580 ret = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1585 ret = nand_status_op(chip, &status);
1589 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page,
1591 chip->legacy.write_buf(chip, buf, len);
1592 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1593 ret = chip->legacy.waitfunc(chip);
1600 if (status & NAND_STATUS_FAIL)
1605 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1608 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1609 * @chip: The NAND chip
1610 * @offset_in_page: offset within the page
1611 * @buf: buffer containing the data to send to the NAND
1612 * @len: length of the buffer
1613 * @force_8bit: force 8-bit bus access
1615 * This function issues a CHANGE WRITE COLUMN operation.
1616 * This function does not select/unselect the CS line.
1618 * Returns 0 on success, a negative error code otherwise.
1620 int nand_change_write_column_op(struct nand_chip *chip,
1621 unsigned int offset_in_page,
1622 const void *buf, unsigned int len,
1625 struct mtd_info *mtd = nand_to_mtd(chip);
1630 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1633 /* Small page NANDs do not support column change. */
1634 if (mtd->writesize <= 512)
1637 if (nand_has_exec_op(chip)) {
1638 const struct nand_interface_config *conf =
1639 nand_get_interface_config(chip);
1641 struct nand_op_instr instrs[] = {
1642 NAND_OP_CMD(NAND_CMD_RNDIN, 0),
1643 NAND_OP_ADDR(2, addrs, NAND_COMMON_TIMING_NS(conf, tCCS_min)),
1644 NAND_OP_DATA_OUT(len, buf, 0),
1646 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1649 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1653 instrs[2].ctx.data.force_8bit = force_8bit;
1655 /* Drop the DATA_OUT instruction if len is set to 0. */
1659 return nand_exec_op(chip, &op);
1662 chip->legacy.cmdfunc(chip, NAND_CMD_RNDIN, offset_in_page, -1);
1664 chip->legacy.write_buf(chip, buf, len);
1668 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1671 * nand_readid_op - Do a READID operation
1672 * @chip: The NAND chip
1673 * @addr: address cycle to pass after the READID command
1674 * @buf: buffer used to store the ID
1675 * @len: length of the buffer
1677 * This function sends a READID command and reads back the ID returned by the
1679 * This function does not select/unselect the CS line.
1681 * Returns 0 on success, a negative error code otherwise.
1683 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1687 u8 *id = buf, *ddrbuf = NULL;
1692 if (nand_has_exec_op(chip)) {
1693 const struct nand_interface_config *conf =
1694 nand_get_interface_config(chip);
1695 struct nand_op_instr instrs[] = {
1696 NAND_OP_CMD(NAND_CMD_READID, 0),
1697 NAND_OP_ADDR(1, &addr,
1698 NAND_COMMON_TIMING_NS(conf, tADL_min)),
1699 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1701 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1704 /* READ_ID data bytes are received twice in NV-DDR mode */
1705 if (len && nand_interface_is_nvddr(conf)) {
1706 ddrbuf = kzalloc(len * 2, GFP_KERNEL);
1710 instrs[2].ctx.data.len *= 2;
1711 instrs[2].ctx.data.buf.in = ddrbuf;
1714 /* Drop the DATA_IN instruction if len is set to 0. */
1718 ret = nand_exec_op(chip, &op);
1719 if (!ret && len && nand_interface_is_nvddr(conf)) {
1720 for (i = 0; i < len; i++)
1721 id[i] = ddrbuf[i * 2];
1729 chip->legacy.cmdfunc(chip, NAND_CMD_READID, addr, -1);
1731 for (i = 0; i < len; i++)
1732 id[i] = chip->legacy.read_byte(chip);
1736 EXPORT_SYMBOL_GPL(nand_readid_op);
1739 * nand_status_op - Do a STATUS operation
1740 * @chip: The NAND chip
1741 * @status: out variable to store the NAND status
1743 * This function sends a STATUS command and reads back the status returned by
1745 * This function does not select/unselect the CS line.
1747 * Returns 0 on success, a negative error code otherwise.
1749 int nand_status_op(struct nand_chip *chip, u8 *status)
1751 if (nand_has_exec_op(chip)) {
1752 const struct nand_interface_config *conf =
1753 nand_get_interface_config(chip);
1755 struct nand_op_instr instrs[] = {
1756 NAND_OP_CMD(NAND_CMD_STATUS,
1757 NAND_COMMON_TIMING_NS(conf, tADL_min)),
1758 NAND_OP_8BIT_DATA_IN(1, status, 0),
1760 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1763 /* The status data byte will be received twice in NV-DDR mode */
1764 if (status && nand_interface_is_nvddr(conf)) {
1765 instrs[1].ctx.data.len *= 2;
1766 instrs[1].ctx.data.buf.in = ddrstatus;
1772 ret = nand_exec_op(chip, &op);
1773 if (!ret && status && nand_interface_is_nvddr(conf))
1774 *status = ddrstatus[0];
1779 chip->legacy.cmdfunc(chip, NAND_CMD_STATUS, -1, -1);
1781 *status = chip->legacy.read_byte(chip);
1785 EXPORT_SYMBOL_GPL(nand_status_op);
1788 * nand_exit_status_op - Exit a STATUS operation
1789 * @chip: The NAND chip
1791 * This function sends a READ0 command to cancel the effect of the STATUS
1792 * command to avoid reading only the status until a new read command is sent.
1794 * This function does not select/unselect the CS line.
1796 * Returns 0 on success, a negative error code otherwise.
1798 int nand_exit_status_op(struct nand_chip *chip)
1800 if (nand_has_exec_op(chip)) {
1801 struct nand_op_instr instrs[] = {
1802 NAND_OP_CMD(NAND_CMD_READ0, 0),
1804 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1806 return nand_exec_op(chip, &op);
1809 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, -1, -1);
1815 * nand_erase_op - Do an erase operation
1816 * @chip: The NAND chip
1817 * @eraseblock: block to erase
1819 * This function sends an ERASE command and waits for the NAND to be ready
1821 * This function does not select/unselect the CS line.
1823 * Returns 0 on success, a negative error code otherwise.
1825 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1827 unsigned int page = eraseblock <<
1828 (chip->phys_erase_shift - chip->page_shift);
1832 if (nand_has_exec_op(chip)) {
1833 const struct nand_interface_config *conf =
1834 nand_get_interface_config(chip);
1835 u8 addrs[3] = { page, page >> 8, page >> 16 };
1836 struct nand_op_instr instrs[] = {
1837 NAND_OP_CMD(NAND_CMD_ERASE1, 0),
1838 NAND_OP_ADDR(2, addrs, 0),
1839 NAND_OP_CMD(NAND_CMD_ERASE2,
1840 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1841 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tBERS_max),
1844 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1846 if (chip->options & NAND_ROW_ADDR_3)
1847 instrs[1].ctx.addr.naddrs++;
1849 ret = nand_exec_op(chip, &op);
1853 ret = nand_status_op(chip, &status);
1857 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE1, -1, page);
1858 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE2, -1, -1);
1860 ret = chip->legacy.waitfunc(chip);
1867 if (status & NAND_STATUS_FAIL)
1872 EXPORT_SYMBOL_GPL(nand_erase_op);
1875 * nand_set_features_op - Do a SET FEATURES operation
1876 * @chip: The NAND chip
1877 * @feature: feature id
1878 * @data: 4 bytes of data
1880 * This function sends a SET FEATURES command and waits for the NAND to be
1881 * ready before returning.
1882 * This function does not select/unselect the CS line.
1884 * Returns 0 on success, a negative error code otherwise.
1886 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1889 const u8 *params = data;
1892 if (nand_has_exec_op(chip)) {
1893 const struct nand_interface_config *conf =
1894 nand_get_interface_config(chip);
1895 struct nand_op_instr instrs[] = {
1896 NAND_OP_CMD(NAND_CMD_SET_FEATURES, 0),
1897 NAND_OP_ADDR(1, &feature, NAND_COMMON_TIMING_NS(conf,
1899 NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
1900 NAND_COMMON_TIMING_NS(conf,
1902 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tFEAT_max),
1905 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1907 return nand_exec_op(chip, &op);
1910 chip->legacy.cmdfunc(chip, NAND_CMD_SET_FEATURES, feature, -1);
1911 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1912 chip->legacy.write_byte(chip, params[i]);
1914 ret = chip->legacy.waitfunc(chip);
1918 if (ret & NAND_STATUS_FAIL)
1925 * nand_get_features_op - Do a GET FEATURES operation
1926 * @chip: The NAND chip
1927 * @feature: feature id
1928 * @data: 4 bytes of data
1930 * This function sends a GET FEATURES command and waits for the NAND to be
1931 * ready before returning.
1932 * This function does not select/unselect the CS line.
1934 * Returns 0 on success, a negative error code otherwise.
1936 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1939 u8 *params = data, ddrbuf[ONFI_SUBFEATURE_PARAM_LEN * 2];
1942 if (nand_has_exec_op(chip)) {
1943 const struct nand_interface_config *conf =
1944 nand_get_interface_config(chip);
1945 struct nand_op_instr instrs[] = {
1946 NAND_OP_CMD(NAND_CMD_GET_FEATURES, 0),
1947 NAND_OP_ADDR(1, &feature,
1948 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1949 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tFEAT_max),
1950 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1951 NAND_OP_8BIT_DATA_IN(ONFI_SUBFEATURE_PARAM_LEN,
1954 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1957 /* GET_FEATURE data bytes are received twice in NV-DDR mode */
1958 if (nand_interface_is_nvddr(conf)) {
1959 instrs[3].ctx.data.len *= 2;
1960 instrs[3].ctx.data.buf.in = ddrbuf;
1963 ret = nand_exec_op(chip, &op);
1964 if (nand_interface_is_nvddr(conf)) {
1965 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; i++)
1966 params[i] = ddrbuf[i * 2];
1972 chip->legacy.cmdfunc(chip, NAND_CMD_GET_FEATURES, feature, -1);
1973 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1974 params[i] = chip->legacy.read_byte(chip);
1979 static int nand_wait_rdy_op(struct nand_chip *chip, unsigned int timeout_ms,
1980 unsigned int delay_ns)
1982 if (nand_has_exec_op(chip)) {
1983 struct nand_op_instr instrs[] = {
1984 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(timeout_ms),
1985 PSEC_TO_NSEC(delay_ns)),
1987 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1989 return nand_exec_op(chip, &op);
1992 /* Apply delay or wait for ready/busy pin */
1993 if (!chip->legacy.dev_ready)
1994 udelay(chip->legacy.chip_delay);
1996 nand_wait_ready(chip);
2002 * nand_reset_op - Do a reset operation
2003 * @chip: The NAND chip
2005 * This function sends a RESET command and waits for the NAND to be ready
2007 * This function does not select/unselect the CS line.
2009 * Returns 0 on success, a negative error code otherwise.
2011 int nand_reset_op(struct nand_chip *chip)
2013 if (nand_has_exec_op(chip)) {
2014 const struct nand_interface_config *conf =
2015 nand_get_interface_config(chip);
2016 struct nand_op_instr instrs[] = {
2017 NAND_OP_CMD(NAND_CMD_RESET,
2018 NAND_COMMON_TIMING_NS(conf, tWB_max)),
2019 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tRST_max),
2022 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2024 return nand_exec_op(chip, &op);
2027 chip->legacy.cmdfunc(chip, NAND_CMD_RESET, -1, -1);
2031 EXPORT_SYMBOL_GPL(nand_reset_op);
2034 * nand_read_data_op - Read data from the NAND
2035 * @chip: The NAND chip
2036 * @buf: buffer used to store the data
2037 * @len: length of the buffer
2038 * @force_8bit: force 8-bit bus access
2039 * @check_only: do not actually run the command, only checks if the
2040 * controller driver supports it
2042 * This function does a raw data read on the bus. Usually used after launching
2043 * another NAND operation like nand_read_page_op().
2044 * This function does not select/unselect the CS line.
2046 * Returns 0 on success, a negative error code otherwise.
2048 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
2049 bool force_8bit, bool check_only)
2054 if (nand_has_exec_op(chip)) {
2055 const struct nand_interface_config *conf =
2056 nand_get_interface_config(chip);
2057 struct nand_op_instr instrs[] = {
2058 NAND_OP_DATA_IN(len, buf, 0),
2060 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2064 instrs[0].ctx.data.force_8bit = force_8bit;
2067 * Parameter payloads (ID, status, features, etc) do not go
2068 * through the same pipeline as regular data, hence the
2069 * force_8bit flag must be set and this also indicates that in
2070 * case NV-DDR timings are being used the data will be received
2073 if (force_8bit && nand_interface_is_nvddr(conf)) {
2074 ddrbuf = kzalloc(len * 2, GFP_KERNEL);
2078 instrs[0].ctx.data.len *= 2;
2079 instrs[0].ctx.data.buf.in = ddrbuf;
2083 ret = nand_check_op(chip, &op);
2088 ret = nand_exec_op(chip, &op);
2089 if (!ret && force_8bit && nand_interface_is_nvddr(conf)) {
2092 for (i = 0; i < len; i++)
2093 dst[i] = ddrbuf[i * 2];
2108 for (i = 0; i < len; i++)
2109 p[i] = chip->legacy.read_byte(chip);
2111 chip->legacy.read_buf(chip, buf, len);
2116 EXPORT_SYMBOL_GPL(nand_read_data_op);
2119 * nand_write_data_op - Write data from the NAND
2120 * @chip: The NAND chip
2121 * @buf: buffer containing the data to send on the bus
2122 * @len: length of the buffer
2123 * @force_8bit: force 8-bit bus access
2125 * This function does a raw data write on the bus. Usually used after launching
2126 * another NAND operation like nand_write_page_begin_op().
2127 * This function does not select/unselect the CS line.
2129 * Returns 0 on success, a negative error code otherwise.
2131 int nand_write_data_op(struct nand_chip *chip, const void *buf,
2132 unsigned int len, bool force_8bit)
2137 if (nand_has_exec_op(chip)) {
2138 struct nand_op_instr instrs[] = {
2139 NAND_OP_DATA_OUT(len, buf, 0),
2141 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2143 instrs[0].ctx.data.force_8bit = force_8bit;
2145 return nand_exec_op(chip, &op);
2152 for (i = 0; i < len; i++)
2153 chip->legacy.write_byte(chip, p[i]);
2155 chip->legacy.write_buf(chip, buf, len);
2160 EXPORT_SYMBOL_GPL(nand_write_data_op);
2163 * struct nand_op_parser_ctx - Context used by the parser
2164 * @instrs: array of all the instructions that must be addressed
2165 * @ninstrs: length of the @instrs array
2166 * @subop: Sub-operation to be passed to the NAND controller
2168 * This structure is used by the core to split NAND operations into
2169 * sub-operations that can be handled by the NAND controller.
2171 struct nand_op_parser_ctx {
2172 const struct nand_op_instr *instrs;
2173 unsigned int ninstrs;
2174 struct nand_subop subop;
2178 * nand_op_parser_must_split_instr - Checks if an instruction must be split
2179 * @pat: the parser pattern element that matches @instr
2180 * @instr: pointer to the instruction to check
2181 * @start_offset: this is an in/out parameter. If @instr has already been
2182 * split, then @start_offset is the offset from which to start
2183 * (either an address cycle or an offset in the data buffer).
2184 * Conversely, if the function returns true (ie. instr must be
2185 * split), this parameter is updated to point to the first
2186 * data/address cycle that has not been taken care of.
2188 * Some NAND controllers are limited and cannot send X address cycles with a
2189 * unique operation, or cannot read/write more than Y bytes at the same time.
2190 * In this case, split the instruction that does not fit in a single
2191 * controller-operation into two or more chunks.
2193 * Returns true if the instruction must be split, false otherwise.
2194 * The @start_offset parameter is also updated to the offset at which the next
2195 * bundle of instruction must start (if an address or a data instruction).
2198 nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat,
2199 const struct nand_op_instr *instr,
2200 unsigned int *start_offset)
2202 switch (pat->type) {
2203 case NAND_OP_ADDR_INSTR:
2204 if (!pat->ctx.addr.maxcycles)
2207 if (instr->ctx.addr.naddrs - *start_offset >
2208 pat->ctx.addr.maxcycles) {
2209 *start_offset += pat->ctx.addr.maxcycles;
2214 case NAND_OP_DATA_IN_INSTR:
2215 case NAND_OP_DATA_OUT_INSTR:
2216 if (!pat->ctx.data.maxlen)
2219 if (instr->ctx.data.len - *start_offset >
2220 pat->ctx.data.maxlen) {
2221 *start_offset += pat->ctx.data.maxlen;
2234 * nand_op_parser_match_pat - Checks if a pattern matches the instructions
2235 * remaining in the parser context
2236 * @pat: the pattern to test
2237 * @ctx: the parser context structure to match with the pattern @pat
2239 * Check if @pat matches the set or a sub-set of instructions remaining in @ctx.
2240 * Returns true if this is the case, false ortherwise. When true is returned,
2241 * @ctx->subop is updated with the set of instructions to be passed to the
2242 * controller driver.
2245 nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
2246 struct nand_op_parser_ctx *ctx)
2248 unsigned int instr_offset = ctx->subop.first_instr_start_off;
2249 const struct nand_op_instr *end = ctx->instrs + ctx->ninstrs;
2250 const struct nand_op_instr *instr = ctx->subop.instrs;
2251 unsigned int i, ninstrs;
2253 for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
2255 * The pattern instruction does not match the operation
2256 * instruction. If the instruction is marked optional in the
2257 * pattern definition, we skip the pattern element and continue
2258 * to the next one. If the element is mandatory, there's no
2259 * match and we can return false directly.
2261 if (instr->type != pat->elems[i].type) {
2262 if (!pat->elems[i].optional)
2269 * Now check the pattern element constraints. If the pattern is
2270 * not able to handle the whole instruction in a single step,
2271 * we have to split it.
2272 * The last_instr_end_off value comes back updated to point to
2273 * the position where we have to split the instruction (the
2274 * start of the next subop chunk).
2276 if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
2289 * This can happen if all instructions of a pattern are optional.
2290 * Still, if there's not at least one instruction handled by this
2291 * pattern, this is not a match, and we should try the next one (if
2298 * We had a match on the pattern head, but the pattern may be longer
2299 * than the instructions we're asked to execute. We need to make sure
2300 * there's no mandatory elements in the pattern tail.
2302 for (; i < pat->nelems; i++) {
2303 if (!pat->elems[i].optional)
2308 * We have a match: update the subop structure accordingly and return
2311 ctx->subop.ninstrs = ninstrs;
2312 ctx->subop.last_instr_end_off = instr_offset;
2317 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
2318 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2320 const struct nand_op_instr *instr;
2324 pr_debug("executing subop (CS%d):\n", ctx->subop.cs);
2326 for (i = 0; i < ctx->ninstrs; i++) {
2327 instr = &ctx->instrs[i];
2329 if (instr == &ctx->subop.instrs[0])
2332 nand_op_trace(prefix, instr);
2334 if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
2339 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2345 static int nand_op_parser_cmp_ctx(const struct nand_op_parser_ctx *a,
2346 const struct nand_op_parser_ctx *b)
2348 if (a->subop.ninstrs < b->subop.ninstrs)
2350 else if (a->subop.ninstrs > b->subop.ninstrs)
2353 if (a->subop.last_instr_end_off < b->subop.last_instr_end_off)
2355 else if (a->subop.last_instr_end_off > b->subop.last_instr_end_off)
2362 * nand_op_parser_exec_op - exec_op parser
2363 * @chip: the NAND chip
2364 * @parser: patterns description provided by the controller driver
2365 * @op: the NAND operation to address
2366 * @check_only: when true, the function only checks if @op can be handled but
2367 * does not execute the operation
2369 * Helper function designed to ease integration of NAND controller drivers that
2370 * only support a limited set of instruction sequences. The supported sequences
2371 * are described in @parser, and the framework takes care of splitting @op into
2372 * multiple sub-operations (if required) and pass them back to the ->exec()
2373 * callback of the matching pattern if @check_only is set to false.
2375 * NAND controller drivers should call this function from their own ->exec_op()
2378 * Returns 0 on success, a negative error code otherwise. A failure can be
2379 * caused by an unsupported operation (none of the supported patterns is able
2380 * to handle the requested operation), or an error returned by one of the
2381 * matching pattern->exec() hook.
2383 int nand_op_parser_exec_op(struct nand_chip *chip,
2384 const struct nand_op_parser *parser,
2385 const struct nand_operation *op, bool check_only)
2387 struct nand_op_parser_ctx ctx = {
2389 .subop.instrs = op->instrs,
2390 .instrs = op->instrs,
2391 .ninstrs = op->ninstrs,
2395 while (ctx.subop.instrs < op->instrs + op->ninstrs) {
2396 const struct nand_op_parser_pattern *pattern;
2397 struct nand_op_parser_ctx best_ctx;
2398 int ret, best_pattern = -1;
2400 for (i = 0; i < parser->npatterns; i++) {
2401 struct nand_op_parser_ctx test_ctx = ctx;
2403 pattern = &parser->patterns[i];
2404 if (!nand_op_parser_match_pat(pattern, &test_ctx))
2407 if (best_pattern >= 0 &&
2408 nand_op_parser_cmp_ctx(&test_ctx, &best_ctx) <= 0)
2412 best_ctx = test_ctx;
2415 if (best_pattern < 0) {
2416 pr_debug("->exec_op() parser: pattern not found!\n");
2421 nand_op_parser_trace(&ctx);
2424 pattern = &parser->patterns[best_pattern];
2425 ret = pattern->exec(chip, &ctx.subop);
2431 * Update the context structure by pointing to the start of the
2434 ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
2435 if (ctx.subop.last_instr_end_off)
2436 ctx.subop.instrs -= 1;
2438 ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
2443 EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
2445 static bool nand_instr_is_data(const struct nand_op_instr *instr)
2447 return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
2448 instr->type == NAND_OP_DATA_OUT_INSTR);
2451 static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
2452 unsigned int instr_idx)
2454 return subop && instr_idx < subop->ninstrs;
2457 static unsigned int nand_subop_get_start_off(const struct nand_subop *subop,
2458 unsigned int instr_idx)
2463 return subop->first_instr_start_off;
2467 * nand_subop_get_addr_start_off - Get the start offset in an address array
2468 * @subop: The entire sub-operation
2469 * @instr_idx: Index of the instruction inside the sub-operation
2471 * During driver development, one could be tempted to directly use the
2472 * ->addr.addrs field of address instructions. This is wrong as address
2473 * instructions might be split.
2475 * Given an address instruction, returns the offset of the first cycle to issue.
2477 unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
2478 unsigned int instr_idx)
2480 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2481 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2484 return nand_subop_get_start_off(subop, instr_idx);
2486 EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
2489 * nand_subop_get_num_addr_cyc - Get the remaining address cycles to assert
2490 * @subop: The entire sub-operation
2491 * @instr_idx: Index of the instruction inside the sub-operation
2493 * During driver development, one could be tempted to directly use the
2494 * ->addr->naddrs field of a data instruction. This is wrong as instructions
2497 * Given an address instruction, returns the number of address cycle to issue.
2499 unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
2500 unsigned int instr_idx)
2502 int start_off, end_off;
2504 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2505 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2508 start_off = nand_subop_get_addr_start_off(subop, instr_idx);
2510 if (instr_idx == subop->ninstrs - 1 &&
2511 subop->last_instr_end_off)
2512 end_off = subop->last_instr_end_off;
2514 end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
2516 return end_off - start_off;
2518 EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
2521 * nand_subop_get_data_start_off - Get the start offset in a data array
2522 * @subop: The entire sub-operation
2523 * @instr_idx: Index of the instruction inside the sub-operation
2525 * During driver development, one could be tempted to directly use the
2526 * ->data->buf.{in,out} field of data instructions. This is wrong as data
2527 * instructions might be split.
2529 * Given a data instruction, returns the offset to start from.
2531 unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
2532 unsigned int instr_idx)
2534 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2535 !nand_instr_is_data(&subop->instrs[instr_idx])))
2538 return nand_subop_get_start_off(subop, instr_idx);
2540 EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
2543 * nand_subop_get_data_len - Get the number of bytes to retrieve
2544 * @subop: The entire sub-operation
2545 * @instr_idx: Index of the instruction inside the sub-operation
2547 * During driver development, one could be tempted to directly use the
2548 * ->data->len field of a data instruction. This is wrong as data instructions
2551 * Returns the length of the chunk of data to send/receive.
2553 unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
2554 unsigned int instr_idx)
2556 int start_off = 0, end_off;
2558 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2559 !nand_instr_is_data(&subop->instrs[instr_idx])))
2562 start_off = nand_subop_get_data_start_off(subop, instr_idx);
2564 if (instr_idx == subop->ninstrs - 1 &&
2565 subop->last_instr_end_off)
2566 end_off = subop->last_instr_end_off;
2568 end_off = subop->instrs[instr_idx].ctx.data.len;
2570 return end_off - start_off;
2572 EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
2575 * nand_reset - Reset and initialize a NAND device
2576 * @chip: The NAND chip
2577 * @chipnr: Internal die id
2579 * Save the timings data structure, then apply SDR timings mode 0 (see
2580 * nand_reset_interface for details), do the reset operation, and apply
2581 * back the previous timings.
2583 * Returns 0 on success, a negative error code otherwise.
2585 int nand_reset(struct nand_chip *chip, int chipnr)
2589 ret = nand_reset_interface(chip, chipnr);
2594 * The CS line has to be released before we can apply the new NAND
2595 * interface settings, hence this weird nand_select_target()
2596 * nand_deselect_target() dance.
2598 nand_select_target(chip, chipnr);
2599 ret = nand_reset_op(chip);
2600 nand_deselect_target(chip);
2604 ret = nand_setup_interface(chip, chipnr);
2610 EXPORT_SYMBOL_GPL(nand_reset);
2613 * nand_get_features - wrapper to perform a GET_FEATURE
2614 * @chip: NAND chip info structure
2615 * @addr: feature address
2616 * @subfeature_param: the subfeature parameters, a four bytes array
2618 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2619 * operation cannot be handled.
2621 int nand_get_features(struct nand_chip *chip, int addr,
2622 u8 *subfeature_param)
2624 if (!nand_supports_get_features(chip, addr))
2627 if (chip->legacy.get_features)
2628 return chip->legacy.get_features(chip, addr, subfeature_param);
2630 return nand_get_features_op(chip, addr, subfeature_param);
2634 * nand_set_features - wrapper to perform a SET_FEATURE
2635 * @chip: NAND chip info structure
2636 * @addr: feature address
2637 * @subfeature_param: the subfeature parameters, a four bytes array
2639 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2640 * operation cannot be handled.
2642 int nand_set_features(struct nand_chip *chip, int addr,
2643 u8 *subfeature_param)
2645 if (!nand_supports_set_features(chip, addr))
2648 if (chip->legacy.set_features)
2649 return chip->legacy.set_features(chip, addr, subfeature_param);
2651 return nand_set_features_op(chip, addr, subfeature_param);
2655 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
2656 * @buf: buffer to test
2657 * @len: buffer length
2658 * @bitflips_threshold: maximum number of bitflips
2660 * Check if a buffer contains only 0xff, which means the underlying region
2661 * has been erased and is ready to be programmed.
2662 * The bitflips_threshold specify the maximum number of bitflips before
2663 * considering the region is not erased.
2664 * Note: The logic of this function has been extracted from the memweight
2665 * implementation, except that nand_check_erased_buf function exit before
2666 * testing the whole buffer if the number of bitflips exceed the
2667 * bitflips_threshold value.
2669 * Returns a positive number of bitflips less than or equal to
2670 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2673 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
2675 const unsigned char *bitmap = buf;
2679 for (; len && ((uintptr_t)bitmap) % sizeof(long);
2681 weight = hweight8(*bitmap);
2682 bitflips += BITS_PER_BYTE - weight;
2683 if (unlikely(bitflips > bitflips_threshold))
2687 for (; len >= sizeof(long);
2688 len -= sizeof(long), bitmap += sizeof(long)) {
2689 unsigned long d = *((unsigned long *)bitmap);
2692 weight = hweight_long(d);
2693 bitflips += BITS_PER_LONG - weight;
2694 if (unlikely(bitflips > bitflips_threshold))
2698 for (; len > 0; len--, bitmap++) {
2699 weight = hweight8(*bitmap);
2700 bitflips += BITS_PER_BYTE - weight;
2701 if (unlikely(bitflips > bitflips_threshold))
2709 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
2711 * @data: data buffer to test
2712 * @datalen: data length
2714 * @ecclen: ECC length
2715 * @extraoob: extra OOB buffer
2716 * @extraooblen: extra OOB length
2717 * @bitflips_threshold: maximum number of bitflips
2719 * Check if a data buffer and its associated ECC and OOB data contains only
2720 * 0xff pattern, which means the underlying region has been erased and is
2721 * ready to be programmed.
2722 * The bitflips_threshold specify the maximum number of bitflips before
2723 * considering the region as not erased.
2726 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
2727 * different from the NAND page size. When fixing bitflips, ECC engines will
2728 * report the number of errors per chunk, and the NAND core infrastructure
2729 * expect you to return the maximum number of bitflips for the whole page.
2730 * This is why you should always use this function on a single chunk and
2731 * not on the whole page. After checking each chunk you should update your
2732 * max_bitflips value accordingly.
2733 * 2/ When checking for bitflips in erased pages you should not only check
2734 * the payload data but also their associated ECC data, because a user might
2735 * have programmed almost all bits to 1 but a few. In this case, we
2736 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
2738 * 3/ The extraoob argument is optional, and should be used if some of your OOB
2739 * data are protected by the ECC engine.
2740 * It could also be used if you support subpages and want to attach some
2741 * extra OOB data to an ECC chunk.
2743 * Returns a positive number of bitflips less than or equal to
2744 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2745 * threshold. In case of success, the passed buffers are filled with 0xff.
2747 int nand_check_erased_ecc_chunk(void *data, int datalen,
2748 void *ecc, int ecclen,
2749 void *extraoob, int extraooblen,
2750 int bitflips_threshold)
2752 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
2754 data_bitflips = nand_check_erased_buf(data, datalen,
2755 bitflips_threshold);
2756 if (data_bitflips < 0)
2757 return data_bitflips;
2759 bitflips_threshold -= data_bitflips;
2761 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
2762 if (ecc_bitflips < 0)
2763 return ecc_bitflips;
2765 bitflips_threshold -= ecc_bitflips;
2767 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
2768 bitflips_threshold);
2769 if (extraoob_bitflips < 0)
2770 return extraoob_bitflips;
2773 memset(data, 0xff, datalen);
2776 memset(ecc, 0xff, ecclen);
2778 if (extraoob_bitflips)
2779 memset(extraoob, 0xff, extraooblen);
2781 return data_bitflips + ecc_bitflips + extraoob_bitflips;
2783 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
2786 * nand_read_page_raw_notsupp - dummy read raw page function
2787 * @chip: nand chip info structure
2788 * @buf: buffer to store read data
2789 * @oob_required: caller requires OOB data read to chip->oob_poi
2790 * @page: page number to read
2792 * Returns -ENOTSUPP unconditionally.
2794 int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf,
2795 int oob_required, int page)
2801 * nand_read_page_raw - [INTERN] read raw page data without ecc
2802 * @chip: nand chip info structure
2803 * @buf: buffer to store read data
2804 * @oob_required: caller requires OOB data read to chip->oob_poi
2805 * @page: page number to read
2807 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2809 int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
2812 struct mtd_info *mtd = nand_to_mtd(chip);
2815 ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
2820 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
2828 EXPORT_SYMBOL(nand_read_page_raw);
2831 * nand_monolithic_read_page_raw - Monolithic page read in raw mode
2832 * @chip: NAND chip info structure
2833 * @buf: buffer to store read data
2834 * @oob_required: caller requires OOB data read to chip->oob_poi
2835 * @page: page number to read
2837 * This is a raw page read, ie. without any error detection/correction.
2838 * Monolithic means we are requesting all the relevant data (main plus
2839 * eventually OOB) to be loaded in the NAND cache and sent over the
2840 * bus (from the NAND chip to the NAND controller) in a single
2841 * operation. This is an alternative to nand_read_page_raw(), which
2842 * first reads the main data, and if the OOB data is requested too,
2843 * then reads more data on the bus.
2845 int nand_monolithic_read_page_raw(struct nand_chip *chip, u8 *buf,
2846 int oob_required, int page)
2848 struct mtd_info *mtd = nand_to_mtd(chip);
2849 unsigned int size = mtd->writesize;
2854 size += mtd->oobsize;
2856 if (buf != chip->data_buf)
2857 read_buf = nand_get_data_buf(chip);
2860 ret = nand_read_page_op(chip, page, 0, read_buf, size);
2864 if (buf != chip->data_buf)
2865 memcpy(buf, read_buf, mtd->writesize);
2869 EXPORT_SYMBOL(nand_monolithic_read_page_raw);
2872 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
2873 * @chip: nand chip info structure
2874 * @buf: buffer to store read data
2875 * @oob_required: caller requires OOB data read to chip->oob_poi
2876 * @page: page number to read
2878 * We need a special oob layout and handling even when OOB isn't used.
2880 static int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf,
2881 int oob_required, int page)
2883 struct mtd_info *mtd = nand_to_mtd(chip);
2884 int eccsize = chip->ecc.size;
2885 int eccbytes = chip->ecc.bytes;
2886 uint8_t *oob = chip->oob_poi;
2887 int steps, size, ret;
2889 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2893 for (steps = chip->ecc.steps; steps > 0; steps--) {
2894 ret = nand_read_data_op(chip, buf, eccsize, false, false);
2900 if (chip->ecc.prepad) {
2901 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2906 oob += chip->ecc.prepad;
2909 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
2915 if (chip->ecc.postpad) {
2916 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2921 oob += chip->ecc.postpad;
2925 size = mtd->oobsize - (oob - chip->oob_poi);
2927 ret = nand_read_data_op(chip, oob, size, false, false);
2936 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
2937 * @chip: nand chip info structure
2938 * @buf: buffer to store read data
2939 * @oob_required: caller requires OOB data read to chip->oob_poi
2940 * @page: page number to read
2942 static int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf,
2943 int oob_required, int page)
2945 struct mtd_info *mtd = nand_to_mtd(chip);
2946 int i, eccsize = chip->ecc.size, ret;
2947 int eccbytes = chip->ecc.bytes;
2948 int eccsteps = chip->ecc.steps;
2950 uint8_t *ecc_calc = chip->ecc.calc_buf;
2951 uint8_t *ecc_code = chip->ecc.code_buf;
2952 unsigned int max_bitflips = 0;
2954 chip->ecc.read_page_raw(chip, buf, 1, page);
2956 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2957 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2959 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2964 eccsteps = chip->ecc.steps;
2967 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2970 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
2972 mtd->ecc_stats.failed++;
2974 mtd->ecc_stats.corrected += stat;
2975 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2978 return max_bitflips;
2982 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
2983 * @chip: nand chip info structure
2984 * @data_offs: offset of requested data within the page
2985 * @readlen: data length
2986 * @bufpoi: buffer to store read data
2987 * @page: page number to read
2989 static int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs,
2990 uint32_t readlen, uint8_t *bufpoi, int page)
2992 struct mtd_info *mtd = nand_to_mtd(chip);
2993 int start_step, end_step, num_steps, ret;
2995 int data_col_addr, i, gaps = 0;
2996 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
2997 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
2998 int index, section = 0;
2999 unsigned int max_bitflips = 0;
3000 struct mtd_oob_region oobregion = { };
3002 /* Column address within the page aligned to ECC size (256bytes) */
3003 start_step = data_offs / chip->ecc.size;
3004 end_step = (data_offs + readlen - 1) / chip->ecc.size;
3005 num_steps = end_step - start_step + 1;
3006 index = start_step * chip->ecc.bytes;
3008 /* Data size aligned to ECC ecc.size */
3009 datafrag_len = num_steps * chip->ecc.size;
3010 eccfrag_len = num_steps * chip->ecc.bytes;
3012 data_col_addr = start_step * chip->ecc.size;
3013 /* If we read not a page aligned data */
3014 p = bufpoi + data_col_addr;
3015 ret = nand_read_page_op(chip, page, data_col_addr, p, datafrag_len);
3020 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
3021 chip->ecc.calculate(chip, p, &chip->ecc.calc_buf[i]);
3024 * The performance is faster if we position offsets according to
3025 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
3027 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
3031 if (oobregion.length < eccfrag_len)
3035 ret = nand_change_read_column_op(chip, mtd->writesize,
3036 chip->oob_poi, mtd->oobsize,
3042 * Send the command to read the particular ECC bytes take care
3043 * about buswidth alignment in read_buf.
3045 aligned_pos = oobregion.offset & ~(busw - 1);
3046 aligned_len = eccfrag_len;
3047 if (oobregion.offset & (busw - 1))
3049 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
3053 ret = nand_change_read_column_op(chip,
3054 mtd->writesize + aligned_pos,
3055 &chip->oob_poi[aligned_pos],
3056 aligned_len, false);
3061 ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
3062 chip->oob_poi, index, eccfrag_len);
3066 p = bufpoi + data_col_addr;
3067 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
3070 stat = chip->ecc.correct(chip, p, &chip->ecc.code_buf[i],
3071 &chip->ecc.calc_buf[i]);
3072 if (stat == -EBADMSG &&
3073 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3074 /* check for empty pages with bitflips */
3075 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3076 &chip->ecc.code_buf[i],
3079 chip->ecc.strength);
3083 mtd->ecc_stats.failed++;
3085 mtd->ecc_stats.corrected += stat;
3086 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3089 return max_bitflips;
3093 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
3094 * @chip: nand chip info structure
3095 * @buf: buffer to store read data
3096 * @oob_required: caller requires OOB data read to chip->oob_poi
3097 * @page: page number to read
3099 * Not for syndrome calculating ECC controllers which need a special oob layout.
3101 static int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf,
3102 int oob_required, int page)
3104 struct mtd_info *mtd = nand_to_mtd(chip);
3105 int i, eccsize = chip->ecc.size, ret;
3106 int eccbytes = chip->ecc.bytes;
3107 int eccsteps = chip->ecc.steps;
3109 uint8_t *ecc_calc = chip->ecc.calc_buf;
3110 uint8_t *ecc_code = chip->ecc.code_buf;
3111 unsigned int max_bitflips = 0;
3113 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3117 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3118 chip->ecc.hwctl(chip, NAND_ECC_READ);
3120 ret = nand_read_data_op(chip, p, eccsize, false, false);
3124 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3127 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false,
3132 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3137 eccsteps = chip->ecc.steps;
3140 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3143 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
3144 if (stat == -EBADMSG &&
3145 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3146 /* check for empty pages with bitflips */
3147 stat = nand_check_erased_ecc_chunk(p, eccsize,
3148 &ecc_code[i], eccbytes,
3150 chip->ecc.strength);
3154 mtd->ecc_stats.failed++;
3156 mtd->ecc_stats.corrected += stat;
3157 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3160 return max_bitflips;
3164 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
3165 * @chip: nand chip info structure
3166 * @buf: buffer to store read data
3167 * @oob_required: caller requires OOB data read to chip->oob_poi
3168 * @page: page number to read
3170 * The hw generator calculates the error syndrome automatically. Therefore we
3171 * need a special oob layout and handling.
3173 static int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf,
3174 int oob_required, int page)
3176 struct mtd_info *mtd = nand_to_mtd(chip);
3177 int ret, i, eccsize = chip->ecc.size;
3178 int eccbytes = chip->ecc.bytes;
3179 int eccsteps = chip->ecc.steps;
3180 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
3182 uint8_t *oob = chip->oob_poi;
3183 unsigned int max_bitflips = 0;
3185 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3189 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3192 chip->ecc.hwctl(chip, NAND_ECC_READ);
3194 ret = nand_read_data_op(chip, p, eccsize, false, false);
3198 if (chip->ecc.prepad) {
3199 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3204 oob += chip->ecc.prepad;
3207 chip->ecc.hwctl(chip, NAND_ECC_READSYN);
3209 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
3213 stat = chip->ecc.correct(chip, p, oob, NULL);
3217 if (chip->ecc.postpad) {
3218 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3223 oob += chip->ecc.postpad;
3226 if (stat == -EBADMSG &&
3227 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3228 /* check for empty pages with bitflips */
3229 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3233 chip->ecc.strength);
3237 mtd->ecc_stats.failed++;
3239 mtd->ecc_stats.corrected += stat;
3240 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3244 /* Calculate remaining oob bytes */
3245 i = mtd->oobsize - (oob - chip->oob_poi);
3247 ret = nand_read_data_op(chip, oob, i, false, false);
3252 return max_bitflips;
3256 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
3257 * @chip: NAND chip object
3258 * @oob: oob destination address
3259 * @ops: oob ops structure
3260 * @len: size of oob to transfer
3262 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
3263 struct mtd_oob_ops *ops, size_t len)
3265 struct mtd_info *mtd = nand_to_mtd(chip);
3268 switch (ops->mode) {
3270 case MTD_OPS_PLACE_OOB:
3272 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
3275 case MTD_OPS_AUTO_OOB:
3276 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
3288 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
3289 * @chip: NAND chip object
3290 * @retry_mode: the retry mode to use
3292 * Some vendors supply a special command to shift the Vt threshold, to be used
3293 * when there are too many bitflips in a page (i.e., ECC error). After setting
3294 * a new threshold, the host should retry reading the page.
3296 static int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
3298 pr_debug("setting READ RETRY mode %d\n", retry_mode);
3300 if (retry_mode >= chip->read_retries)
3303 if (!chip->ops.setup_read_retry)
3306 return chip->ops.setup_read_retry(chip, retry_mode);
3309 static void nand_wait_readrdy(struct nand_chip *chip)
3311 const struct nand_interface_config *conf;
3313 if (!(chip->options & NAND_NEED_READRDY))
3316 conf = nand_get_interface_config(chip);
3317 WARN_ON(nand_wait_rdy_op(chip, NAND_COMMON_TIMING_MS(conf, tR_max), 0));
3321 * nand_do_read_ops - [INTERN] Read data with ECC
3322 * @chip: NAND chip object
3323 * @from: offset to read from
3324 * @ops: oob ops structure
3326 * Internal function. Called with chip held.
3328 static int nand_do_read_ops(struct nand_chip *chip, loff_t from,
3329 struct mtd_oob_ops *ops)
3331 int chipnr, page, realpage, col, bytes, aligned, oob_required;
3332 struct mtd_info *mtd = nand_to_mtd(chip);
3334 uint32_t readlen = ops->len;
3335 uint32_t oobreadlen = ops->ooblen;
3336 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
3338 uint8_t *bufpoi, *oob, *buf;
3340 unsigned int max_bitflips = 0;
3342 bool ecc_fail = false;
3344 /* Check if the region is secured */
3345 if (nand_region_is_secured(chip, from, readlen))
3348 chipnr = (int)(from >> chip->chip_shift);
3349 nand_select_target(chip, chipnr);
3351 realpage = (int)(from >> chip->page_shift);
3352 page = realpage & chip->pagemask;
3354 col = (int)(from & (mtd->writesize - 1));
3358 oob_required = oob ? 1 : 0;
3361 struct mtd_ecc_stats ecc_stats = mtd->ecc_stats;
3363 bytes = min(mtd->writesize - col, readlen);
3364 aligned = (bytes == mtd->writesize);
3368 else if (chip->options & NAND_USES_DMA)
3369 use_bounce_buf = !virt_addr_valid(buf) ||
3370 !IS_ALIGNED((unsigned long)buf,
3375 /* Is the current page in the buffer? */
3376 if (realpage != chip->pagecache.page || oob) {
3377 bufpoi = use_bounce_buf ? chip->data_buf : buf;
3379 if (use_bounce_buf && aligned)
3380 pr_debug("%s: using read bounce buffer for buf@%p\n",
3385 * Now read the page into the buffer. Absent an error,
3386 * the read methods return max bitflips per ecc step.
3388 if (unlikely(ops->mode == MTD_OPS_RAW))
3389 ret = chip->ecc.read_page_raw(chip, bufpoi,
3392 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
3394 ret = chip->ecc.read_subpage(chip, col, bytes,
3397 ret = chip->ecc.read_page(chip, bufpoi,
3398 oob_required, page);
3401 /* Invalidate page cache */
3402 chip->pagecache.page = -1;
3407 * Copy back the data in the initial buffer when reading
3408 * partial pages or when a bounce buffer is required.
3410 if (use_bounce_buf) {
3411 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
3412 !(mtd->ecc_stats.failed - ecc_stats.failed) &&
3413 (ops->mode != MTD_OPS_RAW)) {
3414 chip->pagecache.page = realpage;
3415 chip->pagecache.bitflips = ret;
3417 /* Invalidate page cache */
3418 chip->pagecache.page = -1;
3420 memcpy(buf, bufpoi + col, bytes);
3423 if (unlikely(oob)) {
3424 int toread = min(oobreadlen, max_oobsize);
3427 oob = nand_transfer_oob(chip, oob, ops,
3429 oobreadlen -= toread;
3433 nand_wait_readrdy(chip);
3435 if (mtd->ecc_stats.failed - ecc_stats.failed) {
3436 if (retry_mode + 1 < chip->read_retries) {
3438 ret = nand_setup_read_retry(chip,
3443 /* Reset ecc_stats; retry */
3444 mtd->ecc_stats = ecc_stats;
3447 /* No more retry modes; real failure */
3453 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3455 memcpy(buf, chip->data_buf + col, bytes);
3457 max_bitflips = max_t(unsigned int, max_bitflips,
3458 chip->pagecache.bitflips);
3463 /* Reset to retry mode 0 */
3465 ret = nand_setup_read_retry(chip, 0);
3474 /* For subsequent reads align to page boundary */
3476 /* Increment page address */
3479 page = realpage & chip->pagemask;
3480 /* Check, if we cross a chip boundary */
3483 nand_deselect_target(chip);
3484 nand_select_target(chip, chipnr);
3487 nand_deselect_target(chip);
3489 ops->retlen = ops->len - (size_t) readlen;
3491 ops->oobretlen = ops->ooblen - oobreadlen;
3499 return max_bitflips;
3503 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
3504 * @chip: nand chip info structure
3505 * @page: page number to read
3507 int nand_read_oob_std(struct nand_chip *chip, int page)
3509 struct mtd_info *mtd = nand_to_mtd(chip);
3511 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3513 EXPORT_SYMBOL(nand_read_oob_std);
3516 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
3518 * @chip: nand chip info structure
3519 * @page: page number to read
3521 static int nand_read_oob_syndrome(struct nand_chip *chip, int page)
3523 struct mtd_info *mtd = nand_to_mtd(chip);
3524 int length = mtd->oobsize;
3525 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3526 int eccsize = chip->ecc.size;
3527 uint8_t *bufpoi = chip->oob_poi;
3528 int i, toread, sndrnd = 0, pos, ret;
3530 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
3534 for (i = 0; i < chip->ecc.steps; i++) {
3538 pos = eccsize + i * (eccsize + chunk);
3539 if (mtd->writesize > 512)
3540 ret = nand_change_read_column_op(chip, pos,
3544 ret = nand_read_page_op(chip, page, pos, NULL,
3551 toread = min_t(int, length, chunk);
3553 ret = nand_read_data_op(chip, bufpoi, toread, false, false);
3561 ret = nand_read_data_op(chip, bufpoi, length, false, false);
3570 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
3571 * @chip: nand chip info structure
3572 * @page: page number to write
3574 int nand_write_oob_std(struct nand_chip *chip, int page)
3576 struct mtd_info *mtd = nand_to_mtd(chip);
3578 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
3581 EXPORT_SYMBOL(nand_write_oob_std);
3584 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
3585 * with syndrome - only for large page flash
3586 * @chip: nand chip info structure
3587 * @page: page number to write
3589 static int nand_write_oob_syndrome(struct nand_chip *chip, int page)
3591 struct mtd_info *mtd = nand_to_mtd(chip);
3592 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3593 int eccsize = chip->ecc.size, length = mtd->oobsize;
3594 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
3595 const uint8_t *bufpoi = chip->oob_poi;
3598 * data-ecc-data-ecc ... ecc-oob
3600 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
3602 if (!chip->ecc.prepad && !chip->ecc.postpad) {
3603 pos = steps * (eccsize + chunk);
3608 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
3612 for (i = 0; i < steps; i++) {
3614 if (mtd->writesize <= 512) {
3615 uint32_t fill = 0xFFFFFFFF;
3619 int num = min_t(int, len, 4);
3621 ret = nand_write_data_op(chip, &fill,
3629 pos = eccsize + i * (eccsize + chunk);
3630 ret = nand_change_write_column_op(chip, pos,
3638 len = min_t(int, length, chunk);
3640 ret = nand_write_data_op(chip, bufpoi, len, false);
3648 ret = nand_write_data_op(chip, bufpoi, length, false);
3653 return nand_prog_page_end_op(chip);
3657 * nand_do_read_oob - [INTERN] NAND read out-of-band
3658 * @chip: NAND chip object
3659 * @from: offset to read from
3660 * @ops: oob operations description structure
3662 * NAND read out-of-band data from the spare area.
3664 static int nand_do_read_oob(struct nand_chip *chip, loff_t from,
3665 struct mtd_oob_ops *ops)
3667 struct mtd_info *mtd = nand_to_mtd(chip);
3668 unsigned int max_bitflips = 0;
3669 int page, realpage, chipnr;
3670 struct mtd_ecc_stats stats;
3671 int readlen = ops->ooblen;
3673 uint8_t *buf = ops->oobbuf;
3676 pr_debug("%s: from = 0x%08Lx, len = %i\n",
3677 __func__, (unsigned long long)from, readlen);
3679 /* Check if the region is secured */
3680 if (nand_region_is_secured(chip, from, readlen))
3683 stats = mtd->ecc_stats;
3685 len = mtd_oobavail(mtd, ops);
3687 chipnr = (int)(from >> chip->chip_shift);
3688 nand_select_target(chip, chipnr);
3690 /* Shift to get page */
3691 realpage = (int)(from >> chip->page_shift);
3692 page = realpage & chip->pagemask;
3695 if (ops->mode == MTD_OPS_RAW)
3696 ret = chip->ecc.read_oob_raw(chip, page);
3698 ret = chip->ecc.read_oob(chip, page);
3703 len = min(len, readlen);
3704 buf = nand_transfer_oob(chip, buf, ops, len);
3706 nand_wait_readrdy(chip);
3708 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3714 /* Increment page address */
3717 page = realpage & chip->pagemask;
3718 /* Check, if we cross a chip boundary */
3721 nand_deselect_target(chip);
3722 nand_select_target(chip, chipnr);
3725 nand_deselect_target(chip);
3727 ops->oobretlen = ops->ooblen - readlen;
3732 if (mtd->ecc_stats.failed - stats.failed)
3735 return max_bitflips;
3739 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
3740 * @mtd: MTD device structure
3741 * @from: offset to read from
3742 * @ops: oob operation description structure
3744 * NAND read data and/or out-of-band data.
3746 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
3747 struct mtd_oob_ops *ops)
3749 struct nand_chip *chip = mtd_to_nand(mtd);
3754 if (ops->mode != MTD_OPS_PLACE_OOB &&
3755 ops->mode != MTD_OPS_AUTO_OOB &&
3756 ops->mode != MTD_OPS_RAW)
3759 ret = nand_get_device(chip);
3764 ret = nand_do_read_oob(chip, from, ops);
3766 ret = nand_do_read_ops(chip, from, ops);
3768 nand_release_device(chip);
3773 * nand_write_page_raw_notsupp - dummy raw page write function
3774 * @chip: nand chip info structure
3776 * @oob_required: must write chip->oob_poi to OOB
3777 * @page: page number to write
3779 * Returns -ENOTSUPP unconditionally.
3781 int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf,
3782 int oob_required, int page)
3788 * nand_write_page_raw - [INTERN] raw page write function
3789 * @chip: nand chip info structure
3791 * @oob_required: must write chip->oob_poi to OOB
3792 * @page: page number to write
3794 * Not for syndrome calculating ECC controllers, which use a special oob layout.
3796 int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
3797 int oob_required, int page)
3799 struct mtd_info *mtd = nand_to_mtd(chip);
3802 ret = nand_prog_page_begin_op(chip, page, 0, buf, mtd->writesize);
3807 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
3813 return nand_prog_page_end_op(chip);
3815 EXPORT_SYMBOL(nand_write_page_raw);
3818 * nand_monolithic_write_page_raw - Monolithic page write in raw mode
3819 * @chip: NAND chip info structure
3820 * @buf: data buffer to write
3821 * @oob_required: must write chip->oob_poi to OOB
3822 * @page: page number to write
3824 * This is a raw page write, ie. without any error detection/correction.
3825 * Monolithic means we are requesting all the relevant data (main plus
3826 * eventually OOB) to be sent over the bus and effectively programmed
3827 * into the NAND chip arrays in a single operation. This is an
3828 * alternative to nand_write_page_raw(), which first sends the main
3829 * data, then eventually send the OOB data by latching more data
3830 * cycles on the NAND bus, and finally sends the program command to
3831 * synchronyze the NAND chip cache.
3833 int nand_monolithic_write_page_raw(struct nand_chip *chip, const u8 *buf,
3834 int oob_required, int page)
3836 struct mtd_info *mtd = nand_to_mtd(chip);
3837 unsigned int size = mtd->writesize;
3838 u8 *write_buf = (u8 *)buf;
3841 size += mtd->oobsize;
3843 if (buf != chip->data_buf) {
3844 write_buf = nand_get_data_buf(chip);
3845 memcpy(write_buf, buf, mtd->writesize);
3849 return nand_prog_page_op(chip, page, 0, write_buf, size);
3851 EXPORT_SYMBOL(nand_monolithic_write_page_raw);
3854 * nand_write_page_raw_syndrome - [INTERN] raw page write function
3855 * @chip: nand chip info structure
3857 * @oob_required: must write chip->oob_poi to OOB
3858 * @page: page number to write
3860 * We need a special oob layout and handling even when ECC isn't checked.
3862 static int nand_write_page_raw_syndrome(struct nand_chip *chip,
3863 const uint8_t *buf, int oob_required,
3866 struct mtd_info *mtd = nand_to_mtd(chip);
3867 int eccsize = chip->ecc.size;
3868 int eccbytes = chip->ecc.bytes;
3869 uint8_t *oob = chip->oob_poi;
3870 int steps, size, ret;
3872 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3876 for (steps = chip->ecc.steps; steps > 0; steps--) {
3877 ret = nand_write_data_op(chip, buf, eccsize, false);
3883 if (chip->ecc.prepad) {
3884 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3889 oob += chip->ecc.prepad;
3892 ret = nand_write_data_op(chip, oob, eccbytes, false);
3898 if (chip->ecc.postpad) {
3899 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3904 oob += chip->ecc.postpad;
3908 size = mtd->oobsize - (oob - chip->oob_poi);
3910 ret = nand_write_data_op(chip, oob, size, false);
3915 return nand_prog_page_end_op(chip);
3918 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
3919 * @chip: nand chip info structure
3921 * @oob_required: must write chip->oob_poi to OOB
3922 * @page: page number to write
3924 static int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf,
3925 int oob_required, int page)
3927 struct mtd_info *mtd = nand_to_mtd(chip);
3928 int i, eccsize = chip->ecc.size, ret;
3929 int eccbytes = chip->ecc.bytes;
3930 int eccsteps = chip->ecc.steps;
3931 uint8_t *ecc_calc = chip->ecc.calc_buf;
3932 const uint8_t *p = buf;
3934 /* Software ECC calculation */
3935 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
3936 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3938 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3943 return chip->ecc.write_page_raw(chip, buf, 1, page);
3947 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
3948 * @chip: nand chip info structure
3950 * @oob_required: must write chip->oob_poi to OOB
3951 * @page: page number to write
3953 static int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf,
3954 int oob_required, int page)
3956 struct mtd_info *mtd = nand_to_mtd(chip);
3957 int i, eccsize = chip->ecc.size, ret;
3958 int eccbytes = chip->ecc.bytes;
3959 int eccsteps = chip->ecc.steps;
3960 uint8_t *ecc_calc = chip->ecc.calc_buf;
3961 const uint8_t *p = buf;
3963 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3967 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3968 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3970 ret = nand_write_data_op(chip, p, eccsize, false);
3974 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3977 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3982 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3986 return nand_prog_page_end_op(chip);
3991 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
3992 * @chip: nand chip info structure
3993 * @offset: column address of subpage within the page
3994 * @data_len: data length
3996 * @oob_required: must write chip->oob_poi to OOB
3997 * @page: page number to write
3999 static int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset,
4000 uint32_t data_len, const uint8_t *buf,
4001 int oob_required, int page)
4003 struct mtd_info *mtd = nand_to_mtd(chip);
4004 uint8_t *oob_buf = chip->oob_poi;
4005 uint8_t *ecc_calc = chip->ecc.calc_buf;
4006 int ecc_size = chip->ecc.size;
4007 int ecc_bytes = chip->ecc.bytes;
4008 int ecc_steps = chip->ecc.steps;
4009 uint32_t start_step = offset / ecc_size;
4010 uint32_t end_step = (offset + data_len - 1) / ecc_size;
4011 int oob_bytes = mtd->oobsize / ecc_steps;
4014 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4018 for (step = 0; step < ecc_steps; step++) {
4019 /* configure controller for WRITE access */
4020 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4022 /* write data (untouched subpages already masked by 0xFF) */
4023 ret = nand_write_data_op(chip, buf, ecc_size, false);
4027 /* mask ECC of un-touched subpages by padding 0xFF */
4028 if ((step < start_step) || (step > end_step))
4029 memset(ecc_calc, 0xff, ecc_bytes);
4031 chip->ecc.calculate(chip, buf, ecc_calc);
4033 /* mask OOB of un-touched subpages by padding 0xFF */
4034 /* if oob_required, preserve OOB metadata of written subpage */
4035 if (!oob_required || (step < start_step) || (step > end_step))
4036 memset(oob_buf, 0xff, oob_bytes);
4039 ecc_calc += ecc_bytes;
4040 oob_buf += oob_bytes;
4043 /* copy calculated ECC for whole page to chip->buffer->oob */
4044 /* this include masked-value(0xFF) for unwritten subpages */
4045 ecc_calc = chip->ecc.calc_buf;
4046 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4051 /* write OOB buffer to NAND device */
4052 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
4056 return nand_prog_page_end_op(chip);
4061 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
4062 * @chip: nand chip info structure
4064 * @oob_required: must write chip->oob_poi to OOB
4065 * @page: page number to write
4067 * The hw generator calculates the error syndrome automatically. Therefore we
4068 * need a special oob layout and handling.
4070 static int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf,
4071 int oob_required, int page)
4073 struct mtd_info *mtd = nand_to_mtd(chip);
4074 int i, eccsize = chip->ecc.size;
4075 int eccbytes = chip->ecc.bytes;
4076 int eccsteps = chip->ecc.steps;
4077 const uint8_t *p = buf;
4078 uint8_t *oob = chip->oob_poi;
4081 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4085 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4086 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4088 ret = nand_write_data_op(chip, p, eccsize, false);
4092 if (chip->ecc.prepad) {
4093 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4098 oob += chip->ecc.prepad;
4101 chip->ecc.calculate(chip, p, oob);
4103 ret = nand_write_data_op(chip, oob, eccbytes, false);
4109 if (chip->ecc.postpad) {
4110 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4115 oob += chip->ecc.postpad;
4119 /* Calculate remaining oob bytes */
4120 i = mtd->oobsize - (oob - chip->oob_poi);
4122 ret = nand_write_data_op(chip, oob, i, false);
4127 return nand_prog_page_end_op(chip);
4131 * nand_write_page - write one page
4132 * @chip: NAND chip descriptor
4133 * @offset: address offset within the page
4134 * @data_len: length of actual data to be written
4135 * @buf: the data to write
4136 * @oob_required: must write chip->oob_poi to OOB
4137 * @page: page number to write
4138 * @raw: use _raw version of write_page
4140 static int nand_write_page(struct nand_chip *chip, uint32_t offset,
4141 int data_len, const uint8_t *buf, int oob_required,
4144 struct mtd_info *mtd = nand_to_mtd(chip);
4145 int status, subpage;
4147 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
4148 chip->ecc.write_subpage)
4149 subpage = offset || (data_len < mtd->writesize);
4154 status = chip->ecc.write_page_raw(chip, buf, oob_required,
4157 status = chip->ecc.write_subpage(chip, offset, data_len, buf,
4158 oob_required, page);
4160 status = chip->ecc.write_page(chip, buf, oob_required, page);
4168 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
4171 * nand_do_write_ops - [INTERN] NAND write with ECC
4172 * @chip: NAND chip object
4173 * @to: offset to write to
4174 * @ops: oob operations description structure
4176 * NAND write with ECC.
4178 static int nand_do_write_ops(struct nand_chip *chip, loff_t to,
4179 struct mtd_oob_ops *ops)
4181 struct mtd_info *mtd = nand_to_mtd(chip);
4182 int chipnr, realpage, page, column;
4183 uint32_t writelen = ops->len;
4185 uint32_t oobwritelen = ops->ooblen;
4186 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
4188 uint8_t *oob = ops->oobbuf;
4189 uint8_t *buf = ops->datbuf;
4191 int oob_required = oob ? 1 : 0;
4197 /* Reject writes, which are not page aligned */
4198 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
4199 pr_notice("%s: attempt to write non page aligned data\n",
4204 /* Check if the region is secured */
4205 if (nand_region_is_secured(chip, to, writelen))
4208 column = to & (mtd->writesize - 1);
4210 chipnr = (int)(to >> chip->chip_shift);
4211 nand_select_target(chip, chipnr);
4213 /* Check, if it is write protected */
4214 if (nand_check_wp(chip)) {
4219 realpage = (int)(to >> chip->page_shift);
4220 page = realpage & chip->pagemask;
4222 /* Invalidate the page cache, when we write to the cached page */
4223 if (to <= ((loff_t)chip->pagecache.page << chip->page_shift) &&
4224 ((loff_t)chip->pagecache.page << chip->page_shift) < (to + ops->len))
4225 chip->pagecache.page = -1;
4227 /* Don't allow multipage oob writes with offset */
4228 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
4234 int bytes = mtd->writesize;
4235 uint8_t *wbuf = buf;
4237 int part_pagewr = (column || writelen < mtd->writesize);
4241 else if (chip->options & NAND_USES_DMA)
4242 use_bounce_buf = !virt_addr_valid(buf) ||
4243 !IS_ALIGNED((unsigned long)buf,
4249 * Copy the data from the initial buffer when doing partial page
4250 * writes or when a bounce buffer is required.
4252 if (use_bounce_buf) {
4253 pr_debug("%s: using write bounce buffer for buf@%p\n",
4256 bytes = min_t(int, bytes - column, writelen);
4257 wbuf = nand_get_data_buf(chip);
4258 memset(wbuf, 0xff, mtd->writesize);
4259 memcpy(&wbuf[column], buf, bytes);
4262 if (unlikely(oob)) {
4263 size_t len = min(oobwritelen, oobmaxlen);
4264 oob = nand_fill_oob(chip, oob, len, ops);
4267 /* We still need to erase leftover OOB data */
4268 memset(chip->oob_poi, 0xff, mtd->oobsize);
4271 ret = nand_write_page(chip, column, bytes, wbuf,
4273 (ops->mode == MTD_OPS_RAW));
4285 page = realpage & chip->pagemask;
4286 /* Check, if we cross a chip boundary */
4289 nand_deselect_target(chip);
4290 nand_select_target(chip, chipnr);
4294 ops->retlen = ops->len - writelen;
4296 ops->oobretlen = ops->ooblen;
4299 nand_deselect_target(chip);
4304 * panic_nand_write - [MTD Interface] NAND write with ECC
4305 * @mtd: MTD device structure
4306 * @to: offset to write to
4307 * @len: number of bytes to write
4308 * @retlen: pointer to variable to store the number of written bytes
4309 * @buf: the data to write
4311 * NAND write with ECC. Used when performing writes in interrupt context, this
4312 * may for example be called by mtdoops when writing an oops while in panic.
4314 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
4315 size_t *retlen, const uint8_t *buf)
4317 struct nand_chip *chip = mtd_to_nand(mtd);
4318 int chipnr = (int)(to >> chip->chip_shift);
4319 struct mtd_oob_ops ops;
4322 nand_select_target(chip, chipnr);
4324 /* Wait for the device to get ready */
4325 panic_nand_wait(chip, 400);
4327 memset(&ops, 0, sizeof(ops));
4329 ops.datbuf = (uint8_t *)buf;
4330 ops.mode = MTD_OPS_PLACE_OOB;
4332 ret = nand_do_write_ops(chip, to, &ops);
4334 *retlen = ops.retlen;
4339 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
4340 * @mtd: MTD device structure
4341 * @to: offset to write to
4342 * @ops: oob operation description structure
4344 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
4345 struct mtd_oob_ops *ops)
4347 struct nand_chip *chip = mtd_to_nand(mtd);
4352 ret = nand_get_device(chip);
4356 switch (ops->mode) {
4357 case MTD_OPS_PLACE_OOB:
4358 case MTD_OPS_AUTO_OOB:
4367 ret = nand_do_write_oob(chip, to, ops);
4369 ret = nand_do_write_ops(chip, to, ops);
4372 nand_release_device(chip);
4377 * nand_erase - [MTD Interface] erase block(s)
4378 * @mtd: MTD device structure
4379 * @instr: erase instruction
4381 * Erase one ore more blocks.
4383 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
4385 return nand_erase_nand(mtd_to_nand(mtd), instr, 0);
4389 * nand_erase_nand - [INTERN] erase block(s)
4390 * @chip: NAND chip object
4391 * @instr: erase instruction
4392 * @allowbbt: allow erasing the bbt area
4394 * Erase one ore more blocks.
4396 int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr,
4399 int page, pages_per_block, ret, chipnr;
4402 pr_debug("%s: start = 0x%012llx, len = %llu\n",
4403 __func__, (unsigned long long)instr->addr,
4404 (unsigned long long)instr->len);
4406 if (check_offs_len(chip, instr->addr, instr->len))
4409 /* Check if the region is secured */
4410 if (nand_region_is_secured(chip, instr->addr, instr->len))
4413 /* Grab the lock and see if the device is available */
4414 ret = nand_get_device(chip);
4418 /* Shift to get first page */
4419 page = (int)(instr->addr >> chip->page_shift);
4420 chipnr = (int)(instr->addr >> chip->chip_shift);
4422 /* Calculate pages in each block */
4423 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
4425 /* Select the NAND device */
4426 nand_select_target(chip, chipnr);
4428 /* Check, if it is write protected */
4429 if (nand_check_wp(chip)) {
4430 pr_debug("%s: device is write protected!\n",
4436 /* Loop through the pages */
4440 /* Check if we have a bad block, we do not erase bad blocks! */
4441 if (nand_block_checkbad(chip, ((loff_t) page) <<
4442 chip->page_shift, allowbbt)) {
4443 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
4450 * Invalidate the page cache, if we erase the block which
4451 * contains the current cached page.
4453 if (page <= chip->pagecache.page && chip->pagecache.page <
4454 (page + pages_per_block))
4455 chip->pagecache.page = -1;
4457 ret = nand_erase_op(chip, (page & chip->pagemask) >>
4458 (chip->phys_erase_shift - chip->page_shift));
4460 pr_debug("%s: failed erase, page 0x%08x\n",
4463 ((loff_t)page << chip->page_shift);
4467 /* Increment page address and decrement length */
4468 len -= (1ULL << chip->phys_erase_shift);
4469 page += pages_per_block;
4471 /* Check, if we cross a chip boundary */
4472 if (len && !(page & chip->pagemask)) {
4474 nand_deselect_target(chip);
4475 nand_select_target(chip, chipnr);
4482 /* Deselect and wake up anyone waiting on the device */
4483 nand_deselect_target(chip);
4484 nand_release_device(chip);
4486 /* Return more or less happy */
4491 * nand_sync - [MTD Interface] sync
4492 * @mtd: MTD device structure
4494 * Sync is actually a wait for chip ready function.
4496 static void nand_sync(struct mtd_info *mtd)
4498 struct nand_chip *chip = mtd_to_nand(mtd);
4500 pr_debug("%s: called\n", __func__);
4502 /* Grab the lock and see if the device is available */
4503 WARN_ON(nand_get_device(chip));
4504 /* Release it and go back */
4505 nand_release_device(chip);
4509 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
4510 * @mtd: MTD device structure
4511 * @offs: offset relative to mtd start
4513 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
4515 struct nand_chip *chip = mtd_to_nand(mtd);
4516 int chipnr = (int)(offs >> chip->chip_shift);
4519 /* Select the NAND device */
4520 ret = nand_get_device(chip);
4524 nand_select_target(chip, chipnr);
4526 ret = nand_block_checkbad(chip, offs, 0);
4528 nand_deselect_target(chip);
4529 nand_release_device(chip);
4535 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
4536 * @mtd: MTD device structure
4537 * @ofs: offset relative to mtd start
4539 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
4543 ret = nand_block_isbad(mtd, ofs);
4545 /* If it was bad already, return success and do nothing */
4551 return nand_block_markbad_lowlevel(mtd_to_nand(mtd), ofs);
4555 * nand_suspend - [MTD Interface] Suspend the NAND flash
4556 * @mtd: MTD device structure
4558 * Returns 0 for success or negative error code otherwise.
4560 static int nand_suspend(struct mtd_info *mtd)
4562 struct nand_chip *chip = mtd_to_nand(mtd);
4565 mutex_lock(&chip->lock);
4566 if (chip->ops.suspend)
4567 ret = chip->ops.suspend(chip);
4569 chip->suspended = 1;
4570 mutex_unlock(&chip->lock);
4576 * nand_resume - [MTD Interface] Resume the NAND flash
4577 * @mtd: MTD device structure
4579 static void nand_resume(struct mtd_info *mtd)
4581 struct nand_chip *chip = mtd_to_nand(mtd);
4583 mutex_lock(&chip->lock);
4584 if (chip->suspended) {
4585 if (chip->ops.resume)
4586 chip->ops.resume(chip);
4587 chip->suspended = 0;
4589 pr_err("%s called for a chip which is not in suspended state\n",
4592 mutex_unlock(&chip->lock);
4596 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
4597 * prevent further operations
4598 * @mtd: MTD device structure
4600 static void nand_shutdown(struct mtd_info *mtd)
4606 * nand_lock - [MTD Interface] Lock the NAND flash
4607 * @mtd: MTD device structure
4608 * @ofs: offset byte address
4609 * @len: number of bytes to lock (must be a multiple of block/page size)
4611 static int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4613 struct nand_chip *chip = mtd_to_nand(mtd);
4615 if (!chip->ops.lock_area)
4618 return chip->ops.lock_area(chip, ofs, len);
4622 * nand_unlock - [MTD Interface] Unlock the NAND flash
4623 * @mtd: MTD device structure
4624 * @ofs: offset byte address
4625 * @len: number of bytes to unlock (must be a multiple of block/page size)
4627 static int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4629 struct nand_chip *chip = mtd_to_nand(mtd);
4631 if (!chip->ops.unlock_area)
4634 return chip->ops.unlock_area(chip, ofs, len);
4637 /* Set default functions */
4638 static void nand_set_defaults(struct nand_chip *chip)
4640 /* If no controller is provided, use the dummy, legacy one. */
4641 if (!chip->controller) {
4642 chip->controller = &chip->legacy.dummy_controller;
4643 nand_controller_init(chip->controller);
4646 nand_legacy_set_defaults(chip);
4648 if (!chip->buf_align)
4649 chip->buf_align = 1;
4652 /* Sanitize ONFI strings so we can safely print them */
4653 void sanitize_string(uint8_t *s, size_t len)
4657 /* Null terminate */
4660 /* Remove non printable chars */
4661 for (i = 0; i < len - 1; i++) {
4662 if (s[i] < ' ' || s[i] > 127)
4666 /* Remove trailing spaces */
4671 * nand_id_has_period - Check if an ID string has a given wraparound period
4672 * @id_data: the ID string
4673 * @arrlen: the length of the @id_data array
4674 * @period: the period of repitition
4676 * Check if an ID string is repeated within a given sequence of bytes at
4677 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4678 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4679 * if the repetition has a period of @period; otherwise, returns zero.
4681 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4684 for (i = 0; i < period; i++)
4685 for (j = i + period; j < arrlen; j += period)
4686 if (id_data[i] != id_data[j])
4692 * nand_id_len - Get the length of an ID string returned by CMD_READID
4693 * @id_data: the ID string
4694 * @arrlen: the length of the @id_data array
4696 * Returns the length of the ID string, according to known wraparound/trailing
4697 * zero patterns. If no pattern exists, returns the length of the array.
4699 static int nand_id_len(u8 *id_data, int arrlen)
4701 int last_nonzero, period;
4703 /* Find last non-zero byte */
4704 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4705 if (id_data[last_nonzero])
4709 if (last_nonzero < 0)
4712 /* Calculate wraparound period */
4713 for (period = 1; period < arrlen; period++)
4714 if (nand_id_has_period(id_data, arrlen, period))
4717 /* There's a repeated pattern */
4718 if (period < arrlen)
4721 /* There are trailing zeros */
4722 if (last_nonzero < arrlen - 1)
4723 return last_nonzero + 1;
4725 /* No pattern detected */
4729 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4730 static int nand_get_bits_per_cell(u8 cellinfo)
4734 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4735 bits >>= NAND_CI_CELLTYPE_SHIFT;
4740 * Many new NAND share similar device ID codes, which represent the size of the
4741 * chip. The rest of the parameters must be decoded according to generic or
4742 * manufacturer-specific "extended ID" decoding patterns.
4744 void nand_decode_ext_id(struct nand_chip *chip)
4746 struct nand_memory_organization *memorg;
4747 struct mtd_info *mtd = nand_to_mtd(chip);
4749 u8 *id_data = chip->id.data;
4751 memorg = nanddev_get_memorg(&chip->base);
4753 /* The 3rd id byte holds MLC / multichip data */
4754 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4755 /* The 4th id byte is the important one */
4759 memorg->pagesize = 1024 << (extid & 0x03);
4760 mtd->writesize = memorg->pagesize;
4763 memorg->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
4764 mtd->oobsize = memorg->oobsize;
4766 /* Calc blocksize. Blocksize is multiples of 64KiB */
4767 memorg->pages_per_eraseblock = ((64 * 1024) << (extid & 0x03)) /
4769 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4771 /* Get buswidth information */
4773 chip->options |= NAND_BUSWIDTH_16;
4775 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
4778 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4779 * decodes a matching ID table entry and assigns the MTD size parameters for
4782 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
4784 struct mtd_info *mtd = nand_to_mtd(chip);
4785 struct nand_memory_organization *memorg;
4787 memorg = nanddev_get_memorg(&chip->base);
4789 memorg->pages_per_eraseblock = type->erasesize / type->pagesize;
4790 mtd->erasesize = type->erasesize;
4791 memorg->pagesize = type->pagesize;
4792 mtd->writesize = memorg->pagesize;
4793 memorg->oobsize = memorg->pagesize / 32;
4794 mtd->oobsize = memorg->oobsize;
4796 /* All legacy ID NAND are small-page, SLC */
4797 memorg->bits_per_cell = 1;
4801 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4802 * heuristic patterns using various detected parameters (e.g., manufacturer,
4803 * page size, cell-type information).
4805 static void nand_decode_bbm_options(struct nand_chip *chip)
4807 struct mtd_info *mtd = nand_to_mtd(chip);
4809 /* Set the bad block position */
4810 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4811 chip->badblockpos = NAND_BBM_POS_LARGE;
4813 chip->badblockpos = NAND_BBM_POS_SMALL;
4816 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4818 return type->id_len;
4821 static bool find_full_id_nand(struct nand_chip *chip,
4822 struct nand_flash_dev *type)
4824 struct nand_device *base = &chip->base;
4825 struct nand_ecc_props requirements;
4826 struct mtd_info *mtd = nand_to_mtd(chip);
4827 struct nand_memory_organization *memorg;
4828 u8 *id_data = chip->id.data;
4830 memorg = nanddev_get_memorg(&chip->base);
4832 if (!strncmp(type->id, id_data, type->id_len)) {
4833 memorg->pagesize = type->pagesize;
4834 mtd->writesize = memorg->pagesize;
4835 memorg->pages_per_eraseblock = type->erasesize /
4837 mtd->erasesize = type->erasesize;
4838 memorg->oobsize = type->oobsize;
4839 mtd->oobsize = memorg->oobsize;
4841 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4842 memorg->eraseblocks_per_lun =
4843 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4845 memorg->pages_per_eraseblock);
4846 chip->options |= type->options;
4847 requirements.strength = NAND_ECC_STRENGTH(type);
4848 requirements.step_size = NAND_ECC_STEP(type);
4849 nanddev_set_ecc_requirements(base, &requirements);
4851 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4852 if (!chip->parameters.model)
4861 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
4862 * compliant and does not have a full-id or legacy-id entry in the nand_ids
4865 static void nand_manufacturer_detect(struct nand_chip *chip)
4868 * Try manufacturer detection if available and use
4869 * nand_decode_ext_id() otherwise.
4871 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4872 chip->manufacturer.desc->ops->detect) {
4873 struct nand_memory_organization *memorg;
4875 memorg = nanddev_get_memorg(&chip->base);
4877 /* The 3rd id byte holds MLC / multichip data */
4878 memorg->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
4879 chip->manufacturer.desc->ops->detect(chip);
4881 nand_decode_ext_id(chip);
4886 * Manufacturer initialization. This function is called for all NANDs including
4887 * ONFI and JEDEC compliant ones.
4888 * Manufacturer drivers should put all their specific initialization code in
4889 * their ->init() hook.
4891 static int nand_manufacturer_init(struct nand_chip *chip)
4893 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
4894 !chip->manufacturer.desc->ops->init)
4897 return chip->manufacturer.desc->ops->init(chip);
4901 * Manufacturer cleanup. This function is called for all NANDs including
4902 * ONFI and JEDEC compliant ones.
4903 * Manufacturer drivers should put all their specific cleanup code in their
4906 static void nand_manufacturer_cleanup(struct nand_chip *chip)
4908 /* Release manufacturer private data */
4909 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4910 chip->manufacturer.desc->ops->cleanup)
4911 chip->manufacturer.desc->ops->cleanup(chip);
4915 nand_manufacturer_name(const struct nand_manufacturer_desc *manufacturer_desc)
4917 return manufacturer_desc ? manufacturer_desc->name : "Unknown";
4921 * Get the flash and manufacturer id and lookup if the type is supported.
4923 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
4925 const struct nand_manufacturer_desc *manufacturer_desc;
4926 struct mtd_info *mtd = nand_to_mtd(chip);
4927 struct nand_memory_organization *memorg;
4929 u8 *id_data = chip->id.data;
4934 * Let's start by initializing memorg fields that might be left
4935 * unassigned by the ID-based detection logic.
4937 memorg = nanddev_get_memorg(&chip->base);
4938 memorg->planes_per_lun = 1;
4939 memorg->luns_per_target = 1;
4942 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4945 ret = nand_reset(chip, 0);
4949 /* Select the device */
4950 nand_select_target(chip, 0);
4952 /* Send the command for reading device ID */
4953 ret = nand_readid_op(chip, 0, id_data, 2);
4957 /* Read manufacturer and device IDs */
4958 maf_id = id_data[0];
4959 dev_id = id_data[1];
4962 * Try again to make sure, as some systems the bus-hold or other
4963 * interface concerns can cause random data which looks like a
4964 * possibly credible NAND flash to appear. If the two results do
4965 * not match, ignore the device completely.
4968 /* Read entire ID string */
4969 ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
4973 if (id_data[0] != maf_id || id_data[1] != dev_id) {
4974 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4975 maf_id, dev_id, id_data[0], id_data[1]);
4979 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
4981 /* Try to identify manufacturer */
4982 manufacturer_desc = nand_get_manufacturer_desc(maf_id);
4983 chip->manufacturer.desc = manufacturer_desc;
4986 type = nand_flash_ids;
4989 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
4991 * This is required to make sure initial NAND bus width set by the
4992 * NAND controller driver is coherent with the real NAND bus width
4993 * (extracted by auto-detection code).
4995 busw = chip->options & NAND_BUSWIDTH_16;
4998 * The flag is only set (never cleared), reset it to its default value
4999 * before starting auto-detection.
5001 chip->options &= ~NAND_BUSWIDTH_16;
5003 for (; type->name != NULL; type++) {
5004 if (is_full_id_nand(type)) {
5005 if (find_full_id_nand(chip, type))
5007 } else if (dev_id == type->dev_id) {
5012 if (!type->name || !type->pagesize) {
5013 /* Check if the chip is ONFI compliant */
5014 ret = nand_onfi_detect(chip);
5020 /* Check if the chip is JEDEC compliant */
5021 ret = nand_jedec_detect(chip);
5031 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
5032 if (!chip->parameters.model)
5035 if (!type->pagesize)
5036 nand_manufacturer_detect(chip);
5038 nand_decode_id(chip, type);
5040 /* Get chip options */
5041 chip->options |= type->options;
5043 memorg->eraseblocks_per_lun =
5044 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
5046 memorg->pages_per_eraseblock);
5050 mtd->name = chip->parameters.model;
5052 if (chip->options & NAND_BUSWIDTH_AUTO) {
5053 WARN_ON(busw & NAND_BUSWIDTH_16);
5054 nand_set_defaults(chip);
5055 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
5057 * Check, if buswidth is correct. Hardware drivers should set
5060 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5062 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
5064 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
5065 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
5068 goto free_detect_allocation;
5071 nand_decode_bbm_options(chip);
5073 /* Calculate the address shift from the page size */
5074 chip->page_shift = ffs(mtd->writesize) - 1;
5075 /* Convert chipsize to number of pages per chip -1 */
5076 targetsize = nanddev_target_size(&chip->base);
5077 chip->pagemask = (targetsize >> chip->page_shift) - 1;
5079 chip->bbt_erase_shift = chip->phys_erase_shift =
5080 ffs(mtd->erasesize) - 1;
5081 if (targetsize & 0xffffffff)
5082 chip->chip_shift = ffs((unsigned)targetsize) - 1;
5084 chip->chip_shift = ffs((unsigned)(targetsize >> 32));
5085 chip->chip_shift += 32 - 1;
5088 if (chip->chip_shift - chip->page_shift > 16)
5089 chip->options |= NAND_ROW_ADDR_3;
5091 chip->badblockbits = 8;
5093 nand_legacy_adjust_cmdfunc(chip);
5095 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5097 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
5098 chip->parameters.model);
5099 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
5100 (int)(targetsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
5101 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
5104 free_detect_allocation:
5105 kfree(chip->parameters.model);
5110 static enum nand_ecc_engine_type
5111 of_get_rawnand_ecc_engine_type_legacy(struct device_node *np)
5113 enum nand_ecc_legacy_mode {
5119 NAND_ECC_HW_SYNDROME,
5122 const char * const nand_ecc_legacy_modes[] = {
5123 [NAND_ECC_NONE] = "none",
5124 [NAND_ECC_SOFT] = "soft",
5125 [NAND_ECC_SOFT_BCH] = "soft_bch",
5126 [NAND_ECC_HW] = "hw",
5127 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
5128 [NAND_ECC_ON_DIE] = "on-die",
5130 enum nand_ecc_legacy_mode eng_type;
5134 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5136 return NAND_ECC_ENGINE_TYPE_INVALID;
5138 for (eng_type = NAND_ECC_NONE;
5139 eng_type < ARRAY_SIZE(nand_ecc_legacy_modes); eng_type++) {
5140 if (!strcasecmp(pm, nand_ecc_legacy_modes[eng_type])) {
5143 return NAND_ECC_ENGINE_TYPE_NONE;
5145 case NAND_ECC_SOFT_BCH:
5146 return NAND_ECC_ENGINE_TYPE_SOFT;
5148 case NAND_ECC_HW_SYNDROME:
5149 return NAND_ECC_ENGINE_TYPE_ON_HOST;
5150 case NAND_ECC_ON_DIE:
5151 return NAND_ECC_ENGINE_TYPE_ON_DIE;
5158 return NAND_ECC_ENGINE_TYPE_INVALID;
5161 static enum nand_ecc_placement
5162 of_get_rawnand_ecc_placement_legacy(struct device_node *np)
5167 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5169 if (!strcasecmp(pm, "hw_syndrome"))
5170 return NAND_ECC_PLACEMENT_INTERLEAVED;
5173 return NAND_ECC_PLACEMENT_UNKNOWN;
5176 static enum nand_ecc_algo of_get_rawnand_ecc_algo_legacy(struct device_node *np)
5181 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5183 if (!strcasecmp(pm, "soft"))
5184 return NAND_ECC_ALGO_HAMMING;
5185 else if (!strcasecmp(pm, "soft_bch"))
5186 return NAND_ECC_ALGO_BCH;
5189 return NAND_ECC_ALGO_UNKNOWN;
5192 static void of_get_nand_ecc_legacy_user_config(struct nand_chip *chip)
5194 struct device_node *dn = nand_get_flash_node(chip);
5195 struct nand_ecc_props *user_conf = &chip->base.ecc.user_conf;
5197 if (user_conf->engine_type == NAND_ECC_ENGINE_TYPE_INVALID)
5198 user_conf->engine_type = of_get_rawnand_ecc_engine_type_legacy(dn);
5200 if (user_conf->algo == NAND_ECC_ALGO_UNKNOWN)
5201 user_conf->algo = of_get_rawnand_ecc_algo_legacy(dn);
5203 if (user_conf->placement == NAND_ECC_PLACEMENT_UNKNOWN)
5204 user_conf->placement = of_get_rawnand_ecc_placement_legacy(dn);
5207 static int of_get_nand_bus_width(struct device_node *np)
5211 if (of_property_read_u32(np, "nand-bus-width", &val))
5223 static bool of_get_nand_on_flash_bbt(struct device_node *np)
5225 return of_property_read_bool(np, "nand-on-flash-bbt");
5228 static int of_get_nand_secure_regions(struct nand_chip *chip)
5230 struct device_node *dn = nand_get_flash_node(chip);
5231 struct property *prop;
5234 /* Only proceed if the "secure-regions" property is present in DT */
5235 prop = of_find_property(dn, "secure-regions", NULL);
5239 nr_elem = of_property_count_elems_of_size(dn, "secure-regions", sizeof(u64));
5243 chip->nr_secure_regions = nr_elem / 2;
5244 chip->secure_regions = kcalloc(chip->nr_secure_regions, sizeof(*chip->secure_regions),
5246 if (!chip->secure_regions)
5249 for (i = 0, j = 0; i < chip->nr_secure_regions; i++, j += 2) {
5250 of_property_read_u64_index(dn, "secure-regions", j,
5251 &chip->secure_regions[i].offset);
5252 of_property_read_u64_index(dn, "secure-regions", j + 1,
5253 &chip->secure_regions[i].size);
5260 * rawnand_dt_parse_gpio_cs - Parse the gpio-cs property of a controller
5261 * @dev: Device that will be parsed. Also used for managed allocations.
5262 * @cs_array: Array of GPIO desc pointers allocated on success
5263 * @ncs_array: Number of entries in @cs_array updated on success.
5264 * @return 0 on success, an error otherwise.
5266 int rawnand_dt_parse_gpio_cs(struct device *dev, struct gpio_desc ***cs_array,
5267 unsigned int *ncs_array)
5269 struct device_node *np = dev->of_node;
5270 struct gpio_desc **descs;
5273 ndescs = of_gpio_named_count(np, "cs-gpios");
5275 dev_dbg(dev, "No valid cs-gpios property\n");
5279 descs = devm_kcalloc(dev, ndescs, sizeof(*descs), GFP_KERNEL);
5283 for (i = 0; i < ndescs; i++) {
5284 descs[i] = gpiod_get_index_optional(dev, "cs", i,
5286 if (IS_ERR(descs[i]))
5287 return PTR_ERR(descs[i]);
5290 *ncs_array = ndescs;
5295 EXPORT_SYMBOL(rawnand_dt_parse_gpio_cs);
5297 static int rawnand_dt_init(struct nand_chip *chip)
5299 struct nand_device *nand = mtd_to_nanddev(nand_to_mtd(chip));
5300 struct device_node *dn = nand_get_flash_node(chip);
5305 if (of_get_nand_bus_width(dn) == 16)
5306 chip->options |= NAND_BUSWIDTH_16;
5308 if (of_property_read_bool(dn, "nand-is-boot-medium"))
5309 chip->options |= NAND_IS_BOOT_MEDIUM;
5311 if (of_get_nand_on_flash_bbt(dn))
5312 chip->bbt_options |= NAND_BBT_USE_FLASH;
5314 of_get_nand_ecc_user_config(nand);
5315 of_get_nand_ecc_legacy_user_config(chip);
5318 * If neither the user nor the NAND controller have requested a specific
5319 * ECC engine type, we will default to NAND_ECC_ENGINE_TYPE_ON_HOST.
5321 nand->ecc.defaults.engine_type = NAND_ECC_ENGINE_TYPE_ON_HOST;
5324 * Use the user requested engine type, unless there is none, in this
5325 * case default to the NAND controller choice, otherwise fallback to
5326 * the raw NAND default one.
5328 if (nand->ecc.user_conf.engine_type != NAND_ECC_ENGINE_TYPE_INVALID)
5329 chip->ecc.engine_type = nand->ecc.user_conf.engine_type;
5330 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_INVALID)
5331 chip->ecc.engine_type = nand->ecc.defaults.engine_type;
5333 chip->ecc.placement = nand->ecc.user_conf.placement;
5334 chip->ecc.algo = nand->ecc.user_conf.algo;
5335 chip->ecc.strength = nand->ecc.user_conf.strength;
5336 chip->ecc.size = nand->ecc.user_conf.step_size;
5342 * nand_scan_ident - Scan for the NAND device
5343 * @chip: NAND chip object
5344 * @maxchips: number of chips to scan for
5345 * @table: alternative NAND ID table
5347 * This is the first phase of the normal nand_scan() function. It reads the
5348 * flash ID and sets up MTD fields accordingly.
5350 * This helper used to be called directly from controller drivers that needed
5351 * to tweak some ECC-related parameters before nand_scan_tail(). This separation
5352 * prevented dynamic allocations during this phase which was unconvenient and
5353 * as been banned for the benefit of the ->init_ecc()/cleanup_ecc() hooks.
5355 static int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips,
5356 struct nand_flash_dev *table)
5358 struct mtd_info *mtd = nand_to_mtd(chip);
5359 struct nand_memory_organization *memorg;
5360 int nand_maf_id, nand_dev_id;
5364 memorg = nanddev_get_memorg(&chip->base);
5366 /* Assume all dies are deselected when we enter nand_scan_ident(). */
5369 mutex_init(&chip->lock);
5371 /* Enforce the right timings for reset/detection */
5372 chip->current_interface_config = nand_get_reset_interface_config();
5374 ret = rawnand_dt_init(chip);
5378 if (!mtd->name && mtd->dev.parent)
5379 mtd->name = dev_name(mtd->dev.parent);
5381 /* Set the default functions */
5382 nand_set_defaults(chip);
5384 ret = nand_legacy_check_hooks(chip);
5388 memorg->ntargets = maxchips;
5390 /* Read the flash type */
5391 ret = nand_detect(chip, table);
5393 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
5394 pr_warn("No NAND device found\n");
5395 nand_deselect_target(chip);
5399 nand_maf_id = chip->id.data[0];
5400 nand_dev_id = chip->id.data[1];
5402 nand_deselect_target(chip);
5404 /* Check for a chip array */
5405 for (i = 1; i < maxchips; i++) {
5408 /* See comment in nand_get_flash_type for reset */
5409 ret = nand_reset(chip, i);
5413 nand_select_target(chip, i);
5414 /* Send the command for reading device ID */
5415 ret = nand_readid_op(chip, 0, id, sizeof(id));
5418 /* Read manufacturer and device IDs */
5419 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
5420 nand_deselect_target(chip);
5423 nand_deselect_target(chip);
5426 pr_info("%d chips detected\n", i);
5428 /* Store the number of chips and calc total size for mtd */
5429 memorg->ntargets = i;
5430 mtd->size = i * nanddev_target_size(&chip->base);
5435 static void nand_scan_ident_cleanup(struct nand_chip *chip)
5437 kfree(chip->parameters.model);
5438 kfree(chip->parameters.onfi);
5441 int rawnand_sw_hamming_init(struct nand_chip *chip)
5443 struct nand_ecc_sw_hamming_conf *engine_conf;
5444 struct nand_device *base = &chip->base;
5447 base->ecc.user_conf.engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5448 base->ecc.user_conf.algo = NAND_ECC_ALGO_HAMMING;
5449 base->ecc.user_conf.strength = chip->ecc.strength;
5450 base->ecc.user_conf.step_size = chip->ecc.size;
5452 ret = nand_ecc_sw_hamming_init_ctx(base);
5456 engine_conf = base->ecc.ctx.priv;
5458 if (chip->ecc.options & NAND_ECC_SOFT_HAMMING_SM_ORDER)
5459 engine_conf->sm_order = true;
5461 chip->ecc.size = base->ecc.ctx.conf.step_size;
5462 chip->ecc.strength = base->ecc.ctx.conf.strength;
5463 chip->ecc.total = base->ecc.ctx.total;
5464 chip->ecc.steps = nanddev_get_ecc_nsteps(base);
5465 chip->ecc.bytes = base->ecc.ctx.total / nanddev_get_ecc_nsteps(base);
5469 EXPORT_SYMBOL(rawnand_sw_hamming_init);
5471 int rawnand_sw_hamming_calculate(struct nand_chip *chip,
5472 const unsigned char *buf,
5473 unsigned char *code)
5475 struct nand_device *base = &chip->base;
5477 return nand_ecc_sw_hamming_calculate(base, buf, code);
5479 EXPORT_SYMBOL(rawnand_sw_hamming_calculate);
5481 int rawnand_sw_hamming_correct(struct nand_chip *chip,
5483 unsigned char *read_ecc,
5484 unsigned char *calc_ecc)
5486 struct nand_device *base = &chip->base;
5488 return nand_ecc_sw_hamming_correct(base, buf, read_ecc, calc_ecc);
5490 EXPORT_SYMBOL(rawnand_sw_hamming_correct);
5492 void rawnand_sw_hamming_cleanup(struct nand_chip *chip)
5494 struct nand_device *base = &chip->base;
5496 nand_ecc_sw_hamming_cleanup_ctx(base);
5498 EXPORT_SYMBOL(rawnand_sw_hamming_cleanup);
5500 int rawnand_sw_bch_init(struct nand_chip *chip)
5502 struct nand_device *base = &chip->base;
5503 const struct nand_ecc_props *ecc_conf = nanddev_get_ecc_conf(base);
5506 base->ecc.user_conf.engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5507 base->ecc.user_conf.algo = NAND_ECC_ALGO_BCH;
5508 base->ecc.user_conf.step_size = chip->ecc.size;
5509 base->ecc.user_conf.strength = chip->ecc.strength;
5511 ret = nand_ecc_sw_bch_init_ctx(base);
5515 chip->ecc.size = ecc_conf->step_size;
5516 chip->ecc.strength = ecc_conf->strength;
5517 chip->ecc.total = base->ecc.ctx.total;
5518 chip->ecc.steps = nanddev_get_ecc_nsteps(base);
5519 chip->ecc.bytes = base->ecc.ctx.total / nanddev_get_ecc_nsteps(base);
5523 EXPORT_SYMBOL(rawnand_sw_bch_init);
5525 static int rawnand_sw_bch_calculate(struct nand_chip *chip,
5526 const unsigned char *buf,
5527 unsigned char *code)
5529 struct nand_device *base = &chip->base;
5531 return nand_ecc_sw_bch_calculate(base, buf, code);
5534 int rawnand_sw_bch_correct(struct nand_chip *chip, unsigned char *buf,
5535 unsigned char *read_ecc, unsigned char *calc_ecc)
5537 struct nand_device *base = &chip->base;
5539 return nand_ecc_sw_bch_correct(base, buf, read_ecc, calc_ecc);
5541 EXPORT_SYMBOL(rawnand_sw_bch_correct);
5543 void rawnand_sw_bch_cleanup(struct nand_chip *chip)
5545 struct nand_device *base = &chip->base;
5547 nand_ecc_sw_bch_cleanup_ctx(base);
5549 EXPORT_SYMBOL(rawnand_sw_bch_cleanup);
5551 static int nand_set_ecc_on_host_ops(struct nand_chip *chip)
5553 struct nand_ecc_ctrl *ecc = &chip->ecc;
5555 switch (ecc->placement) {
5556 case NAND_ECC_PLACEMENT_UNKNOWN:
5557 case NAND_ECC_PLACEMENT_OOB:
5558 /* Use standard hwecc read page function? */
5559 if (!ecc->read_page)
5560 ecc->read_page = nand_read_page_hwecc;
5561 if (!ecc->write_page)
5562 ecc->write_page = nand_write_page_hwecc;
5563 if (!ecc->read_page_raw)
5564 ecc->read_page_raw = nand_read_page_raw;
5565 if (!ecc->write_page_raw)
5566 ecc->write_page_raw = nand_write_page_raw;
5568 ecc->read_oob = nand_read_oob_std;
5569 if (!ecc->write_oob)
5570 ecc->write_oob = nand_write_oob_std;
5571 if (!ecc->read_subpage)
5572 ecc->read_subpage = nand_read_subpage;
5573 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5574 ecc->write_subpage = nand_write_subpage_hwecc;
5577 case NAND_ECC_PLACEMENT_INTERLEAVED:
5578 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5580 ecc->read_page == nand_read_page_hwecc ||
5582 ecc->write_page == nand_write_page_hwecc)) {
5583 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5586 /* Use standard syndrome read/write page function? */
5587 if (!ecc->read_page)
5588 ecc->read_page = nand_read_page_syndrome;
5589 if (!ecc->write_page)
5590 ecc->write_page = nand_write_page_syndrome;
5591 if (!ecc->read_page_raw)
5592 ecc->read_page_raw = nand_read_page_raw_syndrome;
5593 if (!ecc->write_page_raw)
5594 ecc->write_page_raw = nand_write_page_raw_syndrome;
5596 ecc->read_oob = nand_read_oob_syndrome;
5597 if (!ecc->write_oob)
5598 ecc->write_oob = nand_write_oob_syndrome;
5602 pr_warn("Invalid NAND_ECC_PLACEMENT %d\n",
5610 static int nand_set_ecc_soft_ops(struct nand_chip *chip)
5612 struct mtd_info *mtd = nand_to_mtd(chip);
5613 struct nand_device *nanddev = mtd_to_nanddev(mtd);
5614 struct nand_ecc_ctrl *ecc = &chip->ecc;
5617 if (WARN_ON(ecc->engine_type != NAND_ECC_ENGINE_TYPE_SOFT))
5620 switch (ecc->algo) {
5621 case NAND_ECC_ALGO_HAMMING:
5622 ecc->calculate = rawnand_sw_hamming_calculate;
5623 ecc->correct = rawnand_sw_hamming_correct;
5624 ecc->read_page = nand_read_page_swecc;
5625 ecc->read_subpage = nand_read_subpage;
5626 ecc->write_page = nand_write_page_swecc;
5627 if (!ecc->read_page_raw)
5628 ecc->read_page_raw = nand_read_page_raw;
5629 if (!ecc->write_page_raw)
5630 ecc->write_page_raw = nand_write_page_raw;
5631 ecc->read_oob = nand_read_oob_std;
5632 ecc->write_oob = nand_write_oob_std;
5638 if (IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_HAMMING_SMC))
5639 ecc->options |= NAND_ECC_SOFT_HAMMING_SM_ORDER;
5641 ret = rawnand_sw_hamming_init(chip);
5643 WARN(1, "Hamming ECC initialization failed!\n");
5648 case NAND_ECC_ALGO_BCH:
5649 if (!IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_BCH)) {
5650 WARN(1, "CONFIG_MTD_NAND_ECC_SW_BCH not enabled\n");
5653 ecc->calculate = rawnand_sw_bch_calculate;
5654 ecc->correct = rawnand_sw_bch_correct;
5655 ecc->read_page = nand_read_page_swecc;
5656 ecc->read_subpage = nand_read_subpage;
5657 ecc->write_page = nand_write_page_swecc;
5658 if (!ecc->read_page_raw)
5659 ecc->read_page_raw = nand_read_page_raw;
5660 if (!ecc->write_page_raw)
5661 ecc->write_page_raw = nand_write_page_raw;
5662 ecc->read_oob = nand_read_oob_std;
5663 ecc->write_oob = nand_write_oob_std;
5666 * We can only maximize ECC config when the default layout is
5667 * used, otherwise we don't know how many bytes can really be
5670 if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH &&
5671 mtd->ooblayout != nand_get_large_page_ooblayout())
5672 nanddev->ecc.user_conf.flags &= ~NAND_ECC_MAXIMIZE_STRENGTH;
5674 ret = rawnand_sw_bch_init(chip);
5676 WARN(1, "BCH ECC initialization failed!\n");
5682 WARN(1, "Unsupported ECC algorithm!\n");
5688 * nand_check_ecc_caps - check the sanity of preset ECC settings
5689 * @chip: nand chip info structure
5690 * @caps: ECC caps info structure
5691 * @oobavail: OOB size that the ECC engine can use
5693 * When ECC step size and strength are already set, check if they are supported
5694 * by the controller and the calculated ECC bytes fit within the chip's OOB.
5695 * On success, the calculated ECC bytes is set.
5698 nand_check_ecc_caps(struct nand_chip *chip,
5699 const struct nand_ecc_caps *caps, int oobavail)
5701 struct mtd_info *mtd = nand_to_mtd(chip);
5702 const struct nand_ecc_step_info *stepinfo;
5703 int preset_step = chip->ecc.size;
5704 int preset_strength = chip->ecc.strength;
5705 int ecc_bytes, nsteps = mtd->writesize / preset_step;
5708 for (i = 0; i < caps->nstepinfos; i++) {
5709 stepinfo = &caps->stepinfos[i];
5711 if (stepinfo->stepsize != preset_step)
5714 for (j = 0; j < stepinfo->nstrengths; j++) {
5715 if (stepinfo->strengths[j] != preset_strength)
5718 ecc_bytes = caps->calc_ecc_bytes(preset_step,
5720 if (WARN_ON_ONCE(ecc_bytes < 0))
5723 if (ecc_bytes * nsteps > oobavail) {
5724 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
5725 preset_step, preset_strength);
5729 chip->ecc.bytes = ecc_bytes;
5735 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
5736 preset_step, preset_strength);
5742 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
5743 * @chip: nand chip info structure
5744 * @caps: ECC engine caps info structure
5745 * @oobavail: OOB size that the ECC engine can use
5747 * If a chip's ECC requirement is provided, try to meet it with the least
5748 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
5749 * On success, the chosen ECC settings are set.
5752 nand_match_ecc_req(struct nand_chip *chip,
5753 const struct nand_ecc_caps *caps, int oobavail)
5755 const struct nand_ecc_props *requirements =
5756 nanddev_get_ecc_requirements(&chip->base);
5757 struct mtd_info *mtd = nand_to_mtd(chip);
5758 const struct nand_ecc_step_info *stepinfo;
5759 int req_step = requirements->step_size;
5760 int req_strength = requirements->strength;
5761 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
5762 int best_step, best_strength, best_ecc_bytes;
5763 int best_ecc_bytes_total = INT_MAX;
5766 /* No information provided by the NAND chip */
5767 if (!req_step || !req_strength)
5770 /* number of correctable bits the chip requires in a page */
5771 req_corr = mtd->writesize / req_step * req_strength;
5773 for (i = 0; i < caps->nstepinfos; i++) {
5774 stepinfo = &caps->stepinfos[i];
5775 step_size = stepinfo->stepsize;
5777 for (j = 0; j < stepinfo->nstrengths; j++) {
5778 strength = stepinfo->strengths[j];
5781 * If both step size and strength are smaller than the
5782 * chip's requirement, it is not easy to compare the
5783 * resulted reliability.
5785 if (step_size < req_step && strength < req_strength)
5788 if (mtd->writesize % step_size)
5791 nsteps = mtd->writesize / step_size;
5793 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5794 if (WARN_ON_ONCE(ecc_bytes < 0))
5796 ecc_bytes_total = ecc_bytes * nsteps;
5798 if (ecc_bytes_total > oobavail ||
5799 strength * nsteps < req_corr)
5803 * We assume the best is to meet the chip's requrement
5804 * with the least number of ECC bytes.
5806 if (ecc_bytes_total < best_ecc_bytes_total) {
5807 best_ecc_bytes_total = ecc_bytes_total;
5808 best_step = step_size;
5809 best_strength = strength;
5810 best_ecc_bytes = ecc_bytes;
5815 if (best_ecc_bytes_total == INT_MAX)
5818 chip->ecc.size = best_step;
5819 chip->ecc.strength = best_strength;
5820 chip->ecc.bytes = best_ecc_bytes;
5826 * nand_maximize_ecc - choose the max ECC strength available
5827 * @chip: nand chip info structure
5828 * @caps: ECC engine caps info structure
5829 * @oobavail: OOB size that the ECC engine can use
5831 * Choose the max ECC strength that is supported on the controller, and can fit
5832 * within the chip's OOB. On success, the chosen ECC settings are set.
5835 nand_maximize_ecc(struct nand_chip *chip,
5836 const struct nand_ecc_caps *caps, int oobavail)
5838 struct mtd_info *mtd = nand_to_mtd(chip);
5839 const struct nand_ecc_step_info *stepinfo;
5840 int step_size, strength, nsteps, ecc_bytes, corr;
5843 int best_strength, best_ecc_bytes;
5846 for (i = 0; i < caps->nstepinfos; i++) {
5847 stepinfo = &caps->stepinfos[i];
5848 step_size = stepinfo->stepsize;
5850 /* If chip->ecc.size is already set, respect it */
5851 if (chip->ecc.size && step_size != chip->ecc.size)
5854 for (j = 0; j < stepinfo->nstrengths; j++) {
5855 strength = stepinfo->strengths[j];
5857 if (mtd->writesize % step_size)
5860 nsteps = mtd->writesize / step_size;
5862 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5863 if (WARN_ON_ONCE(ecc_bytes < 0))
5866 if (ecc_bytes * nsteps > oobavail)
5869 corr = strength * nsteps;
5872 * If the number of correctable bits is the same,
5873 * bigger step_size has more reliability.
5875 if (corr > best_corr ||
5876 (corr == best_corr && step_size > best_step)) {
5878 best_step = step_size;
5879 best_strength = strength;
5880 best_ecc_bytes = ecc_bytes;
5888 chip->ecc.size = best_step;
5889 chip->ecc.strength = best_strength;
5890 chip->ecc.bytes = best_ecc_bytes;
5896 * nand_ecc_choose_conf - Set the ECC strength and ECC step size
5897 * @chip: nand chip info structure
5898 * @caps: ECC engine caps info structure
5899 * @oobavail: OOB size that the ECC engine can use
5901 * Choose the ECC configuration according to following logic.
5903 * 1. If both ECC step size and ECC strength are already set (usually by DT)
5904 * then check if it is supported by this controller.
5905 * 2. If the user provided the nand-ecc-maximize property, then select maximum
5907 * 3. Otherwise, try to match the ECC step size and ECC strength closest
5908 * to the chip's requirement. If available OOB size can't fit the chip
5909 * requirement then fallback to the maximum ECC step size and ECC strength.
5911 * On success, the chosen ECC settings are set.
5913 int nand_ecc_choose_conf(struct nand_chip *chip,
5914 const struct nand_ecc_caps *caps, int oobavail)
5916 struct mtd_info *mtd = nand_to_mtd(chip);
5917 struct nand_device *nanddev = mtd_to_nanddev(mtd);
5919 if (WARN_ON(oobavail < 0 || oobavail > mtd->oobsize))
5922 if (chip->ecc.size && chip->ecc.strength)
5923 return nand_check_ecc_caps(chip, caps, oobavail);
5925 if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH)
5926 return nand_maximize_ecc(chip, caps, oobavail);
5928 if (!nand_match_ecc_req(chip, caps, oobavail))
5931 return nand_maximize_ecc(chip, caps, oobavail);
5933 EXPORT_SYMBOL_GPL(nand_ecc_choose_conf);
5935 static int rawnand_erase(struct nand_device *nand, const struct nand_pos *pos)
5937 struct nand_chip *chip = container_of(nand, struct nand_chip,
5939 unsigned int eb = nanddev_pos_to_row(nand, pos);
5942 eb >>= nand->rowconv.eraseblock_addr_shift;
5944 nand_select_target(chip, pos->target);
5945 ret = nand_erase_op(chip, eb);
5946 nand_deselect_target(chip);
5951 static int rawnand_markbad(struct nand_device *nand,
5952 const struct nand_pos *pos)
5954 struct nand_chip *chip = container_of(nand, struct nand_chip,
5957 return nand_markbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5960 static bool rawnand_isbad(struct nand_device *nand, const struct nand_pos *pos)
5962 struct nand_chip *chip = container_of(nand, struct nand_chip,
5966 nand_select_target(chip, pos->target);
5967 ret = nand_isbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5968 nand_deselect_target(chip);
5973 static const struct nand_ops rawnand_ops = {
5974 .erase = rawnand_erase,
5975 .markbad = rawnand_markbad,
5976 .isbad = rawnand_isbad,
5980 * nand_scan_tail - Scan for the NAND device
5981 * @chip: NAND chip object
5983 * This is the second phase of the normal nand_scan() function. It fills out
5984 * all the uninitialized function pointers with the defaults and scans for a
5985 * bad block table if appropriate.
5987 static int nand_scan_tail(struct nand_chip *chip)
5989 struct mtd_info *mtd = nand_to_mtd(chip);
5990 struct nand_ecc_ctrl *ecc = &chip->ecc;
5993 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
5994 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
5995 !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
5999 chip->data_buf = kmalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
6000 if (!chip->data_buf)
6004 * FIXME: some NAND manufacturer drivers expect the first die to be
6005 * selected when manufacturer->init() is called. They should be fixed
6006 * to explictly select the relevant die when interacting with the NAND
6009 nand_select_target(chip, 0);
6010 ret = nand_manufacturer_init(chip);
6011 nand_deselect_target(chip);
6015 /* Set the internal oob buffer location, just after the page data */
6016 chip->oob_poi = chip->data_buf + mtd->writesize;
6019 * If no default placement scheme is given, select an appropriate one.
6021 if (!mtd->ooblayout &&
6022 !(ecc->engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
6023 ecc->algo == NAND_ECC_ALGO_BCH) &&
6024 !(ecc->engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
6025 ecc->algo == NAND_ECC_ALGO_HAMMING)) {
6026 switch (mtd->oobsize) {
6029 mtd_set_ooblayout(mtd, nand_get_small_page_ooblayout());
6033 mtd_set_ooblayout(mtd,
6034 nand_get_large_page_hamming_ooblayout());
6038 * Expose the whole OOB area to users if ECC_NONE
6039 * is passed. We could do that for all kind of
6040 * ->oobsize, but we must keep the old large/small
6041 * page with ECC layout when ->oobsize <= 128 for
6042 * compatibility reasons.
6044 if (ecc->engine_type == NAND_ECC_ENGINE_TYPE_NONE) {
6045 mtd_set_ooblayout(mtd,
6046 nand_get_large_page_ooblayout());
6050 WARN(1, "No oob scheme defined for oobsize %d\n",
6053 goto err_nand_manuf_cleanup;
6058 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
6059 * selected and we have 256 byte pagesize fallback to software ECC
6062 switch (ecc->engine_type) {
6063 case NAND_ECC_ENGINE_TYPE_ON_HOST:
6064 ret = nand_set_ecc_on_host_ops(chip);
6066 goto err_nand_manuf_cleanup;
6068 if (mtd->writesize >= ecc->size) {
6069 if (!ecc->strength) {
6070 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
6072 goto err_nand_manuf_cleanup;
6076 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
6077 ecc->size, mtd->writesize);
6078 ecc->engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
6079 ecc->algo = NAND_ECC_ALGO_HAMMING;
6082 case NAND_ECC_ENGINE_TYPE_SOFT:
6083 ret = nand_set_ecc_soft_ops(chip);
6085 goto err_nand_manuf_cleanup;
6088 case NAND_ECC_ENGINE_TYPE_ON_DIE:
6089 if (!ecc->read_page || !ecc->write_page) {
6090 WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
6092 goto err_nand_manuf_cleanup;
6095 ecc->read_oob = nand_read_oob_std;
6096 if (!ecc->write_oob)
6097 ecc->write_oob = nand_write_oob_std;
6100 case NAND_ECC_ENGINE_TYPE_NONE:
6101 pr_warn("NAND_ECC_ENGINE_TYPE_NONE selected by board driver. This is not recommended!\n");
6102 ecc->read_page = nand_read_page_raw;
6103 ecc->write_page = nand_write_page_raw;
6104 ecc->read_oob = nand_read_oob_std;
6105 ecc->read_page_raw = nand_read_page_raw;
6106 ecc->write_page_raw = nand_write_page_raw;
6107 ecc->write_oob = nand_write_oob_std;
6108 ecc->size = mtd->writesize;
6114 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->engine_type);
6116 goto err_nand_manuf_cleanup;
6119 if (ecc->correct || ecc->calculate) {
6120 ecc->calc_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
6121 ecc->code_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
6122 if (!ecc->calc_buf || !ecc->code_buf) {
6124 goto err_nand_manuf_cleanup;
6128 /* For many systems, the standard OOB write also works for raw */
6129 if (!ecc->read_oob_raw)
6130 ecc->read_oob_raw = ecc->read_oob;
6131 if (!ecc->write_oob_raw)
6132 ecc->write_oob_raw = ecc->write_oob;
6134 /* propagate ecc info to mtd_info */
6135 mtd->ecc_strength = ecc->strength;
6136 mtd->ecc_step_size = ecc->size;
6139 * Set the number of read / write steps for one page depending on ECC
6143 ecc->steps = mtd->writesize / ecc->size;
6144 if (ecc->steps * ecc->size != mtd->writesize) {
6145 WARN(1, "Invalid ECC parameters\n");
6147 goto err_nand_manuf_cleanup;
6151 ecc->total = ecc->steps * ecc->bytes;
6152 chip->base.ecc.ctx.total = ecc->total;
6155 if (ecc->total > mtd->oobsize) {
6156 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
6158 goto err_nand_manuf_cleanup;
6162 * The number of bytes available for a client to place data into
6163 * the out of band area.
6165 ret = mtd_ooblayout_count_freebytes(mtd);
6169 mtd->oobavail = ret;
6171 /* ECC sanity check: warn if it's too weak */
6172 if (!nand_ecc_is_strong_enough(&chip->base))
6173 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",
6174 mtd->name, chip->ecc.strength, chip->ecc.size,
6175 nanddev_get_ecc_requirements(&chip->base)->strength,
6176 nanddev_get_ecc_requirements(&chip->base)->step_size);
6178 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
6179 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
6180 switch (ecc->steps) {
6182 mtd->subpage_sft = 1;
6187 mtd->subpage_sft = 2;
6191 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
6193 /* Invalidate the pagebuffer reference */
6194 chip->pagecache.page = -1;
6196 /* Large page NAND with SOFT_ECC should support subpage reads */
6197 switch (ecc->engine_type) {
6198 case NAND_ECC_ENGINE_TYPE_SOFT:
6199 if (chip->page_shift > 9)
6200 chip->options |= NAND_SUBPAGE_READ;
6207 ret = nanddev_init(&chip->base, &rawnand_ops, mtd->owner);
6209 goto err_nand_manuf_cleanup;
6211 /* Adjust the MTD_CAP_ flags when NAND_ROM is set. */
6212 if (chip->options & NAND_ROM)
6213 mtd->flags = MTD_CAP_ROM;
6215 /* Fill in remaining MTD driver data */
6216 mtd->_erase = nand_erase;
6218 mtd->_unpoint = NULL;
6219 mtd->_panic_write = panic_nand_write;
6220 mtd->_read_oob = nand_read_oob;
6221 mtd->_write_oob = nand_write_oob;
6222 mtd->_sync = nand_sync;
6223 mtd->_lock = nand_lock;
6224 mtd->_unlock = nand_unlock;
6225 mtd->_suspend = nand_suspend;
6226 mtd->_resume = nand_resume;
6227 mtd->_reboot = nand_shutdown;
6228 mtd->_block_isreserved = nand_block_isreserved;
6229 mtd->_block_isbad = nand_block_isbad;
6230 mtd->_block_markbad = nand_block_markbad;
6231 mtd->_max_bad_blocks = nanddev_mtd_max_bad_blocks;
6234 * Initialize bitflip_threshold to its default prior scan_bbt() call.
6235 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
6238 if (!mtd->bitflip_threshold)
6239 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
6241 /* Find the fastest data interface for this chip */
6242 ret = nand_choose_interface_config(chip);
6244 goto err_nanddev_cleanup;
6246 /* Enter fastest possible mode on all dies. */
6247 for (i = 0; i < nanddev_ntargets(&chip->base); i++) {
6248 ret = nand_setup_interface(chip, i);
6250 goto err_free_interface_config;
6254 * Look for secure regions in the NAND chip. These regions are supposed
6255 * to be protected by a secure element like Trustzone. So the read/write
6256 * accesses to these regions will be blocked in the runtime by this
6259 ret = of_get_nand_secure_regions(chip);
6261 goto err_free_interface_config;
6263 /* Check, if we should skip the bad block table scan */
6264 if (chip->options & NAND_SKIP_BBTSCAN)
6267 /* Build bad block table */
6268 ret = nand_create_bbt(chip);
6270 goto err_free_secure_regions;
6274 err_free_secure_regions:
6275 kfree(chip->secure_regions);
6277 err_free_interface_config:
6278 kfree(chip->best_interface_config);
6280 err_nanddev_cleanup:
6281 nanddev_cleanup(&chip->base);
6283 err_nand_manuf_cleanup:
6284 nand_manufacturer_cleanup(chip);
6287 kfree(chip->data_buf);
6288 kfree(ecc->code_buf);
6289 kfree(ecc->calc_buf);
6294 static int nand_attach(struct nand_chip *chip)
6296 if (chip->controller->ops && chip->controller->ops->attach_chip)
6297 return chip->controller->ops->attach_chip(chip);
6302 static void nand_detach(struct nand_chip *chip)
6304 if (chip->controller->ops && chip->controller->ops->detach_chip)
6305 chip->controller->ops->detach_chip(chip);
6309 * nand_scan_with_ids - [NAND Interface] Scan for the NAND device
6310 * @chip: NAND chip object
6311 * @maxchips: number of chips to scan for.
6312 * @ids: optional flash IDs table
6314 * This fills out all the uninitialized function pointers with the defaults.
6315 * The flash ID is read and the mtd/chip structures are filled with the
6316 * appropriate values.
6318 int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips,
6319 struct nand_flash_dev *ids)
6326 ret = nand_scan_ident(chip, maxchips, ids);
6330 ret = nand_attach(chip);
6334 ret = nand_scan_tail(chip);
6343 nand_scan_ident_cleanup(chip);
6347 EXPORT_SYMBOL(nand_scan_with_ids);
6350 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
6351 * @chip: NAND chip object
6353 void nand_cleanup(struct nand_chip *chip)
6355 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_SOFT) {
6356 if (chip->ecc.algo == NAND_ECC_ALGO_HAMMING)
6357 rawnand_sw_hamming_cleanup(chip);
6358 else if (chip->ecc.algo == NAND_ECC_ALGO_BCH)
6359 rawnand_sw_bch_cleanup(chip);
6362 nanddev_cleanup(&chip->base);
6364 /* Free secure regions data */
6365 kfree(chip->secure_regions);
6367 /* Free bad block table memory */
6369 kfree(chip->data_buf);
6370 kfree(chip->ecc.code_buf);
6371 kfree(chip->ecc.calc_buf);
6373 /* Free bad block descriptor memory */
6374 if (chip->badblock_pattern && chip->badblock_pattern->options
6375 & NAND_BBT_DYNAMICSTRUCT)
6376 kfree(chip->badblock_pattern);
6378 /* Free the data interface */
6379 kfree(chip->best_interface_config);
6381 /* Free manufacturer priv data. */
6382 nand_manufacturer_cleanup(chip);
6384 /* Free controller specific allocations after chip identification */
6387 /* Free identification phase allocations */
6388 nand_scan_ident_cleanup(chip);
6391 EXPORT_SYMBOL_GPL(nand_cleanup);
6393 MODULE_LICENSE("GPL");
6394 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
6395 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
6396 MODULE_DESCRIPTION("Generic NAND flash driver code");