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_ecc.h>
38 #include <linux/mtd/nand_bch.h>
39 #include <linux/interrupt.h>
40 #include <linux/bitops.h>
42 #include <linux/mtd/partitions.h>
44 #include <linux/gpio/consumer.h>
46 #include "internals.h"
48 /* Define default oob placement schemes for large and small page devices */
49 static int nand_ooblayout_ecc_sp(struct mtd_info *mtd, int section,
50 struct mtd_oob_region *oobregion)
52 struct nand_chip *chip = mtd_to_nand(mtd);
53 struct nand_ecc_ctrl *ecc = &chip->ecc;
59 oobregion->offset = 0;
60 if (mtd->oobsize == 16)
61 oobregion->length = 4;
63 oobregion->length = 3;
65 if (mtd->oobsize == 8)
68 oobregion->offset = 6;
69 oobregion->length = ecc->total - 4;
75 static int nand_ooblayout_free_sp(struct mtd_info *mtd, int section,
76 struct mtd_oob_region *oobregion)
81 if (mtd->oobsize == 16) {
85 oobregion->length = 8;
86 oobregion->offset = 8;
88 oobregion->length = 2;
90 oobregion->offset = 3;
92 oobregion->offset = 6;
98 const struct mtd_ooblayout_ops nand_ooblayout_sp_ops = {
99 .ecc = nand_ooblayout_ecc_sp,
100 .free = nand_ooblayout_free_sp,
102 EXPORT_SYMBOL_GPL(nand_ooblayout_sp_ops);
104 static int nand_ooblayout_ecc_lp(struct mtd_info *mtd, int section,
105 struct mtd_oob_region *oobregion)
107 struct nand_chip *chip = mtd_to_nand(mtd);
108 struct nand_ecc_ctrl *ecc = &chip->ecc;
110 if (section || !ecc->total)
113 oobregion->length = ecc->total;
114 oobregion->offset = mtd->oobsize - oobregion->length;
119 static int nand_ooblayout_free_lp(struct mtd_info *mtd, int section,
120 struct mtd_oob_region *oobregion)
122 struct nand_chip *chip = mtd_to_nand(mtd);
123 struct nand_ecc_ctrl *ecc = &chip->ecc;
128 oobregion->length = mtd->oobsize - ecc->total - 2;
129 oobregion->offset = 2;
134 const struct mtd_ooblayout_ops nand_ooblayout_lp_ops = {
135 .ecc = nand_ooblayout_ecc_lp,
136 .free = nand_ooblayout_free_lp,
138 EXPORT_SYMBOL_GPL(nand_ooblayout_lp_ops);
141 * Support the old "large page" layout used for 1-bit Hamming ECC where ECC
142 * are placed at a fixed offset.
144 static int nand_ooblayout_ecc_lp_hamming(struct mtd_info *mtd, int section,
145 struct mtd_oob_region *oobregion)
147 struct nand_chip *chip = mtd_to_nand(mtd);
148 struct nand_ecc_ctrl *ecc = &chip->ecc;
153 switch (mtd->oobsize) {
155 oobregion->offset = 40;
158 oobregion->offset = 80;
164 oobregion->length = ecc->total;
165 if (oobregion->offset + oobregion->length > mtd->oobsize)
171 static int nand_ooblayout_free_lp_hamming(struct mtd_info *mtd, int section,
172 struct mtd_oob_region *oobregion)
174 struct nand_chip *chip = mtd_to_nand(mtd);
175 struct nand_ecc_ctrl *ecc = &chip->ecc;
178 if (section < 0 || section > 1)
181 switch (mtd->oobsize) {
193 oobregion->offset = 2;
194 oobregion->length = ecc_offset - 2;
196 oobregion->offset = ecc_offset + ecc->total;
197 oobregion->length = mtd->oobsize - oobregion->offset;
203 static const struct mtd_ooblayout_ops nand_ooblayout_lp_hamming_ops = {
204 .ecc = nand_ooblayout_ecc_lp_hamming,
205 .free = nand_ooblayout_free_lp_hamming,
208 static int check_offs_len(struct nand_chip *chip, loff_t ofs, uint64_t len)
212 /* Start address must align on block boundary */
213 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
214 pr_debug("%s: unaligned address\n", __func__);
218 /* Length must align on block boundary */
219 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
220 pr_debug("%s: length not block aligned\n", __func__);
228 * nand_select_target() - Select a NAND target (A.K.A. die)
229 * @chip: NAND chip object
230 * @cs: the CS line to select. Note that this CS id is always from the chip
231 * PoV, not the controller one
233 * Select a NAND target so that further operations executed on @chip go to the
234 * selected NAND target.
236 void nand_select_target(struct nand_chip *chip, unsigned int cs)
239 * cs should always lie between 0 and nanddev_ntargets(), when that's
240 * not the case it's a bug and the caller should be fixed.
242 if (WARN_ON(cs > nanddev_ntargets(&chip->base)))
247 if (chip->legacy.select_chip)
248 chip->legacy.select_chip(chip, cs);
250 EXPORT_SYMBOL_GPL(nand_select_target);
253 * nand_deselect_target() - Deselect the currently selected target
254 * @chip: NAND chip object
256 * Deselect the currently selected NAND target. The result of operations
257 * executed on @chip after the target has been deselected is undefined.
259 void nand_deselect_target(struct nand_chip *chip)
261 if (chip->legacy.select_chip)
262 chip->legacy.select_chip(chip, -1);
266 EXPORT_SYMBOL_GPL(nand_deselect_target);
269 * nand_release_device - [GENERIC] release chip
270 * @chip: NAND chip object
272 * Release chip lock and wake up anyone waiting on the device.
274 static void nand_release_device(struct nand_chip *chip)
276 /* Release the controller and the chip */
277 mutex_unlock(&chip->controller->lock);
278 mutex_unlock(&chip->lock);
282 * nand_bbm_get_next_page - Get the next page for bad block markers
283 * @chip: NAND chip object
284 * @page: First page to start checking for bad block marker usage
286 * Returns an integer that corresponds to the page offset within a block, for
287 * a page that is used to store bad block markers. If no more pages are
288 * available, -EINVAL is returned.
290 int nand_bbm_get_next_page(struct nand_chip *chip, int page)
292 struct mtd_info *mtd = nand_to_mtd(chip);
293 int last_page = ((mtd->erasesize - mtd->writesize) >>
294 chip->page_shift) & chip->pagemask;
296 if (page == 0 && chip->options & NAND_BBM_FIRSTPAGE)
298 else if (page <= 1 && chip->options & NAND_BBM_SECONDPAGE)
300 else if (page <= last_page && chip->options & NAND_BBM_LASTPAGE)
307 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
308 * @chip: NAND chip object
309 * @ofs: offset from device start
311 * Check, if the block is bad.
313 static int nand_block_bad(struct nand_chip *chip, loff_t ofs)
315 int first_page, page_offset;
319 first_page = (int)(ofs >> chip->page_shift) & chip->pagemask;
320 page_offset = nand_bbm_get_next_page(chip, 0);
322 while (page_offset >= 0) {
323 res = chip->ecc.read_oob(chip, first_page + page_offset);
327 bad = chip->oob_poi[chip->badblockpos];
329 if (likely(chip->badblockbits == 8))
332 res = hweight8(bad) < chip->badblockbits;
336 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
342 static int nand_isbad_bbm(struct nand_chip *chip, loff_t ofs)
344 if (chip->legacy.block_bad)
345 return chip->legacy.block_bad(chip, ofs);
347 return nand_block_bad(chip, ofs);
351 * nand_get_device - [GENERIC] Get chip for selected access
352 * @chip: NAND chip structure
354 * Lock the device and its controller for exclusive access
356 * Return: -EBUSY if the chip has been suspended, 0 otherwise
358 static int nand_get_device(struct nand_chip *chip)
360 mutex_lock(&chip->lock);
361 if (chip->suspended) {
362 mutex_unlock(&chip->lock);
365 mutex_lock(&chip->controller->lock);
371 * nand_check_wp - [GENERIC] check if the chip is write protected
372 * @chip: NAND chip object
374 * Check, if the device is write protected. The function expects, that the
375 * device is already selected.
377 static int nand_check_wp(struct nand_chip *chip)
382 /* Broken xD cards report WP despite being writable */
383 if (chip->options & NAND_BROKEN_XD)
386 /* Check the WP bit */
387 ret = nand_status_op(chip, &status);
391 return status & NAND_STATUS_WP ? 0 : 1;
395 * nand_fill_oob - [INTERN] Transfer client buffer to oob
396 * @chip: NAND chip object
397 * @oob: oob data buffer
398 * @len: oob data write length
399 * @ops: oob ops structure
401 static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len,
402 struct mtd_oob_ops *ops)
404 struct mtd_info *mtd = nand_to_mtd(chip);
408 * Initialise to all 0xFF, to avoid the possibility of left over OOB
409 * data from a previous OOB read.
411 memset(chip->oob_poi, 0xff, mtd->oobsize);
415 case MTD_OPS_PLACE_OOB:
417 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
420 case MTD_OPS_AUTO_OOB:
421 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
433 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
434 * @chip: NAND chip object
435 * @to: offset to write to
436 * @ops: oob operation description structure
438 * NAND write out-of-band.
440 static int nand_do_write_oob(struct nand_chip *chip, loff_t to,
441 struct mtd_oob_ops *ops)
443 struct mtd_info *mtd = nand_to_mtd(chip);
444 int chipnr, page, status, len, ret;
446 pr_debug("%s: to = 0x%08x, len = %i\n",
447 __func__, (unsigned int)to, (int)ops->ooblen);
449 len = mtd_oobavail(mtd, ops);
451 /* Do not allow write past end of page */
452 if ((ops->ooboffs + ops->ooblen) > len) {
453 pr_debug("%s: attempt to write past end of page\n",
458 chipnr = (int)(to >> chip->chip_shift);
461 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
462 * of my DiskOnChip 2000 test units) will clear the whole data page too
463 * if we don't do this. I have no clue why, but I seem to have 'fixed'
464 * it in the doc2000 driver in August 1999. dwmw2.
466 ret = nand_reset(chip, chipnr);
470 nand_select_target(chip, chipnr);
472 /* Shift to get page */
473 page = (int)(to >> chip->page_shift);
475 /* Check, if it is write protected */
476 if (nand_check_wp(chip)) {
477 nand_deselect_target(chip);
481 /* Invalidate the page cache, if we write to the cached page */
482 if (page == chip->pagecache.page)
483 chip->pagecache.page = -1;
485 nand_fill_oob(chip, ops->oobbuf, ops->ooblen, ops);
487 if (ops->mode == MTD_OPS_RAW)
488 status = chip->ecc.write_oob_raw(chip, page & chip->pagemask);
490 status = chip->ecc.write_oob(chip, page & chip->pagemask);
492 nand_deselect_target(chip);
497 ops->oobretlen = ops->ooblen;
503 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
504 * @chip: NAND chip object
505 * @ofs: offset from device start
507 * This is the default implementation, which can be overridden by a hardware
508 * specific driver. It provides the details for writing a bad block marker to a
511 static int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
513 struct mtd_info *mtd = nand_to_mtd(chip);
514 struct mtd_oob_ops ops;
515 uint8_t buf[2] = { 0, 0 };
516 int ret = 0, res, page_offset;
518 memset(&ops, 0, sizeof(ops));
520 ops.ooboffs = chip->badblockpos;
521 if (chip->options & NAND_BUSWIDTH_16) {
522 ops.ooboffs &= ~0x01;
523 ops.len = ops.ooblen = 2;
525 ops.len = ops.ooblen = 1;
527 ops.mode = MTD_OPS_PLACE_OOB;
529 page_offset = nand_bbm_get_next_page(chip, 0);
531 while (page_offset >= 0) {
532 res = nand_do_write_oob(chip,
533 ofs + (page_offset * mtd->writesize),
539 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
546 * nand_markbad_bbm - mark a block by updating the BBM
547 * @chip: NAND chip object
548 * @ofs: offset of the block to mark bad
550 int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
552 if (chip->legacy.block_markbad)
553 return chip->legacy.block_markbad(chip, ofs);
555 return nand_default_block_markbad(chip, ofs);
559 * nand_block_markbad_lowlevel - mark a block bad
560 * @chip: NAND chip object
561 * @ofs: offset from device start
563 * This function performs the generic NAND bad block marking steps (i.e., bad
564 * block table(s) and/or marker(s)). We only allow the hardware driver to
565 * specify how to write bad block markers to OOB (chip->legacy.block_markbad).
567 * We try operations in the following order:
569 * (1) erase the affected block, to allow OOB marker to be written cleanly
570 * (2) write bad block marker to OOB area of affected block (unless flag
571 * NAND_BBT_NO_OOB_BBM is present)
574 * Note that we retain the first error encountered in (2) or (3), finish the
575 * procedures, and dump the error in the end.
577 static int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
579 struct mtd_info *mtd = nand_to_mtd(chip);
582 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
583 struct erase_info einfo;
585 /* Attempt erase before marking OOB */
586 memset(&einfo, 0, sizeof(einfo));
588 einfo.len = 1ULL << chip->phys_erase_shift;
589 nand_erase_nand(chip, &einfo, 0);
591 /* Write bad block marker to OOB */
592 ret = nand_get_device(chip);
596 ret = nand_markbad_bbm(chip, ofs);
597 nand_release_device(chip);
600 /* Mark block bad in BBT */
602 res = nand_markbad_bbt(chip, ofs);
608 mtd->ecc_stats.badblocks++;
614 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
615 * @mtd: MTD device structure
616 * @ofs: offset from device start
618 * Check if the block is marked as reserved.
620 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
622 struct nand_chip *chip = mtd_to_nand(mtd);
626 /* Return info from the table */
627 return nand_isreserved_bbt(chip, ofs);
631 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
632 * @chip: NAND chip object
633 * @ofs: offset from device start
634 * @allowbbt: 1, if its allowed to access the bbt area
636 * Check, if the block is bad. Either by reading the bad block table or
637 * calling of the scan function.
639 static int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
641 /* Return info from the table */
643 return nand_isbad_bbt(chip, ofs, allowbbt);
645 return nand_isbad_bbm(chip, ofs);
649 * nand_soft_waitrdy - Poll STATUS reg until RDY bit is set to 1
650 * @chip: NAND chip structure
651 * @timeout_ms: Timeout in ms
653 * Poll the STATUS register using ->exec_op() until the RDY bit becomes 1.
654 * If that does not happen whitin the specified timeout, -ETIMEDOUT is
657 * This helper is intended to be used when the controller does not have access
658 * to the NAND R/B pin.
660 * Be aware that calling this helper from an ->exec_op() implementation means
661 * ->exec_op() must be re-entrant.
663 * Return 0 if the NAND chip is ready, a negative error otherwise.
665 int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
667 const struct nand_sdr_timings *timings;
671 if (!nand_has_exec_op(chip))
674 /* Wait tWB before polling the STATUS reg. */
675 timings = nand_get_sdr_timings(&chip->data_interface);
676 ndelay(PSEC_TO_NSEC(timings->tWB_max));
678 ret = nand_status_op(chip, NULL);
682 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms);
684 ret = nand_read_data_op(chip, &status, sizeof(status), true);
688 if (status & NAND_STATUS_READY)
692 * Typical lowest execution time for a tR on most NANDs is 10us,
693 * use this as polling delay before doing something smarter (ie.
694 * deriving a delay from the timeout value, timeout_ms/ratio).
697 } while (time_before(jiffies, timeout_ms));
700 * We have to exit READ_STATUS mode in order to read real data on the
701 * bus in case the WAITRDY instruction is preceding a DATA_IN
704 nand_exit_status_op(chip);
709 return status & NAND_STATUS_READY ? 0 : -ETIMEDOUT;
711 EXPORT_SYMBOL_GPL(nand_soft_waitrdy);
714 * nand_gpio_waitrdy - Poll R/B GPIO pin until ready
715 * @chip: NAND chip structure
716 * @gpiod: GPIO descriptor of R/B pin
717 * @timeout_ms: Timeout in ms
719 * Poll the R/B GPIO pin until it becomes ready. If that does not happen
720 * whitin the specified timeout, -ETIMEDOUT is returned.
722 * This helper is intended to be used when the controller has access to the
723 * NAND R/B pin over GPIO.
725 * Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.
727 int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
728 unsigned long timeout_ms)
730 /* Wait until R/B pin indicates chip is ready or timeout occurs */
731 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms);
733 if (gpiod_get_value_cansleep(gpiod))
737 } while (time_before(jiffies, timeout_ms));
739 return gpiod_get_value_cansleep(gpiod) ? 0 : -ETIMEDOUT;
741 EXPORT_SYMBOL_GPL(nand_gpio_waitrdy);
744 * panic_nand_wait - [GENERIC] wait until the command is done
745 * @chip: NAND chip structure
748 * Wait for command done. This is a helper function for nand_wait used when
749 * we are in interrupt context. May happen when in panic and trying to write
750 * an oops through mtdoops.
752 void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
755 for (i = 0; i < timeo; i++) {
756 if (chip->legacy.dev_ready) {
757 if (chip->legacy.dev_ready(chip))
763 ret = nand_read_data_op(chip, &status, sizeof(status),
768 if (status & NAND_STATUS_READY)
775 static bool nand_supports_get_features(struct nand_chip *chip, int addr)
777 return (chip->parameters.supports_set_get_features &&
778 test_bit(addr, chip->parameters.get_feature_list));
781 static bool nand_supports_set_features(struct nand_chip *chip, int addr)
783 return (chip->parameters.supports_set_get_features &&
784 test_bit(addr, chip->parameters.set_feature_list));
788 * nand_reset_data_interface - Reset data interface and timings
789 * @chip: The NAND chip
790 * @chipnr: Internal die id
792 * Reset the Data interface and timings to ONFI mode 0.
794 * Returns 0 for success or negative error code otherwise.
796 static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
800 if (!nand_has_setup_data_iface(chip))
804 * The ONFI specification says:
806 * To transition from NV-DDR or NV-DDR2 to the SDR data
807 * interface, the host shall use the Reset (FFh) command
808 * using SDR timing mode 0. A device in any timing mode is
809 * required to recognize Reset (FFh) command issued in SDR
813 * Configure the data interface in SDR mode and set the
814 * timings to timing mode 0.
817 onfi_fill_data_interface(chip, NAND_SDR_IFACE, 0);
818 ret = chip->controller->ops->setup_data_interface(chip, chipnr,
819 &chip->data_interface);
821 pr_err("Failed to configure data interface to SDR timing mode 0\n");
827 * nand_setup_data_interface - Setup the best data interface and timings
828 * @chip: The NAND chip
829 * @chipnr: Internal die id
831 * Find and configure the best data interface and NAND timings supported by
832 * the chip and the driver.
833 * First tries to retrieve supported timing modes from ONFI information,
834 * and if the NAND chip does not support ONFI, relies on the
835 * ->onfi_timing_mode_default specified in the nand_ids table.
837 * Returns 0 for success or negative error code otherwise.
839 static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
841 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
842 chip->onfi_timing_mode_default,
846 if (!nand_has_setup_data_iface(chip))
849 /* Change the mode on the chip side (if supported by the NAND chip) */
850 if (nand_supports_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE)) {
851 nand_select_target(chip, chipnr);
852 ret = nand_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
854 nand_deselect_target(chip);
859 /* Change the mode on the controller side */
860 ret = chip->controller->ops->setup_data_interface(chip, chipnr,
861 &chip->data_interface);
865 /* Check the mode has been accepted by the chip, if supported */
866 if (!nand_supports_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE))
869 memset(tmode_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
870 nand_select_target(chip, chipnr);
871 ret = nand_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
873 nand_deselect_target(chip);
877 if (tmode_param[0] != chip->onfi_timing_mode_default) {
878 pr_warn("timing mode %d not acknowledged by the NAND chip\n",
879 chip->onfi_timing_mode_default);
887 * Fallback to mode 0 if the chip explicitly did not ack the chosen
890 nand_reset_data_interface(chip, chipnr);
891 nand_select_target(chip, chipnr);
893 nand_deselect_target(chip);
899 * nand_init_data_interface - find the best data interface and timings
900 * @chip: The NAND chip
902 * Find the best data interface and NAND timings supported by the chip
904 * First tries to retrieve supported timing modes from ONFI information,
905 * and if the NAND chip does not support ONFI, relies on the
906 * ->onfi_timing_mode_default specified in the nand_ids table. After this
907 * function nand_chip->data_interface is initialized with the best timing mode
910 * Returns 0 for success or negative error code otherwise.
912 static int nand_init_data_interface(struct nand_chip *chip)
914 int modes, mode, ret;
916 if (!nand_has_setup_data_iface(chip))
920 * First try to identify the best timings from ONFI parameters and
921 * if the NAND does not support ONFI, fallback to the default ONFI
924 if (chip->parameters.onfi) {
925 modes = chip->parameters.onfi->async_timing_mode;
927 if (!chip->onfi_timing_mode_default)
930 modes = GENMASK(chip->onfi_timing_mode_default, 0);
933 for (mode = fls(modes) - 1; mode >= 0; mode--) {
934 ret = onfi_fill_data_interface(chip, NAND_SDR_IFACE, mode);
939 * Pass NAND_DATA_IFACE_CHECK_ONLY to only check if the
940 * controller supports the requested timings.
942 ret = chip->controller->ops->setup_data_interface(chip,
943 NAND_DATA_IFACE_CHECK_ONLY,
944 &chip->data_interface);
946 chip->onfi_timing_mode_default = mode;
955 * nand_fill_column_cycles - fill the column cycles of an address
956 * @chip: The NAND chip
957 * @addrs: Array of address cycles to fill
958 * @offset_in_page: The offset in the page
960 * Fills the first or the first two bytes of the @addrs field depending
961 * on the NAND bus width and the page size.
963 * Returns the number of cycles needed to encode the column, or a negative
964 * error code in case one of the arguments is invalid.
966 static int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs,
967 unsigned int offset_in_page)
969 struct mtd_info *mtd = nand_to_mtd(chip);
971 /* Make sure the offset is less than the actual page size. */
972 if (offset_in_page > mtd->writesize + mtd->oobsize)
976 * On small page NANDs, there's a dedicated command to access the OOB
977 * area, and the column address is relative to the start of the OOB
978 * area, not the start of the page. Asjust the address accordingly.
980 if (mtd->writesize <= 512 && offset_in_page >= mtd->writesize)
981 offset_in_page -= mtd->writesize;
984 * The offset in page is expressed in bytes, if the NAND bus is 16-bit
985 * wide, then it must be divided by 2.
987 if (chip->options & NAND_BUSWIDTH_16) {
988 if (WARN_ON(offset_in_page % 2))
994 addrs[0] = offset_in_page;
997 * Small page NANDs use 1 cycle for the columns, while large page NANDs
1000 if (mtd->writesize <= 512)
1003 addrs[1] = offset_in_page >> 8;
1008 static int nand_sp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1009 unsigned int offset_in_page, void *buf,
1012 struct mtd_info *mtd = nand_to_mtd(chip);
1013 const struct nand_sdr_timings *sdr =
1014 nand_get_sdr_timings(&chip->data_interface);
1016 struct nand_op_instr instrs[] = {
1017 NAND_OP_CMD(NAND_CMD_READ0, 0),
1018 NAND_OP_ADDR(3, addrs, PSEC_TO_NSEC(sdr->tWB_max)),
1019 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1020 PSEC_TO_NSEC(sdr->tRR_min)),
1021 NAND_OP_DATA_IN(len, buf, 0),
1023 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1026 /* Drop the DATA_IN instruction if len is set to 0. */
1030 if (offset_in_page >= mtd->writesize)
1031 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1032 else if (offset_in_page >= 256 &&
1033 !(chip->options & NAND_BUSWIDTH_16))
1034 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1036 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1041 addrs[2] = page >> 8;
1043 if (chip->options & NAND_ROW_ADDR_3) {
1044 addrs[3] = page >> 16;
1045 instrs[1].ctx.addr.naddrs++;
1048 return nand_exec_op(chip, &op);
1051 static int nand_lp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1052 unsigned int offset_in_page, void *buf,
1055 const struct nand_sdr_timings *sdr =
1056 nand_get_sdr_timings(&chip->data_interface);
1058 struct nand_op_instr instrs[] = {
1059 NAND_OP_CMD(NAND_CMD_READ0, 0),
1060 NAND_OP_ADDR(4, addrs, 0),
1061 NAND_OP_CMD(NAND_CMD_READSTART, PSEC_TO_NSEC(sdr->tWB_max)),
1062 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1063 PSEC_TO_NSEC(sdr->tRR_min)),
1064 NAND_OP_DATA_IN(len, buf, 0),
1066 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1069 /* Drop the DATA_IN instruction if len is set to 0. */
1073 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1078 addrs[3] = page >> 8;
1080 if (chip->options & NAND_ROW_ADDR_3) {
1081 addrs[4] = page >> 16;
1082 instrs[1].ctx.addr.naddrs++;
1085 return nand_exec_op(chip, &op);
1089 * nand_read_page_op - Do a READ PAGE operation
1090 * @chip: The NAND chip
1091 * @page: page to read
1092 * @offset_in_page: offset within the page
1093 * @buf: buffer used to store the data
1094 * @len: length of the buffer
1096 * This function issues a READ PAGE operation.
1097 * This function does not select/unselect the CS line.
1099 * Returns 0 on success, a negative error code otherwise.
1101 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1102 unsigned int offset_in_page, void *buf, unsigned int len)
1104 struct mtd_info *mtd = nand_to_mtd(chip);
1109 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1112 if (nand_has_exec_op(chip)) {
1113 if (mtd->writesize > 512)
1114 return nand_lp_exec_read_page_op(chip, page,
1115 offset_in_page, buf,
1118 return nand_sp_exec_read_page_op(chip, page, offset_in_page,
1122 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, offset_in_page, page);
1124 chip->legacy.read_buf(chip, buf, len);
1128 EXPORT_SYMBOL_GPL(nand_read_page_op);
1131 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1132 * @chip: The NAND chip
1133 * @page: parameter page to read
1134 * @buf: buffer used to store the data
1135 * @len: length of the buffer
1137 * This function issues a READ PARAMETER PAGE operation.
1138 * This function does not select/unselect the CS line.
1140 * Returns 0 on success, a negative error code otherwise.
1142 int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1151 if (nand_has_exec_op(chip)) {
1152 const struct nand_sdr_timings *sdr =
1153 nand_get_sdr_timings(&chip->data_interface);
1154 struct nand_op_instr instrs[] = {
1155 NAND_OP_CMD(NAND_CMD_PARAM, 0),
1156 NAND_OP_ADDR(1, &page, PSEC_TO_NSEC(sdr->tWB_max)),
1157 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1158 PSEC_TO_NSEC(sdr->tRR_min)),
1159 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1161 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1163 /* Drop the DATA_IN instruction if len is set to 0. */
1167 return nand_exec_op(chip, &op);
1170 chip->legacy.cmdfunc(chip, NAND_CMD_PARAM, page, -1);
1171 for (i = 0; i < len; i++)
1172 p[i] = chip->legacy.read_byte(chip);
1178 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1179 * @chip: The NAND chip
1180 * @offset_in_page: offset within the page
1181 * @buf: buffer used to store the data
1182 * @len: length of the buffer
1183 * @force_8bit: force 8-bit bus access
1185 * This function issues a CHANGE READ COLUMN operation.
1186 * This function does not select/unselect the CS line.
1188 * Returns 0 on success, a negative error code otherwise.
1190 int nand_change_read_column_op(struct nand_chip *chip,
1191 unsigned int offset_in_page, void *buf,
1192 unsigned int len, bool force_8bit)
1194 struct mtd_info *mtd = nand_to_mtd(chip);
1199 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1202 /* Small page NANDs do not support column change. */
1203 if (mtd->writesize <= 512)
1206 if (nand_has_exec_op(chip)) {
1207 const struct nand_sdr_timings *sdr =
1208 nand_get_sdr_timings(&chip->data_interface);
1210 struct nand_op_instr instrs[] = {
1211 NAND_OP_CMD(NAND_CMD_RNDOUT, 0),
1212 NAND_OP_ADDR(2, addrs, 0),
1213 NAND_OP_CMD(NAND_CMD_RNDOUTSTART,
1214 PSEC_TO_NSEC(sdr->tCCS_min)),
1215 NAND_OP_DATA_IN(len, buf, 0),
1217 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1220 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1224 /* Drop the DATA_IN instruction if len is set to 0. */
1228 instrs[3].ctx.data.force_8bit = force_8bit;
1230 return nand_exec_op(chip, &op);
1233 chip->legacy.cmdfunc(chip, NAND_CMD_RNDOUT, offset_in_page, -1);
1235 chip->legacy.read_buf(chip, buf, len);
1239 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1242 * nand_read_oob_op - Do a READ OOB operation
1243 * @chip: The NAND chip
1244 * @page: page to read
1245 * @offset_in_oob: offset within the OOB area
1246 * @buf: buffer used to store the data
1247 * @len: length of the buffer
1249 * This function issues a READ OOB operation.
1250 * This function does not select/unselect the CS line.
1252 * Returns 0 on success, a negative error code otherwise.
1254 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1255 unsigned int offset_in_oob, void *buf, unsigned int len)
1257 struct mtd_info *mtd = nand_to_mtd(chip);
1262 if (offset_in_oob + len > mtd->oobsize)
1265 if (nand_has_exec_op(chip))
1266 return nand_read_page_op(chip, page,
1267 mtd->writesize + offset_in_oob,
1270 chip->legacy.cmdfunc(chip, NAND_CMD_READOOB, offset_in_oob, page);
1272 chip->legacy.read_buf(chip, buf, len);
1276 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1278 static int nand_exec_prog_page_op(struct nand_chip *chip, unsigned int page,
1279 unsigned int offset_in_page, const void *buf,
1280 unsigned int len, bool prog)
1282 struct mtd_info *mtd = nand_to_mtd(chip);
1283 const struct nand_sdr_timings *sdr =
1284 nand_get_sdr_timings(&chip->data_interface);
1286 struct nand_op_instr instrs[] = {
1288 * The first instruction will be dropped if we're dealing
1289 * with a large page NAND and adjusted if we're dealing
1290 * with a small page NAND and the page offset is > 255.
1292 NAND_OP_CMD(NAND_CMD_READ0, 0),
1293 NAND_OP_CMD(NAND_CMD_SEQIN, 0),
1294 NAND_OP_ADDR(0, addrs, PSEC_TO_NSEC(sdr->tADL_min)),
1295 NAND_OP_DATA_OUT(len, buf, 0),
1296 NAND_OP_CMD(NAND_CMD_PAGEPROG, PSEC_TO_NSEC(sdr->tWB_max)),
1297 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1299 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1300 int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
1307 addrs[naddrs++] = page;
1308 addrs[naddrs++] = page >> 8;
1309 if (chip->options & NAND_ROW_ADDR_3)
1310 addrs[naddrs++] = page >> 16;
1312 instrs[2].ctx.addr.naddrs = naddrs;
1314 /* Drop the last two instructions if we're not programming the page. */
1317 /* Also drop the DATA_OUT instruction if empty. */
1322 if (mtd->writesize <= 512) {
1324 * Small pages need some more tweaking: we have to adjust the
1325 * first instruction depending on the page offset we're trying
1328 if (offset_in_page >= mtd->writesize)
1329 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1330 else if (offset_in_page >= 256 &&
1331 !(chip->options & NAND_BUSWIDTH_16))
1332 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1335 * Drop the first command if we're dealing with a large page
1342 ret = nand_exec_op(chip, &op);
1346 ret = nand_status_op(chip, &status);
1354 * nand_prog_page_begin_op - starts a PROG PAGE operation
1355 * @chip: The NAND chip
1356 * @page: page to write
1357 * @offset_in_page: offset within the page
1358 * @buf: buffer containing the data to write to the page
1359 * @len: length of the buffer
1361 * This function issues the first half of a PROG PAGE operation.
1362 * This function does not select/unselect the CS line.
1364 * Returns 0 on success, a negative error code otherwise.
1366 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1367 unsigned int offset_in_page, const void *buf,
1370 struct mtd_info *mtd = nand_to_mtd(chip);
1375 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1378 if (nand_has_exec_op(chip))
1379 return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1382 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page, page);
1385 chip->legacy.write_buf(chip, buf, len);
1389 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1392 * nand_prog_page_end_op - ends a PROG PAGE operation
1393 * @chip: The NAND chip
1395 * This function issues the second half of a PROG PAGE operation.
1396 * This function does not select/unselect the CS line.
1398 * Returns 0 on success, a negative error code otherwise.
1400 int nand_prog_page_end_op(struct nand_chip *chip)
1405 if (nand_has_exec_op(chip)) {
1406 const struct nand_sdr_timings *sdr =
1407 nand_get_sdr_timings(&chip->data_interface);
1408 struct nand_op_instr instrs[] = {
1409 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1410 PSEC_TO_NSEC(sdr->tWB_max)),
1411 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1413 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1415 ret = nand_exec_op(chip, &op);
1419 ret = nand_status_op(chip, &status);
1423 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1424 ret = chip->legacy.waitfunc(chip);
1431 if (status & NAND_STATUS_FAIL)
1436 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1439 * nand_prog_page_op - Do a full PROG PAGE operation
1440 * @chip: The NAND chip
1441 * @page: page to write
1442 * @offset_in_page: offset within the page
1443 * @buf: buffer containing the data to write to the page
1444 * @len: length of the buffer
1446 * This function issues a full PROG PAGE operation.
1447 * This function does not select/unselect the CS line.
1449 * Returns 0 on success, a negative error code otherwise.
1451 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1452 unsigned int offset_in_page, const void *buf,
1455 struct mtd_info *mtd = nand_to_mtd(chip);
1461 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1464 if (nand_has_exec_op(chip)) {
1465 status = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1468 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page,
1470 chip->legacy.write_buf(chip, buf, len);
1471 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1472 status = chip->legacy.waitfunc(chip);
1475 if (status & NAND_STATUS_FAIL)
1480 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1483 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1484 * @chip: The NAND chip
1485 * @offset_in_page: offset within the page
1486 * @buf: buffer containing the data to send to the NAND
1487 * @len: length of the buffer
1488 * @force_8bit: force 8-bit bus access
1490 * This function issues a CHANGE WRITE COLUMN operation.
1491 * This function does not select/unselect the CS line.
1493 * Returns 0 on success, a negative error code otherwise.
1495 int nand_change_write_column_op(struct nand_chip *chip,
1496 unsigned int offset_in_page,
1497 const void *buf, unsigned int len,
1500 struct mtd_info *mtd = nand_to_mtd(chip);
1505 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1508 /* Small page NANDs do not support column change. */
1509 if (mtd->writesize <= 512)
1512 if (nand_has_exec_op(chip)) {
1513 const struct nand_sdr_timings *sdr =
1514 nand_get_sdr_timings(&chip->data_interface);
1516 struct nand_op_instr instrs[] = {
1517 NAND_OP_CMD(NAND_CMD_RNDIN, 0),
1518 NAND_OP_ADDR(2, addrs, PSEC_TO_NSEC(sdr->tCCS_min)),
1519 NAND_OP_DATA_OUT(len, buf, 0),
1521 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1524 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1528 instrs[2].ctx.data.force_8bit = force_8bit;
1530 /* Drop the DATA_OUT instruction if len is set to 0. */
1534 return nand_exec_op(chip, &op);
1537 chip->legacy.cmdfunc(chip, NAND_CMD_RNDIN, offset_in_page, -1);
1539 chip->legacy.write_buf(chip, buf, len);
1543 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1546 * nand_readid_op - Do a READID operation
1547 * @chip: The NAND chip
1548 * @addr: address cycle to pass after the READID command
1549 * @buf: buffer used to store the ID
1550 * @len: length of the buffer
1552 * This function sends a READID command and reads back the ID returned by the
1554 * This function does not select/unselect the CS line.
1556 * Returns 0 on success, a negative error code otherwise.
1558 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1567 if (nand_has_exec_op(chip)) {
1568 const struct nand_sdr_timings *sdr =
1569 nand_get_sdr_timings(&chip->data_interface);
1570 struct nand_op_instr instrs[] = {
1571 NAND_OP_CMD(NAND_CMD_READID, 0),
1572 NAND_OP_ADDR(1, &addr, PSEC_TO_NSEC(sdr->tADL_min)),
1573 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1575 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1577 /* Drop the DATA_IN instruction if len is set to 0. */
1581 return nand_exec_op(chip, &op);
1584 chip->legacy.cmdfunc(chip, NAND_CMD_READID, addr, -1);
1586 for (i = 0; i < len; i++)
1587 id[i] = chip->legacy.read_byte(chip);
1591 EXPORT_SYMBOL_GPL(nand_readid_op);
1594 * nand_status_op - Do a STATUS operation
1595 * @chip: The NAND chip
1596 * @status: out variable to store the NAND status
1598 * This function sends a STATUS command and reads back the status returned by
1600 * This function does not select/unselect the CS line.
1602 * Returns 0 on success, a negative error code otherwise.
1604 int nand_status_op(struct nand_chip *chip, u8 *status)
1606 if (nand_has_exec_op(chip)) {
1607 const struct nand_sdr_timings *sdr =
1608 nand_get_sdr_timings(&chip->data_interface);
1609 struct nand_op_instr instrs[] = {
1610 NAND_OP_CMD(NAND_CMD_STATUS,
1611 PSEC_TO_NSEC(sdr->tADL_min)),
1612 NAND_OP_8BIT_DATA_IN(1, status, 0),
1614 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1619 return nand_exec_op(chip, &op);
1622 chip->legacy.cmdfunc(chip, NAND_CMD_STATUS, -1, -1);
1624 *status = chip->legacy.read_byte(chip);
1628 EXPORT_SYMBOL_GPL(nand_status_op);
1631 * nand_exit_status_op - Exit a STATUS operation
1632 * @chip: The NAND chip
1634 * This function sends a READ0 command to cancel the effect of the STATUS
1635 * command to avoid reading only the status until a new read command is sent.
1637 * This function does not select/unselect the CS line.
1639 * Returns 0 on success, a negative error code otherwise.
1641 int nand_exit_status_op(struct nand_chip *chip)
1643 if (nand_has_exec_op(chip)) {
1644 struct nand_op_instr instrs[] = {
1645 NAND_OP_CMD(NAND_CMD_READ0, 0),
1647 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1649 return nand_exec_op(chip, &op);
1652 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, -1, -1);
1658 * nand_erase_op - Do an erase operation
1659 * @chip: The NAND chip
1660 * @eraseblock: block to erase
1662 * This function sends an ERASE command and waits for the NAND to be ready
1664 * This function does not select/unselect the CS line.
1666 * Returns 0 on success, a negative error code otherwise.
1668 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1670 unsigned int page = eraseblock <<
1671 (chip->phys_erase_shift - chip->page_shift);
1675 if (nand_has_exec_op(chip)) {
1676 const struct nand_sdr_timings *sdr =
1677 nand_get_sdr_timings(&chip->data_interface);
1678 u8 addrs[3] = { page, page >> 8, page >> 16 };
1679 struct nand_op_instr instrs[] = {
1680 NAND_OP_CMD(NAND_CMD_ERASE1, 0),
1681 NAND_OP_ADDR(2, addrs, 0),
1682 NAND_OP_CMD(NAND_CMD_ERASE2,
1683 PSEC_TO_MSEC(sdr->tWB_max)),
1684 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tBERS_max), 0),
1686 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1688 if (chip->options & NAND_ROW_ADDR_3)
1689 instrs[1].ctx.addr.naddrs++;
1691 ret = nand_exec_op(chip, &op);
1695 ret = nand_status_op(chip, &status);
1699 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE1, -1, page);
1700 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE2, -1, -1);
1702 ret = chip->legacy.waitfunc(chip);
1709 if (status & NAND_STATUS_FAIL)
1714 EXPORT_SYMBOL_GPL(nand_erase_op);
1717 * nand_set_features_op - Do a SET FEATURES operation
1718 * @chip: The NAND chip
1719 * @feature: feature id
1720 * @data: 4 bytes of data
1722 * This function sends a SET FEATURES command and waits for the NAND to be
1723 * ready before returning.
1724 * This function does not select/unselect the CS line.
1726 * Returns 0 on success, a negative error code otherwise.
1728 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1731 const u8 *params = data;
1734 if (nand_has_exec_op(chip)) {
1735 const struct nand_sdr_timings *sdr =
1736 nand_get_sdr_timings(&chip->data_interface);
1737 struct nand_op_instr instrs[] = {
1738 NAND_OP_CMD(NAND_CMD_SET_FEATURES, 0),
1739 NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tADL_min)),
1740 NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
1741 PSEC_TO_NSEC(sdr->tWB_max)),
1742 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max), 0),
1744 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1746 return nand_exec_op(chip, &op);
1749 chip->legacy.cmdfunc(chip, NAND_CMD_SET_FEATURES, feature, -1);
1750 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1751 chip->legacy.write_byte(chip, params[i]);
1753 ret = chip->legacy.waitfunc(chip);
1757 if (ret & NAND_STATUS_FAIL)
1764 * nand_get_features_op - Do a GET FEATURES operation
1765 * @chip: The NAND chip
1766 * @feature: feature id
1767 * @data: 4 bytes of data
1769 * This function sends a GET FEATURES command and waits for the NAND to be
1770 * ready before returning.
1771 * This function does not select/unselect the CS line.
1773 * Returns 0 on success, a negative error code otherwise.
1775 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1781 if (nand_has_exec_op(chip)) {
1782 const struct nand_sdr_timings *sdr =
1783 nand_get_sdr_timings(&chip->data_interface);
1784 struct nand_op_instr instrs[] = {
1785 NAND_OP_CMD(NAND_CMD_GET_FEATURES, 0),
1786 NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tWB_max)),
1787 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max),
1788 PSEC_TO_NSEC(sdr->tRR_min)),
1789 NAND_OP_8BIT_DATA_IN(ONFI_SUBFEATURE_PARAM_LEN,
1792 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1794 return nand_exec_op(chip, &op);
1797 chip->legacy.cmdfunc(chip, NAND_CMD_GET_FEATURES, feature, -1);
1798 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1799 params[i] = chip->legacy.read_byte(chip);
1804 static int nand_wait_rdy_op(struct nand_chip *chip, unsigned int timeout_ms,
1805 unsigned int delay_ns)
1807 if (nand_has_exec_op(chip)) {
1808 struct nand_op_instr instrs[] = {
1809 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(timeout_ms),
1810 PSEC_TO_NSEC(delay_ns)),
1812 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1814 return nand_exec_op(chip, &op);
1817 /* Apply delay or wait for ready/busy pin */
1818 if (!chip->legacy.dev_ready)
1819 udelay(chip->legacy.chip_delay);
1821 nand_wait_ready(chip);
1827 * nand_reset_op - Do a reset operation
1828 * @chip: The NAND chip
1830 * This function sends a RESET command and waits for the NAND to be ready
1832 * This function does not select/unselect the CS line.
1834 * Returns 0 on success, a negative error code otherwise.
1836 int nand_reset_op(struct nand_chip *chip)
1838 if (nand_has_exec_op(chip)) {
1839 const struct nand_sdr_timings *sdr =
1840 nand_get_sdr_timings(&chip->data_interface);
1841 struct nand_op_instr instrs[] = {
1842 NAND_OP_CMD(NAND_CMD_RESET, PSEC_TO_NSEC(sdr->tWB_max)),
1843 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tRST_max), 0),
1845 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1847 return nand_exec_op(chip, &op);
1850 chip->legacy.cmdfunc(chip, NAND_CMD_RESET, -1, -1);
1854 EXPORT_SYMBOL_GPL(nand_reset_op);
1857 * nand_read_data_op - Read data from the NAND
1858 * @chip: The NAND chip
1859 * @buf: buffer used to store the data
1860 * @len: length of the buffer
1861 * @force_8bit: force 8-bit bus access
1863 * This function does a raw data read on the bus. Usually used after launching
1864 * another NAND operation like nand_read_page_op().
1865 * This function does not select/unselect the CS line.
1867 * Returns 0 on success, a negative error code otherwise.
1869 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
1875 if (nand_has_exec_op(chip)) {
1876 struct nand_op_instr instrs[] = {
1877 NAND_OP_DATA_IN(len, buf, 0),
1879 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1881 instrs[0].ctx.data.force_8bit = force_8bit;
1883 return nand_exec_op(chip, &op);
1890 for (i = 0; i < len; i++)
1891 p[i] = chip->legacy.read_byte(chip);
1893 chip->legacy.read_buf(chip, buf, len);
1898 EXPORT_SYMBOL_GPL(nand_read_data_op);
1901 * nand_write_data_op - Write data from the NAND
1902 * @chip: The NAND chip
1903 * @buf: buffer containing the data to send on the bus
1904 * @len: length of the buffer
1905 * @force_8bit: force 8-bit bus access
1907 * This function does a raw data write on the bus. Usually used after launching
1908 * another NAND operation like nand_write_page_begin_op().
1909 * This function does not select/unselect the CS line.
1911 * Returns 0 on success, a negative error code otherwise.
1913 int nand_write_data_op(struct nand_chip *chip, const void *buf,
1914 unsigned int len, bool force_8bit)
1919 if (nand_has_exec_op(chip)) {
1920 struct nand_op_instr instrs[] = {
1921 NAND_OP_DATA_OUT(len, buf, 0),
1923 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1925 instrs[0].ctx.data.force_8bit = force_8bit;
1927 return nand_exec_op(chip, &op);
1934 for (i = 0; i < len; i++)
1935 chip->legacy.write_byte(chip, p[i]);
1937 chip->legacy.write_buf(chip, buf, len);
1942 EXPORT_SYMBOL_GPL(nand_write_data_op);
1945 * struct nand_op_parser_ctx - Context used by the parser
1946 * @instrs: array of all the instructions that must be addressed
1947 * @ninstrs: length of the @instrs array
1948 * @subop: Sub-operation to be passed to the NAND controller
1950 * This structure is used by the core to split NAND operations into
1951 * sub-operations that can be handled by the NAND controller.
1953 struct nand_op_parser_ctx {
1954 const struct nand_op_instr *instrs;
1955 unsigned int ninstrs;
1956 struct nand_subop subop;
1960 * nand_op_parser_must_split_instr - Checks if an instruction must be split
1961 * @pat: the parser pattern element that matches @instr
1962 * @instr: pointer to the instruction to check
1963 * @start_offset: this is an in/out parameter. If @instr has already been
1964 * split, then @start_offset is the offset from which to start
1965 * (either an address cycle or an offset in the data buffer).
1966 * Conversely, if the function returns true (ie. instr must be
1967 * split), this parameter is updated to point to the first
1968 * data/address cycle that has not been taken care of.
1970 * Some NAND controllers are limited and cannot send X address cycles with a
1971 * unique operation, or cannot read/write more than Y bytes at the same time.
1972 * In this case, split the instruction that does not fit in a single
1973 * controller-operation into two or more chunks.
1975 * Returns true if the instruction must be split, false otherwise.
1976 * The @start_offset parameter is also updated to the offset at which the next
1977 * bundle of instruction must start (if an address or a data instruction).
1980 nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat,
1981 const struct nand_op_instr *instr,
1982 unsigned int *start_offset)
1984 switch (pat->type) {
1985 case NAND_OP_ADDR_INSTR:
1986 if (!pat->ctx.addr.maxcycles)
1989 if (instr->ctx.addr.naddrs - *start_offset >
1990 pat->ctx.addr.maxcycles) {
1991 *start_offset += pat->ctx.addr.maxcycles;
1996 case NAND_OP_DATA_IN_INSTR:
1997 case NAND_OP_DATA_OUT_INSTR:
1998 if (!pat->ctx.data.maxlen)
2001 if (instr->ctx.data.len - *start_offset >
2002 pat->ctx.data.maxlen) {
2003 *start_offset += pat->ctx.data.maxlen;
2016 * nand_op_parser_match_pat - Checks if a pattern matches the instructions
2017 * remaining in the parser context
2018 * @pat: the pattern to test
2019 * @ctx: the parser context structure to match with the pattern @pat
2021 * Check if @pat matches the set or a sub-set of instructions remaining in @ctx.
2022 * Returns true if this is the case, false ortherwise. When true is returned,
2023 * @ctx->subop is updated with the set of instructions to be passed to the
2024 * controller driver.
2027 nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
2028 struct nand_op_parser_ctx *ctx)
2030 unsigned int instr_offset = ctx->subop.first_instr_start_off;
2031 const struct nand_op_instr *end = ctx->instrs + ctx->ninstrs;
2032 const struct nand_op_instr *instr = ctx->subop.instrs;
2033 unsigned int i, ninstrs;
2035 for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
2037 * The pattern instruction does not match the operation
2038 * instruction. If the instruction is marked optional in the
2039 * pattern definition, we skip the pattern element and continue
2040 * to the next one. If the element is mandatory, there's no
2041 * match and we can return false directly.
2043 if (instr->type != pat->elems[i].type) {
2044 if (!pat->elems[i].optional)
2051 * Now check the pattern element constraints. If the pattern is
2052 * not able to handle the whole instruction in a single step,
2053 * we have to split it.
2054 * The last_instr_end_off value comes back updated to point to
2055 * the position where we have to split the instruction (the
2056 * start of the next subop chunk).
2058 if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
2071 * This can happen if all instructions of a pattern are optional.
2072 * Still, if there's not at least one instruction handled by this
2073 * pattern, this is not a match, and we should try the next one (if
2080 * We had a match on the pattern head, but the pattern may be longer
2081 * than the instructions we're asked to execute. We need to make sure
2082 * there's no mandatory elements in the pattern tail.
2084 for (; i < pat->nelems; i++) {
2085 if (!pat->elems[i].optional)
2090 * We have a match: update the subop structure accordingly and return
2093 ctx->subop.ninstrs = ninstrs;
2094 ctx->subop.last_instr_end_off = instr_offset;
2099 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
2100 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2102 const struct nand_op_instr *instr;
2106 pr_debug("executing subop:\n");
2108 for (i = 0; i < ctx->ninstrs; i++) {
2109 instr = &ctx->instrs[i];
2111 if (instr == &ctx->subop.instrs[0])
2114 switch (instr->type) {
2115 case NAND_OP_CMD_INSTR:
2116 pr_debug("%sCMD [0x%02x]\n", prefix,
2117 instr->ctx.cmd.opcode);
2119 case NAND_OP_ADDR_INSTR:
2120 pr_debug("%sADDR [%d cyc: %*ph]\n", prefix,
2121 instr->ctx.addr.naddrs,
2122 instr->ctx.addr.naddrs < 64 ?
2123 instr->ctx.addr.naddrs : 64,
2124 instr->ctx.addr.addrs);
2126 case NAND_OP_DATA_IN_INSTR:
2127 pr_debug("%sDATA_IN [%d B%s]\n", prefix,
2128 instr->ctx.data.len,
2129 instr->ctx.data.force_8bit ?
2130 ", force 8-bit" : "");
2132 case NAND_OP_DATA_OUT_INSTR:
2133 pr_debug("%sDATA_OUT [%d B%s]\n", prefix,
2134 instr->ctx.data.len,
2135 instr->ctx.data.force_8bit ?
2136 ", force 8-bit" : "");
2138 case NAND_OP_WAITRDY_INSTR:
2139 pr_debug("%sWAITRDY [max %d ms]\n", prefix,
2140 instr->ctx.waitrdy.timeout_ms);
2144 if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
2149 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2156 * nand_op_parser_exec_op - exec_op parser
2157 * @chip: the NAND chip
2158 * @parser: patterns description provided by the controller driver
2159 * @op: the NAND operation to address
2160 * @check_only: when true, the function only checks if @op can be handled but
2161 * does not execute the operation
2163 * Helper function designed to ease integration of NAND controller drivers that
2164 * only support a limited set of instruction sequences. The supported sequences
2165 * are described in @parser, and the framework takes care of splitting @op into
2166 * multiple sub-operations (if required) and pass them back to the ->exec()
2167 * callback of the matching pattern if @check_only is set to false.
2169 * NAND controller drivers should call this function from their own ->exec_op()
2172 * Returns 0 on success, a negative error code otherwise. A failure can be
2173 * caused by an unsupported operation (none of the supported patterns is able
2174 * to handle the requested operation), or an error returned by one of the
2175 * matching pattern->exec() hook.
2177 int nand_op_parser_exec_op(struct nand_chip *chip,
2178 const struct nand_op_parser *parser,
2179 const struct nand_operation *op, bool check_only)
2181 struct nand_op_parser_ctx ctx = {
2182 .subop.instrs = op->instrs,
2183 .instrs = op->instrs,
2184 .ninstrs = op->ninstrs,
2188 while (ctx.subop.instrs < op->instrs + op->ninstrs) {
2191 for (i = 0; i < parser->npatterns; i++) {
2192 const struct nand_op_parser_pattern *pattern;
2194 pattern = &parser->patterns[i];
2195 if (!nand_op_parser_match_pat(pattern, &ctx))
2198 nand_op_parser_trace(&ctx);
2203 ret = pattern->exec(chip, &ctx.subop);
2210 if (i == parser->npatterns) {
2211 pr_debug("->exec_op() parser: pattern not found!\n");
2216 * Update the context structure by pointing to the start of the
2219 ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
2220 if (ctx.subop.last_instr_end_off)
2221 ctx.subop.instrs -= 1;
2223 ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
2228 EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
2230 static bool nand_instr_is_data(const struct nand_op_instr *instr)
2232 return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
2233 instr->type == NAND_OP_DATA_OUT_INSTR);
2236 static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
2237 unsigned int instr_idx)
2239 return subop && instr_idx < subop->ninstrs;
2242 static unsigned int nand_subop_get_start_off(const struct nand_subop *subop,
2243 unsigned int instr_idx)
2248 return subop->first_instr_start_off;
2252 * nand_subop_get_addr_start_off - Get the start offset in an address array
2253 * @subop: The entire sub-operation
2254 * @instr_idx: Index of the instruction inside the sub-operation
2256 * During driver development, one could be tempted to directly use the
2257 * ->addr.addrs field of address instructions. This is wrong as address
2258 * instructions might be split.
2260 * Given an address instruction, returns the offset of the first cycle to issue.
2262 unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
2263 unsigned int instr_idx)
2265 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2266 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2269 return nand_subop_get_start_off(subop, instr_idx);
2271 EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
2274 * nand_subop_get_num_addr_cyc - Get the remaining address cycles to assert
2275 * @subop: The entire sub-operation
2276 * @instr_idx: Index of the instruction inside the sub-operation
2278 * During driver development, one could be tempted to directly use the
2279 * ->addr->naddrs field of a data instruction. This is wrong as instructions
2282 * Given an address instruction, returns the number of address cycle to issue.
2284 unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
2285 unsigned int instr_idx)
2287 int start_off, end_off;
2289 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2290 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2293 start_off = nand_subop_get_addr_start_off(subop, instr_idx);
2295 if (instr_idx == subop->ninstrs - 1 &&
2296 subop->last_instr_end_off)
2297 end_off = subop->last_instr_end_off;
2299 end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
2301 return end_off - start_off;
2303 EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
2306 * nand_subop_get_data_start_off - Get the start offset in a data array
2307 * @subop: The entire sub-operation
2308 * @instr_idx: Index of the instruction inside the sub-operation
2310 * During driver development, one could be tempted to directly use the
2311 * ->data->buf.{in,out} field of data instructions. This is wrong as data
2312 * instructions might be split.
2314 * Given a data instruction, returns the offset to start from.
2316 unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
2317 unsigned int instr_idx)
2319 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2320 !nand_instr_is_data(&subop->instrs[instr_idx])))
2323 return nand_subop_get_start_off(subop, instr_idx);
2325 EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
2328 * nand_subop_get_data_len - Get the number of bytes to retrieve
2329 * @subop: The entire sub-operation
2330 * @instr_idx: Index of the instruction inside the sub-operation
2332 * During driver development, one could be tempted to directly use the
2333 * ->data->len field of a data instruction. This is wrong as data instructions
2336 * Returns the length of the chunk of data to send/receive.
2338 unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
2339 unsigned int instr_idx)
2341 int start_off = 0, end_off;
2343 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2344 !nand_instr_is_data(&subop->instrs[instr_idx])))
2347 start_off = nand_subop_get_data_start_off(subop, instr_idx);
2349 if (instr_idx == subop->ninstrs - 1 &&
2350 subop->last_instr_end_off)
2351 end_off = subop->last_instr_end_off;
2353 end_off = subop->instrs[instr_idx].ctx.data.len;
2355 return end_off - start_off;
2357 EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
2360 * nand_reset - Reset and initialize a NAND device
2361 * @chip: The NAND chip
2362 * @chipnr: Internal die id
2364 * Save the timings data structure, then apply SDR timings mode 0 (see
2365 * nand_reset_data_interface for details), do the reset operation, and
2366 * apply back the previous timings.
2368 * Returns 0 on success, a negative error code otherwise.
2370 int nand_reset(struct nand_chip *chip, int chipnr)
2372 struct nand_data_interface saved_data_intf = chip->data_interface;
2375 ret = nand_reset_data_interface(chip, chipnr);
2380 * The CS line has to be released before we can apply the new NAND
2381 * interface settings, hence this weird nand_select_target()
2382 * nand_deselect_target() dance.
2384 nand_select_target(chip, chipnr);
2385 ret = nand_reset_op(chip);
2386 nand_deselect_target(chip);
2391 * A nand_reset_data_interface() put both the NAND chip and the NAND
2392 * controller in timings mode 0. If the default mode for this chip is
2393 * also 0, no need to proceed to the change again. Plus, at probe time,
2394 * nand_setup_data_interface() uses ->set/get_features() which would
2395 * fail anyway as the parameter page is not available yet.
2397 if (!chip->onfi_timing_mode_default)
2400 chip->data_interface = saved_data_intf;
2401 ret = nand_setup_data_interface(chip, chipnr);
2407 EXPORT_SYMBOL_GPL(nand_reset);
2410 * nand_get_features - wrapper to perform a GET_FEATURE
2411 * @chip: NAND chip info structure
2412 * @addr: feature address
2413 * @subfeature_param: the subfeature parameters, a four bytes array
2415 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2416 * operation cannot be handled.
2418 int nand_get_features(struct nand_chip *chip, int addr,
2419 u8 *subfeature_param)
2421 if (!nand_supports_get_features(chip, addr))
2424 if (chip->legacy.get_features)
2425 return chip->legacy.get_features(chip, addr, subfeature_param);
2427 return nand_get_features_op(chip, addr, subfeature_param);
2431 * nand_set_features - wrapper to perform a SET_FEATURE
2432 * @chip: NAND chip info structure
2433 * @addr: feature address
2434 * @subfeature_param: the subfeature parameters, a four bytes array
2436 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2437 * operation cannot be handled.
2439 int nand_set_features(struct nand_chip *chip, int addr,
2440 u8 *subfeature_param)
2442 if (!nand_supports_set_features(chip, addr))
2445 if (chip->legacy.set_features)
2446 return chip->legacy.set_features(chip, addr, subfeature_param);
2448 return nand_set_features_op(chip, addr, subfeature_param);
2452 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
2453 * @buf: buffer to test
2454 * @len: buffer length
2455 * @bitflips_threshold: maximum number of bitflips
2457 * Check if a buffer contains only 0xff, which means the underlying region
2458 * has been erased and is ready to be programmed.
2459 * The bitflips_threshold specify the maximum number of bitflips before
2460 * considering the region is not erased.
2461 * Note: The logic of this function has been extracted from the memweight
2462 * implementation, except that nand_check_erased_buf function exit before
2463 * testing the whole buffer if the number of bitflips exceed the
2464 * bitflips_threshold value.
2466 * Returns a positive number of bitflips less than or equal to
2467 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2470 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
2472 const unsigned char *bitmap = buf;
2476 for (; len && ((uintptr_t)bitmap) % sizeof(long);
2478 weight = hweight8(*bitmap);
2479 bitflips += BITS_PER_BYTE - weight;
2480 if (unlikely(bitflips > bitflips_threshold))
2484 for (; len >= sizeof(long);
2485 len -= sizeof(long), bitmap += sizeof(long)) {
2486 unsigned long d = *((unsigned long *)bitmap);
2489 weight = hweight_long(d);
2490 bitflips += BITS_PER_LONG - weight;
2491 if (unlikely(bitflips > bitflips_threshold))
2495 for (; len > 0; len--, bitmap++) {
2496 weight = hweight8(*bitmap);
2497 bitflips += BITS_PER_BYTE - weight;
2498 if (unlikely(bitflips > bitflips_threshold))
2506 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
2508 * @data: data buffer to test
2509 * @datalen: data length
2511 * @ecclen: ECC length
2512 * @extraoob: extra OOB buffer
2513 * @extraooblen: extra OOB length
2514 * @bitflips_threshold: maximum number of bitflips
2516 * Check if a data buffer and its associated ECC and OOB data contains only
2517 * 0xff pattern, which means the underlying region has been erased and is
2518 * ready to be programmed.
2519 * The bitflips_threshold specify the maximum number of bitflips before
2520 * considering the region as not erased.
2523 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
2524 * different from the NAND page size. When fixing bitflips, ECC engines will
2525 * report the number of errors per chunk, and the NAND core infrastructure
2526 * expect you to return the maximum number of bitflips for the whole page.
2527 * This is why you should always use this function on a single chunk and
2528 * not on the whole page. After checking each chunk you should update your
2529 * max_bitflips value accordingly.
2530 * 2/ When checking for bitflips in erased pages you should not only check
2531 * the payload data but also their associated ECC data, because a user might
2532 * have programmed almost all bits to 1 but a few. In this case, we
2533 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
2535 * 3/ The extraoob argument is optional, and should be used if some of your OOB
2536 * data are protected by the ECC engine.
2537 * It could also be used if you support subpages and want to attach some
2538 * extra OOB data to an ECC chunk.
2540 * Returns a positive number of bitflips less than or equal to
2541 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2542 * threshold. In case of success, the passed buffers are filled with 0xff.
2544 int nand_check_erased_ecc_chunk(void *data, int datalen,
2545 void *ecc, int ecclen,
2546 void *extraoob, int extraooblen,
2547 int bitflips_threshold)
2549 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
2551 data_bitflips = nand_check_erased_buf(data, datalen,
2552 bitflips_threshold);
2553 if (data_bitflips < 0)
2554 return data_bitflips;
2556 bitflips_threshold -= data_bitflips;
2558 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
2559 if (ecc_bitflips < 0)
2560 return ecc_bitflips;
2562 bitflips_threshold -= ecc_bitflips;
2564 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
2565 bitflips_threshold);
2566 if (extraoob_bitflips < 0)
2567 return extraoob_bitflips;
2570 memset(data, 0xff, datalen);
2573 memset(ecc, 0xff, ecclen);
2575 if (extraoob_bitflips)
2576 memset(extraoob, 0xff, extraooblen);
2578 return data_bitflips + ecc_bitflips + extraoob_bitflips;
2580 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
2583 * nand_read_page_raw_notsupp - dummy read raw page function
2584 * @chip: nand chip info structure
2585 * @buf: buffer to store read data
2586 * @oob_required: caller requires OOB data read to chip->oob_poi
2587 * @page: page number to read
2589 * Returns -ENOTSUPP unconditionally.
2591 int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf,
2592 int oob_required, int page)
2598 * nand_read_page_raw - [INTERN] read raw page data without ecc
2599 * @chip: nand chip info structure
2600 * @buf: buffer to store read data
2601 * @oob_required: caller requires OOB data read to chip->oob_poi
2602 * @page: page number to read
2604 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2606 int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
2609 struct mtd_info *mtd = nand_to_mtd(chip);
2612 ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
2617 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
2625 EXPORT_SYMBOL(nand_read_page_raw);
2628 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
2629 * @chip: nand chip info structure
2630 * @buf: buffer to store read data
2631 * @oob_required: caller requires OOB data read to chip->oob_poi
2632 * @page: page number to read
2634 * We need a special oob layout and handling even when OOB isn't used.
2636 static int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf,
2637 int oob_required, int page)
2639 struct mtd_info *mtd = nand_to_mtd(chip);
2640 int eccsize = chip->ecc.size;
2641 int eccbytes = chip->ecc.bytes;
2642 uint8_t *oob = chip->oob_poi;
2643 int steps, size, ret;
2645 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2649 for (steps = chip->ecc.steps; steps > 0; steps--) {
2650 ret = nand_read_data_op(chip, buf, eccsize, false);
2656 if (chip->ecc.prepad) {
2657 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2662 oob += chip->ecc.prepad;
2665 ret = nand_read_data_op(chip, oob, eccbytes, false);
2671 if (chip->ecc.postpad) {
2672 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2677 oob += chip->ecc.postpad;
2681 size = mtd->oobsize - (oob - chip->oob_poi);
2683 ret = nand_read_data_op(chip, oob, size, false);
2692 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
2693 * @chip: nand chip info structure
2694 * @buf: buffer to store read data
2695 * @oob_required: caller requires OOB data read to chip->oob_poi
2696 * @page: page number to read
2698 static int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf,
2699 int oob_required, int page)
2701 struct mtd_info *mtd = nand_to_mtd(chip);
2702 int i, eccsize = chip->ecc.size, ret;
2703 int eccbytes = chip->ecc.bytes;
2704 int eccsteps = chip->ecc.steps;
2706 uint8_t *ecc_calc = chip->ecc.calc_buf;
2707 uint8_t *ecc_code = chip->ecc.code_buf;
2708 unsigned int max_bitflips = 0;
2710 chip->ecc.read_page_raw(chip, buf, 1, page);
2712 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2713 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2715 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2720 eccsteps = chip->ecc.steps;
2723 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2726 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
2728 mtd->ecc_stats.failed++;
2730 mtd->ecc_stats.corrected += stat;
2731 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2734 return max_bitflips;
2738 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
2739 * @chip: nand chip info structure
2740 * @data_offs: offset of requested data within the page
2741 * @readlen: data length
2742 * @bufpoi: buffer to store read data
2743 * @page: page number to read
2745 static int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs,
2746 uint32_t readlen, uint8_t *bufpoi, int page)
2748 struct mtd_info *mtd = nand_to_mtd(chip);
2749 int start_step, end_step, num_steps, ret;
2751 int data_col_addr, i, gaps = 0;
2752 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
2753 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
2754 int index, section = 0;
2755 unsigned int max_bitflips = 0;
2756 struct mtd_oob_region oobregion = { };
2758 /* Column address within the page aligned to ECC size (256bytes) */
2759 start_step = data_offs / chip->ecc.size;
2760 end_step = (data_offs + readlen - 1) / chip->ecc.size;
2761 num_steps = end_step - start_step + 1;
2762 index = start_step * chip->ecc.bytes;
2764 /* Data size aligned to ECC ecc.size */
2765 datafrag_len = num_steps * chip->ecc.size;
2766 eccfrag_len = num_steps * chip->ecc.bytes;
2768 data_col_addr = start_step * chip->ecc.size;
2769 /* If we read not a page aligned data */
2770 p = bufpoi + data_col_addr;
2771 ret = nand_read_page_op(chip, page, data_col_addr, p, datafrag_len);
2776 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
2777 chip->ecc.calculate(chip, p, &chip->ecc.calc_buf[i]);
2780 * The performance is faster if we position offsets according to
2781 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
2783 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
2787 if (oobregion.length < eccfrag_len)
2791 ret = nand_change_read_column_op(chip, mtd->writesize,
2792 chip->oob_poi, mtd->oobsize,
2798 * Send the command to read the particular ECC bytes take care
2799 * about buswidth alignment in read_buf.
2801 aligned_pos = oobregion.offset & ~(busw - 1);
2802 aligned_len = eccfrag_len;
2803 if (oobregion.offset & (busw - 1))
2805 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
2809 ret = nand_change_read_column_op(chip,
2810 mtd->writesize + aligned_pos,
2811 &chip->oob_poi[aligned_pos],
2812 aligned_len, false);
2817 ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
2818 chip->oob_poi, index, eccfrag_len);
2822 p = bufpoi + data_col_addr;
2823 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
2826 stat = chip->ecc.correct(chip, p, &chip->ecc.code_buf[i],
2827 &chip->ecc.calc_buf[i]);
2828 if (stat == -EBADMSG &&
2829 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2830 /* check for empty pages with bitflips */
2831 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
2832 &chip->ecc.code_buf[i],
2835 chip->ecc.strength);
2839 mtd->ecc_stats.failed++;
2841 mtd->ecc_stats.corrected += stat;
2842 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2845 return max_bitflips;
2849 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
2850 * @chip: nand chip info structure
2851 * @buf: buffer to store read data
2852 * @oob_required: caller requires OOB data read to chip->oob_poi
2853 * @page: page number to read
2855 * Not for syndrome calculating ECC controllers which need a special oob layout.
2857 static int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf,
2858 int oob_required, int page)
2860 struct mtd_info *mtd = nand_to_mtd(chip);
2861 int i, eccsize = chip->ecc.size, ret;
2862 int eccbytes = chip->ecc.bytes;
2863 int eccsteps = chip->ecc.steps;
2865 uint8_t *ecc_calc = chip->ecc.calc_buf;
2866 uint8_t *ecc_code = chip->ecc.code_buf;
2867 unsigned int max_bitflips = 0;
2869 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2873 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2874 chip->ecc.hwctl(chip, NAND_ECC_READ);
2876 ret = nand_read_data_op(chip, p, eccsize, false);
2880 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2883 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2887 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2892 eccsteps = chip->ecc.steps;
2895 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2898 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
2899 if (stat == -EBADMSG &&
2900 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2901 /* check for empty pages with bitflips */
2902 stat = nand_check_erased_ecc_chunk(p, eccsize,
2903 &ecc_code[i], eccbytes,
2905 chip->ecc.strength);
2909 mtd->ecc_stats.failed++;
2911 mtd->ecc_stats.corrected += stat;
2912 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2915 return max_bitflips;
2919 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
2920 * @chip: nand chip info structure
2921 * @buf: buffer to store read data
2922 * @oob_required: caller requires OOB data read to chip->oob_poi
2923 * @page: page number to read
2925 * Hardware ECC for large page chips, require OOB to be read first. For this
2926 * ECC mode, the write_page method is re-used from ECC_HW. These methods
2927 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
2928 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
2929 * the data area, by overwriting the NAND manufacturer bad block markings.
2931 static int nand_read_page_hwecc_oob_first(struct nand_chip *chip, uint8_t *buf,
2932 int oob_required, int page)
2934 struct mtd_info *mtd = nand_to_mtd(chip);
2935 int i, eccsize = chip->ecc.size, ret;
2936 int eccbytes = chip->ecc.bytes;
2937 int eccsteps = chip->ecc.steps;
2939 uint8_t *ecc_code = chip->ecc.code_buf;
2940 uint8_t *ecc_calc = chip->ecc.calc_buf;
2941 unsigned int max_bitflips = 0;
2943 /* Read the OOB area first */
2944 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2948 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2952 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2957 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2960 chip->ecc.hwctl(chip, NAND_ECC_READ);
2962 ret = nand_read_data_op(chip, p, eccsize, false);
2966 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2968 stat = chip->ecc.correct(chip, p, &ecc_code[i], NULL);
2969 if (stat == -EBADMSG &&
2970 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2971 /* check for empty pages with bitflips */
2972 stat = nand_check_erased_ecc_chunk(p, eccsize,
2973 &ecc_code[i], eccbytes,
2975 chip->ecc.strength);
2979 mtd->ecc_stats.failed++;
2981 mtd->ecc_stats.corrected += stat;
2982 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2985 return max_bitflips;
2989 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
2990 * @chip: nand chip info structure
2991 * @buf: buffer to store read data
2992 * @oob_required: caller requires OOB data read to chip->oob_poi
2993 * @page: page number to read
2995 * The hw generator calculates the error syndrome automatically. Therefore we
2996 * need a special oob layout and handling.
2998 static int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf,
2999 int oob_required, int page)
3001 struct mtd_info *mtd = nand_to_mtd(chip);
3002 int ret, i, eccsize = chip->ecc.size;
3003 int eccbytes = chip->ecc.bytes;
3004 int eccsteps = chip->ecc.steps;
3005 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
3007 uint8_t *oob = chip->oob_poi;
3008 unsigned int max_bitflips = 0;
3010 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3014 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3017 chip->ecc.hwctl(chip, NAND_ECC_READ);
3019 ret = nand_read_data_op(chip, p, eccsize, false);
3023 if (chip->ecc.prepad) {
3024 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3029 oob += chip->ecc.prepad;
3032 chip->ecc.hwctl(chip, NAND_ECC_READSYN);
3034 ret = nand_read_data_op(chip, oob, eccbytes, false);
3038 stat = chip->ecc.correct(chip, p, oob, NULL);
3042 if (chip->ecc.postpad) {
3043 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3048 oob += chip->ecc.postpad;
3051 if (stat == -EBADMSG &&
3052 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3053 /* check for empty pages with bitflips */
3054 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3058 chip->ecc.strength);
3062 mtd->ecc_stats.failed++;
3064 mtd->ecc_stats.corrected += stat;
3065 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3069 /* Calculate remaining oob bytes */
3070 i = mtd->oobsize - (oob - chip->oob_poi);
3072 ret = nand_read_data_op(chip, oob, i, false);
3077 return max_bitflips;
3081 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
3082 * @chip: NAND chip object
3083 * @oob: oob destination address
3084 * @ops: oob ops structure
3085 * @len: size of oob to transfer
3087 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
3088 struct mtd_oob_ops *ops, size_t len)
3090 struct mtd_info *mtd = nand_to_mtd(chip);
3093 switch (ops->mode) {
3095 case MTD_OPS_PLACE_OOB:
3097 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
3100 case MTD_OPS_AUTO_OOB:
3101 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
3113 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
3114 * @chip: NAND chip object
3115 * @retry_mode: the retry mode to use
3117 * Some vendors supply a special command to shift the Vt threshold, to be used
3118 * when there are too many bitflips in a page (i.e., ECC error). After setting
3119 * a new threshold, the host should retry reading the page.
3121 static int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
3123 pr_debug("setting READ RETRY mode %d\n", retry_mode);
3125 if (retry_mode >= chip->read_retries)
3128 if (!chip->setup_read_retry)
3131 return chip->setup_read_retry(chip, retry_mode);
3134 static void nand_wait_readrdy(struct nand_chip *chip)
3136 const struct nand_sdr_timings *sdr;
3138 if (!(chip->options & NAND_NEED_READRDY))
3141 sdr = nand_get_sdr_timings(&chip->data_interface);
3142 WARN_ON(nand_wait_rdy_op(chip, PSEC_TO_MSEC(sdr->tR_max), 0));
3146 * nand_do_read_ops - [INTERN] Read data with ECC
3147 * @chip: NAND chip object
3148 * @from: offset to read from
3149 * @ops: oob ops structure
3151 * Internal function. Called with chip held.
3153 static int nand_do_read_ops(struct nand_chip *chip, loff_t from,
3154 struct mtd_oob_ops *ops)
3156 int chipnr, page, realpage, col, bytes, aligned, oob_required;
3157 struct mtd_info *mtd = nand_to_mtd(chip);
3159 uint32_t readlen = ops->len;
3160 uint32_t oobreadlen = ops->ooblen;
3161 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
3163 uint8_t *bufpoi, *oob, *buf;
3165 unsigned int max_bitflips = 0;
3167 bool ecc_fail = false;
3169 chipnr = (int)(from >> chip->chip_shift);
3170 nand_select_target(chip, chipnr);
3172 realpage = (int)(from >> chip->page_shift);
3173 page = realpage & chip->pagemask;
3175 col = (int)(from & (mtd->writesize - 1));
3179 oob_required = oob ? 1 : 0;
3182 unsigned int ecc_failures = mtd->ecc_stats.failed;
3184 bytes = min(mtd->writesize - col, readlen);
3185 aligned = (bytes == mtd->writesize);
3189 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
3190 use_bufpoi = !virt_addr_valid(buf) ||
3191 !IS_ALIGNED((unsigned long)buf,
3196 /* Is the current page in the buffer? */
3197 if (realpage != chip->pagecache.page || oob) {
3198 bufpoi = use_bufpoi ? chip->data_buf : buf;
3200 if (use_bufpoi && aligned)
3201 pr_debug("%s: using read bounce buffer for buf@%p\n",
3206 * Now read the page into the buffer. Absent an error,
3207 * the read methods return max bitflips per ecc step.
3209 if (unlikely(ops->mode == MTD_OPS_RAW))
3210 ret = chip->ecc.read_page_raw(chip, bufpoi,
3213 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
3215 ret = chip->ecc.read_subpage(chip, col, bytes,
3218 ret = chip->ecc.read_page(chip, bufpoi,
3219 oob_required, page);
3222 /* Invalidate page cache */
3223 chip->pagecache.page = -1;
3227 /* Transfer not aligned data */
3229 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
3230 !(mtd->ecc_stats.failed - ecc_failures) &&
3231 (ops->mode != MTD_OPS_RAW)) {
3232 chip->pagecache.page = realpage;
3233 chip->pagecache.bitflips = ret;
3235 /* Invalidate page cache */
3236 chip->pagecache.page = -1;
3238 memcpy(buf, chip->data_buf + col, bytes);
3241 if (unlikely(oob)) {
3242 int toread = min(oobreadlen, max_oobsize);
3245 oob = nand_transfer_oob(chip, oob, ops,
3247 oobreadlen -= toread;
3251 nand_wait_readrdy(chip);
3253 if (mtd->ecc_stats.failed - ecc_failures) {
3254 if (retry_mode + 1 < chip->read_retries) {
3256 ret = nand_setup_read_retry(chip,
3261 /* Reset failures; retry */
3262 mtd->ecc_stats.failed = ecc_failures;
3265 /* No more retry modes; real failure */
3271 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3273 memcpy(buf, chip->data_buf + col, bytes);
3275 max_bitflips = max_t(unsigned int, max_bitflips,
3276 chip->pagecache.bitflips);
3281 /* Reset to retry mode 0 */
3283 ret = nand_setup_read_retry(chip, 0);
3292 /* For subsequent reads align to page boundary */
3294 /* Increment page address */
3297 page = realpage & chip->pagemask;
3298 /* Check, if we cross a chip boundary */
3301 nand_deselect_target(chip);
3302 nand_select_target(chip, chipnr);
3305 nand_deselect_target(chip);
3307 ops->retlen = ops->len - (size_t) readlen;
3309 ops->oobretlen = ops->ooblen - oobreadlen;
3317 return max_bitflips;
3321 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
3322 * @chip: nand chip info structure
3323 * @page: page number to read
3325 int nand_read_oob_std(struct nand_chip *chip, int page)
3327 struct mtd_info *mtd = nand_to_mtd(chip);
3329 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3331 EXPORT_SYMBOL(nand_read_oob_std);
3334 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
3336 * @chip: nand chip info structure
3337 * @page: page number to read
3339 static int nand_read_oob_syndrome(struct nand_chip *chip, int page)
3341 struct mtd_info *mtd = nand_to_mtd(chip);
3342 int length = mtd->oobsize;
3343 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3344 int eccsize = chip->ecc.size;
3345 uint8_t *bufpoi = chip->oob_poi;
3346 int i, toread, sndrnd = 0, pos, ret;
3348 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
3352 for (i = 0; i < chip->ecc.steps; i++) {
3356 pos = eccsize + i * (eccsize + chunk);
3357 if (mtd->writesize > 512)
3358 ret = nand_change_read_column_op(chip, pos,
3362 ret = nand_read_page_op(chip, page, pos, NULL,
3369 toread = min_t(int, length, chunk);
3371 ret = nand_read_data_op(chip, bufpoi, toread, false);
3379 ret = nand_read_data_op(chip, bufpoi, length, false);
3388 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
3389 * @chip: nand chip info structure
3390 * @page: page number to write
3392 int nand_write_oob_std(struct nand_chip *chip, int page)
3394 struct mtd_info *mtd = nand_to_mtd(chip);
3396 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
3399 EXPORT_SYMBOL(nand_write_oob_std);
3402 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
3403 * with syndrome - only for large page flash
3404 * @chip: nand chip info structure
3405 * @page: page number to write
3407 static int nand_write_oob_syndrome(struct nand_chip *chip, int page)
3409 struct mtd_info *mtd = nand_to_mtd(chip);
3410 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3411 int eccsize = chip->ecc.size, length = mtd->oobsize;
3412 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
3413 const uint8_t *bufpoi = chip->oob_poi;
3416 * data-ecc-data-ecc ... ecc-oob
3418 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
3420 if (!chip->ecc.prepad && !chip->ecc.postpad) {
3421 pos = steps * (eccsize + chunk);
3426 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
3430 for (i = 0; i < steps; i++) {
3432 if (mtd->writesize <= 512) {
3433 uint32_t fill = 0xFFFFFFFF;
3437 int num = min_t(int, len, 4);
3439 ret = nand_write_data_op(chip, &fill,
3447 pos = eccsize + i * (eccsize + chunk);
3448 ret = nand_change_write_column_op(chip, pos,
3456 len = min_t(int, length, chunk);
3458 ret = nand_write_data_op(chip, bufpoi, len, false);
3466 ret = nand_write_data_op(chip, bufpoi, length, false);
3471 return nand_prog_page_end_op(chip);
3475 * nand_do_read_oob - [INTERN] NAND read out-of-band
3476 * @chip: NAND chip object
3477 * @from: offset to read from
3478 * @ops: oob operations description structure
3480 * NAND read out-of-band data from the spare area.
3482 static int nand_do_read_oob(struct nand_chip *chip, loff_t from,
3483 struct mtd_oob_ops *ops)
3485 struct mtd_info *mtd = nand_to_mtd(chip);
3486 unsigned int max_bitflips = 0;
3487 int page, realpage, chipnr;
3488 struct mtd_ecc_stats stats;
3489 int readlen = ops->ooblen;
3491 uint8_t *buf = ops->oobbuf;
3494 pr_debug("%s: from = 0x%08Lx, len = %i\n",
3495 __func__, (unsigned long long)from, readlen);
3497 stats = mtd->ecc_stats;
3499 len = mtd_oobavail(mtd, ops);
3501 chipnr = (int)(from >> chip->chip_shift);
3502 nand_select_target(chip, chipnr);
3504 /* Shift to get page */
3505 realpage = (int)(from >> chip->page_shift);
3506 page = realpage & chip->pagemask;
3509 if (ops->mode == MTD_OPS_RAW)
3510 ret = chip->ecc.read_oob_raw(chip, page);
3512 ret = chip->ecc.read_oob(chip, page);
3517 len = min(len, readlen);
3518 buf = nand_transfer_oob(chip, buf, ops, len);
3520 nand_wait_readrdy(chip);
3522 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3528 /* Increment page address */
3531 page = realpage & chip->pagemask;
3532 /* Check, if we cross a chip boundary */
3535 nand_deselect_target(chip);
3536 nand_select_target(chip, chipnr);
3539 nand_deselect_target(chip);
3541 ops->oobretlen = ops->ooblen - readlen;
3546 if (mtd->ecc_stats.failed - stats.failed)
3549 return max_bitflips;
3553 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
3554 * @mtd: MTD device structure
3555 * @from: offset to read from
3556 * @ops: oob operation description structure
3558 * NAND read data and/or out-of-band data.
3560 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
3561 struct mtd_oob_ops *ops)
3563 struct nand_chip *chip = mtd_to_nand(mtd);
3568 if (ops->mode != MTD_OPS_PLACE_OOB &&
3569 ops->mode != MTD_OPS_AUTO_OOB &&
3570 ops->mode != MTD_OPS_RAW)
3573 ret = nand_get_device(chip);
3578 ret = nand_do_read_oob(chip, from, ops);
3580 ret = nand_do_read_ops(chip, from, ops);
3582 nand_release_device(chip);
3587 * nand_write_page_raw_notsupp - dummy raw page write function
3588 * @chip: nand chip info structure
3590 * @oob_required: must write chip->oob_poi to OOB
3591 * @page: page number to write
3593 * Returns -ENOTSUPP unconditionally.
3595 int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf,
3596 int oob_required, int page)
3602 * nand_write_page_raw - [INTERN] raw page write function
3603 * @chip: nand chip info structure
3605 * @oob_required: must write chip->oob_poi to OOB
3606 * @page: page number to write
3608 * Not for syndrome calculating ECC controllers, which use a special oob layout.
3610 int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
3611 int oob_required, int page)
3613 struct mtd_info *mtd = nand_to_mtd(chip);
3616 ret = nand_prog_page_begin_op(chip, page, 0, buf, mtd->writesize);
3621 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
3627 return nand_prog_page_end_op(chip);
3629 EXPORT_SYMBOL(nand_write_page_raw);
3632 * nand_write_page_raw_syndrome - [INTERN] raw page write function
3633 * @chip: nand chip info structure
3635 * @oob_required: must write chip->oob_poi to OOB
3636 * @page: page number to write
3638 * We need a special oob layout and handling even when ECC isn't checked.
3640 static int nand_write_page_raw_syndrome(struct nand_chip *chip,
3641 const uint8_t *buf, int oob_required,
3644 struct mtd_info *mtd = nand_to_mtd(chip);
3645 int eccsize = chip->ecc.size;
3646 int eccbytes = chip->ecc.bytes;
3647 uint8_t *oob = chip->oob_poi;
3648 int steps, size, ret;
3650 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3654 for (steps = chip->ecc.steps; steps > 0; steps--) {
3655 ret = nand_write_data_op(chip, buf, eccsize, false);
3661 if (chip->ecc.prepad) {
3662 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3667 oob += chip->ecc.prepad;
3670 ret = nand_write_data_op(chip, oob, eccbytes, false);
3676 if (chip->ecc.postpad) {
3677 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3682 oob += chip->ecc.postpad;
3686 size = mtd->oobsize - (oob - chip->oob_poi);
3688 ret = nand_write_data_op(chip, oob, size, false);
3693 return nand_prog_page_end_op(chip);
3696 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
3697 * @chip: nand chip info structure
3699 * @oob_required: must write chip->oob_poi to OOB
3700 * @page: page number to write
3702 static int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf,
3703 int oob_required, int page)
3705 struct mtd_info *mtd = nand_to_mtd(chip);
3706 int i, eccsize = chip->ecc.size, ret;
3707 int eccbytes = chip->ecc.bytes;
3708 int eccsteps = chip->ecc.steps;
3709 uint8_t *ecc_calc = chip->ecc.calc_buf;
3710 const uint8_t *p = buf;
3712 /* Software ECC calculation */
3713 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
3714 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3716 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3721 return chip->ecc.write_page_raw(chip, buf, 1, page);
3725 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
3726 * @chip: nand chip info structure
3728 * @oob_required: must write chip->oob_poi to OOB
3729 * @page: page number to write
3731 static int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf,
3732 int oob_required, int page)
3734 struct mtd_info *mtd = nand_to_mtd(chip);
3735 int i, eccsize = chip->ecc.size, ret;
3736 int eccbytes = chip->ecc.bytes;
3737 int eccsteps = chip->ecc.steps;
3738 uint8_t *ecc_calc = chip->ecc.calc_buf;
3739 const uint8_t *p = buf;
3741 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3745 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3746 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3748 ret = nand_write_data_op(chip, p, eccsize, false);
3752 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3755 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3760 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3764 return nand_prog_page_end_op(chip);
3769 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
3770 * @chip: nand chip info structure
3771 * @offset: column address of subpage within the page
3772 * @data_len: data length
3774 * @oob_required: must write chip->oob_poi to OOB
3775 * @page: page number to write
3777 static int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset,
3778 uint32_t data_len, const uint8_t *buf,
3779 int oob_required, int page)
3781 struct mtd_info *mtd = nand_to_mtd(chip);
3782 uint8_t *oob_buf = chip->oob_poi;
3783 uint8_t *ecc_calc = chip->ecc.calc_buf;
3784 int ecc_size = chip->ecc.size;
3785 int ecc_bytes = chip->ecc.bytes;
3786 int ecc_steps = chip->ecc.steps;
3787 uint32_t start_step = offset / ecc_size;
3788 uint32_t end_step = (offset + data_len - 1) / ecc_size;
3789 int oob_bytes = mtd->oobsize / ecc_steps;
3792 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3796 for (step = 0; step < ecc_steps; step++) {
3797 /* configure controller for WRITE access */
3798 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3800 /* write data (untouched subpages already masked by 0xFF) */
3801 ret = nand_write_data_op(chip, buf, ecc_size, false);
3805 /* mask ECC of un-touched subpages by padding 0xFF */
3806 if ((step < start_step) || (step > end_step))
3807 memset(ecc_calc, 0xff, ecc_bytes);
3809 chip->ecc.calculate(chip, buf, ecc_calc);
3811 /* mask OOB of un-touched subpages by padding 0xFF */
3812 /* if oob_required, preserve OOB metadata of written subpage */
3813 if (!oob_required || (step < start_step) || (step > end_step))
3814 memset(oob_buf, 0xff, oob_bytes);
3817 ecc_calc += ecc_bytes;
3818 oob_buf += oob_bytes;
3821 /* copy calculated ECC for whole page to chip->buffer->oob */
3822 /* this include masked-value(0xFF) for unwritten subpages */
3823 ecc_calc = chip->ecc.calc_buf;
3824 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3829 /* write OOB buffer to NAND device */
3830 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3834 return nand_prog_page_end_op(chip);
3839 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
3840 * @chip: nand chip info structure
3842 * @oob_required: must write chip->oob_poi to OOB
3843 * @page: page number to write
3845 * The hw generator calculates the error syndrome automatically. Therefore we
3846 * need a special oob layout and handling.
3848 static int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf,
3849 int oob_required, int page)
3851 struct mtd_info *mtd = nand_to_mtd(chip);
3852 int i, eccsize = chip->ecc.size;
3853 int eccbytes = chip->ecc.bytes;
3854 int eccsteps = chip->ecc.steps;
3855 const uint8_t *p = buf;
3856 uint8_t *oob = chip->oob_poi;
3859 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3863 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3864 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3866 ret = nand_write_data_op(chip, p, eccsize, false);
3870 if (chip->ecc.prepad) {
3871 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3876 oob += chip->ecc.prepad;
3879 chip->ecc.calculate(chip, p, oob);
3881 ret = nand_write_data_op(chip, oob, eccbytes, false);
3887 if (chip->ecc.postpad) {
3888 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3893 oob += chip->ecc.postpad;
3897 /* Calculate remaining oob bytes */
3898 i = mtd->oobsize - (oob - chip->oob_poi);
3900 ret = nand_write_data_op(chip, oob, i, false);
3905 return nand_prog_page_end_op(chip);
3909 * nand_write_page - write one page
3910 * @chip: NAND chip descriptor
3911 * @offset: address offset within the page
3912 * @data_len: length of actual data to be written
3913 * @buf: the data to write
3914 * @oob_required: must write chip->oob_poi to OOB
3915 * @page: page number to write
3916 * @raw: use _raw version of write_page
3918 static int nand_write_page(struct nand_chip *chip, uint32_t offset,
3919 int data_len, const uint8_t *buf, int oob_required,
3922 struct mtd_info *mtd = nand_to_mtd(chip);
3923 int status, subpage;
3925 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
3926 chip->ecc.write_subpage)
3927 subpage = offset || (data_len < mtd->writesize);
3932 status = chip->ecc.write_page_raw(chip, buf, oob_required,
3935 status = chip->ecc.write_subpage(chip, offset, data_len, buf,
3936 oob_required, page);
3938 status = chip->ecc.write_page(chip, buf, oob_required, page);
3946 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
3949 * nand_do_write_ops - [INTERN] NAND write with ECC
3950 * @chip: NAND chip object
3951 * @to: offset to write to
3952 * @ops: oob operations description structure
3954 * NAND write with ECC.
3956 static int nand_do_write_ops(struct nand_chip *chip, loff_t to,
3957 struct mtd_oob_ops *ops)
3959 struct mtd_info *mtd = nand_to_mtd(chip);
3960 int chipnr, realpage, page, column;
3961 uint32_t writelen = ops->len;
3963 uint32_t oobwritelen = ops->ooblen;
3964 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
3966 uint8_t *oob = ops->oobbuf;
3967 uint8_t *buf = ops->datbuf;
3969 int oob_required = oob ? 1 : 0;
3975 /* Reject writes, which are not page aligned */
3976 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
3977 pr_notice("%s: attempt to write non page aligned data\n",
3982 column = to & (mtd->writesize - 1);
3984 chipnr = (int)(to >> chip->chip_shift);
3985 nand_select_target(chip, chipnr);
3987 /* Check, if it is write protected */
3988 if (nand_check_wp(chip)) {
3993 realpage = (int)(to >> chip->page_shift);
3994 page = realpage & chip->pagemask;
3996 /* Invalidate the page cache, when we write to the cached page */
3997 if (to <= ((loff_t)chip->pagecache.page << chip->page_shift) &&
3998 ((loff_t)chip->pagecache.page << chip->page_shift) < (to + ops->len))
3999 chip->pagecache.page = -1;
4001 /* Don't allow multipage oob writes with offset */
4002 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
4008 int bytes = mtd->writesize;
4009 uint8_t *wbuf = buf;
4011 int part_pagewr = (column || writelen < mtd->writesize);
4015 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
4016 use_bufpoi = !virt_addr_valid(buf) ||
4017 !IS_ALIGNED((unsigned long)buf,
4022 /* Partial page write?, or need to use bounce buffer */
4024 pr_debug("%s: using write bounce buffer for buf@%p\n",
4027 bytes = min_t(int, bytes - column, writelen);
4028 wbuf = nand_get_data_buf(chip);
4029 memset(wbuf, 0xff, mtd->writesize);
4030 memcpy(&wbuf[column], buf, bytes);
4033 if (unlikely(oob)) {
4034 size_t len = min(oobwritelen, oobmaxlen);
4035 oob = nand_fill_oob(chip, oob, len, ops);
4038 /* We still need to erase leftover OOB data */
4039 memset(chip->oob_poi, 0xff, mtd->oobsize);
4042 ret = nand_write_page(chip, column, bytes, wbuf,
4044 (ops->mode == MTD_OPS_RAW));
4056 page = realpage & chip->pagemask;
4057 /* Check, if we cross a chip boundary */
4060 nand_deselect_target(chip);
4061 nand_select_target(chip, chipnr);
4065 ops->retlen = ops->len - writelen;
4067 ops->oobretlen = ops->ooblen;
4070 nand_deselect_target(chip);
4075 * panic_nand_write - [MTD Interface] NAND write with ECC
4076 * @mtd: MTD device structure
4077 * @to: offset to write to
4078 * @len: number of bytes to write
4079 * @retlen: pointer to variable to store the number of written bytes
4080 * @buf: the data to write
4082 * NAND write with ECC. Used when performing writes in interrupt context, this
4083 * may for example be called by mtdoops when writing an oops while in panic.
4085 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
4086 size_t *retlen, const uint8_t *buf)
4088 struct nand_chip *chip = mtd_to_nand(mtd);
4089 int chipnr = (int)(to >> chip->chip_shift);
4090 struct mtd_oob_ops ops;
4093 nand_select_target(chip, chipnr);
4095 /* Wait for the device to get ready */
4096 panic_nand_wait(chip, 400);
4098 memset(&ops, 0, sizeof(ops));
4100 ops.datbuf = (uint8_t *)buf;
4101 ops.mode = MTD_OPS_PLACE_OOB;
4103 ret = nand_do_write_ops(chip, to, &ops);
4105 *retlen = ops.retlen;
4110 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
4111 * @mtd: MTD device structure
4112 * @to: offset to write to
4113 * @ops: oob operation description structure
4115 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
4116 struct mtd_oob_ops *ops)
4118 struct nand_chip *chip = mtd_to_nand(mtd);
4119 int ret = -ENOTSUPP;
4123 ret = nand_get_device(chip);
4127 switch (ops->mode) {
4128 case MTD_OPS_PLACE_OOB:
4129 case MTD_OPS_AUTO_OOB:
4138 ret = nand_do_write_oob(chip, to, ops);
4140 ret = nand_do_write_ops(chip, to, ops);
4143 nand_release_device(chip);
4148 * nand_erase - [MTD Interface] erase block(s)
4149 * @mtd: MTD device structure
4150 * @instr: erase instruction
4152 * Erase one ore more blocks.
4154 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
4156 return nand_erase_nand(mtd_to_nand(mtd), instr, 0);
4160 * nand_erase_nand - [INTERN] erase block(s)
4161 * @chip: NAND chip object
4162 * @instr: erase instruction
4163 * @allowbbt: allow erasing the bbt area
4165 * Erase one ore more blocks.
4167 int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr,
4170 int page, pages_per_block, ret, chipnr;
4173 pr_debug("%s: start = 0x%012llx, len = %llu\n",
4174 __func__, (unsigned long long)instr->addr,
4175 (unsigned long long)instr->len);
4177 if (check_offs_len(chip, instr->addr, instr->len))
4180 /* Grab the lock and see if the device is available */
4181 ret = nand_get_device(chip);
4185 /* Shift to get first page */
4186 page = (int)(instr->addr >> chip->page_shift);
4187 chipnr = (int)(instr->addr >> chip->chip_shift);
4189 /* Calculate pages in each block */
4190 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
4192 /* Select the NAND device */
4193 nand_select_target(chip, chipnr);
4195 /* Check, if it is write protected */
4196 if (nand_check_wp(chip)) {
4197 pr_debug("%s: device is write protected!\n",
4203 /* Loop through the pages */
4207 /* Check if we have a bad block, we do not erase bad blocks! */
4208 if (nand_block_checkbad(chip, ((loff_t) page) <<
4209 chip->page_shift, allowbbt)) {
4210 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
4217 * Invalidate the page cache, if we erase the block which
4218 * contains the current cached page.
4220 if (page <= chip->pagecache.page && chip->pagecache.page <
4221 (page + pages_per_block))
4222 chip->pagecache.page = -1;
4224 ret = nand_erase_op(chip, (page & chip->pagemask) >>
4225 (chip->phys_erase_shift - chip->page_shift));
4227 pr_debug("%s: failed erase, page 0x%08x\n",
4230 ((loff_t)page << chip->page_shift);
4234 /* Increment page address and decrement length */
4235 len -= (1ULL << chip->phys_erase_shift);
4236 page += pages_per_block;
4238 /* Check, if we cross a chip boundary */
4239 if (len && !(page & chip->pagemask)) {
4241 nand_deselect_target(chip);
4242 nand_select_target(chip, chipnr);
4249 /* Deselect and wake up anyone waiting on the device */
4250 nand_deselect_target(chip);
4251 nand_release_device(chip);
4253 /* Return more or less happy */
4258 * nand_sync - [MTD Interface] sync
4259 * @mtd: MTD device structure
4261 * Sync is actually a wait for chip ready function.
4263 static void nand_sync(struct mtd_info *mtd)
4265 struct nand_chip *chip = mtd_to_nand(mtd);
4267 pr_debug("%s: called\n", __func__);
4269 /* Grab the lock and see if the device is available */
4270 WARN_ON(nand_get_device(chip));
4271 /* Release it and go back */
4272 nand_release_device(chip);
4276 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
4277 * @mtd: MTD device structure
4278 * @offs: offset relative to mtd start
4280 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
4282 struct nand_chip *chip = mtd_to_nand(mtd);
4283 int chipnr = (int)(offs >> chip->chip_shift);
4286 /* Select the NAND device */
4287 ret = nand_get_device(chip);
4291 nand_select_target(chip, chipnr);
4293 ret = nand_block_checkbad(chip, offs, 0);
4295 nand_deselect_target(chip);
4296 nand_release_device(chip);
4302 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
4303 * @mtd: MTD device structure
4304 * @ofs: offset relative to mtd start
4306 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
4310 ret = nand_block_isbad(mtd, ofs);
4312 /* If it was bad already, return success and do nothing */
4318 return nand_block_markbad_lowlevel(mtd_to_nand(mtd), ofs);
4322 * nand_suspend - [MTD Interface] Suspend the NAND flash
4323 * @mtd: MTD device structure
4325 static int nand_suspend(struct mtd_info *mtd)
4327 struct nand_chip *chip = mtd_to_nand(mtd);
4329 mutex_lock(&chip->lock);
4330 chip->suspended = 1;
4331 mutex_unlock(&chip->lock);
4337 * nand_resume - [MTD Interface] Resume the NAND flash
4338 * @mtd: MTD device structure
4340 static void nand_resume(struct mtd_info *mtd)
4342 struct nand_chip *chip = mtd_to_nand(mtd);
4344 mutex_lock(&chip->lock);
4345 if (chip->suspended)
4346 chip->suspended = 0;
4348 pr_err("%s called for a chip which is not in suspended state\n",
4350 mutex_unlock(&chip->lock);
4354 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
4355 * prevent further operations
4356 * @mtd: MTD device structure
4358 static void nand_shutdown(struct mtd_info *mtd)
4363 /* Set default functions */
4364 static void nand_set_defaults(struct nand_chip *chip)
4366 /* If no controller is provided, use the dummy, legacy one. */
4367 if (!chip->controller) {
4368 chip->controller = &chip->legacy.dummy_controller;
4369 nand_controller_init(chip->controller);
4372 nand_legacy_set_defaults(chip);
4374 if (!chip->buf_align)
4375 chip->buf_align = 1;
4378 /* Sanitize ONFI strings so we can safely print them */
4379 void sanitize_string(uint8_t *s, size_t len)
4383 /* Null terminate */
4386 /* Remove non printable chars */
4387 for (i = 0; i < len - 1; i++) {
4388 if (s[i] < ' ' || s[i] > 127)
4392 /* Remove trailing spaces */
4397 * nand_id_has_period - Check if an ID string has a given wraparound period
4398 * @id_data: the ID string
4399 * @arrlen: the length of the @id_data array
4400 * @period: the period of repitition
4402 * Check if an ID string is repeated within a given sequence of bytes at
4403 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4404 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4405 * if the repetition has a period of @period; otherwise, returns zero.
4407 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4410 for (i = 0; i < period; i++)
4411 for (j = i + period; j < arrlen; j += period)
4412 if (id_data[i] != id_data[j])
4418 * nand_id_len - Get the length of an ID string returned by CMD_READID
4419 * @id_data: the ID string
4420 * @arrlen: the length of the @id_data array
4422 * Returns the length of the ID string, according to known wraparound/trailing
4423 * zero patterns. If no pattern exists, returns the length of the array.
4425 static int nand_id_len(u8 *id_data, int arrlen)
4427 int last_nonzero, period;
4429 /* Find last non-zero byte */
4430 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4431 if (id_data[last_nonzero])
4435 if (last_nonzero < 0)
4438 /* Calculate wraparound period */
4439 for (period = 1; period < arrlen; period++)
4440 if (nand_id_has_period(id_data, arrlen, period))
4443 /* There's a repeated pattern */
4444 if (period < arrlen)
4447 /* There are trailing zeros */
4448 if (last_nonzero < arrlen - 1)
4449 return last_nonzero + 1;
4451 /* No pattern detected */
4455 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4456 static int nand_get_bits_per_cell(u8 cellinfo)
4460 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4461 bits >>= NAND_CI_CELLTYPE_SHIFT;
4466 * Many new NAND share similar device ID codes, which represent the size of the
4467 * chip. The rest of the parameters must be decoded according to generic or
4468 * manufacturer-specific "extended ID" decoding patterns.
4470 void nand_decode_ext_id(struct nand_chip *chip)
4472 struct nand_memory_organization *memorg;
4473 struct mtd_info *mtd = nand_to_mtd(chip);
4475 u8 *id_data = chip->id.data;
4477 memorg = nanddev_get_memorg(&chip->base);
4479 /* The 3rd id byte holds MLC / multichip data */
4480 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4481 /* The 4th id byte is the important one */
4485 memorg->pagesize = 1024 << (extid & 0x03);
4486 mtd->writesize = memorg->pagesize;
4489 memorg->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
4490 mtd->oobsize = memorg->oobsize;
4492 /* Calc blocksize. Blocksize is multiples of 64KiB */
4493 memorg->pages_per_eraseblock = ((64 * 1024) << (extid & 0x03)) /
4495 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4497 /* Get buswidth information */
4499 chip->options |= NAND_BUSWIDTH_16;
4501 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
4504 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4505 * decodes a matching ID table entry and assigns the MTD size parameters for
4508 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
4510 struct mtd_info *mtd = nand_to_mtd(chip);
4511 struct nand_memory_organization *memorg;
4513 memorg = nanddev_get_memorg(&chip->base);
4515 memorg->pages_per_eraseblock = type->erasesize / type->pagesize;
4516 mtd->erasesize = type->erasesize;
4517 memorg->pagesize = type->pagesize;
4518 mtd->writesize = memorg->pagesize;
4519 memorg->oobsize = memorg->pagesize / 32;
4520 mtd->oobsize = memorg->oobsize;
4522 /* All legacy ID NAND are small-page, SLC */
4523 memorg->bits_per_cell = 1;
4527 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4528 * heuristic patterns using various detected parameters (e.g., manufacturer,
4529 * page size, cell-type information).
4531 static void nand_decode_bbm_options(struct nand_chip *chip)
4533 struct mtd_info *mtd = nand_to_mtd(chip);
4535 /* Set the bad block position */
4536 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4537 chip->badblockpos = NAND_BBM_POS_LARGE;
4539 chip->badblockpos = NAND_BBM_POS_SMALL;
4542 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4544 return type->id_len;
4547 static bool find_full_id_nand(struct nand_chip *chip,
4548 struct nand_flash_dev *type)
4550 struct mtd_info *mtd = nand_to_mtd(chip);
4551 struct nand_memory_organization *memorg;
4552 u8 *id_data = chip->id.data;
4554 memorg = nanddev_get_memorg(&chip->base);
4556 if (!strncmp(type->id, id_data, type->id_len)) {
4557 memorg->pagesize = type->pagesize;
4558 mtd->writesize = memorg->pagesize;
4559 memorg->pages_per_eraseblock = type->erasesize /
4561 mtd->erasesize = type->erasesize;
4562 memorg->oobsize = type->oobsize;
4563 mtd->oobsize = memorg->oobsize;
4565 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4566 memorg->eraseblocks_per_lun =
4567 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4569 memorg->pages_per_eraseblock);
4570 chip->options |= type->options;
4571 chip->base.eccreq.strength = NAND_ECC_STRENGTH(type);
4572 chip->base.eccreq.step_size = NAND_ECC_STEP(type);
4573 chip->onfi_timing_mode_default =
4574 type->onfi_timing_mode_default;
4576 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4577 if (!chip->parameters.model)
4586 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
4587 * compliant and does not have a full-id or legacy-id entry in the nand_ids
4590 static void nand_manufacturer_detect(struct nand_chip *chip)
4593 * Try manufacturer detection if available and use
4594 * nand_decode_ext_id() otherwise.
4596 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4597 chip->manufacturer.desc->ops->detect) {
4598 struct nand_memory_organization *memorg;
4600 memorg = nanddev_get_memorg(&chip->base);
4602 /* The 3rd id byte holds MLC / multichip data */
4603 memorg->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
4604 chip->manufacturer.desc->ops->detect(chip);
4606 nand_decode_ext_id(chip);
4611 * Manufacturer initialization. This function is called for all NANDs including
4612 * ONFI and JEDEC compliant ones.
4613 * Manufacturer drivers should put all their specific initialization code in
4614 * their ->init() hook.
4616 static int nand_manufacturer_init(struct nand_chip *chip)
4618 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
4619 !chip->manufacturer.desc->ops->init)
4622 return chip->manufacturer.desc->ops->init(chip);
4626 * Manufacturer cleanup. This function is called for all NANDs including
4627 * ONFI and JEDEC compliant ones.
4628 * Manufacturer drivers should put all their specific cleanup code in their
4631 static void nand_manufacturer_cleanup(struct nand_chip *chip)
4633 /* Release manufacturer private data */
4634 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4635 chip->manufacturer.desc->ops->cleanup)
4636 chip->manufacturer.desc->ops->cleanup(chip);
4640 nand_manufacturer_name(const struct nand_manufacturer *manufacturer)
4642 return manufacturer ? manufacturer->name : "Unknown";
4646 * Get the flash and manufacturer id and lookup if the type is supported.
4648 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
4650 const struct nand_manufacturer *manufacturer;
4651 struct mtd_info *mtd = nand_to_mtd(chip);
4652 struct nand_memory_organization *memorg;
4654 u8 *id_data = chip->id.data;
4659 * Let's start by initializing memorg fields that might be left
4660 * unassigned by the ID-based detection logic.
4662 memorg = nanddev_get_memorg(&chip->base);
4663 memorg->planes_per_lun = 1;
4664 memorg->luns_per_target = 1;
4667 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4670 ret = nand_reset(chip, 0);
4674 /* Select the device */
4675 nand_select_target(chip, 0);
4677 /* Send the command for reading device ID */
4678 ret = nand_readid_op(chip, 0, id_data, 2);
4682 /* Read manufacturer and device IDs */
4683 maf_id = id_data[0];
4684 dev_id = id_data[1];
4687 * Try again to make sure, as some systems the bus-hold or other
4688 * interface concerns can cause random data which looks like a
4689 * possibly credible NAND flash to appear. If the two results do
4690 * not match, ignore the device completely.
4693 /* Read entire ID string */
4694 ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
4698 if (id_data[0] != maf_id || id_data[1] != dev_id) {
4699 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4700 maf_id, dev_id, id_data[0], id_data[1]);
4704 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
4706 /* Try to identify manufacturer */
4707 manufacturer = nand_get_manufacturer(maf_id);
4708 chip->manufacturer.desc = manufacturer;
4711 type = nand_flash_ids;
4714 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
4716 * This is required to make sure initial NAND bus width set by the
4717 * NAND controller driver is coherent with the real NAND bus width
4718 * (extracted by auto-detection code).
4720 busw = chip->options & NAND_BUSWIDTH_16;
4723 * The flag is only set (never cleared), reset it to its default value
4724 * before starting auto-detection.
4726 chip->options &= ~NAND_BUSWIDTH_16;
4728 for (; type->name != NULL; type++) {
4729 if (is_full_id_nand(type)) {
4730 if (find_full_id_nand(chip, type))
4732 } else if (dev_id == type->dev_id) {
4737 if (!type->name || !type->pagesize) {
4738 /* Check if the chip is ONFI compliant */
4739 ret = nand_onfi_detect(chip);
4745 /* Check if the chip is JEDEC compliant */
4746 ret = nand_jedec_detect(chip);
4756 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4757 if (!chip->parameters.model)
4760 if (!type->pagesize)
4761 nand_manufacturer_detect(chip);
4763 nand_decode_id(chip, type);
4765 /* Get chip options */
4766 chip->options |= type->options;
4768 memorg->eraseblocks_per_lun =
4769 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4771 memorg->pages_per_eraseblock);
4775 mtd->name = chip->parameters.model;
4777 if (chip->options & NAND_BUSWIDTH_AUTO) {
4778 WARN_ON(busw & NAND_BUSWIDTH_16);
4779 nand_set_defaults(chip);
4780 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4782 * Check, if buswidth is correct. Hardware drivers should set
4785 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4787 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4789 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
4790 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
4793 goto free_detect_allocation;
4796 nand_decode_bbm_options(chip);
4798 /* Calculate the address shift from the page size */
4799 chip->page_shift = ffs(mtd->writesize) - 1;
4800 /* Convert chipsize to number of pages per chip -1 */
4801 targetsize = nanddev_target_size(&chip->base);
4802 chip->pagemask = (targetsize >> chip->page_shift) - 1;
4804 chip->bbt_erase_shift = chip->phys_erase_shift =
4805 ffs(mtd->erasesize) - 1;
4806 if (targetsize & 0xffffffff)
4807 chip->chip_shift = ffs((unsigned)targetsize) - 1;
4809 chip->chip_shift = ffs((unsigned)(targetsize >> 32));
4810 chip->chip_shift += 32 - 1;
4813 if (chip->chip_shift - chip->page_shift > 16)
4814 chip->options |= NAND_ROW_ADDR_3;
4816 chip->badblockbits = 8;
4818 nand_legacy_adjust_cmdfunc(chip);
4820 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4822 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4823 chip->parameters.model);
4824 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4825 (int)(targetsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4826 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4829 free_detect_allocation:
4830 kfree(chip->parameters.model);
4835 static const char * const nand_ecc_modes[] = {
4836 [NAND_ECC_NONE] = "none",
4837 [NAND_ECC_SOFT] = "soft",
4838 [NAND_ECC_HW] = "hw",
4839 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
4840 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
4841 [NAND_ECC_ON_DIE] = "on-die",
4844 static int of_get_nand_ecc_mode(struct device_node *np)
4849 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4853 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
4854 if (!strcasecmp(pm, nand_ecc_modes[i]))
4858 * For backward compatibility we support few obsoleted values that don't
4859 * have their mappings into nand_ecc_modes_t anymore (they were merged
4860 * with other enums).
4862 if (!strcasecmp(pm, "soft_bch"))
4863 return NAND_ECC_SOFT;
4868 static const char * const nand_ecc_algos[] = {
4869 [NAND_ECC_HAMMING] = "hamming",
4870 [NAND_ECC_BCH] = "bch",
4871 [NAND_ECC_RS] = "rs",
4874 static int of_get_nand_ecc_algo(struct device_node *np)
4879 err = of_property_read_string(np, "nand-ecc-algo", &pm);
4881 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
4882 if (!strcasecmp(pm, nand_ecc_algos[i]))
4888 * For backward compatibility we also read "nand-ecc-mode" checking
4889 * for some obsoleted values that were specifying ECC algorithm.
4891 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4895 if (!strcasecmp(pm, "soft"))
4896 return NAND_ECC_HAMMING;
4897 else if (!strcasecmp(pm, "soft_bch"))
4898 return NAND_ECC_BCH;
4903 static int of_get_nand_ecc_step_size(struct device_node *np)
4908 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
4909 return ret ? ret : val;
4912 static int of_get_nand_ecc_strength(struct device_node *np)
4917 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
4918 return ret ? ret : val;
4921 static int of_get_nand_bus_width(struct device_node *np)
4925 if (of_property_read_u32(np, "nand-bus-width", &val))
4937 static bool of_get_nand_on_flash_bbt(struct device_node *np)
4939 return of_property_read_bool(np, "nand-on-flash-bbt");
4942 static int nand_dt_init(struct nand_chip *chip)
4944 struct device_node *dn = nand_get_flash_node(chip);
4945 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
4950 if (of_get_nand_bus_width(dn) == 16)
4951 chip->options |= NAND_BUSWIDTH_16;
4953 if (of_property_read_bool(dn, "nand-is-boot-medium"))
4954 chip->options |= NAND_IS_BOOT_MEDIUM;
4956 if (of_get_nand_on_flash_bbt(dn))
4957 chip->bbt_options |= NAND_BBT_USE_FLASH;
4959 ecc_mode = of_get_nand_ecc_mode(dn);
4960 ecc_algo = of_get_nand_ecc_algo(dn);
4961 ecc_strength = of_get_nand_ecc_strength(dn);
4962 ecc_step = of_get_nand_ecc_step_size(dn);
4965 chip->ecc.mode = ecc_mode;
4968 chip->ecc.algo = ecc_algo;
4970 if (ecc_strength >= 0)
4971 chip->ecc.strength = ecc_strength;
4974 chip->ecc.size = ecc_step;
4976 if (of_property_read_bool(dn, "nand-ecc-maximize"))
4977 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4983 * nand_scan_ident - Scan for the NAND device
4984 * @chip: NAND chip object
4985 * @maxchips: number of chips to scan for
4986 * @table: alternative NAND ID table
4988 * This is the first phase of the normal nand_scan() function. It reads the
4989 * flash ID and sets up MTD fields accordingly.
4991 * This helper used to be called directly from controller drivers that needed
4992 * to tweak some ECC-related parameters before nand_scan_tail(). This separation
4993 * prevented dynamic allocations during this phase which was unconvenient and
4994 * as been banned for the benefit of the ->init_ecc()/cleanup_ecc() hooks.
4996 static int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips,
4997 struct nand_flash_dev *table)
4999 struct mtd_info *mtd = nand_to_mtd(chip);
5000 struct nand_memory_organization *memorg;
5001 int nand_maf_id, nand_dev_id;
5005 memorg = nanddev_get_memorg(&chip->base);
5007 /* Assume all dies are deselected when we enter nand_scan_ident(). */
5010 mutex_init(&chip->lock);
5012 /* Enforce the right timings for reset/detection */
5013 onfi_fill_data_interface(chip, NAND_SDR_IFACE, 0);
5015 ret = nand_dt_init(chip);
5019 if (!mtd->name && mtd->dev.parent)
5020 mtd->name = dev_name(mtd->dev.parent);
5022 /* Set the default functions */
5023 nand_set_defaults(chip);
5025 ret = nand_legacy_check_hooks(chip);
5029 memorg->ntargets = maxchips;
5031 /* Read the flash type */
5032 ret = nand_detect(chip, table);
5034 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
5035 pr_warn("No NAND device found\n");
5036 nand_deselect_target(chip);
5040 nand_maf_id = chip->id.data[0];
5041 nand_dev_id = chip->id.data[1];
5043 nand_deselect_target(chip);
5045 /* Check for a chip array */
5046 for (i = 1; i < maxchips; i++) {
5049 /* See comment in nand_get_flash_type for reset */
5050 ret = nand_reset(chip, i);
5054 nand_select_target(chip, i);
5055 /* Send the command for reading device ID */
5056 ret = nand_readid_op(chip, 0, id, sizeof(id));
5059 /* Read manufacturer and device IDs */
5060 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
5061 nand_deselect_target(chip);
5064 nand_deselect_target(chip);
5067 pr_info("%d chips detected\n", i);
5069 /* Store the number of chips and calc total size for mtd */
5070 memorg->ntargets = i;
5071 mtd->size = i * nanddev_target_size(&chip->base);
5076 static void nand_scan_ident_cleanup(struct nand_chip *chip)
5078 kfree(chip->parameters.model);
5079 kfree(chip->parameters.onfi);
5082 static int nand_set_ecc_soft_ops(struct nand_chip *chip)
5084 struct mtd_info *mtd = nand_to_mtd(chip);
5085 struct nand_ecc_ctrl *ecc = &chip->ecc;
5087 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
5090 switch (ecc->algo) {
5091 case NAND_ECC_HAMMING:
5092 ecc->calculate = nand_calculate_ecc;
5093 ecc->correct = nand_correct_data;
5094 ecc->read_page = nand_read_page_swecc;
5095 ecc->read_subpage = nand_read_subpage;
5096 ecc->write_page = nand_write_page_swecc;
5097 ecc->read_page_raw = nand_read_page_raw;
5098 ecc->write_page_raw = nand_write_page_raw;
5099 ecc->read_oob = nand_read_oob_std;
5100 ecc->write_oob = nand_write_oob_std;
5106 if (IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_HAMMING_SMC))
5107 ecc->options |= NAND_ECC_SOFT_HAMMING_SM_ORDER;
5111 if (!mtd_nand_has_bch()) {
5112 WARN(1, "CONFIG_MTD_NAND_ECC_SW_BCH not enabled\n");
5115 ecc->calculate = nand_bch_calculate_ecc;
5116 ecc->correct = nand_bch_correct_data;
5117 ecc->read_page = nand_read_page_swecc;
5118 ecc->read_subpage = nand_read_subpage;
5119 ecc->write_page = nand_write_page_swecc;
5120 ecc->read_page_raw = nand_read_page_raw;
5121 ecc->write_page_raw = nand_write_page_raw;
5122 ecc->read_oob = nand_read_oob_std;
5123 ecc->write_oob = nand_write_oob_std;
5126 * Board driver should supply ecc.size and ecc.strength
5127 * values to select how many bits are correctable.
5128 * Otherwise, default to 4 bits for large page devices.
5130 if (!ecc->size && (mtd->oobsize >= 64)) {
5136 * if no ecc placement scheme was provided pickup the default
5139 if (!mtd->ooblayout) {
5140 /* handle large page devices only */
5141 if (mtd->oobsize < 64) {
5142 WARN(1, "OOB layout is required when using software BCH on small pages\n");
5146 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
5151 * We can only maximize ECC config when the default layout is
5152 * used, otherwise we don't know how many bytes can really be
5155 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
5156 ecc->options & NAND_ECC_MAXIMIZE) {
5159 /* Always prefer 1k blocks over 512bytes ones */
5161 steps = mtd->writesize / ecc->size;
5163 /* Reserve 2 bytes for the BBM */
5164 bytes = (mtd->oobsize - 2) / steps;
5165 ecc->strength = bytes * 8 / fls(8 * ecc->size);
5168 /* See nand_bch_init() for details. */
5170 ecc->priv = nand_bch_init(mtd);
5172 WARN(1, "BCH ECC initialization failed!\n");
5177 WARN(1, "Unsupported ECC algorithm!\n");
5183 * nand_check_ecc_caps - check the sanity of preset ECC settings
5184 * @chip: nand chip info structure
5185 * @caps: ECC caps info structure
5186 * @oobavail: OOB size that the ECC engine can use
5188 * When ECC step size and strength are already set, check if they are supported
5189 * by the controller and the calculated ECC bytes fit within the chip's OOB.
5190 * On success, the calculated ECC bytes is set.
5193 nand_check_ecc_caps(struct nand_chip *chip,
5194 const struct nand_ecc_caps *caps, int oobavail)
5196 struct mtd_info *mtd = nand_to_mtd(chip);
5197 const struct nand_ecc_step_info *stepinfo;
5198 int preset_step = chip->ecc.size;
5199 int preset_strength = chip->ecc.strength;
5200 int ecc_bytes, nsteps = mtd->writesize / preset_step;
5203 for (i = 0; i < caps->nstepinfos; i++) {
5204 stepinfo = &caps->stepinfos[i];
5206 if (stepinfo->stepsize != preset_step)
5209 for (j = 0; j < stepinfo->nstrengths; j++) {
5210 if (stepinfo->strengths[j] != preset_strength)
5213 ecc_bytes = caps->calc_ecc_bytes(preset_step,
5215 if (WARN_ON_ONCE(ecc_bytes < 0))
5218 if (ecc_bytes * nsteps > oobavail) {
5219 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
5220 preset_step, preset_strength);
5224 chip->ecc.bytes = ecc_bytes;
5230 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
5231 preset_step, preset_strength);
5237 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
5238 * @chip: nand chip info structure
5239 * @caps: ECC engine caps info structure
5240 * @oobavail: OOB size that the ECC engine can use
5242 * If a chip's ECC requirement is provided, try to meet it with the least
5243 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
5244 * On success, the chosen ECC settings are set.
5247 nand_match_ecc_req(struct nand_chip *chip,
5248 const struct nand_ecc_caps *caps, int oobavail)
5250 struct mtd_info *mtd = nand_to_mtd(chip);
5251 const struct nand_ecc_step_info *stepinfo;
5252 int req_step = chip->base.eccreq.step_size;
5253 int req_strength = chip->base.eccreq.strength;
5254 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
5255 int best_step, best_strength, best_ecc_bytes;
5256 int best_ecc_bytes_total = INT_MAX;
5259 /* No information provided by the NAND chip */
5260 if (!req_step || !req_strength)
5263 /* number of correctable bits the chip requires in a page */
5264 req_corr = mtd->writesize / req_step * req_strength;
5266 for (i = 0; i < caps->nstepinfos; i++) {
5267 stepinfo = &caps->stepinfos[i];
5268 step_size = stepinfo->stepsize;
5270 for (j = 0; j < stepinfo->nstrengths; j++) {
5271 strength = stepinfo->strengths[j];
5274 * If both step size and strength are smaller than the
5275 * chip's requirement, it is not easy to compare the
5276 * resulted reliability.
5278 if (step_size < req_step && strength < req_strength)
5281 if (mtd->writesize % step_size)
5284 nsteps = mtd->writesize / step_size;
5286 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5287 if (WARN_ON_ONCE(ecc_bytes < 0))
5289 ecc_bytes_total = ecc_bytes * nsteps;
5291 if (ecc_bytes_total > oobavail ||
5292 strength * nsteps < req_corr)
5296 * We assume the best is to meet the chip's requrement
5297 * with the least number of ECC bytes.
5299 if (ecc_bytes_total < best_ecc_bytes_total) {
5300 best_ecc_bytes_total = ecc_bytes_total;
5301 best_step = step_size;
5302 best_strength = strength;
5303 best_ecc_bytes = ecc_bytes;
5308 if (best_ecc_bytes_total == INT_MAX)
5311 chip->ecc.size = best_step;
5312 chip->ecc.strength = best_strength;
5313 chip->ecc.bytes = best_ecc_bytes;
5319 * nand_maximize_ecc - choose the max ECC strength available
5320 * @chip: nand chip info structure
5321 * @caps: ECC engine caps info structure
5322 * @oobavail: OOB size that the ECC engine can use
5324 * Choose the max ECC strength that is supported on the controller, and can fit
5325 * within the chip's OOB. On success, the chosen ECC settings are set.
5328 nand_maximize_ecc(struct nand_chip *chip,
5329 const struct nand_ecc_caps *caps, int oobavail)
5331 struct mtd_info *mtd = nand_to_mtd(chip);
5332 const struct nand_ecc_step_info *stepinfo;
5333 int step_size, strength, nsteps, ecc_bytes, corr;
5336 int best_strength, best_ecc_bytes;
5339 for (i = 0; i < caps->nstepinfos; i++) {
5340 stepinfo = &caps->stepinfos[i];
5341 step_size = stepinfo->stepsize;
5343 /* If chip->ecc.size is already set, respect it */
5344 if (chip->ecc.size && step_size != chip->ecc.size)
5347 for (j = 0; j < stepinfo->nstrengths; j++) {
5348 strength = stepinfo->strengths[j];
5350 if (mtd->writesize % step_size)
5353 nsteps = mtd->writesize / step_size;
5355 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5356 if (WARN_ON_ONCE(ecc_bytes < 0))
5359 if (ecc_bytes * nsteps > oobavail)
5362 corr = strength * nsteps;
5365 * If the number of correctable bits is the same,
5366 * bigger step_size has more reliability.
5368 if (corr > best_corr ||
5369 (corr == best_corr && step_size > best_step)) {
5371 best_step = step_size;
5372 best_strength = strength;
5373 best_ecc_bytes = ecc_bytes;
5381 chip->ecc.size = best_step;
5382 chip->ecc.strength = best_strength;
5383 chip->ecc.bytes = best_ecc_bytes;
5389 * nand_ecc_choose_conf - Set the ECC strength and ECC step size
5390 * @chip: nand chip info structure
5391 * @caps: ECC engine caps info structure
5392 * @oobavail: OOB size that the ECC engine can use
5394 * Choose the ECC configuration according to following logic
5396 * 1. If both ECC step size and ECC strength are already set (usually by DT)
5397 * then check if it is supported by this controller.
5398 * 2. If NAND_ECC_MAXIMIZE is set, then select maximum ECC strength.
5399 * 3. Otherwise, try to match the ECC step size and ECC strength closest
5400 * to the chip's requirement. If available OOB size can't fit the chip
5401 * requirement then fallback to the maximum ECC step size and ECC strength.
5403 * On success, the chosen ECC settings are set.
5405 int nand_ecc_choose_conf(struct nand_chip *chip,
5406 const struct nand_ecc_caps *caps, int oobavail)
5408 struct mtd_info *mtd = nand_to_mtd(chip);
5410 if (WARN_ON(oobavail < 0 || oobavail > mtd->oobsize))
5413 if (chip->ecc.size && chip->ecc.strength)
5414 return nand_check_ecc_caps(chip, caps, oobavail);
5416 if (chip->ecc.options & NAND_ECC_MAXIMIZE)
5417 return nand_maximize_ecc(chip, caps, oobavail);
5419 if (!nand_match_ecc_req(chip, caps, oobavail))
5422 return nand_maximize_ecc(chip, caps, oobavail);
5424 EXPORT_SYMBOL_GPL(nand_ecc_choose_conf);
5427 * Check if the chip configuration meet the datasheet requirements.
5429 * If our configuration corrects A bits per B bytes and the minimum
5430 * required correction level is X bits per Y bytes, then we must ensure
5431 * both of the following are true:
5433 * (1) A / B >= X / Y
5436 * Requirement (1) ensures we can correct for the required bitflip density.
5437 * Requirement (2) ensures we can correct even when all bitflips are clumped
5438 * in the same sector.
5440 static bool nand_ecc_strength_good(struct nand_chip *chip)
5442 struct mtd_info *mtd = nand_to_mtd(chip);
5443 struct nand_ecc_ctrl *ecc = &chip->ecc;
5446 if (ecc->size == 0 || chip->base.eccreq.step_size == 0)
5447 /* Not enough information */
5451 * We get the number of corrected bits per page to compare
5452 * the correction density.
5454 corr = (mtd->writesize * ecc->strength) / ecc->size;
5455 ds_corr = (mtd->writesize * chip->base.eccreq.strength) /
5456 chip->base.eccreq.step_size;
5458 return corr >= ds_corr && ecc->strength >= chip->base.eccreq.strength;
5461 static int rawnand_erase(struct nand_device *nand, const struct nand_pos *pos)
5463 struct nand_chip *chip = container_of(nand, struct nand_chip,
5465 unsigned int eb = nanddev_pos_to_row(nand, pos);
5468 eb >>= nand->rowconv.eraseblock_addr_shift;
5470 nand_select_target(chip, pos->target);
5471 ret = nand_erase_op(chip, eb);
5472 nand_deselect_target(chip);
5477 static int rawnand_markbad(struct nand_device *nand,
5478 const struct nand_pos *pos)
5480 struct nand_chip *chip = container_of(nand, struct nand_chip,
5483 return nand_markbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5486 static bool rawnand_isbad(struct nand_device *nand, const struct nand_pos *pos)
5488 struct nand_chip *chip = container_of(nand, struct nand_chip,
5492 nand_select_target(chip, pos->target);
5493 ret = nand_isbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5494 nand_deselect_target(chip);
5499 static const struct nand_ops rawnand_ops = {
5500 .erase = rawnand_erase,
5501 .markbad = rawnand_markbad,
5502 .isbad = rawnand_isbad,
5506 * nand_scan_tail - Scan for the NAND device
5507 * @chip: NAND chip object
5509 * This is the second phase of the normal nand_scan() function. It fills out
5510 * all the uninitialized function pointers with the defaults and scans for a
5511 * bad block table if appropriate.
5513 static int nand_scan_tail(struct nand_chip *chip)
5515 struct mtd_info *mtd = nand_to_mtd(chip);
5516 struct nand_ecc_ctrl *ecc = &chip->ecc;
5519 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
5520 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
5521 !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
5525 chip->data_buf = kmalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
5526 if (!chip->data_buf)
5530 * FIXME: some NAND manufacturer drivers expect the first die to be
5531 * selected when manufacturer->init() is called. They should be fixed
5532 * to explictly select the relevant die when interacting with the NAND
5535 nand_select_target(chip, 0);
5536 ret = nand_manufacturer_init(chip);
5537 nand_deselect_target(chip);
5541 /* Set the internal oob buffer location, just after the page data */
5542 chip->oob_poi = chip->data_buf + mtd->writesize;
5545 * If no default placement scheme is given, select an appropriate one.
5547 if (!mtd->ooblayout &&
5548 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
5549 switch (mtd->oobsize) {
5552 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
5556 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_hamming_ops);
5560 * Expose the whole OOB area to users if ECC_NONE
5561 * is passed. We could do that for all kind of
5562 * ->oobsize, but we must keep the old large/small
5563 * page with ECC layout when ->oobsize <= 128 for
5564 * compatibility reasons.
5566 if (ecc->mode == NAND_ECC_NONE) {
5567 mtd_set_ooblayout(mtd,
5568 &nand_ooblayout_lp_ops);
5572 WARN(1, "No oob scheme defined for oobsize %d\n",
5575 goto err_nand_manuf_cleanup;
5580 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
5581 * selected and we have 256 byte pagesize fallback to software ECC
5584 switch (ecc->mode) {
5585 case NAND_ECC_HW_OOB_FIRST:
5586 /* Similar to NAND_ECC_HW, but a separate read_page handle */
5587 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
5588 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5590 goto err_nand_manuf_cleanup;
5592 if (!ecc->read_page)
5593 ecc->read_page = nand_read_page_hwecc_oob_first;
5597 /* Use standard hwecc read page function? */
5598 if (!ecc->read_page)
5599 ecc->read_page = nand_read_page_hwecc;
5600 if (!ecc->write_page)
5601 ecc->write_page = nand_write_page_hwecc;
5602 if (!ecc->read_page_raw)
5603 ecc->read_page_raw = nand_read_page_raw;
5604 if (!ecc->write_page_raw)
5605 ecc->write_page_raw = nand_write_page_raw;
5607 ecc->read_oob = nand_read_oob_std;
5608 if (!ecc->write_oob)
5609 ecc->write_oob = nand_write_oob_std;
5610 if (!ecc->read_subpage)
5611 ecc->read_subpage = nand_read_subpage;
5612 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5613 ecc->write_subpage = nand_write_subpage_hwecc;
5616 case NAND_ECC_HW_SYNDROME:
5617 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5619 ecc->read_page == nand_read_page_hwecc ||
5621 ecc->write_page == nand_write_page_hwecc)) {
5622 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5624 goto err_nand_manuf_cleanup;
5626 /* Use standard syndrome read/write page function? */
5627 if (!ecc->read_page)
5628 ecc->read_page = nand_read_page_syndrome;
5629 if (!ecc->write_page)
5630 ecc->write_page = nand_write_page_syndrome;
5631 if (!ecc->read_page_raw)
5632 ecc->read_page_raw = nand_read_page_raw_syndrome;
5633 if (!ecc->write_page_raw)
5634 ecc->write_page_raw = nand_write_page_raw_syndrome;
5636 ecc->read_oob = nand_read_oob_syndrome;
5637 if (!ecc->write_oob)
5638 ecc->write_oob = nand_write_oob_syndrome;
5640 if (mtd->writesize >= ecc->size) {
5641 if (!ecc->strength) {
5642 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
5644 goto err_nand_manuf_cleanup;
5648 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
5649 ecc->size, mtd->writesize);
5650 ecc->mode = NAND_ECC_SOFT;
5651 ecc->algo = NAND_ECC_HAMMING;
5655 ret = nand_set_ecc_soft_ops(chip);
5658 goto err_nand_manuf_cleanup;
5662 case NAND_ECC_ON_DIE:
5663 if (!ecc->read_page || !ecc->write_page) {
5664 WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
5666 goto err_nand_manuf_cleanup;
5669 ecc->read_oob = nand_read_oob_std;
5670 if (!ecc->write_oob)
5671 ecc->write_oob = nand_write_oob_std;
5675 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
5676 ecc->read_page = nand_read_page_raw;
5677 ecc->write_page = nand_write_page_raw;
5678 ecc->read_oob = nand_read_oob_std;
5679 ecc->read_page_raw = nand_read_page_raw;
5680 ecc->write_page_raw = nand_write_page_raw;
5681 ecc->write_oob = nand_write_oob_std;
5682 ecc->size = mtd->writesize;
5688 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
5690 goto err_nand_manuf_cleanup;
5693 if (ecc->correct || ecc->calculate) {
5694 ecc->calc_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
5695 ecc->code_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
5696 if (!ecc->calc_buf || !ecc->code_buf) {
5698 goto err_nand_manuf_cleanup;
5702 /* For many systems, the standard OOB write also works for raw */
5703 if (!ecc->read_oob_raw)
5704 ecc->read_oob_raw = ecc->read_oob;
5705 if (!ecc->write_oob_raw)
5706 ecc->write_oob_raw = ecc->write_oob;
5708 /* propagate ecc info to mtd_info */
5709 mtd->ecc_strength = ecc->strength;
5710 mtd->ecc_step_size = ecc->size;
5713 * Set the number of read / write steps for one page depending on ECC
5716 ecc->steps = mtd->writesize / ecc->size;
5717 if (ecc->steps * ecc->size != mtd->writesize) {
5718 WARN(1, "Invalid ECC parameters\n");
5720 goto err_nand_manuf_cleanup;
5722 ecc->total = ecc->steps * ecc->bytes;
5723 if (ecc->total > mtd->oobsize) {
5724 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
5726 goto err_nand_manuf_cleanup;
5730 * The number of bytes available for a client to place data into
5731 * the out of band area.
5733 ret = mtd_ooblayout_count_freebytes(mtd);
5737 mtd->oobavail = ret;
5739 /* ECC sanity check: warn if it's too weak */
5740 if (!nand_ecc_strength_good(chip))
5741 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
5744 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
5745 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
5746 switch (ecc->steps) {
5748 mtd->subpage_sft = 1;
5753 mtd->subpage_sft = 2;
5757 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
5759 /* Invalidate the pagebuffer reference */
5760 chip->pagecache.page = -1;
5762 /* Large page NAND with SOFT_ECC should support subpage reads */
5763 switch (ecc->mode) {
5765 if (chip->page_shift > 9)
5766 chip->options |= NAND_SUBPAGE_READ;
5773 ret = nanddev_init(&chip->base, &rawnand_ops, mtd->owner);
5775 goto err_nand_manuf_cleanup;
5777 /* Adjust the MTD_CAP_ flags when NAND_ROM is set. */
5778 if (chip->options & NAND_ROM)
5779 mtd->flags = MTD_CAP_ROM;
5781 /* Fill in remaining MTD driver data */
5782 mtd->_erase = nand_erase;
5784 mtd->_unpoint = NULL;
5785 mtd->_panic_write = panic_nand_write;
5786 mtd->_read_oob = nand_read_oob;
5787 mtd->_write_oob = nand_write_oob;
5788 mtd->_sync = nand_sync;
5790 mtd->_unlock = NULL;
5791 mtd->_suspend = nand_suspend;
5792 mtd->_resume = nand_resume;
5793 mtd->_reboot = nand_shutdown;
5794 mtd->_block_isreserved = nand_block_isreserved;
5795 mtd->_block_isbad = nand_block_isbad;
5796 mtd->_block_markbad = nand_block_markbad;
5797 mtd->_max_bad_blocks = nanddev_mtd_max_bad_blocks;
5800 * Initialize bitflip_threshold to its default prior scan_bbt() call.
5801 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
5804 if (!mtd->bitflip_threshold)
5805 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
5807 /* Initialize the ->data_interface field. */
5808 ret = nand_init_data_interface(chip);
5810 goto err_nanddev_cleanup;
5812 /* Enter fastest possible mode on all dies. */
5813 for (i = 0; i < nanddev_ntargets(&chip->base); i++) {
5814 ret = nand_setup_data_interface(chip, i);
5816 goto err_nanddev_cleanup;
5819 /* Check, if we should skip the bad block table scan */
5820 if (chip->options & NAND_SKIP_BBTSCAN)
5823 /* Build bad block table */
5824 ret = nand_create_bbt(chip);
5826 goto err_nanddev_cleanup;
5831 err_nanddev_cleanup:
5832 nanddev_cleanup(&chip->base);
5834 err_nand_manuf_cleanup:
5835 nand_manufacturer_cleanup(chip);
5838 kfree(chip->data_buf);
5839 kfree(ecc->code_buf);
5840 kfree(ecc->calc_buf);
5845 static int nand_attach(struct nand_chip *chip)
5847 if (chip->controller->ops && chip->controller->ops->attach_chip)
5848 return chip->controller->ops->attach_chip(chip);
5853 static void nand_detach(struct nand_chip *chip)
5855 if (chip->controller->ops && chip->controller->ops->detach_chip)
5856 chip->controller->ops->detach_chip(chip);
5860 * nand_scan_with_ids - [NAND Interface] Scan for the NAND device
5861 * @chip: NAND chip object
5862 * @maxchips: number of chips to scan for.
5863 * @ids: optional flash IDs table
5865 * This fills out all the uninitialized function pointers with the defaults.
5866 * The flash ID is read and the mtd/chip structures are filled with the
5867 * appropriate values.
5869 int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips,
5870 struct nand_flash_dev *ids)
5877 ret = nand_scan_ident(chip, maxchips, ids);
5881 ret = nand_attach(chip);
5885 ret = nand_scan_tail(chip);
5894 nand_scan_ident_cleanup(chip);
5898 EXPORT_SYMBOL(nand_scan_with_ids);
5901 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
5902 * @chip: NAND chip object
5904 void nand_cleanup(struct nand_chip *chip)
5906 if (chip->ecc.mode == NAND_ECC_SOFT &&
5907 chip->ecc.algo == NAND_ECC_BCH)
5908 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
5910 /* Free bad block table memory */
5912 kfree(chip->data_buf);
5913 kfree(chip->ecc.code_buf);
5914 kfree(chip->ecc.calc_buf);
5916 /* Free bad block descriptor memory */
5917 if (chip->badblock_pattern && chip->badblock_pattern->options
5918 & NAND_BBT_DYNAMICSTRUCT)
5919 kfree(chip->badblock_pattern);
5921 /* Free manufacturer priv data. */
5922 nand_manufacturer_cleanup(chip);
5924 /* Free controller specific allocations after chip identification */
5927 /* Free identification phase allocations */
5928 nand_scan_ident_cleanup(chip);
5931 EXPORT_SYMBOL_GPL(nand_cleanup);
5934 * nand_release - [NAND Interface] Unregister the MTD device and free resources
5935 * held by the NAND device
5936 * @chip: NAND chip object
5938 void nand_release(struct nand_chip *chip)
5940 mtd_device_unregister(nand_to_mtd(chip));
5943 EXPORT_SYMBOL_GPL(nand_release);
5945 MODULE_LICENSE("GPL");
5946 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
5947 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
5948 MODULE_DESCRIPTION("Generic NAND flash driver code");