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 nand_pairing_dist3_get_info(struct mtd_info *mtd, int page,
209 struct mtd_pairing_info *info)
211 int lastpage = (mtd->erasesize / mtd->writesize) - 1;
214 if (page == lastpage)
217 if (!page || (page & 1)) {
219 info->pair = (page + 1) / 2;
222 info->pair = (page + 1 - dist) / 2;
228 static int nand_pairing_dist3_get_wunit(struct mtd_info *mtd,
229 const struct mtd_pairing_info *info)
231 int lastpair = ((mtd->erasesize / mtd->writesize) - 1) / 2;
232 int page = info->pair * 2;
235 if (!info->group && !info->pair)
238 if (info->pair == lastpair && info->group)
246 if (page >= mtd->erasesize / mtd->writesize)
252 const struct mtd_pairing_scheme dist3_pairing_scheme = {
254 .get_info = nand_pairing_dist3_get_info,
255 .get_wunit = nand_pairing_dist3_get_wunit,
258 static int check_offs_len(struct nand_chip *chip, loff_t ofs, uint64_t len)
262 /* Start address must align on block boundary */
263 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
264 pr_debug("%s: unaligned address\n", __func__);
268 /* Length must align on block boundary */
269 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
270 pr_debug("%s: length not block aligned\n", __func__);
278 * nand_extract_bits - Copy unaligned bits from one buffer to another one
279 * @dst: destination buffer
280 * @dst_off: bit offset at which the writing starts
281 * @src: source buffer
282 * @src_off: bit offset at which the reading starts
283 * @nbits: number of bits to copy from @src to @dst
285 * Copy bits from one memory region to another (overlap authorized).
287 void nand_extract_bits(u8 *dst, unsigned int dst_off, const u8 *src,
288 unsigned int src_off, unsigned int nbits)
298 n = min3(8 - dst_off, 8 - src_off, nbits);
300 tmp = (*src >> src_off) & GENMASK(n - 1, 0);
301 *dst &= ~GENMASK(n - 1 + dst_off, dst_off);
302 *dst |= tmp << dst_off;
319 EXPORT_SYMBOL_GPL(nand_extract_bits);
322 * nand_select_target() - Select a NAND target (A.K.A. die)
323 * @chip: NAND chip object
324 * @cs: the CS line to select. Note that this CS id is always from the chip
325 * PoV, not the controller one
327 * Select a NAND target so that further operations executed on @chip go to the
328 * selected NAND target.
330 void nand_select_target(struct nand_chip *chip, unsigned int cs)
333 * cs should always lie between 0 and nanddev_ntargets(), when that's
334 * not the case it's a bug and the caller should be fixed.
336 if (WARN_ON(cs > nanddev_ntargets(&chip->base)))
341 if (chip->legacy.select_chip)
342 chip->legacy.select_chip(chip, cs);
344 EXPORT_SYMBOL_GPL(nand_select_target);
347 * nand_deselect_target() - Deselect the currently selected target
348 * @chip: NAND chip object
350 * Deselect the currently selected NAND target. The result of operations
351 * executed on @chip after the target has been deselected is undefined.
353 void nand_deselect_target(struct nand_chip *chip)
355 if (chip->legacy.select_chip)
356 chip->legacy.select_chip(chip, -1);
360 EXPORT_SYMBOL_GPL(nand_deselect_target);
363 * nand_release_device - [GENERIC] release chip
364 * @chip: NAND chip object
366 * Release chip lock and wake up anyone waiting on the device.
368 static void nand_release_device(struct nand_chip *chip)
370 /* Release the controller and the chip */
371 mutex_unlock(&chip->controller->lock);
372 mutex_unlock(&chip->lock);
376 * nand_bbm_get_next_page - Get the next page for bad block markers
377 * @chip: NAND chip object
378 * @page: First page to start checking for bad block marker usage
380 * Returns an integer that corresponds to the page offset within a block, for
381 * a page that is used to store bad block markers. If no more pages are
382 * available, -EINVAL is returned.
384 int nand_bbm_get_next_page(struct nand_chip *chip, int page)
386 struct mtd_info *mtd = nand_to_mtd(chip);
387 int last_page = ((mtd->erasesize - mtd->writesize) >>
388 chip->page_shift) & chip->pagemask;
389 unsigned int bbm_flags = NAND_BBM_FIRSTPAGE | NAND_BBM_SECONDPAGE
392 if (page == 0 && !(chip->options & bbm_flags))
394 if (page == 0 && chip->options & NAND_BBM_FIRSTPAGE)
396 if (page <= 1 && chip->options & NAND_BBM_SECONDPAGE)
398 if (page <= last_page && chip->options & NAND_BBM_LASTPAGE)
405 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
406 * @chip: NAND chip object
407 * @ofs: offset from device start
409 * Check, if the block is bad.
411 static int nand_block_bad(struct nand_chip *chip, loff_t ofs)
413 int first_page, page_offset;
417 first_page = (int)(ofs >> chip->page_shift) & chip->pagemask;
418 page_offset = nand_bbm_get_next_page(chip, 0);
420 while (page_offset >= 0) {
421 res = chip->ecc.read_oob(chip, first_page + page_offset);
425 bad = chip->oob_poi[chip->badblockpos];
427 if (likely(chip->badblockbits == 8))
430 res = hweight8(bad) < chip->badblockbits;
434 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
440 static int nand_isbad_bbm(struct nand_chip *chip, loff_t ofs)
442 if (chip->options & NAND_NO_BBM_QUIRK)
445 if (chip->legacy.block_bad)
446 return chip->legacy.block_bad(chip, ofs);
448 return nand_block_bad(chip, ofs);
452 * nand_get_device - [GENERIC] Get chip for selected access
453 * @chip: NAND chip structure
455 * Lock the device and its controller for exclusive access
457 * Return: -EBUSY if the chip has been suspended, 0 otherwise
459 static int nand_get_device(struct nand_chip *chip)
461 mutex_lock(&chip->lock);
462 if (chip->suspended) {
463 mutex_unlock(&chip->lock);
466 mutex_lock(&chip->controller->lock);
472 * nand_check_wp - [GENERIC] check if the chip is write protected
473 * @chip: NAND chip object
475 * Check, if the device is write protected. The function expects, that the
476 * device is already selected.
478 static int nand_check_wp(struct nand_chip *chip)
483 /* Broken xD cards report WP despite being writable */
484 if (chip->options & NAND_BROKEN_XD)
487 /* Check the WP bit */
488 ret = nand_status_op(chip, &status);
492 return status & NAND_STATUS_WP ? 0 : 1;
496 * nand_fill_oob - [INTERN] Transfer client buffer to oob
497 * @chip: NAND chip object
498 * @oob: oob data buffer
499 * @len: oob data write length
500 * @ops: oob ops structure
502 static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len,
503 struct mtd_oob_ops *ops)
505 struct mtd_info *mtd = nand_to_mtd(chip);
509 * Initialise to all 0xFF, to avoid the possibility of left over OOB
510 * data from a previous OOB read.
512 memset(chip->oob_poi, 0xff, mtd->oobsize);
516 case MTD_OPS_PLACE_OOB:
518 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
521 case MTD_OPS_AUTO_OOB:
522 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
534 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
535 * @chip: NAND chip object
536 * @to: offset to write to
537 * @ops: oob operation description structure
539 * NAND write out-of-band.
541 static int nand_do_write_oob(struct nand_chip *chip, loff_t to,
542 struct mtd_oob_ops *ops)
544 struct mtd_info *mtd = nand_to_mtd(chip);
545 int chipnr, page, status, len, ret;
547 pr_debug("%s: to = 0x%08x, len = %i\n",
548 __func__, (unsigned int)to, (int)ops->ooblen);
550 len = mtd_oobavail(mtd, ops);
552 /* Do not allow write past end of page */
553 if ((ops->ooboffs + ops->ooblen) > len) {
554 pr_debug("%s: attempt to write past end of page\n",
559 chipnr = (int)(to >> chip->chip_shift);
562 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
563 * of my DiskOnChip 2000 test units) will clear the whole data page too
564 * if we don't do this. I have no clue why, but I seem to have 'fixed'
565 * it in the doc2000 driver in August 1999. dwmw2.
567 ret = nand_reset(chip, chipnr);
571 nand_select_target(chip, chipnr);
573 /* Shift to get page */
574 page = (int)(to >> chip->page_shift);
576 /* Check, if it is write protected */
577 if (nand_check_wp(chip)) {
578 nand_deselect_target(chip);
582 /* Invalidate the page cache, if we write to the cached page */
583 if (page == chip->pagecache.page)
584 chip->pagecache.page = -1;
586 nand_fill_oob(chip, ops->oobbuf, ops->ooblen, ops);
588 if (ops->mode == MTD_OPS_RAW)
589 status = chip->ecc.write_oob_raw(chip, page & chip->pagemask);
591 status = chip->ecc.write_oob(chip, page & chip->pagemask);
593 nand_deselect_target(chip);
598 ops->oobretlen = ops->ooblen;
604 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
605 * @chip: NAND chip object
606 * @ofs: offset from device start
608 * This is the default implementation, which can be overridden by a hardware
609 * specific driver. It provides the details for writing a bad block marker to a
612 static int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
614 struct mtd_info *mtd = nand_to_mtd(chip);
615 struct mtd_oob_ops ops;
616 uint8_t buf[2] = { 0, 0 };
617 int ret = 0, res, page_offset;
619 memset(&ops, 0, sizeof(ops));
621 ops.ooboffs = chip->badblockpos;
622 if (chip->options & NAND_BUSWIDTH_16) {
623 ops.ooboffs &= ~0x01;
624 ops.len = ops.ooblen = 2;
626 ops.len = ops.ooblen = 1;
628 ops.mode = MTD_OPS_PLACE_OOB;
630 page_offset = nand_bbm_get_next_page(chip, 0);
632 while (page_offset >= 0) {
633 res = nand_do_write_oob(chip,
634 ofs + (page_offset * mtd->writesize),
640 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
647 * nand_markbad_bbm - mark a block by updating the BBM
648 * @chip: NAND chip object
649 * @ofs: offset of the block to mark bad
651 int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
653 if (chip->legacy.block_markbad)
654 return chip->legacy.block_markbad(chip, ofs);
656 return nand_default_block_markbad(chip, ofs);
660 * nand_block_markbad_lowlevel - mark a block bad
661 * @chip: NAND chip object
662 * @ofs: offset from device start
664 * This function performs the generic NAND bad block marking steps (i.e., bad
665 * block table(s) and/or marker(s)). We only allow the hardware driver to
666 * specify how to write bad block markers to OOB (chip->legacy.block_markbad).
668 * We try operations in the following order:
670 * (1) erase the affected block, to allow OOB marker to be written cleanly
671 * (2) write bad block marker to OOB area of affected block (unless flag
672 * NAND_BBT_NO_OOB_BBM is present)
675 * Note that we retain the first error encountered in (2) or (3), finish the
676 * procedures, and dump the error in the end.
678 static int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
680 struct mtd_info *mtd = nand_to_mtd(chip);
683 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
684 struct erase_info einfo;
686 /* Attempt erase before marking OOB */
687 memset(&einfo, 0, sizeof(einfo));
689 einfo.len = 1ULL << chip->phys_erase_shift;
690 nand_erase_nand(chip, &einfo, 0);
692 /* Write bad block marker to OOB */
693 ret = nand_get_device(chip);
697 ret = nand_markbad_bbm(chip, ofs);
698 nand_release_device(chip);
701 /* Mark block bad in BBT */
703 res = nand_markbad_bbt(chip, ofs);
709 mtd->ecc_stats.badblocks++;
715 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
716 * @mtd: MTD device structure
717 * @ofs: offset from device start
719 * Check if the block is marked as reserved.
721 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
723 struct nand_chip *chip = mtd_to_nand(mtd);
727 /* Return info from the table */
728 return nand_isreserved_bbt(chip, ofs);
732 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
733 * @chip: NAND chip object
734 * @ofs: offset from device start
735 * @allowbbt: 1, if its allowed to access the bbt area
737 * Check, if the block is bad. Either by reading the bad block table or
738 * calling of the scan function.
740 static int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
742 /* Return info from the table */
744 return nand_isbad_bbt(chip, ofs, allowbbt);
746 return nand_isbad_bbm(chip, ofs);
750 * nand_soft_waitrdy - Poll STATUS reg until RDY bit is set to 1
751 * @chip: NAND chip structure
752 * @timeout_ms: Timeout in ms
754 * Poll the STATUS register using ->exec_op() until the RDY bit becomes 1.
755 * If that does not happen whitin the specified timeout, -ETIMEDOUT is
758 * This helper is intended to be used when the controller does not have access
759 * to the NAND R/B pin.
761 * Be aware that calling this helper from an ->exec_op() implementation means
762 * ->exec_op() must be re-entrant.
764 * Return 0 if the NAND chip is ready, a negative error otherwise.
766 int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
768 const struct nand_sdr_timings *timings;
772 if (!nand_has_exec_op(chip))
775 /* Wait tWB before polling the STATUS reg. */
776 timings = nand_get_sdr_timings(nand_get_interface_config(chip));
777 ndelay(PSEC_TO_NSEC(timings->tWB_max));
779 ret = nand_status_op(chip, NULL);
784 * +1 below is necessary because if we are now in the last fraction
785 * of jiffy and msecs_to_jiffies is 1 then we will wait only that
786 * small jiffy fraction - possibly leading to false timeout
788 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
790 ret = nand_read_data_op(chip, &status, sizeof(status), true,
795 if (status & NAND_STATUS_READY)
799 * Typical lowest execution time for a tR on most NANDs is 10us,
800 * use this as polling delay before doing something smarter (ie.
801 * deriving a delay from the timeout value, timeout_ms/ratio).
804 } while (time_before(jiffies, timeout_ms));
807 * We have to exit READ_STATUS mode in order to read real data on the
808 * bus in case the WAITRDY instruction is preceding a DATA_IN
811 nand_exit_status_op(chip);
816 return status & NAND_STATUS_READY ? 0 : -ETIMEDOUT;
818 EXPORT_SYMBOL_GPL(nand_soft_waitrdy);
821 * nand_gpio_waitrdy - Poll R/B GPIO pin until ready
822 * @chip: NAND chip structure
823 * @gpiod: GPIO descriptor of R/B pin
824 * @timeout_ms: Timeout in ms
826 * Poll the R/B GPIO pin until it becomes ready. If that does not happen
827 * whitin the specified timeout, -ETIMEDOUT is returned.
829 * This helper is intended to be used when the controller has access to the
830 * NAND R/B pin over GPIO.
832 * Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.
834 int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
835 unsigned long timeout_ms)
839 * Wait until R/B pin indicates chip is ready or timeout occurs.
840 * +1 below is necessary because if we are now in the last fraction
841 * of jiffy and msecs_to_jiffies is 1 then we will wait only that
842 * small jiffy fraction - possibly leading to false timeout.
844 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
846 if (gpiod_get_value_cansleep(gpiod))
850 } while (time_before(jiffies, timeout_ms));
852 return gpiod_get_value_cansleep(gpiod) ? 0 : -ETIMEDOUT;
854 EXPORT_SYMBOL_GPL(nand_gpio_waitrdy);
857 * panic_nand_wait - [GENERIC] wait until the command is done
858 * @chip: NAND chip structure
861 * Wait for command done. This is a helper function for nand_wait used when
862 * we are in interrupt context. May happen when in panic and trying to write
863 * an oops through mtdoops.
865 void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
868 for (i = 0; i < timeo; i++) {
869 if (chip->legacy.dev_ready) {
870 if (chip->legacy.dev_ready(chip))
876 ret = nand_read_data_op(chip, &status, sizeof(status),
881 if (status & NAND_STATUS_READY)
888 static bool nand_supports_get_features(struct nand_chip *chip, int addr)
890 return (chip->parameters.supports_set_get_features &&
891 test_bit(addr, chip->parameters.get_feature_list));
894 static bool nand_supports_set_features(struct nand_chip *chip, int addr)
896 return (chip->parameters.supports_set_get_features &&
897 test_bit(addr, chip->parameters.set_feature_list));
901 * nand_reset_interface - Reset data interface and timings
902 * @chip: The NAND chip
903 * @chipnr: Internal die id
905 * Reset the Data interface and timings to ONFI mode 0.
907 * Returns 0 for success or negative error code otherwise.
909 static int nand_reset_interface(struct nand_chip *chip, int chipnr)
911 const struct nand_controller_ops *ops = chip->controller->ops;
914 if (!nand_controller_can_setup_interface(chip))
918 * The ONFI specification says:
920 * To transition from NV-DDR or NV-DDR2 to the SDR data
921 * interface, the host shall use the Reset (FFh) command
922 * using SDR timing mode 0. A device in any timing mode is
923 * required to recognize Reset (FFh) command issued in SDR
927 * Configure the data interface in SDR mode and set the
928 * timings to timing mode 0.
931 chip->current_interface_config = nand_get_reset_interface_config();
932 ret = ops->setup_interface(chip, chipnr,
933 chip->current_interface_config);
935 pr_err("Failed to configure data interface to SDR timing mode 0\n");
941 * nand_setup_interface - Setup the best data interface and timings
942 * @chip: The NAND chip
943 * @chipnr: Internal die id
945 * Configure what has been reported to be the best data interface and NAND
946 * timings supported by the chip and the driver.
948 * Returns 0 for success or negative error code otherwise.
950 static int nand_setup_interface(struct nand_chip *chip, int chipnr)
952 const struct nand_controller_ops *ops = chip->controller->ops;
953 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = { };
956 if (!nand_controller_can_setup_interface(chip))
960 * A nand_reset_interface() put both the NAND chip and the NAND
961 * controller in timings mode 0. If the default mode for this chip is
962 * also 0, no need to proceed to the change again. Plus, at probe time,
963 * nand_setup_interface() uses ->set/get_features() which would
964 * fail anyway as the parameter page is not available yet.
966 if (!chip->best_interface_config)
969 tmode_param[0] = chip->best_interface_config->timings.mode;
971 /* Change the mode on the chip side (if supported by the NAND chip) */
972 if (nand_supports_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE)) {
973 nand_select_target(chip, chipnr);
974 ret = nand_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
976 nand_deselect_target(chip);
981 /* Change the mode on the controller side */
982 ret = ops->setup_interface(chip, chipnr, chip->best_interface_config);
986 /* Check the mode has been accepted by the chip, if supported */
987 if (!nand_supports_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE))
988 goto update_interface_config;
990 memset(tmode_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
991 nand_select_target(chip, chipnr);
992 ret = nand_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
994 nand_deselect_target(chip);
998 if (tmode_param[0] != chip->best_interface_config->timings.mode) {
999 pr_warn("timing mode %d not acknowledged by the NAND chip\n",
1000 chip->best_interface_config->timings.mode);
1001 goto err_reset_chip;
1004 update_interface_config:
1005 chip->current_interface_config = chip->best_interface_config;
1011 * Fallback to mode 0 if the chip explicitly did not ack the chosen
1014 nand_reset_interface(chip, chipnr);
1015 nand_select_target(chip, chipnr);
1016 nand_reset_op(chip);
1017 nand_deselect_target(chip);
1023 * nand_choose_best_sdr_timings - Pick up the best SDR timings that both the
1024 * NAND controller and the NAND chip support
1025 * @chip: the NAND chip
1026 * @iface: the interface configuration (can eventually be updated)
1027 * @spec_timings: specific timings, when not fitting the ONFI specification
1029 * If specific timings are provided, use them. Otherwise, retrieve supported
1030 * timing modes from ONFI information.
1032 int nand_choose_best_sdr_timings(struct nand_chip *chip,
1033 struct nand_interface_config *iface,
1034 struct nand_sdr_timings *spec_timings)
1036 const struct nand_controller_ops *ops = chip->controller->ops;
1037 int best_mode = 0, mode, ret;
1039 iface->type = NAND_SDR_IFACE;
1042 iface->timings.sdr = *spec_timings;
1043 iface->timings.mode = onfi_find_closest_sdr_mode(spec_timings);
1045 /* Verify the controller supports the requested interface */
1046 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
1049 chip->best_interface_config = iface;
1053 /* Fallback to slower modes */
1054 best_mode = iface->timings.mode;
1055 } else if (chip->parameters.onfi) {
1056 best_mode = fls(chip->parameters.onfi->async_timing_mode) - 1;
1059 for (mode = best_mode; mode >= 0; mode--) {
1060 onfi_fill_interface_config(chip, iface, NAND_SDR_IFACE, mode);
1062 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
1068 chip->best_interface_config = iface;
1074 * nand_choose_interface_config - find the best data interface and timings
1075 * @chip: The NAND chip
1077 * Find the best data interface and NAND timings supported by the chip
1078 * and the driver. Eventually let the NAND manufacturer driver propose his own
1081 * After this function nand_chip->interface_config is initialized with the best
1082 * timing mode available.
1084 * Returns 0 for success or negative error code otherwise.
1086 static int nand_choose_interface_config(struct nand_chip *chip)
1088 struct nand_interface_config *iface;
1091 if (!nand_controller_can_setup_interface(chip))
1094 iface = kzalloc(sizeof(*iface), GFP_KERNEL);
1098 if (chip->ops.choose_interface_config)
1099 ret = chip->ops.choose_interface_config(chip, iface);
1101 ret = nand_choose_best_sdr_timings(chip, iface, NULL);
1110 * nand_fill_column_cycles - fill the column cycles of an address
1111 * @chip: The NAND chip
1112 * @addrs: Array of address cycles to fill
1113 * @offset_in_page: The offset in the page
1115 * Fills the first or the first two bytes of the @addrs field depending
1116 * on the NAND bus width and the page size.
1118 * Returns the number of cycles needed to encode the column, or a negative
1119 * error code in case one of the arguments is invalid.
1121 static int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs,
1122 unsigned int offset_in_page)
1124 struct mtd_info *mtd = nand_to_mtd(chip);
1126 /* Make sure the offset is less than the actual page size. */
1127 if (offset_in_page > mtd->writesize + mtd->oobsize)
1131 * On small page NANDs, there's a dedicated command to access the OOB
1132 * area, and the column address is relative to the start of the OOB
1133 * area, not the start of the page. Asjust the address accordingly.
1135 if (mtd->writesize <= 512 && offset_in_page >= mtd->writesize)
1136 offset_in_page -= mtd->writesize;
1139 * The offset in page is expressed in bytes, if the NAND bus is 16-bit
1140 * wide, then it must be divided by 2.
1142 if (chip->options & NAND_BUSWIDTH_16) {
1143 if (WARN_ON(offset_in_page % 2))
1146 offset_in_page /= 2;
1149 addrs[0] = offset_in_page;
1152 * Small page NANDs use 1 cycle for the columns, while large page NANDs
1155 if (mtd->writesize <= 512)
1158 addrs[1] = offset_in_page >> 8;
1163 static int nand_sp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1164 unsigned int offset_in_page, void *buf,
1167 const struct nand_sdr_timings *sdr =
1168 nand_get_sdr_timings(nand_get_interface_config(chip));
1169 struct mtd_info *mtd = nand_to_mtd(chip);
1171 struct nand_op_instr instrs[] = {
1172 NAND_OP_CMD(NAND_CMD_READ0, 0),
1173 NAND_OP_ADDR(3, addrs, PSEC_TO_NSEC(sdr->tWB_max)),
1174 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1175 PSEC_TO_NSEC(sdr->tRR_min)),
1176 NAND_OP_DATA_IN(len, buf, 0),
1178 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1181 /* Drop the DATA_IN instruction if len is set to 0. */
1185 if (offset_in_page >= mtd->writesize)
1186 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1187 else if (offset_in_page >= 256 &&
1188 !(chip->options & NAND_BUSWIDTH_16))
1189 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1191 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1196 addrs[2] = page >> 8;
1198 if (chip->options & NAND_ROW_ADDR_3) {
1199 addrs[3] = page >> 16;
1200 instrs[1].ctx.addr.naddrs++;
1203 return nand_exec_op(chip, &op);
1206 static int nand_lp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1207 unsigned int offset_in_page, void *buf,
1210 const struct nand_sdr_timings *sdr =
1211 nand_get_sdr_timings(nand_get_interface_config(chip));
1213 struct nand_op_instr instrs[] = {
1214 NAND_OP_CMD(NAND_CMD_READ0, 0),
1215 NAND_OP_ADDR(4, addrs, 0),
1216 NAND_OP_CMD(NAND_CMD_READSTART, PSEC_TO_NSEC(sdr->tWB_max)),
1217 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1218 PSEC_TO_NSEC(sdr->tRR_min)),
1219 NAND_OP_DATA_IN(len, buf, 0),
1221 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1224 /* Drop the DATA_IN instruction if len is set to 0. */
1228 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1233 addrs[3] = page >> 8;
1235 if (chip->options & NAND_ROW_ADDR_3) {
1236 addrs[4] = page >> 16;
1237 instrs[1].ctx.addr.naddrs++;
1240 return nand_exec_op(chip, &op);
1244 * nand_read_page_op - Do a READ PAGE operation
1245 * @chip: The NAND chip
1246 * @page: page to read
1247 * @offset_in_page: offset within the page
1248 * @buf: buffer used to store the data
1249 * @len: length of the buffer
1251 * This function issues a READ PAGE operation.
1252 * This function does not select/unselect the CS line.
1254 * Returns 0 on success, a negative error code otherwise.
1256 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1257 unsigned int offset_in_page, void *buf, unsigned int len)
1259 struct mtd_info *mtd = nand_to_mtd(chip);
1264 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1267 if (nand_has_exec_op(chip)) {
1268 if (mtd->writesize > 512)
1269 return nand_lp_exec_read_page_op(chip, page,
1270 offset_in_page, buf,
1273 return nand_sp_exec_read_page_op(chip, page, offset_in_page,
1277 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, offset_in_page, page);
1279 chip->legacy.read_buf(chip, buf, len);
1283 EXPORT_SYMBOL_GPL(nand_read_page_op);
1286 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1287 * @chip: The NAND chip
1288 * @page: parameter page to read
1289 * @buf: buffer used to store the data
1290 * @len: length of the buffer
1292 * This function issues a READ PARAMETER PAGE operation.
1293 * This function does not select/unselect the CS line.
1295 * Returns 0 on success, a negative error code otherwise.
1297 int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1306 if (nand_has_exec_op(chip)) {
1307 const struct nand_sdr_timings *sdr =
1308 nand_get_sdr_timings(nand_get_interface_config(chip));
1309 struct nand_op_instr instrs[] = {
1310 NAND_OP_CMD(NAND_CMD_PARAM, 0),
1311 NAND_OP_ADDR(1, &page, PSEC_TO_NSEC(sdr->tWB_max)),
1312 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1313 PSEC_TO_NSEC(sdr->tRR_min)),
1314 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1316 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1318 /* Drop the DATA_IN instruction if len is set to 0. */
1322 return nand_exec_op(chip, &op);
1325 chip->legacy.cmdfunc(chip, NAND_CMD_PARAM, page, -1);
1326 for (i = 0; i < len; i++)
1327 p[i] = chip->legacy.read_byte(chip);
1333 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1334 * @chip: The NAND chip
1335 * @offset_in_page: offset within the page
1336 * @buf: buffer used to store the data
1337 * @len: length of the buffer
1338 * @force_8bit: force 8-bit bus access
1340 * This function issues a CHANGE READ COLUMN operation.
1341 * This function does not select/unselect the CS line.
1343 * Returns 0 on success, a negative error code otherwise.
1345 int nand_change_read_column_op(struct nand_chip *chip,
1346 unsigned int offset_in_page, void *buf,
1347 unsigned int len, bool force_8bit)
1349 struct mtd_info *mtd = nand_to_mtd(chip);
1354 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1357 /* Small page NANDs do not support column change. */
1358 if (mtd->writesize <= 512)
1361 if (nand_has_exec_op(chip)) {
1362 const struct nand_sdr_timings *sdr =
1363 nand_get_sdr_timings(nand_get_interface_config(chip));
1365 struct nand_op_instr instrs[] = {
1366 NAND_OP_CMD(NAND_CMD_RNDOUT, 0),
1367 NAND_OP_ADDR(2, addrs, 0),
1368 NAND_OP_CMD(NAND_CMD_RNDOUTSTART,
1369 PSEC_TO_NSEC(sdr->tCCS_min)),
1370 NAND_OP_DATA_IN(len, buf, 0),
1372 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1375 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1379 /* Drop the DATA_IN instruction if len is set to 0. */
1383 instrs[3].ctx.data.force_8bit = force_8bit;
1385 return nand_exec_op(chip, &op);
1388 chip->legacy.cmdfunc(chip, NAND_CMD_RNDOUT, offset_in_page, -1);
1390 chip->legacy.read_buf(chip, buf, len);
1394 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1397 * nand_read_oob_op - Do a READ OOB operation
1398 * @chip: The NAND chip
1399 * @page: page to read
1400 * @offset_in_oob: offset within the OOB area
1401 * @buf: buffer used to store the data
1402 * @len: length of the buffer
1404 * This function issues a READ OOB operation.
1405 * This function does not select/unselect the CS line.
1407 * Returns 0 on success, a negative error code otherwise.
1409 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1410 unsigned int offset_in_oob, void *buf, unsigned int len)
1412 struct mtd_info *mtd = nand_to_mtd(chip);
1417 if (offset_in_oob + len > mtd->oobsize)
1420 if (nand_has_exec_op(chip))
1421 return nand_read_page_op(chip, page,
1422 mtd->writesize + offset_in_oob,
1425 chip->legacy.cmdfunc(chip, NAND_CMD_READOOB, offset_in_oob, page);
1427 chip->legacy.read_buf(chip, buf, len);
1431 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1433 static int nand_exec_prog_page_op(struct nand_chip *chip, unsigned int page,
1434 unsigned int offset_in_page, const void *buf,
1435 unsigned int len, bool prog)
1437 const struct nand_sdr_timings *sdr =
1438 nand_get_sdr_timings(nand_get_interface_config(chip));
1439 struct mtd_info *mtd = nand_to_mtd(chip);
1441 struct nand_op_instr instrs[] = {
1443 * The first instruction will be dropped if we're dealing
1444 * with a large page NAND and adjusted if we're dealing
1445 * with a small page NAND and the page offset is > 255.
1447 NAND_OP_CMD(NAND_CMD_READ0, 0),
1448 NAND_OP_CMD(NAND_CMD_SEQIN, 0),
1449 NAND_OP_ADDR(0, addrs, PSEC_TO_NSEC(sdr->tADL_min)),
1450 NAND_OP_DATA_OUT(len, buf, 0),
1451 NAND_OP_CMD(NAND_CMD_PAGEPROG, PSEC_TO_NSEC(sdr->tWB_max)),
1452 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1454 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1455 int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
1462 addrs[naddrs++] = page;
1463 addrs[naddrs++] = page >> 8;
1464 if (chip->options & NAND_ROW_ADDR_3)
1465 addrs[naddrs++] = page >> 16;
1467 instrs[2].ctx.addr.naddrs = naddrs;
1469 /* Drop the last two instructions if we're not programming the page. */
1472 /* Also drop the DATA_OUT instruction if empty. */
1477 if (mtd->writesize <= 512) {
1479 * Small pages need some more tweaking: we have to adjust the
1480 * first instruction depending on the page offset we're trying
1483 if (offset_in_page >= mtd->writesize)
1484 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1485 else if (offset_in_page >= 256 &&
1486 !(chip->options & NAND_BUSWIDTH_16))
1487 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1490 * Drop the first command if we're dealing with a large page
1497 ret = nand_exec_op(chip, &op);
1501 ret = nand_status_op(chip, &status);
1509 * nand_prog_page_begin_op - starts a PROG PAGE operation
1510 * @chip: The NAND chip
1511 * @page: page to write
1512 * @offset_in_page: offset within the page
1513 * @buf: buffer containing the data to write to the page
1514 * @len: length of the buffer
1516 * This function issues the first half of a PROG PAGE operation.
1517 * This function does not select/unselect the CS line.
1519 * Returns 0 on success, a negative error code otherwise.
1521 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1522 unsigned int offset_in_page, const void *buf,
1525 struct mtd_info *mtd = nand_to_mtd(chip);
1530 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1533 if (nand_has_exec_op(chip))
1534 return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1537 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page, page);
1540 chip->legacy.write_buf(chip, buf, len);
1544 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1547 * nand_prog_page_end_op - ends a PROG PAGE operation
1548 * @chip: The NAND chip
1550 * This function issues the second half of a PROG PAGE operation.
1551 * This function does not select/unselect the CS line.
1553 * Returns 0 on success, a negative error code otherwise.
1555 int nand_prog_page_end_op(struct nand_chip *chip)
1560 if (nand_has_exec_op(chip)) {
1561 const struct nand_sdr_timings *sdr =
1562 nand_get_sdr_timings(nand_get_interface_config(chip));
1563 struct nand_op_instr instrs[] = {
1564 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1565 PSEC_TO_NSEC(sdr->tWB_max)),
1566 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1568 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1570 ret = nand_exec_op(chip, &op);
1574 ret = nand_status_op(chip, &status);
1578 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1579 ret = chip->legacy.waitfunc(chip);
1586 if (status & NAND_STATUS_FAIL)
1591 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1594 * nand_prog_page_op - Do a full PROG PAGE operation
1595 * @chip: The NAND chip
1596 * @page: page to write
1597 * @offset_in_page: offset within the page
1598 * @buf: buffer containing the data to write to the page
1599 * @len: length of the buffer
1601 * This function issues a full PROG PAGE operation.
1602 * This function does not select/unselect the CS line.
1604 * Returns 0 on success, a negative error code otherwise.
1606 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1607 unsigned int offset_in_page, const void *buf,
1610 struct mtd_info *mtd = nand_to_mtd(chip);
1616 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1619 if (nand_has_exec_op(chip)) {
1620 status = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1623 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page,
1625 chip->legacy.write_buf(chip, buf, len);
1626 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1627 status = chip->legacy.waitfunc(chip);
1630 if (status & NAND_STATUS_FAIL)
1635 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1638 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1639 * @chip: The NAND chip
1640 * @offset_in_page: offset within the page
1641 * @buf: buffer containing the data to send to the NAND
1642 * @len: length of the buffer
1643 * @force_8bit: force 8-bit bus access
1645 * This function issues a CHANGE WRITE COLUMN operation.
1646 * This function does not select/unselect the CS line.
1648 * Returns 0 on success, a negative error code otherwise.
1650 int nand_change_write_column_op(struct nand_chip *chip,
1651 unsigned int offset_in_page,
1652 const void *buf, unsigned int len,
1655 struct mtd_info *mtd = nand_to_mtd(chip);
1660 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1663 /* Small page NANDs do not support column change. */
1664 if (mtd->writesize <= 512)
1667 if (nand_has_exec_op(chip)) {
1668 const struct nand_sdr_timings *sdr =
1669 nand_get_sdr_timings(nand_get_interface_config(chip));
1671 struct nand_op_instr instrs[] = {
1672 NAND_OP_CMD(NAND_CMD_RNDIN, 0),
1673 NAND_OP_ADDR(2, addrs, PSEC_TO_NSEC(sdr->tCCS_min)),
1674 NAND_OP_DATA_OUT(len, buf, 0),
1676 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1679 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1683 instrs[2].ctx.data.force_8bit = force_8bit;
1685 /* Drop the DATA_OUT instruction if len is set to 0. */
1689 return nand_exec_op(chip, &op);
1692 chip->legacy.cmdfunc(chip, NAND_CMD_RNDIN, offset_in_page, -1);
1694 chip->legacy.write_buf(chip, buf, len);
1698 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1701 * nand_readid_op - Do a READID operation
1702 * @chip: The NAND chip
1703 * @addr: address cycle to pass after the READID command
1704 * @buf: buffer used to store the ID
1705 * @len: length of the buffer
1707 * This function sends a READID command and reads back the ID returned by the
1709 * This function does not select/unselect the CS line.
1711 * Returns 0 on success, a negative error code otherwise.
1713 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1722 if (nand_has_exec_op(chip)) {
1723 const struct nand_sdr_timings *sdr =
1724 nand_get_sdr_timings(nand_get_interface_config(chip));
1725 struct nand_op_instr instrs[] = {
1726 NAND_OP_CMD(NAND_CMD_READID, 0),
1727 NAND_OP_ADDR(1, &addr, PSEC_TO_NSEC(sdr->tADL_min)),
1728 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1730 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1732 /* Drop the DATA_IN instruction if len is set to 0. */
1736 return nand_exec_op(chip, &op);
1739 chip->legacy.cmdfunc(chip, NAND_CMD_READID, addr, -1);
1741 for (i = 0; i < len; i++)
1742 id[i] = chip->legacy.read_byte(chip);
1746 EXPORT_SYMBOL_GPL(nand_readid_op);
1749 * nand_status_op - Do a STATUS operation
1750 * @chip: The NAND chip
1751 * @status: out variable to store the NAND status
1753 * This function sends a STATUS command and reads back the status returned by
1755 * This function does not select/unselect the CS line.
1757 * Returns 0 on success, a negative error code otherwise.
1759 int nand_status_op(struct nand_chip *chip, u8 *status)
1761 if (nand_has_exec_op(chip)) {
1762 const struct nand_sdr_timings *sdr =
1763 nand_get_sdr_timings(nand_get_interface_config(chip));
1764 struct nand_op_instr instrs[] = {
1765 NAND_OP_CMD(NAND_CMD_STATUS,
1766 PSEC_TO_NSEC(sdr->tADL_min)),
1767 NAND_OP_8BIT_DATA_IN(1, status, 0),
1769 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1774 return nand_exec_op(chip, &op);
1777 chip->legacy.cmdfunc(chip, NAND_CMD_STATUS, -1, -1);
1779 *status = chip->legacy.read_byte(chip);
1783 EXPORT_SYMBOL_GPL(nand_status_op);
1786 * nand_exit_status_op - Exit a STATUS operation
1787 * @chip: The NAND chip
1789 * This function sends a READ0 command to cancel the effect of the STATUS
1790 * command to avoid reading only the status until a new read command is sent.
1792 * This function does not select/unselect the CS line.
1794 * Returns 0 on success, a negative error code otherwise.
1796 int nand_exit_status_op(struct nand_chip *chip)
1798 if (nand_has_exec_op(chip)) {
1799 struct nand_op_instr instrs[] = {
1800 NAND_OP_CMD(NAND_CMD_READ0, 0),
1802 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1804 return nand_exec_op(chip, &op);
1807 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, -1, -1);
1813 * nand_erase_op - Do an erase operation
1814 * @chip: The NAND chip
1815 * @eraseblock: block to erase
1817 * This function sends an ERASE command and waits for the NAND to be ready
1819 * This function does not select/unselect the CS line.
1821 * Returns 0 on success, a negative error code otherwise.
1823 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1825 unsigned int page = eraseblock <<
1826 (chip->phys_erase_shift - chip->page_shift);
1830 if (nand_has_exec_op(chip)) {
1831 const struct nand_sdr_timings *sdr =
1832 nand_get_sdr_timings(nand_get_interface_config(chip));
1833 u8 addrs[3] = { page, page >> 8, page >> 16 };
1834 struct nand_op_instr instrs[] = {
1835 NAND_OP_CMD(NAND_CMD_ERASE1, 0),
1836 NAND_OP_ADDR(2, addrs, 0),
1837 NAND_OP_CMD(NAND_CMD_ERASE2,
1838 PSEC_TO_MSEC(sdr->tWB_max)),
1839 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tBERS_max), 0),
1841 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1843 if (chip->options & NAND_ROW_ADDR_3)
1844 instrs[1].ctx.addr.naddrs++;
1846 ret = nand_exec_op(chip, &op);
1850 ret = nand_status_op(chip, &status);
1854 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE1, -1, page);
1855 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE2, -1, -1);
1857 ret = chip->legacy.waitfunc(chip);
1864 if (status & NAND_STATUS_FAIL)
1869 EXPORT_SYMBOL_GPL(nand_erase_op);
1872 * nand_set_features_op - Do a SET FEATURES operation
1873 * @chip: The NAND chip
1874 * @feature: feature id
1875 * @data: 4 bytes of data
1877 * This function sends a SET FEATURES command and waits for the NAND to be
1878 * ready before returning.
1879 * This function does not select/unselect the CS line.
1881 * Returns 0 on success, a negative error code otherwise.
1883 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1886 const u8 *params = data;
1889 if (nand_has_exec_op(chip)) {
1890 const struct nand_sdr_timings *sdr =
1891 nand_get_sdr_timings(nand_get_interface_config(chip));
1892 struct nand_op_instr instrs[] = {
1893 NAND_OP_CMD(NAND_CMD_SET_FEATURES, 0),
1894 NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tADL_min)),
1895 NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
1896 PSEC_TO_NSEC(sdr->tWB_max)),
1897 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max), 0),
1899 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1901 return nand_exec_op(chip, &op);
1904 chip->legacy.cmdfunc(chip, NAND_CMD_SET_FEATURES, feature, -1);
1905 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1906 chip->legacy.write_byte(chip, params[i]);
1908 ret = chip->legacy.waitfunc(chip);
1912 if (ret & NAND_STATUS_FAIL)
1919 * nand_get_features_op - Do a GET FEATURES operation
1920 * @chip: The NAND chip
1921 * @feature: feature id
1922 * @data: 4 bytes of data
1924 * This function sends a GET FEATURES command and waits for the NAND to be
1925 * ready before returning.
1926 * This function does not select/unselect the CS line.
1928 * Returns 0 on success, a negative error code otherwise.
1930 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1936 if (nand_has_exec_op(chip)) {
1937 const struct nand_sdr_timings *sdr =
1938 nand_get_sdr_timings(nand_get_interface_config(chip));
1939 struct nand_op_instr instrs[] = {
1940 NAND_OP_CMD(NAND_CMD_GET_FEATURES, 0),
1941 NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tWB_max)),
1942 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max),
1943 PSEC_TO_NSEC(sdr->tRR_min)),
1944 NAND_OP_8BIT_DATA_IN(ONFI_SUBFEATURE_PARAM_LEN,
1947 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1949 return nand_exec_op(chip, &op);
1952 chip->legacy.cmdfunc(chip, NAND_CMD_GET_FEATURES, feature, -1);
1953 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1954 params[i] = chip->legacy.read_byte(chip);
1959 static int nand_wait_rdy_op(struct nand_chip *chip, unsigned int timeout_ms,
1960 unsigned int delay_ns)
1962 if (nand_has_exec_op(chip)) {
1963 struct nand_op_instr instrs[] = {
1964 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(timeout_ms),
1965 PSEC_TO_NSEC(delay_ns)),
1967 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1969 return nand_exec_op(chip, &op);
1972 /* Apply delay or wait for ready/busy pin */
1973 if (!chip->legacy.dev_ready)
1974 udelay(chip->legacy.chip_delay);
1976 nand_wait_ready(chip);
1982 * nand_reset_op - Do a reset operation
1983 * @chip: The NAND chip
1985 * This function sends a RESET command and waits for the NAND to be ready
1987 * This function does not select/unselect the CS line.
1989 * Returns 0 on success, a negative error code otherwise.
1991 int nand_reset_op(struct nand_chip *chip)
1993 if (nand_has_exec_op(chip)) {
1994 const struct nand_sdr_timings *sdr =
1995 nand_get_sdr_timings(nand_get_interface_config(chip));
1996 struct nand_op_instr instrs[] = {
1997 NAND_OP_CMD(NAND_CMD_RESET, PSEC_TO_NSEC(sdr->tWB_max)),
1998 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tRST_max), 0),
2000 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2002 return nand_exec_op(chip, &op);
2005 chip->legacy.cmdfunc(chip, NAND_CMD_RESET, -1, -1);
2009 EXPORT_SYMBOL_GPL(nand_reset_op);
2012 * nand_read_data_op - Read data from the NAND
2013 * @chip: The NAND chip
2014 * @buf: buffer used to store the data
2015 * @len: length of the buffer
2016 * @force_8bit: force 8-bit bus access
2017 * @check_only: do not actually run the command, only checks if the
2018 * controller driver supports it
2020 * This function does a raw data read on the bus. Usually used after launching
2021 * another NAND operation like nand_read_page_op().
2022 * This function does not select/unselect the CS line.
2024 * Returns 0 on success, a negative error code otherwise.
2026 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
2027 bool force_8bit, bool check_only)
2032 if (nand_has_exec_op(chip)) {
2033 struct nand_op_instr instrs[] = {
2034 NAND_OP_DATA_IN(len, buf, 0),
2036 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2038 instrs[0].ctx.data.force_8bit = force_8bit;
2041 return nand_check_op(chip, &op);
2043 return nand_exec_op(chip, &op);
2053 for (i = 0; i < len; i++)
2054 p[i] = chip->legacy.read_byte(chip);
2056 chip->legacy.read_buf(chip, buf, len);
2061 EXPORT_SYMBOL_GPL(nand_read_data_op);
2064 * nand_write_data_op - Write data from the NAND
2065 * @chip: The NAND chip
2066 * @buf: buffer containing the data to send on the bus
2067 * @len: length of the buffer
2068 * @force_8bit: force 8-bit bus access
2070 * This function does a raw data write on the bus. Usually used after launching
2071 * another NAND operation like nand_write_page_begin_op().
2072 * This function does not select/unselect the CS line.
2074 * Returns 0 on success, a negative error code otherwise.
2076 int nand_write_data_op(struct nand_chip *chip, const void *buf,
2077 unsigned int len, bool force_8bit)
2082 if (nand_has_exec_op(chip)) {
2083 struct nand_op_instr instrs[] = {
2084 NAND_OP_DATA_OUT(len, buf, 0),
2086 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2088 instrs[0].ctx.data.force_8bit = force_8bit;
2090 return nand_exec_op(chip, &op);
2097 for (i = 0; i < len; i++)
2098 chip->legacy.write_byte(chip, p[i]);
2100 chip->legacy.write_buf(chip, buf, len);
2105 EXPORT_SYMBOL_GPL(nand_write_data_op);
2108 * struct nand_op_parser_ctx - Context used by the parser
2109 * @instrs: array of all the instructions that must be addressed
2110 * @ninstrs: length of the @instrs array
2111 * @subop: Sub-operation to be passed to the NAND controller
2113 * This structure is used by the core to split NAND operations into
2114 * sub-operations that can be handled by the NAND controller.
2116 struct nand_op_parser_ctx {
2117 const struct nand_op_instr *instrs;
2118 unsigned int ninstrs;
2119 struct nand_subop subop;
2123 * nand_op_parser_must_split_instr - Checks if an instruction must be split
2124 * @pat: the parser pattern element that matches @instr
2125 * @instr: pointer to the instruction to check
2126 * @start_offset: this is an in/out parameter. If @instr has already been
2127 * split, then @start_offset is the offset from which to start
2128 * (either an address cycle or an offset in the data buffer).
2129 * Conversely, if the function returns true (ie. instr must be
2130 * split), this parameter is updated to point to the first
2131 * data/address cycle that has not been taken care of.
2133 * Some NAND controllers are limited and cannot send X address cycles with a
2134 * unique operation, or cannot read/write more than Y bytes at the same time.
2135 * In this case, split the instruction that does not fit in a single
2136 * controller-operation into two or more chunks.
2138 * Returns true if the instruction must be split, false otherwise.
2139 * The @start_offset parameter is also updated to the offset at which the next
2140 * bundle of instruction must start (if an address or a data instruction).
2143 nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat,
2144 const struct nand_op_instr *instr,
2145 unsigned int *start_offset)
2147 switch (pat->type) {
2148 case NAND_OP_ADDR_INSTR:
2149 if (!pat->ctx.addr.maxcycles)
2152 if (instr->ctx.addr.naddrs - *start_offset >
2153 pat->ctx.addr.maxcycles) {
2154 *start_offset += pat->ctx.addr.maxcycles;
2159 case NAND_OP_DATA_IN_INSTR:
2160 case NAND_OP_DATA_OUT_INSTR:
2161 if (!pat->ctx.data.maxlen)
2164 if (instr->ctx.data.len - *start_offset >
2165 pat->ctx.data.maxlen) {
2166 *start_offset += pat->ctx.data.maxlen;
2179 * nand_op_parser_match_pat - Checks if a pattern matches the instructions
2180 * remaining in the parser context
2181 * @pat: the pattern to test
2182 * @ctx: the parser context structure to match with the pattern @pat
2184 * Check if @pat matches the set or a sub-set of instructions remaining in @ctx.
2185 * Returns true if this is the case, false ortherwise. When true is returned,
2186 * @ctx->subop is updated with the set of instructions to be passed to the
2187 * controller driver.
2190 nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
2191 struct nand_op_parser_ctx *ctx)
2193 unsigned int instr_offset = ctx->subop.first_instr_start_off;
2194 const struct nand_op_instr *end = ctx->instrs + ctx->ninstrs;
2195 const struct nand_op_instr *instr = ctx->subop.instrs;
2196 unsigned int i, ninstrs;
2198 for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
2200 * The pattern instruction does not match the operation
2201 * instruction. If the instruction is marked optional in the
2202 * pattern definition, we skip the pattern element and continue
2203 * to the next one. If the element is mandatory, there's no
2204 * match and we can return false directly.
2206 if (instr->type != pat->elems[i].type) {
2207 if (!pat->elems[i].optional)
2214 * Now check the pattern element constraints. If the pattern is
2215 * not able to handle the whole instruction in a single step,
2216 * we have to split it.
2217 * The last_instr_end_off value comes back updated to point to
2218 * the position where we have to split the instruction (the
2219 * start of the next subop chunk).
2221 if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
2234 * This can happen if all instructions of a pattern are optional.
2235 * Still, if there's not at least one instruction handled by this
2236 * pattern, this is not a match, and we should try the next one (if
2243 * We had a match on the pattern head, but the pattern may be longer
2244 * than the instructions we're asked to execute. We need to make sure
2245 * there's no mandatory elements in the pattern tail.
2247 for (; i < pat->nelems; i++) {
2248 if (!pat->elems[i].optional)
2253 * We have a match: update the subop structure accordingly and return
2256 ctx->subop.ninstrs = ninstrs;
2257 ctx->subop.last_instr_end_off = instr_offset;
2262 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
2263 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2265 const struct nand_op_instr *instr;
2269 pr_debug("executing subop (CS%d):\n", ctx->subop.cs);
2271 for (i = 0; i < ctx->ninstrs; i++) {
2272 instr = &ctx->instrs[i];
2274 if (instr == &ctx->subop.instrs[0])
2277 nand_op_trace(prefix, instr);
2279 if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
2284 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2290 static int nand_op_parser_cmp_ctx(const struct nand_op_parser_ctx *a,
2291 const struct nand_op_parser_ctx *b)
2293 if (a->subop.ninstrs < b->subop.ninstrs)
2295 else if (a->subop.ninstrs > b->subop.ninstrs)
2298 if (a->subop.last_instr_end_off < b->subop.last_instr_end_off)
2300 else if (a->subop.last_instr_end_off > b->subop.last_instr_end_off)
2307 * nand_op_parser_exec_op - exec_op parser
2308 * @chip: the NAND chip
2309 * @parser: patterns description provided by the controller driver
2310 * @op: the NAND operation to address
2311 * @check_only: when true, the function only checks if @op can be handled but
2312 * does not execute the operation
2314 * Helper function designed to ease integration of NAND controller drivers that
2315 * only support a limited set of instruction sequences. The supported sequences
2316 * are described in @parser, and the framework takes care of splitting @op into
2317 * multiple sub-operations (if required) and pass them back to the ->exec()
2318 * callback of the matching pattern if @check_only is set to false.
2320 * NAND controller drivers should call this function from their own ->exec_op()
2323 * Returns 0 on success, a negative error code otherwise. A failure can be
2324 * caused by an unsupported operation (none of the supported patterns is able
2325 * to handle the requested operation), or an error returned by one of the
2326 * matching pattern->exec() hook.
2328 int nand_op_parser_exec_op(struct nand_chip *chip,
2329 const struct nand_op_parser *parser,
2330 const struct nand_operation *op, bool check_only)
2332 struct nand_op_parser_ctx ctx = {
2334 .subop.instrs = op->instrs,
2335 .instrs = op->instrs,
2336 .ninstrs = op->ninstrs,
2340 while (ctx.subop.instrs < op->instrs + op->ninstrs) {
2341 const struct nand_op_parser_pattern *pattern;
2342 struct nand_op_parser_ctx best_ctx;
2343 int ret, best_pattern = -1;
2345 for (i = 0; i < parser->npatterns; i++) {
2346 struct nand_op_parser_ctx test_ctx = ctx;
2348 pattern = &parser->patterns[i];
2349 if (!nand_op_parser_match_pat(pattern, &test_ctx))
2352 if (best_pattern >= 0 &&
2353 nand_op_parser_cmp_ctx(&test_ctx, &best_ctx) <= 0)
2357 best_ctx = test_ctx;
2360 if (best_pattern < 0) {
2361 pr_debug("->exec_op() parser: pattern not found!\n");
2366 nand_op_parser_trace(&ctx);
2369 pattern = &parser->patterns[best_pattern];
2370 ret = pattern->exec(chip, &ctx.subop);
2376 * Update the context structure by pointing to the start of the
2379 ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
2380 if (ctx.subop.last_instr_end_off)
2381 ctx.subop.instrs -= 1;
2383 ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
2388 EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
2390 static bool nand_instr_is_data(const struct nand_op_instr *instr)
2392 return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
2393 instr->type == NAND_OP_DATA_OUT_INSTR);
2396 static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
2397 unsigned int instr_idx)
2399 return subop && instr_idx < subop->ninstrs;
2402 static unsigned int nand_subop_get_start_off(const struct nand_subop *subop,
2403 unsigned int instr_idx)
2408 return subop->first_instr_start_off;
2412 * nand_subop_get_addr_start_off - Get the start offset in an address array
2413 * @subop: The entire sub-operation
2414 * @instr_idx: Index of the instruction inside the sub-operation
2416 * During driver development, one could be tempted to directly use the
2417 * ->addr.addrs field of address instructions. This is wrong as address
2418 * instructions might be split.
2420 * Given an address instruction, returns the offset of the first cycle to issue.
2422 unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
2423 unsigned int instr_idx)
2425 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2426 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2429 return nand_subop_get_start_off(subop, instr_idx);
2431 EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
2434 * nand_subop_get_num_addr_cyc - Get the remaining address cycles to assert
2435 * @subop: The entire sub-operation
2436 * @instr_idx: Index of the instruction inside the sub-operation
2438 * During driver development, one could be tempted to directly use the
2439 * ->addr->naddrs field of a data instruction. This is wrong as instructions
2442 * Given an address instruction, returns the number of address cycle to issue.
2444 unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
2445 unsigned int instr_idx)
2447 int start_off, end_off;
2449 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2450 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2453 start_off = nand_subop_get_addr_start_off(subop, instr_idx);
2455 if (instr_idx == subop->ninstrs - 1 &&
2456 subop->last_instr_end_off)
2457 end_off = subop->last_instr_end_off;
2459 end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
2461 return end_off - start_off;
2463 EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
2466 * nand_subop_get_data_start_off - Get the start offset in a data array
2467 * @subop: The entire sub-operation
2468 * @instr_idx: Index of the instruction inside the sub-operation
2470 * During driver development, one could be tempted to directly use the
2471 * ->data->buf.{in,out} field of data instructions. This is wrong as data
2472 * instructions might be split.
2474 * Given a data instruction, returns the offset to start from.
2476 unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
2477 unsigned int instr_idx)
2479 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2480 !nand_instr_is_data(&subop->instrs[instr_idx])))
2483 return nand_subop_get_start_off(subop, instr_idx);
2485 EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
2488 * nand_subop_get_data_len - Get the number of bytes to retrieve
2489 * @subop: The entire sub-operation
2490 * @instr_idx: Index of the instruction inside the sub-operation
2492 * During driver development, one could be tempted to directly use the
2493 * ->data->len field of a data instruction. This is wrong as data instructions
2496 * Returns the length of the chunk of data to send/receive.
2498 unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
2499 unsigned int instr_idx)
2501 int start_off = 0, end_off;
2503 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2504 !nand_instr_is_data(&subop->instrs[instr_idx])))
2507 start_off = nand_subop_get_data_start_off(subop, instr_idx);
2509 if (instr_idx == subop->ninstrs - 1 &&
2510 subop->last_instr_end_off)
2511 end_off = subop->last_instr_end_off;
2513 end_off = subop->instrs[instr_idx].ctx.data.len;
2515 return end_off - start_off;
2517 EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
2520 * nand_reset - Reset and initialize a NAND device
2521 * @chip: The NAND chip
2522 * @chipnr: Internal die id
2524 * Save the timings data structure, then apply SDR timings mode 0 (see
2525 * nand_reset_interface for details), do the reset operation, and apply
2526 * back the previous timings.
2528 * Returns 0 on success, a negative error code otherwise.
2530 int nand_reset(struct nand_chip *chip, int chipnr)
2534 ret = nand_reset_interface(chip, chipnr);
2539 * The CS line has to be released before we can apply the new NAND
2540 * interface settings, hence this weird nand_select_target()
2541 * nand_deselect_target() dance.
2543 nand_select_target(chip, chipnr);
2544 ret = nand_reset_op(chip);
2545 nand_deselect_target(chip);
2549 ret = nand_setup_interface(chip, chipnr);
2555 EXPORT_SYMBOL_GPL(nand_reset);
2558 * nand_get_features - wrapper to perform a GET_FEATURE
2559 * @chip: NAND chip info structure
2560 * @addr: feature address
2561 * @subfeature_param: the subfeature parameters, a four bytes array
2563 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2564 * operation cannot be handled.
2566 int nand_get_features(struct nand_chip *chip, int addr,
2567 u8 *subfeature_param)
2569 if (!nand_supports_get_features(chip, addr))
2572 if (chip->legacy.get_features)
2573 return chip->legacy.get_features(chip, addr, subfeature_param);
2575 return nand_get_features_op(chip, addr, subfeature_param);
2579 * nand_set_features - wrapper to perform a SET_FEATURE
2580 * @chip: NAND chip info structure
2581 * @addr: feature address
2582 * @subfeature_param: the subfeature parameters, a four bytes array
2584 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2585 * operation cannot be handled.
2587 int nand_set_features(struct nand_chip *chip, int addr,
2588 u8 *subfeature_param)
2590 if (!nand_supports_set_features(chip, addr))
2593 if (chip->legacy.set_features)
2594 return chip->legacy.set_features(chip, addr, subfeature_param);
2596 return nand_set_features_op(chip, addr, subfeature_param);
2600 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
2601 * @buf: buffer to test
2602 * @len: buffer length
2603 * @bitflips_threshold: maximum number of bitflips
2605 * Check if a buffer contains only 0xff, which means the underlying region
2606 * has been erased and is ready to be programmed.
2607 * The bitflips_threshold specify the maximum number of bitflips before
2608 * considering the region is not erased.
2609 * Note: The logic of this function has been extracted from the memweight
2610 * implementation, except that nand_check_erased_buf function exit before
2611 * testing the whole buffer if the number of bitflips exceed the
2612 * bitflips_threshold value.
2614 * Returns a positive number of bitflips less than or equal to
2615 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2618 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
2620 const unsigned char *bitmap = buf;
2624 for (; len && ((uintptr_t)bitmap) % sizeof(long);
2626 weight = hweight8(*bitmap);
2627 bitflips += BITS_PER_BYTE - weight;
2628 if (unlikely(bitflips > bitflips_threshold))
2632 for (; len >= sizeof(long);
2633 len -= sizeof(long), bitmap += sizeof(long)) {
2634 unsigned long d = *((unsigned long *)bitmap);
2637 weight = hweight_long(d);
2638 bitflips += BITS_PER_LONG - weight;
2639 if (unlikely(bitflips > bitflips_threshold))
2643 for (; len > 0; len--, bitmap++) {
2644 weight = hweight8(*bitmap);
2645 bitflips += BITS_PER_BYTE - weight;
2646 if (unlikely(bitflips > bitflips_threshold))
2654 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
2656 * @data: data buffer to test
2657 * @datalen: data length
2659 * @ecclen: ECC length
2660 * @extraoob: extra OOB buffer
2661 * @extraooblen: extra OOB length
2662 * @bitflips_threshold: maximum number of bitflips
2664 * Check if a data buffer and its associated ECC and OOB data contains only
2665 * 0xff pattern, which means the underlying region has been erased and is
2666 * ready to be programmed.
2667 * The bitflips_threshold specify the maximum number of bitflips before
2668 * considering the region as not erased.
2671 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
2672 * different from the NAND page size. When fixing bitflips, ECC engines will
2673 * report the number of errors per chunk, and the NAND core infrastructure
2674 * expect you to return the maximum number of bitflips for the whole page.
2675 * This is why you should always use this function on a single chunk and
2676 * not on the whole page. After checking each chunk you should update your
2677 * max_bitflips value accordingly.
2678 * 2/ When checking for bitflips in erased pages you should not only check
2679 * the payload data but also their associated ECC data, because a user might
2680 * have programmed almost all bits to 1 but a few. In this case, we
2681 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
2683 * 3/ The extraoob argument is optional, and should be used if some of your OOB
2684 * data are protected by the ECC engine.
2685 * It could also be used if you support subpages and want to attach some
2686 * extra OOB data to an ECC chunk.
2688 * Returns a positive number of bitflips less than or equal to
2689 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2690 * threshold. In case of success, the passed buffers are filled with 0xff.
2692 int nand_check_erased_ecc_chunk(void *data, int datalen,
2693 void *ecc, int ecclen,
2694 void *extraoob, int extraooblen,
2695 int bitflips_threshold)
2697 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
2699 data_bitflips = nand_check_erased_buf(data, datalen,
2700 bitflips_threshold);
2701 if (data_bitflips < 0)
2702 return data_bitflips;
2704 bitflips_threshold -= data_bitflips;
2706 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
2707 if (ecc_bitflips < 0)
2708 return ecc_bitflips;
2710 bitflips_threshold -= ecc_bitflips;
2712 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
2713 bitflips_threshold);
2714 if (extraoob_bitflips < 0)
2715 return extraoob_bitflips;
2718 memset(data, 0xff, datalen);
2721 memset(ecc, 0xff, ecclen);
2723 if (extraoob_bitflips)
2724 memset(extraoob, 0xff, extraooblen);
2726 return data_bitflips + ecc_bitflips + extraoob_bitflips;
2728 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
2731 * nand_read_page_raw_notsupp - dummy read raw page function
2732 * @chip: nand chip info structure
2733 * @buf: buffer to store read data
2734 * @oob_required: caller requires OOB data read to chip->oob_poi
2735 * @page: page number to read
2737 * Returns -ENOTSUPP unconditionally.
2739 int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf,
2740 int oob_required, int page)
2746 * nand_read_page_raw - [INTERN] read raw page data without ecc
2747 * @chip: nand chip info structure
2748 * @buf: buffer to store read data
2749 * @oob_required: caller requires OOB data read to chip->oob_poi
2750 * @page: page number to read
2752 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2754 int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
2757 struct mtd_info *mtd = nand_to_mtd(chip);
2760 ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
2765 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
2773 EXPORT_SYMBOL(nand_read_page_raw);
2776 * nand_monolithic_read_page_raw - Monolithic page read in raw mode
2777 * @chip: NAND chip info structure
2778 * @buf: buffer to store read data
2779 * @oob_required: caller requires OOB data read to chip->oob_poi
2780 * @page: page number to read
2782 * This is a raw page read, ie. without any error detection/correction.
2783 * Monolithic means we are requesting all the relevant data (main plus
2784 * eventually OOB) to be loaded in the NAND cache and sent over the
2785 * bus (from the NAND chip to the NAND controller) in a single
2786 * operation. This is an alternative to nand_read_page_raw(), which
2787 * first reads the main data, and if the OOB data is requested too,
2788 * then reads more data on the bus.
2790 int nand_monolithic_read_page_raw(struct nand_chip *chip, u8 *buf,
2791 int oob_required, int page)
2793 struct mtd_info *mtd = nand_to_mtd(chip);
2794 unsigned int size = mtd->writesize;
2799 size += mtd->oobsize;
2801 if (buf != chip->data_buf)
2802 read_buf = nand_get_data_buf(chip);
2805 ret = nand_read_page_op(chip, page, 0, read_buf, size);
2809 if (buf != chip->data_buf)
2810 memcpy(buf, read_buf, mtd->writesize);
2814 EXPORT_SYMBOL(nand_monolithic_read_page_raw);
2817 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
2818 * @chip: nand chip info structure
2819 * @buf: buffer to store read data
2820 * @oob_required: caller requires OOB data read to chip->oob_poi
2821 * @page: page number to read
2823 * We need a special oob layout and handling even when OOB isn't used.
2825 static int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf,
2826 int oob_required, int page)
2828 struct mtd_info *mtd = nand_to_mtd(chip);
2829 int eccsize = chip->ecc.size;
2830 int eccbytes = chip->ecc.bytes;
2831 uint8_t *oob = chip->oob_poi;
2832 int steps, size, ret;
2834 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2838 for (steps = chip->ecc.steps; steps > 0; steps--) {
2839 ret = nand_read_data_op(chip, buf, eccsize, false, false);
2845 if (chip->ecc.prepad) {
2846 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2851 oob += chip->ecc.prepad;
2854 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
2860 if (chip->ecc.postpad) {
2861 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2866 oob += chip->ecc.postpad;
2870 size = mtd->oobsize - (oob - chip->oob_poi);
2872 ret = nand_read_data_op(chip, oob, size, false, false);
2881 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
2882 * @chip: nand chip info structure
2883 * @buf: buffer to store read data
2884 * @oob_required: caller requires OOB data read to chip->oob_poi
2885 * @page: page number to read
2887 static int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf,
2888 int oob_required, int page)
2890 struct mtd_info *mtd = nand_to_mtd(chip);
2891 int i, eccsize = chip->ecc.size, ret;
2892 int eccbytes = chip->ecc.bytes;
2893 int eccsteps = chip->ecc.steps;
2895 uint8_t *ecc_calc = chip->ecc.calc_buf;
2896 uint8_t *ecc_code = chip->ecc.code_buf;
2897 unsigned int max_bitflips = 0;
2899 chip->ecc.read_page_raw(chip, buf, 1, page);
2901 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2902 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2904 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2909 eccsteps = chip->ecc.steps;
2912 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2915 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
2917 mtd->ecc_stats.failed++;
2919 mtd->ecc_stats.corrected += stat;
2920 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2923 return max_bitflips;
2927 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
2928 * @chip: nand chip info structure
2929 * @data_offs: offset of requested data within the page
2930 * @readlen: data length
2931 * @bufpoi: buffer to store read data
2932 * @page: page number to read
2934 static int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs,
2935 uint32_t readlen, uint8_t *bufpoi, int page)
2937 struct mtd_info *mtd = nand_to_mtd(chip);
2938 int start_step, end_step, num_steps, ret;
2940 int data_col_addr, i, gaps = 0;
2941 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
2942 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
2943 int index, section = 0;
2944 unsigned int max_bitflips = 0;
2945 struct mtd_oob_region oobregion = { };
2947 /* Column address within the page aligned to ECC size (256bytes) */
2948 start_step = data_offs / chip->ecc.size;
2949 end_step = (data_offs + readlen - 1) / chip->ecc.size;
2950 num_steps = end_step - start_step + 1;
2951 index = start_step * chip->ecc.bytes;
2953 /* Data size aligned to ECC ecc.size */
2954 datafrag_len = num_steps * chip->ecc.size;
2955 eccfrag_len = num_steps * chip->ecc.bytes;
2957 data_col_addr = start_step * chip->ecc.size;
2958 /* If we read not a page aligned data */
2959 p = bufpoi + data_col_addr;
2960 ret = nand_read_page_op(chip, page, data_col_addr, p, datafrag_len);
2965 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
2966 chip->ecc.calculate(chip, p, &chip->ecc.calc_buf[i]);
2969 * The performance is faster if we position offsets according to
2970 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
2972 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
2976 if (oobregion.length < eccfrag_len)
2980 ret = nand_change_read_column_op(chip, mtd->writesize,
2981 chip->oob_poi, mtd->oobsize,
2987 * Send the command to read the particular ECC bytes take care
2988 * about buswidth alignment in read_buf.
2990 aligned_pos = oobregion.offset & ~(busw - 1);
2991 aligned_len = eccfrag_len;
2992 if (oobregion.offset & (busw - 1))
2994 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
2998 ret = nand_change_read_column_op(chip,
2999 mtd->writesize + aligned_pos,
3000 &chip->oob_poi[aligned_pos],
3001 aligned_len, false);
3006 ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
3007 chip->oob_poi, index, eccfrag_len);
3011 p = bufpoi + data_col_addr;
3012 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
3015 stat = chip->ecc.correct(chip, p, &chip->ecc.code_buf[i],
3016 &chip->ecc.calc_buf[i]);
3017 if (stat == -EBADMSG &&
3018 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3019 /* check for empty pages with bitflips */
3020 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3021 &chip->ecc.code_buf[i],
3024 chip->ecc.strength);
3028 mtd->ecc_stats.failed++;
3030 mtd->ecc_stats.corrected += stat;
3031 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3034 return max_bitflips;
3038 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
3039 * @chip: nand chip info structure
3040 * @buf: buffer to store read data
3041 * @oob_required: caller requires OOB data read to chip->oob_poi
3042 * @page: page number to read
3044 * Not for syndrome calculating ECC controllers which need a special oob layout.
3046 static int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf,
3047 int oob_required, int page)
3049 struct mtd_info *mtd = nand_to_mtd(chip);
3050 int i, eccsize = chip->ecc.size, ret;
3051 int eccbytes = chip->ecc.bytes;
3052 int eccsteps = chip->ecc.steps;
3054 uint8_t *ecc_calc = chip->ecc.calc_buf;
3055 uint8_t *ecc_code = chip->ecc.code_buf;
3056 unsigned int max_bitflips = 0;
3058 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3062 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3063 chip->ecc.hwctl(chip, NAND_ECC_READ);
3065 ret = nand_read_data_op(chip, p, eccsize, false, false);
3069 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3072 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false,
3077 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3082 eccsteps = chip->ecc.steps;
3085 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3088 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
3089 if (stat == -EBADMSG &&
3090 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3091 /* check for empty pages with bitflips */
3092 stat = nand_check_erased_ecc_chunk(p, eccsize,
3093 &ecc_code[i], eccbytes,
3095 chip->ecc.strength);
3099 mtd->ecc_stats.failed++;
3101 mtd->ecc_stats.corrected += stat;
3102 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3105 return max_bitflips;
3109 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
3110 * @chip: nand chip info structure
3111 * @buf: buffer to store read data
3112 * @oob_required: caller requires OOB data read to chip->oob_poi
3113 * @page: page number to read
3115 * The hw generator calculates the error syndrome automatically. Therefore we
3116 * need a special oob layout and handling.
3118 static int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf,
3119 int oob_required, int page)
3121 struct mtd_info *mtd = nand_to_mtd(chip);
3122 int ret, i, eccsize = chip->ecc.size;
3123 int eccbytes = chip->ecc.bytes;
3124 int eccsteps = chip->ecc.steps;
3125 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
3127 uint8_t *oob = chip->oob_poi;
3128 unsigned int max_bitflips = 0;
3130 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3134 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3137 chip->ecc.hwctl(chip, NAND_ECC_READ);
3139 ret = nand_read_data_op(chip, p, eccsize, false, false);
3143 if (chip->ecc.prepad) {
3144 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3149 oob += chip->ecc.prepad;
3152 chip->ecc.hwctl(chip, NAND_ECC_READSYN);
3154 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
3158 stat = chip->ecc.correct(chip, p, oob, NULL);
3162 if (chip->ecc.postpad) {
3163 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3168 oob += chip->ecc.postpad;
3171 if (stat == -EBADMSG &&
3172 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3173 /* check for empty pages with bitflips */
3174 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3178 chip->ecc.strength);
3182 mtd->ecc_stats.failed++;
3184 mtd->ecc_stats.corrected += stat;
3185 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3189 /* Calculate remaining oob bytes */
3190 i = mtd->oobsize - (oob - chip->oob_poi);
3192 ret = nand_read_data_op(chip, oob, i, false, false);
3197 return max_bitflips;
3201 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
3202 * @chip: NAND chip object
3203 * @oob: oob destination address
3204 * @ops: oob ops structure
3205 * @len: size of oob to transfer
3207 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
3208 struct mtd_oob_ops *ops, size_t len)
3210 struct mtd_info *mtd = nand_to_mtd(chip);
3213 switch (ops->mode) {
3215 case MTD_OPS_PLACE_OOB:
3217 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
3220 case MTD_OPS_AUTO_OOB:
3221 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
3233 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
3234 * @chip: NAND chip object
3235 * @retry_mode: the retry mode to use
3237 * Some vendors supply a special command to shift the Vt threshold, to be used
3238 * when there are too many bitflips in a page (i.e., ECC error). After setting
3239 * a new threshold, the host should retry reading the page.
3241 static int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
3243 pr_debug("setting READ RETRY mode %d\n", retry_mode);
3245 if (retry_mode >= chip->read_retries)
3248 if (!chip->ops.setup_read_retry)
3251 return chip->ops.setup_read_retry(chip, retry_mode);
3254 static void nand_wait_readrdy(struct nand_chip *chip)
3256 const struct nand_sdr_timings *sdr;
3258 if (!(chip->options & NAND_NEED_READRDY))
3261 sdr = nand_get_sdr_timings(nand_get_interface_config(chip));
3262 WARN_ON(nand_wait_rdy_op(chip, PSEC_TO_MSEC(sdr->tR_max), 0));
3266 * nand_do_read_ops - [INTERN] Read data with ECC
3267 * @chip: NAND chip object
3268 * @from: offset to read from
3269 * @ops: oob ops structure
3271 * Internal function. Called with chip held.
3273 static int nand_do_read_ops(struct nand_chip *chip, loff_t from,
3274 struct mtd_oob_ops *ops)
3276 int chipnr, page, realpage, col, bytes, aligned, oob_required;
3277 struct mtd_info *mtd = nand_to_mtd(chip);
3279 uint32_t readlen = ops->len;
3280 uint32_t oobreadlen = ops->ooblen;
3281 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
3283 uint8_t *bufpoi, *oob, *buf;
3285 unsigned int max_bitflips = 0;
3287 bool ecc_fail = false;
3289 chipnr = (int)(from >> chip->chip_shift);
3290 nand_select_target(chip, chipnr);
3292 realpage = (int)(from >> chip->page_shift);
3293 page = realpage & chip->pagemask;
3295 col = (int)(from & (mtd->writesize - 1));
3299 oob_required = oob ? 1 : 0;
3302 struct mtd_ecc_stats ecc_stats = mtd->ecc_stats;
3304 bytes = min(mtd->writesize - col, readlen);
3305 aligned = (bytes == mtd->writesize);
3309 else if (chip->options & NAND_USES_DMA)
3310 use_bounce_buf = !virt_addr_valid(buf) ||
3311 !IS_ALIGNED((unsigned long)buf,
3316 /* Is the current page in the buffer? */
3317 if (realpage != chip->pagecache.page || oob) {
3318 bufpoi = use_bounce_buf ? chip->data_buf : buf;
3320 if (use_bounce_buf && aligned)
3321 pr_debug("%s: using read bounce buffer for buf@%p\n",
3326 * Now read the page into the buffer. Absent an error,
3327 * the read methods return max bitflips per ecc step.
3329 if (unlikely(ops->mode == MTD_OPS_RAW))
3330 ret = chip->ecc.read_page_raw(chip, bufpoi,
3333 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
3335 ret = chip->ecc.read_subpage(chip, col, bytes,
3338 ret = chip->ecc.read_page(chip, bufpoi,
3339 oob_required, page);
3342 /* Invalidate page cache */
3343 chip->pagecache.page = -1;
3348 * Copy back the data in the initial buffer when reading
3349 * partial pages or when a bounce buffer is required.
3351 if (use_bounce_buf) {
3352 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
3353 !(mtd->ecc_stats.failed - ecc_stats.failed) &&
3354 (ops->mode != MTD_OPS_RAW)) {
3355 chip->pagecache.page = realpage;
3356 chip->pagecache.bitflips = ret;
3358 /* Invalidate page cache */
3359 chip->pagecache.page = -1;
3361 memcpy(buf, bufpoi + col, bytes);
3364 if (unlikely(oob)) {
3365 int toread = min(oobreadlen, max_oobsize);
3368 oob = nand_transfer_oob(chip, oob, ops,
3370 oobreadlen -= toread;
3374 nand_wait_readrdy(chip);
3376 if (mtd->ecc_stats.failed - ecc_stats.failed) {
3377 if (retry_mode + 1 < chip->read_retries) {
3379 ret = nand_setup_read_retry(chip,
3384 /* Reset ecc_stats; retry */
3385 mtd->ecc_stats = ecc_stats;
3388 /* No more retry modes; real failure */
3394 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3396 memcpy(buf, chip->data_buf + col, bytes);
3398 max_bitflips = max_t(unsigned int, max_bitflips,
3399 chip->pagecache.bitflips);
3404 /* Reset to retry mode 0 */
3406 ret = nand_setup_read_retry(chip, 0);
3415 /* For subsequent reads align to page boundary */
3417 /* Increment page address */
3420 page = realpage & chip->pagemask;
3421 /* Check, if we cross a chip boundary */
3424 nand_deselect_target(chip);
3425 nand_select_target(chip, chipnr);
3428 nand_deselect_target(chip);
3430 ops->retlen = ops->len - (size_t) readlen;
3432 ops->oobretlen = ops->ooblen - oobreadlen;
3440 return max_bitflips;
3444 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
3445 * @chip: nand chip info structure
3446 * @page: page number to read
3448 int nand_read_oob_std(struct nand_chip *chip, int page)
3450 struct mtd_info *mtd = nand_to_mtd(chip);
3452 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3454 EXPORT_SYMBOL(nand_read_oob_std);
3457 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
3459 * @chip: nand chip info structure
3460 * @page: page number to read
3462 static int nand_read_oob_syndrome(struct nand_chip *chip, int page)
3464 struct mtd_info *mtd = nand_to_mtd(chip);
3465 int length = mtd->oobsize;
3466 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3467 int eccsize = chip->ecc.size;
3468 uint8_t *bufpoi = chip->oob_poi;
3469 int i, toread, sndrnd = 0, pos, ret;
3471 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
3475 for (i = 0; i < chip->ecc.steps; i++) {
3479 pos = eccsize + i * (eccsize + chunk);
3480 if (mtd->writesize > 512)
3481 ret = nand_change_read_column_op(chip, pos,
3485 ret = nand_read_page_op(chip, page, pos, NULL,
3492 toread = min_t(int, length, chunk);
3494 ret = nand_read_data_op(chip, bufpoi, toread, false, false);
3502 ret = nand_read_data_op(chip, bufpoi, length, false, false);
3511 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
3512 * @chip: nand chip info structure
3513 * @page: page number to write
3515 int nand_write_oob_std(struct nand_chip *chip, int page)
3517 struct mtd_info *mtd = nand_to_mtd(chip);
3519 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
3522 EXPORT_SYMBOL(nand_write_oob_std);
3525 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
3526 * with syndrome - only for large page flash
3527 * @chip: nand chip info structure
3528 * @page: page number to write
3530 static int nand_write_oob_syndrome(struct nand_chip *chip, int page)
3532 struct mtd_info *mtd = nand_to_mtd(chip);
3533 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3534 int eccsize = chip->ecc.size, length = mtd->oobsize;
3535 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
3536 const uint8_t *bufpoi = chip->oob_poi;
3539 * data-ecc-data-ecc ... ecc-oob
3541 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
3543 if (!chip->ecc.prepad && !chip->ecc.postpad) {
3544 pos = steps * (eccsize + chunk);
3549 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
3553 for (i = 0; i < steps; i++) {
3555 if (mtd->writesize <= 512) {
3556 uint32_t fill = 0xFFFFFFFF;
3560 int num = min_t(int, len, 4);
3562 ret = nand_write_data_op(chip, &fill,
3570 pos = eccsize + i * (eccsize + chunk);
3571 ret = nand_change_write_column_op(chip, pos,
3579 len = min_t(int, length, chunk);
3581 ret = nand_write_data_op(chip, bufpoi, len, false);
3589 ret = nand_write_data_op(chip, bufpoi, length, false);
3594 return nand_prog_page_end_op(chip);
3598 * nand_do_read_oob - [INTERN] NAND read out-of-band
3599 * @chip: NAND chip object
3600 * @from: offset to read from
3601 * @ops: oob operations description structure
3603 * NAND read out-of-band data from the spare area.
3605 static int nand_do_read_oob(struct nand_chip *chip, loff_t from,
3606 struct mtd_oob_ops *ops)
3608 struct mtd_info *mtd = nand_to_mtd(chip);
3609 unsigned int max_bitflips = 0;
3610 int page, realpage, chipnr;
3611 struct mtd_ecc_stats stats;
3612 int readlen = ops->ooblen;
3614 uint8_t *buf = ops->oobbuf;
3617 pr_debug("%s: from = 0x%08Lx, len = %i\n",
3618 __func__, (unsigned long long)from, readlen);
3620 stats = mtd->ecc_stats;
3622 len = mtd_oobavail(mtd, ops);
3624 chipnr = (int)(from >> chip->chip_shift);
3625 nand_select_target(chip, chipnr);
3627 /* Shift to get page */
3628 realpage = (int)(from >> chip->page_shift);
3629 page = realpage & chip->pagemask;
3632 if (ops->mode == MTD_OPS_RAW)
3633 ret = chip->ecc.read_oob_raw(chip, page);
3635 ret = chip->ecc.read_oob(chip, page);
3640 len = min(len, readlen);
3641 buf = nand_transfer_oob(chip, buf, ops, len);
3643 nand_wait_readrdy(chip);
3645 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3651 /* Increment page address */
3654 page = realpage & chip->pagemask;
3655 /* Check, if we cross a chip boundary */
3658 nand_deselect_target(chip);
3659 nand_select_target(chip, chipnr);
3662 nand_deselect_target(chip);
3664 ops->oobretlen = ops->ooblen - readlen;
3669 if (mtd->ecc_stats.failed - stats.failed)
3672 return max_bitflips;
3676 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
3677 * @mtd: MTD device structure
3678 * @from: offset to read from
3679 * @ops: oob operation description structure
3681 * NAND read data and/or out-of-band data.
3683 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
3684 struct mtd_oob_ops *ops)
3686 struct nand_chip *chip = mtd_to_nand(mtd);
3691 if (ops->mode != MTD_OPS_PLACE_OOB &&
3692 ops->mode != MTD_OPS_AUTO_OOB &&
3693 ops->mode != MTD_OPS_RAW)
3696 ret = nand_get_device(chip);
3701 ret = nand_do_read_oob(chip, from, ops);
3703 ret = nand_do_read_ops(chip, from, ops);
3705 nand_release_device(chip);
3710 * nand_write_page_raw_notsupp - dummy raw page write function
3711 * @chip: nand chip info structure
3713 * @oob_required: must write chip->oob_poi to OOB
3714 * @page: page number to write
3716 * Returns -ENOTSUPP unconditionally.
3718 int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf,
3719 int oob_required, int page)
3725 * nand_write_page_raw - [INTERN] raw 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 * Not for syndrome calculating ECC controllers, which use a special oob layout.
3733 int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
3734 int oob_required, int page)
3736 struct mtd_info *mtd = nand_to_mtd(chip);
3739 ret = nand_prog_page_begin_op(chip, page, 0, buf, mtd->writesize);
3744 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
3750 return nand_prog_page_end_op(chip);
3752 EXPORT_SYMBOL(nand_write_page_raw);
3755 * nand_monolithic_write_page_raw - Monolithic page write in raw mode
3756 * @chip: NAND chip info structure
3757 * @buf: data buffer to write
3758 * @oob_required: must write chip->oob_poi to OOB
3759 * @page: page number to write
3761 * This is a raw page write, ie. without any error detection/correction.
3762 * Monolithic means we are requesting all the relevant data (main plus
3763 * eventually OOB) to be sent over the bus and effectively programmed
3764 * into the NAND chip arrays in a single operation. This is an
3765 * alternative to nand_write_page_raw(), which first sends the main
3766 * data, then eventually send the OOB data by latching more data
3767 * cycles on the NAND bus, and finally sends the program command to
3768 * synchronyze the NAND chip cache.
3770 int nand_monolithic_write_page_raw(struct nand_chip *chip, const u8 *buf,
3771 int oob_required, int page)
3773 struct mtd_info *mtd = nand_to_mtd(chip);
3774 unsigned int size = mtd->writesize;
3775 u8 *write_buf = (u8 *)buf;
3778 size += mtd->oobsize;
3780 if (buf != chip->data_buf) {
3781 write_buf = nand_get_data_buf(chip);
3782 memcpy(write_buf, buf, mtd->writesize);
3786 return nand_prog_page_op(chip, page, 0, write_buf, size);
3788 EXPORT_SYMBOL(nand_monolithic_write_page_raw);
3791 * nand_write_page_raw_syndrome - [INTERN] raw page write function
3792 * @chip: nand chip info structure
3794 * @oob_required: must write chip->oob_poi to OOB
3795 * @page: page number to write
3797 * We need a special oob layout and handling even when ECC isn't checked.
3799 static int nand_write_page_raw_syndrome(struct nand_chip *chip,
3800 const uint8_t *buf, int oob_required,
3803 struct mtd_info *mtd = nand_to_mtd(chip);
3804 int eccsize = chip->ecc.size;
3805 int eccbytes = chip->ecc.bytes;
3806 uint8_t *oob = chip->oob_poi;
3807 int steps, size, ret;
3809 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3813 for (steps = chip->ecc.steps; steps > 0; steps--) {
3814 ret = nand_write_data_op(chip, buf, eccsize, false);
3820 if (chip->ecc.prepad) {
3821 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3826 oob += chip->ecc.prepad;
3829 ret = nand_write_data_op(chip, oob, eccbytes, false);
3835 if (chip->ecc.postpad) {
3836 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3841 oob += chip->ecc.postpad;
3845 size = mtd->oobsize - (oob - chip->oob_poi);
3847 ret = nand_write_data_op(chip, oob, size, false);
3852 return nand_prog_page_end_op(chip);
3855 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
3856 * @chip: nand chip info structure
3858 * @oob_required: must write chip->oob_poi to OOB
3859 * @page: page number to write
3861 static int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf,
3862 int oob_required, int page)
3864 struct mtd_info *mtd = nand_to_mtd(chip);
3865 int i, eccsize = chip->ecc.size, ret;
3866 int eccbytes = chip->ecc.bytes;
3867 int eccsteps = chip->ecc.steps;
3868 uint8_t *ecc_calc = chip->ecc.calc_buf;
3869 const uint8_t *p = buf;
3871 /* Software ECC calculation */
3872 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
3873 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3875 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3880 return chip->ecc.write_page_raw(chip, buf, 1, page);
3884 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
3885 * @chip: nand chip info structure
3887 * @oob_required: must write chip->oob_poi to OOB
3888 * @page: page number to write
3890 static int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf,
3891 int oob_required, int page)
3893 struct mtd_info *mtd = nand_to_mtd(chip);
3894 int i, eccsize = chip->ecc.size, ret;
3895 int eccbytes = chip->ecc.bytes;
3896 int eccsteps = chip->ecc.steps;
3897 uint8_t *ecc_calc = chip->ecc.calc_buf;
3898 const uint8_t *p = buf;
3900 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3904 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3905 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3907 ret = nand_write_data_op(chip, p, eccsize, false);
3911 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3914 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3919 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3923 return nand_prog_page_end_op(chip);
3928 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
3929 * @chip: nand chip info structure
3930 * @offset: column address of subpage within the page
3931 * @data_len: data length
3933 * @oob_required: must write chip->oob_poi to OOB
3934 * @page: page number to write
3936 static int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset,
3937 uint32_t data_len, const uint8_t *buf,
3938 int oob_required, int page)
3940 struct mtd_info *mtd = nand_to_mtd(chip);
3941 uint8_t *oob_buf = chip->oob_poi;
3942 uint8_t *ecc_calc = chip->ecc.calc_buf;
3943 int ecc_size = chip->ecc.size;
3944 int ecc_bytes = chip->ecc.bytes;
3945 int ecc_steps = chip->ecc.steps;
3946 uint32_t start_step = offset / ecc_size;
3947 uint32_t end_step = (offset + data_len - 1) / ecc_size;
3948 int oob_bytes = mtd->oobsize / ecc_steps;
3951 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3955 for (step = 0; step < ecc_steps; step++) {
3956 /* configure controller for WRITE access */
3957 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3959 /* write data (untouched subpages already masked by 0xFF) */
3960 ret = nand_write_data_op(chip, buf, ecc_size, false);
3964 /* mask ECC of un-touched subpages by padding 0xFF */
3965 if ((step < start_step) || (step > end_step))
3966 memset(ecc_calc, 0xff, ecc_bytes);
3968 chip->ecc.calculate(chip, buf, ecc_calc);
3970 /* mask OOB of un-touched subpages by padding 0xFF */
3971 /* if oob_required, preserve OOB metadata of written subpage */
3972 if (!oob_required || (step < start_step) || (step > end_step))
3973 memset(oob_buf, 0xff, oob_bytes);
3976 ecc_calc += ecc_bytes;
3977 oob_buf += oob_bytes;
3980 /* copy calculated ECC for whole page to chip->buffer->oob */
3981 /* this include masked-value(0xFF) for unwritten subpages */
3982 ecc_calc = chip->ecc.calc_buf;
3983 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3988 /* write OOB buffer to NAND device */
3989 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3993 return nand_prog_page_end_op(chip);
3998 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
3999 * @chip: nand chip info structure
4001 * @oob_required: must write chip->oob_poi to OOB
4002 * @page: page number to write
4004 * The hw generator calculates the error syndrome automatically. Therefore we
4005 * need a special oob layout and handling.
4007 static int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf,
4008 int oob_required, int page)
4010 struct mtd_info *mtd = nand_to_mtd(chip);
4011 int i, eccsize = chip->ecc.size;
4012 int eccbytes = chip->ecc.bytes;
4013 int eccsteps = chip->ecc.steps;
4014 const uint8_t *p = buf;
4015 uint8_t *oob = chip->oob_poi;
4018 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4022 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4023 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4025 ret = nand_write_data_op(chip, p, eccsize, false);
4029 if (chip->ecc.prepad) {
4030 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4035 oob += chip->ecc.prepad;
4038 chip->ecc.calculate(chip, p, oob);
4040 ret = nand_write_data_op(chip, oob, eccbytes, false);
4046 if (chip->ecc.postpad) {
4047 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4052 oob += chip->ecc.postpad;
4056 /* Calculate remaining oob bytes */
4057 i = mtd->oobsize - (oob - chip->oob_poi);
4059 ret = nand_write_data_op(chip, oob, i, false);
4064 return nand_prog_page_end_op(chip);
4068 * nand_write_page - write one page
4069 * @chip: NAND chip descriptor
4070 * @offset: address offset within the page
4071 * @data_len: length of actual data to be written
4072 * @buf: the data to write
4073 * @oob_required: must write chip->oob_poi to OOB
4074 * @page: page number to write
4075 * @raw: use _raw version of write_page
4077 static int nand_write_page(struct nand_chip *chip, uint32_t offset,
4078 int data_len, const uint8_t *buf, int oob_required,
4081 struct mtd_info *mtd = nand_to_mtd(chip);
4082 int status, subpage;
4084 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
4085 chip->ecc.write_subpage)
4086 subpage = offset || (data_len < mtd->writesize);
4091 status = chip->ecc.write_page_raw(chip, buf, oob_required,
4094 status = chip->ecc.write_subpage(chip, offset, data_len, buf,
4095 oob_required, page);
4097 status = chip->ecc.write_page(chip, buf, oob_required, page);
4105 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
4108 * nand_do_write_ops - [INTERN] NAND write with ECC
4109 * @chip: NAND chip object
4110 * @to: offset to write to
4111 * @ops: oob operations description structure
4113 * NAND write with ECC.
4115 static int nand_do_write_ops(struct nand_chip *chip, loff_t to,
4116 struct mtd_oob_ops *ops)
4118 struct mtd_info *mtd = nand_to_mtd(chip);
4119 int chipnr, realpage, page, column;
4120 uint32_t writelen = ops->len;
4122 uint32_t oobwritelen = ops->ooblen;
4123 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
4125 uint8_t *oob = ops->oobbuf;
4126 uint8_t *buf = ops->datbuf;
4128 int oob_required = oob ? 1 : 0;
4134 /* Reject writes, which are not page aligned */
4135 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
4136 pr_notice("%s: attempt to write non page aligned data\n",
4141 column = to & (mtd->writesize - 1);
4143 chipnr = (int)(to >> chip->chip_shift);
4144 nand_select_target(chip, chipnr);
4146 /* Check, if it is write protected */
4147 if (nand_check_wp(chip)) {
4152 realpage = (int)(to >> chip->page_shift);
4153 page = realpage & chip->pagemask;
4155 /* Invalidate the page cache, when we write to the cached page */
4156 if (to <= ((loff_t)chip->pagecache.page << chip->page_shift) &&
4157 ((loff_t)chip->pagecache.page << chip->page_shift) < (to + ops->len))
4158 chip->pagecache.page = -1;
4160 /* Don't allow multipage oob writes with offset */
4161 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
4167 int bytes = mtd->writesize;
4168 uint8_t *wbuf = buf;
4170 int part_pagewr = (column || writelen < mtd->writesize);
4174 else if (chip->options & NAND_USES_DMA)
4175 use_bounce_buf = !virt_addr_valid(buf) ||
4176 !IS_ALIGNED((unsigned long)buf,
4182 * Copy the data from the initial buffer when doing partial page
4183 * writes or when a bounce buffer is required.
4185 if (use_bounce_buf) {
4186 pr_debug("%s: using write bounce buffer for buf@%p\n",
4189 bytes = min_t(int, bytes - column, writelen);
4190 wbuf = nand_get_data_buf(chip);
4191 memset(wbuf, 0xff, mtd->writesize);
4192 memcpy(&wbuf[column], buf, bytes);
4195 if (unlikely(oob)) {
4196 size_t len = min(oobwritelen, oobmaxlen);
4197 oob = nand_fill_oob(chip, oob, len, ops);
4200 /* We still need to erase leftover OOB data */
4201 memset(chip->oob_poi, 0xff, mtd->oobsize);
4204 ret = nand_write_page(chip, column, bytes, wbuf,
4206 (ops->mode == MTD_OPS_RAW));
4218 page = realpage & chip->pagemask;
4219 /* Check, if we cross a chip boundary */
4222 nand_deselect_target(chip);
4223 nand_select_target(chip, chipnr);
4227 ops->retlen = ops->len - writelen;
4229 ops->oobretlen = ops->ooblen;
4232 nand_deselect_target(chip);
4237 * panic_nand_write - [MTD Interface] NAND write with ECC
4238 * @mtd: MTD device structure
4239 * @to: offset to write to
4240 * @len: number of bytes to write
4241 * @retlen: pointer to variable to store the number of written bytes
4242 * @buf: the data to write
4244 * NAND write with ECC. Used when performing writes in interrupt context, this
4245 * may for example be called by mtdoops when writing an oops while in panic.
4247 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
4248 size_t *retlen, const uint8_t *buf)
4250 struct nand_chip *chip = mtd_to_nand(mtd);
4251 int chipnr = (int)(to >> chip->chip_shift);
4252 struct mtd_oob_ops ops;
4255 nand_select_target(chip, chipnr);
4257 /* Wait for the device to get ready */
4258 panic_nand_wait(chip, 400);
4260 memset(&ops, 0, sizeof(ops));
4262 ops.datbuf = (uint8_t *)buf;
4263 ops.mode = MTD_OPS_PLACE_OOB;
4265 ret = nand_do_write_ops(chip, to, &ops);
4267 *retlen = ops.retlen;
4272 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
4273 * @mtd: MTD device structure
4274 * @to: offset to write to
4275 * @ops: oob operation description structure
4277 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
4278 struct mtd_oob_ops *ops)
4280 struct nand_chip *chip = mtd_to_nand(mtd);
4285 ret = nand_get_device(chip);
4289 switch (ops->mode) {
4290 case MTD_OPS_PLACE_OOB:
4291 case MTD_OPS_AUTO_OOB:
4300 ret = nand_do_write_oob(chip, to, ops);
4302 ret = nand_do_write_ops(chip, to, ops);
4305 nand_release_device(chip);
4310 * nand_erase - [MTD Interface] erase block(s)
4311 * @mtd: MTD device structure
4312 * @instr: erase instruction
4314 * Erase one ore more blocks.
4316 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
4318 return nand_erase_nand(mtd_to_nand(mtd), instr, 0);
4322 * nand_erase_nand - [INTERN] erase block(s)
4323 * @chip: NAND chip object
4324 * @instr: erase instruction
4325 * @allowbbt: allow erasing the bbt area
4327 * Erase one ore more blocks.
4329 int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr,
4332 int page, pages_per_block, ret, chipnr;
4335 pr_debug("%s: start = 0x%012llx, len = %llu\n",
4336 __func__, (unsigned long long)instr->addr,
4337 (unsigned long long)instr->len);
4339 if (check_offs_len(chip, instr->addr, instr->len))
4342 /* Grab the lock and see if the device is available */
4343 ret = nand_get_device(chip);
4347 /* Shift to get first page */
4348 page = (int)(instr->addr >> chip->page_shift);
4349 chipnr = (int)(instr->addr >> chip->chip_shift);
4351 /* Calculate pages in each block */
4352 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
4354 /* Select the NAND device */
4355 nand_select_target(chip, chipnr);
4357 /* Check, if it is write protected */
4358 if (nand_check_wp(chip)) {
4359 pr_debug("%s: device is write protected!\n",
4365 /* Loop through the pages */
4369 /* Check if we have a bad block, we do not erase bad blocks! */
4370 if (nand_block_checkbad(chip, ((loff_t) page) <<
4371 chip->page_shift, allowbbt)) {
4372 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
4379 * Invalidate the page cache, if we erase the block which
4380 * contains the current cached page.
4382 if (page <= chip->pagecache.page && chip->pagecache.page <
4383 (page + pages_per_block))
4384 chip->pagecache.page = -1;
4386 ret = nand_erase_op(chip, (page & chip->pagemask) >>
4387 (chip->phys_erase_shift - chip->page_shift));
4389 pr_debug("%s: failed erase, page 0x%08x\n",
4392 ((loff_t)page << chip->page_shift);
4396 /* Increment page address and decrement length */
4397 len -= (1ULL << chip->phys_erase_shift);
4398 page += pages_per_block;
4400 /* Check, if we cross a chip boundary */
4401 if (len && !(page & chip->pagemask)) {
4403 nand_deselect_target(chip);
4404 nand_select_target(chip, chipnr);
4411 /* Deselect and wake up anyone waiting on the device */
4412 nand_deselect_target(chip);
4413 nand_release_device(chip);
4415 /* Return more or less happy */
4420 * nand_sync - [MTD Interface] sync
4421 * @mtd: MTD device structure
4423 * Sync is actually a wait for chip ready function.
4425 static void nand_sync(struct mtd_info *mtd)
4427 struct nand_chip *chip = mtd_to_nand(mtd);
4429 pr_debug("%s: called\n", __func__);
4431 /* Grab the lock and see if the device is available */
4432 WARN_ON(nand_get_device(chip));
4433 /* Release it and go back */
4434 nand_release_device(chip);
4438 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
4439 * @mtd: MTD device structure
4440 * @offs: offset relative to mtd start
4442 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
4444 struct nand_chip *chip = mtd_to_nand(mtd);
4445 int chipnr = (int)(offs >> chip->chip_shift);
4448 /* Select the NAND device */
4449 ret = nand_get_device(chip);
4453 nand_select_target(chip, chipnr);
4455 ret = nand_block_checkbad(chip, offs, 0);
4457 nand_deselect_target(chip);
4458 nand_release_device(chip);
4464 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
4465 * @mtd: MTD device structure
4466 * @ofs: offset relative to mtd start
4468 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
4472 ret = nand_block_isbad(mtd, ofs);
4474 /* If it was bad already, return success and do nothing */
4480 return nand_block_markbad_lowlevel(mtd_to_nand(mtd), ofs);
4484 * nand_suspend - [MTD Interface] Suspend the NAND flash
4485 * @mtd: MTD device structure
4487 * Returns 0 for success or negative error code otherwise.
4489 static int nand_suspend(struct mtd_info *mtd)
4491 struct nand_chip *chip = mtd_to_nand(mtd);
4494 mutex_lock(&chip->lock);
4495 if (chip->ops.suspend)
4496 ret = chip->ops.suspend(chip);
4498 chip->suspended = 1;
4499 mutex_unlock(&chip->lock);
4505 * nand_resume - [MTD Interface] Resume the NAND flash
4506 * @mtd: MTD device structure
4508 static void nand_resume(struct mtd_info *mtd)
4510 struct nand_chip *chip = mtd_to_nand(mtd);
4512 mutex_lock(&chip->lock);
4513 if (chip->suspended) {
4514 if (chip->ops.resume)
4515 chip->ops.resume(chip);
4516 chip->suspended = 0;
4518 pr_err("%s called for a chip which is not in suspended state\n",
4521 mutex_unlock(&chip->lock);
4525 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
4526 * prevent further operations
4527 * @mtd: MTD device structure
4529 static void nand_shutdown(struct mtd_info *mtd)
4535 * nand_lock - [MTD Interface] Lock the NAND flash
4536 * @mtd: MTD device structure
4537 * @ofs: offset byte address
4538 * @len: number of bytes to lock (must be a multiple of block/page size)
4540 static int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4542 struct nand_chip *chip = mtd_to_nand(mtd);
4544 if (!chip->ops.lock_area)
4547 return chip->ops.lock_area(chip, ofs, len);
4551 * nand_unlock - [MTD Interface] Unlock the NAND flash
4552 * @mtd: MTD device structure
4553 * @ofs: offset byte address
4554 * @len: number of bytes to unlock (must be a multiple of block/page size)
4556 static int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4558 struct nand_chip *chip = mtd_to_nand(mtd);
4560 if (!chip->ops.unlock_area)
4563 return chip->ops.unlock_area(chip, ofs, len);
4566 /* Set default functions */
4567 static void nand_set_defaults(struct nand_chip *chip)
4569 /* If no controller is provided, use the dummy, legacy one. */
4570 if (!chip->controller) {
4571 chip->controller = &chip->legacy.dummy_controller;
4572 nand_controller_init(chip->controller);
4575 nand_legacy_set_defaults(chip);
4577 if (!chip->buf_align)
4578 chip->buf_align = 1;
4581 /* Sanitize ONFI strings so we can safely print them */
4582 void sanitize_string(uint8_t *s, size_t len)
4586 /* Null terminate */
4589 /* Remove non printable chars */
4590 for (i = 0; i < len - 1; i++) {
4591 if (s[i] < ' ' || s[i] > 127)
4595 /* Remove trailing spaces */
4600 * nand_id_has_period - Check if an ID string has a given wraparound period
4601 * @id_data: the ID string
4602 * @arrlen: the length of the @id_data array
4603 * @period: the period of repitition
4605 * Check if an ID string is repeated within a given sequence of bytes at
4606 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4607 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4608 * if the repetition has a period of @period; otherwise, returns zero.
4610 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4613 for (i = 0; i < period; i++)
4614 for (j = i + period; j < arrlen; j += period)
4615 if (id_data[i] != id_data[j])
4621 * nand_id_len - Get the length of an ID string returned by CMD_READID
4622 * @id_data: the ID string
4623 * @arrlen: the length of the @id_data array
4625 * Returns the length of the ID string, according to known wraparound/trailing
4626 * zero patterns. If no pattern exists, returns the length of the array.
4628 static int nand_id_len(u8 *id_data, int arrlen)
4630 int last_nonzero, period;
4632 /* Find last non-zero byte */
4633 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4634 if (id_data[last_nonzero])
4638 if (last_nonzero < 0)
4641 /* Calculate wraparound period */
4642 for (period = 1; period < arrlen; period++)
4643 if (nand_id_has_period(id_data, arrlen, period))
4646 /* There's a repeated pattern */
4647 if (period < arrlen)
4650 /* There are trailing zeros */
4651 if (last_nonzero < arrlen - 1)
4652 return last_nonzero + 1;
4654 /* No pattern detected */
4658 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4659 static int nand_get_bits_per_cell(u8 cellinfo)
4663 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4664 bits >>= NAND_CI_CELLTYPE_SHIFT;
4669 * Many new NAND share similar device ID codes, which represent the size of the
4670 * chip. The rest of the parameters must be decoded according to generic or
4671 * manufacturer-specific "extended ID" decoding patterns.
4673 void nand_decode_ext_id(struct nand_chip *chip)
4675 struct nand_memory_organization *memorg;
4676 struct mtd_info *mtd = nand_to_mtd(chip);
4678 u8 *id_data = chip->id.data;
4680 memorg = nanddev_get_memorg(&chip->base);
4682 /* The 3rd id byte holds MLC / multichip data */
4683 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4684 /* The 4th id byte is the important one */
4688 memorg->pagesize = 1024 << (extid & 0x03);
4689 mtd->writesize = memorg->pagesize;
4692 memorg->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
4693 mtd->oobsize = memorg->oobsize;
4695 /* Calc blocksize. Blocksize is multiples of 64KiB */
4696 memorg->pages_per_eraseblock = ((64 * 1024) << (extid & 0x03)) /
4698 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4700 /* Get buswidth information */
4702 chip->options |= NAND_BUSWIDTH_16;
4704 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
4707 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4708 * decodes a matching ID table entry and assigns the MTD size parameters for
4711 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
4713 struct mtd_info *mtd = nand_to_mtd(chip);
4714 struct nand_memory_organization *memorg;
4716 memorg = nanddev_get_memorg(&chip->base);
4718 memorg->pages_per_eraseblock = type->erasesize / type->pagesize;
4719 mtd->erasesize = type->erasesize;
4720 memorg->pagesize = type->pagesize;
4721 mtd->writesize = memorg->pagesize;
4722 memorg->oobsize = memorg->pagesize / 32;
4723 mtd->oobsize = memorg->oobsize;
4725 /* All legacy ID NAND are small-page, SLC */
4726 memorg->bits_per_cell = 1;
4730 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4731 * heuristic patterns using various detected parameters (e.g., manufacturer,
4732 * page size, cell-type information).
4734 static void nand_decode_bbm_options(struct nand_chip *chip)
4736 struct mtd_info *mtd = nand_to_mtd(chip);
4738 /* Set the bad block position */
4739 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4740 chip->badblockpos = NAND_BBM_POS_LARGE;
4742 chip->badblockpos = NAND_BBM_POS_SMALL;
4745 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4747 return type->id_len;
4750 static bool find_full_id_nand(struct nand_chip *chip,
4751 struct nand_flash_dev *type)
4753 struct nand_device *base = &chip->base;
4754 struct nand_ecc_props requirements;
4755 struct mtd_info *mtd = nand_to_mtd(chip);
4756 struct nand_memory_organization *memorg;
4757 u8 *id_data = chip->id.data;
4759 memorg = nanddev_get_memorg(&chip->base);
4761 if (!strncmp(type->id, id_data, type->id_len)) {
4762 memorg->pagesize = type->pagesize;
4763 mtd->writesize = memorg->pagesize;
4764 memorg->pages_per_eraseblock = type->erasesize /
4766 mtd->erasesize = type->erasesize;
4767 memorg->oobsize = type->oobsize;
4768 mtd->oobsize = memorg->oobsize;
4770 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4771 memorg->eraseblocks_per_lun =
4772 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4774 memorg->pages_per_eraseblock);
4775 chip->options |= type->options;
4776 requirements.strength = NAND_ECC_STRENGTH(type);
4777 requirements.step_size = NAND_ECC_STEP(type);
4778 nanddev_set_ecc_requirements(base, &requirements);
4780 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4781 if (!chip->parameters.model)
4790 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
4791 * compliant and does not have a full-id or legacy-id entry in the nand_ids
4794 static void nand_manufacturer_detect(struct nand_chip *chip)
4797 * Try manufacturer detection if available and use
4798 * nand_decode_ext_id() otherwise.
4800 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4801 chip->manufacturer.desc->ops->detect) {
4802 struct nand_memory_organization *memorg;
4804 memorg = nanddev_get_memorg(&chip->base);
4806 /* The 3rd id byte holds MLC / multichip data */
4807 memorg->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
4808 chip->manufacturer.desc->ops->detect(chip);
4810 nand_decode_ext_id(chip);
4815 * Manufacturer initialization. This function is called for all NANDs including
4816 * ONFI and JEDEC compliant ones.
4817 * Manufacturer drivers should put all their specific initialization code in
4818 * their ->init() hook.
4820 static int nand_manufacturer_init(struct nand_chip *chip)
4822 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
4823 !chip->manufacturer.desc->ops->init)
4826 return chip->manufacturer.desc->ops->init(chip);
4830 * Manufacturer cleanup. This function is called for all NANDs including
4831 * ONFI and JEDEC compliant ones.
4832 * Manufacturer drivers should put all their specific cleanup code in their
4835 static void nand_manufacturer_cleanup(struct nand_chip *chip)
4837 /* Release manufacturer private data */
4838 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4839 chip->manufacturer.desc->ops->cleanup)
4840 chip->manufacturer.desc->ops->cleanup(chip);
4844 nand_manufacturer_name(const struct nand_manufacturer_desc *manufacturer_desc)
4846 return manufacturer_desc ? manufacturer_desc->name : "Unknown";
4850 * Get the flash and manufacturer id and lookup if the type is supported.
4852 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
4854 const struct nand_manufacturer_desc *manufacturer_desc;
4855 struct mtd_info *mtd = nand_to_mtd(chip);
4856 struct nand_memory_organization *memorg;
4858 u8 *id_data = chip->id.data;
4863 * Let's start by initializing memorg fields that might be left
4864 * unassigned by the ID-based detection logic.
4866 memorg = nanddev_get_memorg(&chip->base);
4867 memorg->planes_per_lun = 1;
4868 memorg->luns_per_target = 1;
4871 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4874 ret = nand_reset(chip, 0);
4878 /* Select the device */
4879 nand_select_target(chip, 0);
4881 /* Send the command for reading device ID */
4882 ret = nand_readid_op(chip, 0, id_data, 2);
4886 /* Read manufacturer and device IDs */
4887 maf_id = id_data[0];
4888 dev_id = id_data[1];
4891 * Try again to make sure, as some systems the bus-hold or other
4892 * interface concerns can cause random data which looks like a
4893 * possibly credible NAND flash to appear. If the two results do
4894 * not match, ignore the device completely.
4897 /* Read entire ID string */
4898 ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
4902 if (id_data[0] != maf_id || id_data[1] != dev_id) {
4903 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4904 maf_id, dev_id, id_data[0], id_data[1]);
4908 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
4910 /* Try to identify manufacturer */
4911 manufacturer_desc = nand_get_manufacturer_desc(maf_id);
4912 chip->manufacturer.desc = manufacturer_desc;
4915 type = nand_flash_ids;
4918 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
4920 * This is required to make sure initial NAND bus width set by the
4921 * NAND controller driver is coherent with the real NAND bus width
4922 * (extracted by auto-detection code).
4924 busw = chip->options & NAND_BUSWIDTH_16;
4927 * The flag is only set (never cleared), reset it to its default value
4928 * before starting auto-detection.
4930 chip->options &= ~NAND_BUSWIDTH_16;
4932 for (; type->name != NULL; type++) {
4933 if (is_full_id_nand(type)) {
4934 if (find_full_id_nand(chip, type))
4936 } else if (dev_id == type->dev_id) {
4941 if (!type->name || !type->pagesize) {
4942 /* Check if the chip is ONFI compliant */
4943 ret = nand_onfi_detect(chip);
4949 /* Check if the chip is JEDEC compliant */
4950 ret = nand_jedec_detect(chip);
4960 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4961 if (!chip->parameters.model)
4964 if (!type->pagesize)
4965 nand_manufacturer_detect(chip);
4967 nand_decode_id(chip, type);
4969 /* Get chip options */
4970 chip->options |= type->options;
4972 memorg->eraseblocks_per_lun =
4973 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4975 memorg->pages_per_eraseblock);
4979 mtd->name = chip->parameters.model;
4981 if (chip->options & NAND_BUSWIDTH_AUTO) {
4982 WARN_ON(busw & NAND_BUSWIDTH_16);
4983 nand_set_defaults(chip);
4984 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4986 * Check, if buswidth is correct. Hardware drivers should set
4989 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4991 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
4993 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
4994 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
4997 goto free_detect_allocation;
5000 nand_decode_bbm_options(chip);
5002 /* Calculate the address shift from the page size */
5003 chip->page_shift = ffs(mtd->writesize) - 1;
5004 /* Convert chipsize to number of pages per chip -1 */
5005 targetsize = nanddev_target_size(&chip->base);
5006 chip->pagemask = (targetsize >> chip->page_shift) - 1;
5008 chip->bbt_erase_shift = chip->phys_erase_shift =
5009 ffs(mtd->erasesize) - 1;
5010 if (targetsize & 0xffffffff)
5011 chip->chip_shift = ffs((unsigned)targetsize) - 1;
5013 chip->chip_shift = ffs((unsigned)(targetsize >> 32));
5014 chip->chip_shift += 32 - 1;
5017 if (chip->chip_shift - chip->page_shift > 16)
5018 chip->options |= NAND_ROW_ADDR_3;
5020 chip->badblockbits = 8;
5022 nand_legacy_adjust_cmdfunc(chip);
5024 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5026 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
5027 chip->parameters.model);
5028 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
5029 (int)(targetsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
5030 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
5033 free_detect_allocation:
5034 kfree(chip->parameters.model);
5039 static const char * const nand_ecc_modes[] = {
5040 [NAND_ECC_NONE] = "none",
5041 [NAND_ECC_SOFT] = "soft",
5042 [NAND_ECC_HW] = "hw",
5043 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
5044 [NAND_ECC_ON_DIE] = "on-die",
5047 static enum nand_ecc_engine_type
5048 of_get_nand_ecc_engine_type(struct device_node *np)
5050 enum nand_ecc_mode eng_type;
5054 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5056 return NAND_ECC_ENGINE_TYPE_INVALID;
5058 for (eng_type = NAND_ECC_NONE;
5059 eng_type < ARRAY_SIZE(nand_ecc_modes); eng_type++) {
5060 if (!strcasecmp(pm, nand_ecc_modes[eng_type])) {
5063 return NAND_ECC_ENGINE_TYPE_NONE;
5065 return NAND_ECC_ENGINE_TYPE_SOFT;
5067 case NAND_ECC_HW_SYNDROME:
5068 return NAND_ECC_ENGINE_TYPE_ON_HOST;
5069 case NAND_ECC_ON_DIE:
5070 return NAND_ECC_ENGINE_TYPE_ON_DIE;
5078 * For backward compatibility we support few obsoleted values that don't
5079 * have their mappings into the nand_ecc_engine_providers enum anymore
5080 * (they were merged with other enums).
5082 if (!strcasecmp(pm, "soft_bch"))
5083 return NAND_ECC_ENGINE_TYPE_SOFT;
5085 return NAND_ECC_ENGINE_TYPE_INVALID;
5088 static const char * const nand_ecc_algos[] = {
5089 [NAND_ECC_ALGO_HAMMING] = "hamming",
5090 [NAND_ECC_ALGO_BCH] = "bch",
5091 [NAND_ECC_ALGO_RS] = "rs",
5094 static enum nand_ecc_algo of_get_nand_ecc_algo(struct device_node *np)
5096 enum nand_ecc_algo ecc_algo;
5100 err = of_property_read_string(np, "nand-ecc-algo", &pm);
5102 for (ecc_algo = NAND_ECC_ALGO_HAMMING;
5103 ecc_algo < ARRAY_SIZE(nand_ecc_algos);
5105 if (!strcasecmp(pm, nand_ecc_algos[ecc_algo]))
5111 * For backward compatibility we also read "nand-ecc-mode" checking
5112 * for some obsoleted values that were specifying ECC algorithm.
5114 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5116 if (!strcasecmp(pm, "soft"))
5117 return NAND_ECC_ALGO_HAMMING;
5118 else if (!strcasecmp(pm, "soft_bch"))
5119 return NAND_ECC_ALGO_BCH;
5122 return NAND_ECC_ALGO_UNKNOWN;
5125 static int of_get_nand_ecc_step_size(struct device_node *np)
5130 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
5131 return ret ? ret : val;
5134 static int of_get_nand_ecc_strength(struct device_node *np)
5139 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
5140 return ret ? ret : val;
5143 static int of_get_nand_bus_width(struct device_node *np)
5147 if (of_property_read_u32(np, "nand-bus-width", &val))
5159 static bool of_get_nand_on_flash_bbt(struct device_node *np)
5161 return of_property_read_bool(np, "nand-on-flash-bbt");
5164 static int nand_dt_init(struct nand_chip *chip)
5166 struct device_node *dn = nand_get_flash_node(chip);
5167 enum nand_ecc_engine_type ecc_type;
5168 enum nand_ecc_algo ecc_algo;
5169 int ecc_strength, ecc_step;
5174 if (of_get_nand_bus_width(dn) == 16)
5175 chip->options |= NAND_BUSWIDTH_16;
5177 if (of_property_read_bool(dn, "nand-is-boot-medium"))
5178 chip->options |= NAND_IS_BOOT_MEDIUM;
5180 if (of_get_nand_on_flash_bbt(dn))
5181 chip->bbt_options |= NAND_BBT_USE_FLASH;
5183 ecc_type = of_get_nand_ecc_engine_type(dn);
5184 ecc_algo = of_get_nand_ecc_algo(dn);
5185 ecc_strength = of_get_nand_ecc_strength(dn);
5186 ecc_step = of_get_nand_ecc_step_size(dn);
5188 if (ecc_type != NAND_ECC_ENGINE_TYPE_INVALID)
5189 chip->ecc.engine_type = ecc_type;
5191 if (ecc_algo != NAND_ECC_ALGO_UNKNOWN)
5192 chip->ecc.algo = ecc_algo;
5194 if (ecc_strength >= 0)
5195 chip->ecc.strength = ecc_strength;
5198 chip->ecc.size = ecc_step;
5200 if (of_property_read_bool(dn, "nand-ecc-maximize"))
5201 chip->ecc.options |= NAND_ECC_MAXIMIZE;
5207 * nand_scan_ident - Scan for the NAND device
5208 * @chip: NAND chip object
5209 * @maxchips: number of chips to scan for
5210 * @table: alternative NAND ID table
5212 * This is the first phase of the normal nand_scan() function. It reads the
5213 * flash ID and sets up MTD fields accordingly.
5215 * This helper used to be called directly from controller drivers that needed
5216 * to tweak some ECC-related parameters before nand_scan_tail(). This separation
5217 * prevented dynamic allocations during this phase which was unconvenient and
5218 * as been banned for the benefit of the ->init_ecc()/cleanup_ecc() hooks.
5220 static int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips,
5221 struct nand_flash_dev *table)
5223 struct mtd_info *mtd = nand_to_mtd(chip);
5224 struct nand_memory_organization *memorg;
5225 int nand_maf_id, nand_dev_id;
5229 memorg = nanddev_get_memorg(&chip->base);
5231 /* Assume all dies are deselected when we enter nand_scan_ident(). */
5234 mutex_init(&chip->lock);
5236 /* Enforce the right timings for reset/detection */
5237 chip->current_interface_config = nand_get_reset_interface_config();
5239 ret = nand_dt_init(chip);
5243 if (!mtd->name && mtd->dev.parent)
5244 mtd->name = dev_name(mtd->dev.parent);
5246 /* Set the default functions */
5247 nand_set_defaults(chip);
5249 ret = nand_legacy_check_hooks(chip);
5253 memorg->ntargets = maxchips;
5255 /* Read the flash type */
5256 ret = nand_detect(chip, table);
5258 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
5259 pr_warn("No NAND device found\n");
5260 nand_deselect_target(chip);
5264 nand_maf_id = chip->id.data[0];
5265 nand_dev_id = chip->id.data[1];
5267 nand_deselect_target(chip);
5269 /* Check for a chip array */
5270 for (i = 1; i < maxchips; i++) {
5273 /* See comment in nand_get_flash_type for reset */
5274 ret = nand_reset(chip, i);
5278 nand_select_target(chip, i);
5279 /* Send the command for reading device ID */
5280 ret = nand_readid_op(chip, 0, id, sizeof(id));
5283 /* Read manufacturer and device IDs */
5284 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
5285 nand_deselect_target(chip);
5288 nand_deselect_target(chip);
5291 pr_info("%d chips detected\n", i);
5293 /* Store the number of chips and calc total size for mtd */
5294 memorg->ntargets = i;
5295 mtd->size = i * nanddev_target_size(&chip->base);
5300 static void nand_scan_ident_cleanup(struct nand_chip *chip)
5302 kfree(chip->parameters.model);
5303 kfree(chip->parameters.onfi);
5306 static int nand_set_ecc_soft_ops(struct nand_chip *chip)
5308 struct mtd_info *mtd = nand_to_mtd(chip);
5309 struct nand_ecc_ctrl *ecc = &chip->ecc;
5311 if (WARN_ON(ecc->engine_type != NAND_ECC_ENGINE_TYPE_SOFT))
5314 switch (ecc->algo) {
5315 case NAND_ECC_ALGO_HAMMING:
5316 ecc->calculate = nand_calculate_ecc;
5317 ecc->correct = nand_correct_data;
5318 ecc->read_page = nand_read_page_swecc;
5319 ecc->read_subpage = nand_read_subpage;
5320 ecc->write_page = nand_write_page_swecc;
5321 if (!ecc->read_page_raw)
5322 ecc->read_page_raw = nand_read_page_raw;
5323 if (!ecc->write_page_raw)
5324 ecc->write_page_raw = nand_write_page_raw;
5325 ecc->read_oob = nand_read_oob_std;
5326 ecc->write_oob = nand_write_oob_std;
5332 if (IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_HAMMING_SMC))
5333 ecc->options |= NAND_ECC_SOFT_HAMMING_SM_ORDER;
5336 case NAND_ECC_ALGO_BCH:
5337 if (!mtd_nand_has_bch()) {
5338 WARN(1, "CONFIG_MTD_NAND_ECC_SW_BCH not enabled\n");
5341 ecc->calculate = nand_bch_calculate_ecc;
5342 ecc->correct = nand_bch_correct_data;
5343 ecc->read_page = nand_read_page_swecc;
5344 ecc->read_subpage = nand_read_subpage;
5345 ecc->write_page = nand_write_page_swecc;
5346 if (!ecc->read_page_raw)
5347 ecc->read_page_raw = nand_read_page_raw;
5348 if (!ecc->write_page_raw)
5349 ecc->write_page_raw = nand_write_page_raw;
5350 ecc->read_oob = nand_read_oob_std;
5351 ecc->write_oob = nand_write_oob_std;
5354 * Board driver should supply ecc.size and ecc.strength
5355 * values to select how many bits are correctable.
5356 * Otherwise, default to 4 bits for large page devices.
5358 if (!ecc->size && (mtd->oobsize >= 64)) {
5364 * if no ecc placement scheme was provided pickup the default
5367 if (!mtd->ooblayout) {
5368 /* handle large page devices only */
5369 if (mtd->oobsize < 64) {
5370 WARN(1, "OOB layout is required when using software BCH on small pages\n");
5374 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
5379 * We can only maximize ECC config when the default layout is
5380 * used, otherwise we don't know how many bytes can really be
5383 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
5384 ecc->options & NAND_ECC_MAXIMIZE) {
5387 /* Always prefer 1k blocks over 512bytes ones */
5389 steps = mtd->writesize / ecc->size;
5391 /* Reserve 2 bytes for the BBM */
5392 bytes = (mtd->oobsize - 2) / steps;
5393 ecc->strength = bytes * 8 / fls(8 * ecc->size);
5396 /* See nand_bch_init() for details. */
5398 ecc->priv = nand_bch_init(mtd);
5400 WARN(1, "BCH ECC initialization failed!\n");
5405 WARN(1, "Unsupported ECC algorithm!\n");
5411 * nand_check_ecc_caps - check the sanity of preset ECC settings
5412 * @chip: nand chip info structure
5413 * @caps: ECC caps info structure
5414 * @oobavail: OOB size that the ECC engine can use
5416 * When ECC step size and strength are already set, check if they are supported
5417 * by the controller and the calculated ECC bytes fit within the chip's OOB.
5418 * On success, the calculated ECC bytes is set.
5421 nand_check_ecc_caps(struct nand_chip *chip,
5422 const struct nand_ecc_caps *caps, int oobavail)
5424 struct mtd_info *mtd = nand_to_mtd(chip);
5425 const struct nand_ecc_step_info *stepinfo;
5426 int preset_step = chip->ecc.size;
5427 int preset_strength = chip->ecc.strength;
5428 int ecc_bytes, nsteps = mtd->writesize / preset_step;
5431 for (i = 0; i < caps->nstepinfos; i++) {
5432 stepinfo = &caps->stepinfos[i];
5434 if (stepinfo->stepsize != preset_step)
5437 for (j = 0; j < stepinfo->nstrengths; j++) {
5438 if (stepinfo->strengths[j] != preset_strength)
5441 ecc_bytes = caps->calc_ecc_bytes(preset_step,
5443 if (WARN_ON_ONCE(ecc_bytes < 0))
5446 if (ecc_bytes * nsteps > oobavail) {
5447 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
5448 preset_step, preset_strength);
5452 chip->ecc.bytes = ecc_bytes;
5458 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
5459 preset_step, preset_strength);
5465 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
5466 * @chip: nand chip info structure
5467 * @caps: ECC engine caps info structure
5468 * @oobavail: OOB size that the ECC engine can use
5470 * If a chip's ECC requirement is provided, try to meet it with the least
5471 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
5472 * On success, the chosen ECC settings are set.
5475 nand_match_ecc_req(struct nand_chip *chip,
5476 const struct nand_ecc_caps *caps, int oobavail)
5478 const struct nand_ecc_props *requirements =
5479 nanddev_get_ecc_requirements(&chip->base);
5480 struct mtd_info *mtd = nand_to_mtd(chip);
5481 const struct nand_ecc_step_info *stepinfo;
5482 int req_step = requirements->step_size;
5483 int req_strength = requirements->strength;
5484 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
5485 int best_step, best_strength, best_ecc_bytes;
5486 int best_ecc_bytes_total = INT_MAX;
5489 /* No information provided by the NAND chip */
5490 if (!req_step || !req_strength)
5493 /* number of correctable bits the chip requires in a page */
5494 req_corr = mtd->writesize / req_step * req_strength;
5496 for (i = 0; i < caps->nstepinfos; i++) {
5497 stepinfo = &caps->stepinfos[i];
5498 step_size = stepinfo->stepsize;
5500 for (j = 0; j < stepinfo->nstrengths; j++) {
5501 strength = stepinfo->strengths[j];
5504 * If both step size and strength are smaller than the
5505 * chip's requirement, it is not easy to compare the
5506 * resulted reliability.
5508 if (step_size < req_step && strength < req_strength)
5511 if (mtd->writesize % step_size)
5514 nsteps = mtd->writesize / step_size;
5516 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5517 if (WARN_ON_ONCE(ecc_bytes < 0))
5519 ecc_bytes_total = ecc_bytes * nsteps;
5521 if (ecc_bytes_total > oobavail ||
5522 strength * nsteps < req_corr)
5526 * We assume the best is to meet the chip's requrement
5527 * with the least number of ECC bytes.
5529 if (ecc_bytes_total < best_ecc_bytes_total) {
5530 best_ecc_bytes_total = ecc_bytes_total;
5531 best_step = step_size;
5532 best_strength = strength;
5533 best_ecc_bytes = ecc_bytes;
5538 if (best_ecc_bytes_total == INT_MAX)
5541 chip->ecc.size = best_step;
5542 chip->ecc.strength = best_strength;
5543 chip->ecc.bytes = best_ecc_bytes;
5549 * nand_maximize_ecc - choose the max ECC strength available
5550 * @chip: nand chip info structure
5551 * @caps: ECC engine caps info structure
5552 * @oobavail: OOB size that the ECC engine can use
5554 * Choose the max ECC strength that is supported on the controller, and can fit
5555 * within the chip's OOB. On success, the chosen ECC settings are set.
5558 nand_maximize_ecc(struct nand_chip *chip,
5559 const struct nand_ecc_caps *caps, int oobavail)
5561 struct mtd_info *mtd = nand_to_mtd(chip);
5562 const struct nand_ecc_step_info *stepinfo;
5563 int step_size, strength, nsteps, ecc_bytes, corr;
5566 int best_strength, best_ecc_bytes;
5569 for (i = 0; i < caps->nstepinfos; i++) {
5570 stepinfo = &caps->stepinfos[i];
5571 step_size = stepinfo->stepsize;
5573 /* If chip->ecc.size is already set, respect it */
5574 if (chip->ecc.size && step_size != chip->ecc.size)
5577 for (j = 0; j < stepinfo->nstrengths; j++) {
5578 strength = stepinfo->strengths[j];
5580 if (mtd->writesize % step_size)
5583 nsteps = mtd->writesize / step_size;
5585 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5586 if (WARN_ON_ONCE(ecc_bytes < 0))
5589 if (ecc_bytes * nsteps > oobavail)
5592 corr = strength * nsteps;
5595 * If the number of correctable bits is the same,
5596 * bigger step_size has more reliability.
5598 if (corr > best_corr ||
5599 (corr == best_corr && step_size > best_step)) {
5601 best_step = step_size;
5602 best_strength = strength;
5603 best_ecc_bytes = ecc_bytes;
5611 chip->ecc.size = best_step;
5612 chip->ecc.strength = best_strength;
5613 chip->ecc.bytes = best_ecc_bytes;
5619 * nand_ecc_choose_conf - Set the ECC strength and ECC step size
5620 * @chip: nand chip info structure
5621 * @caps: ECC engine caps info structure
5622 * @oobavail: OOB size that the ECC engine can use
5624 * Choose the ECC configuration according to following logic
5626 * 1. If both ECC step size and ECC strength are already set (usually by DT)
5627 * then check if it is supported by this controller.
5628 * 2. If NAND_ECC_MAXIMIZE is set, then select maximum ECC strength.
5629 * 3. Otherwise, try to match the ECC step size and ECC strength closest
5630 * to the chip's requirement. If available OOB size can't fit the chip
5631 * requirement then fallback to the maximum ECC step size and ECC strength.
5633 * On success, the chosen ECC settings are set.
5635 int nand_ecc_choose_conf(struct nand_chip *chip,
5636 const struct nand_ecc_caps *caps, int oobavail)
5638 struct mtd_info *mtd = nand_to_mtd(chip);
5640 if (WARN_ON(oobavail < 0 || oobavail > mtd->oobsize))
5643 if (chip->ecc.size && chip->ecc.strength)
5644 return nand_check_ecc_caps(chip, caps, oobavail);
5646 if (chip->ecc.options & NAND_ECC_MAXIMIZE)
5647 return nand_maximize_ecc(chip, caps, oobavail);
5649 if (!nand_match_ecc_req(chip, caps, oobavail))
5652 return nand_maximize_ecc(chip, caps, oobavail);
5654 EXPORT_SYMBOL_GPL(nand_ecc_choose_conf);
5657 * Check if the chip configuration meet the datasheet requirements.
5659 * If our configuration corrects A bits per B bytes and the minimum
5660 * required correction level is X bits per Y bytes, then we must ensure
5661 * both of the following are true:
5663 * (1) A / B >= X / Y
5666 * Requirement (1) ensures we can correct for the required bitflip density.
5667 * Requirement (2) ensures we can correct even when all bitflips are clumped
5668 * in the same sector.
5670 static bool nand_ecc_strength_good(struct nand_chip *chip)
5672 struct mtd_info *mtd = nand_to_mtd(chip);
5673 struct nand_ecc_ctrl *ecc = &chip->ecc;
5674 const struct nand_ecc_props *requirements =
5675 nanddev_get_ecc_requirements(&chip->base);
5678 if (ecc->size == 0 || requirements->step_size == 0)
5679 /* Not enough information */
5683 * We get the number of corrected bits per page to compare
5684 * the correction density.
5686 corr = (mtd->writesize * ecc->strength) / ecc->size;
5687 ds_corr = (mtd->writesize * requirements->strength) /
5688 requirements->step_size;
5690 return corr >= ds_corr && ecc->strength >= requirements->strength;
5693 static int rawnand_erase(struct nand_device *nand, const struct nand_pos *pos)
5695 struct nand_chip *chip = container_of(nand, struct nand_chip,
5697 unsigned int eb = nanddev_pos_to_row(nand, pos);
5700 eb >>= nand->rowconv.eraseblock_addr_shift;
5702 nand_select_target(chip, pos->target);
5703 ret = nand_erase_op(chip, eb);
5704 nand_deselect_target(chip);
5709 static int rawnand_markbad(struct nand_device *nand,
5710 const struct nand_pos *pos)
5712 struct nand_chip *chip = container_of(nand, struct nand_chip,
5715 return nand_markbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5718 static bool rawnand_isbad(struct nand_device *nand, const struct nand_pos *pos)
5720 struct nand_chip *chip = container_of(nand, struct nand_chip,
5724 nand_select_target(chip, pos->target);
5725 ret = nand_isbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5726 nand_deselect_target(chip);
5731 static const struct nand_ops rawnand_ops = {
5732 .erase = rawnand_erase,
5733 .markbad = rawnand_markbad,
5734 .isbad = rawnand_isbad,
5738 * nand_scan_tail - Scan for the NAND device
5739 * @chip: NAND chip object
5741 * This is the second phase of the normal nand_scan() function. It fills out
5742 * all the uninitialized function pointers with the defaults and scans for a
5743 * bad block table if appropriate.
5745 static int nand_scan_tail(struct nand_chip *chip)
5747 struct mtd_info *mtd = nand_to_mtd(chip);
5748 struct nand_ecc_ctrl *ecc = &chip->ecc;
5751 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
5752 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
5753 !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
5757 chip->data_buf = kmalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
5758 if (!chip->data_buf)
5762 * FIXME: some NAND manufacturer drivers expect the first die to be
5763 * selected when manufacturer->init() is called. They should be fixed
5764 * to explictly select the relevant die when interacting with the NAND
5767 nand_select_target(chip, 0);
5768 ret = nand_manufacturer_init(chip);
5769 nand_deselect_target(chip);
5773 /* Set the internal oob buffer location, just after the page data */
5774 chip->oob_poi = chip->data_buf + mtd->writesize;
5777 * If no default placement scheme is given, select an appropriate one.
5779 if (!mtd->ooblayout &&
5780 !(ecc->engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
5781 ecc->algo == NAND_ECC_ALGO_BCH)) {
5782 switch (mtd->oobsize) {
5785 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
5789 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_hamming_ops);
5793 * Expose the whole OOB area to users if ECC_NONE
5794 * is passed. We could do that for all kind of
5795 * ->oobsize, but we must keep the old large/small
5796 * page with ECC layout when ->oobsize <= 128 for
5797 * compatibility reasons.
5799 if (ecc->engine_type == NAND_ECC_ENGINE_TYPE_NONE) {
5800 mtd_set_ooblayout(mtd,
5801 &nand_ooblayout_lp_ops);
5805 WARN(1, "No oob scheme defined for oobsize %d\n",
5808 goto err_nand_manuf_cleanup;
5813 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
5814 * selected and we have 256 byte pagesize fallback to software ECC
5817 switch (ecc->engine_type) {
5818 case NAND_ECC_ENGINE_TYPE_ON_HOST:
5820 switch (ecc->placement) {
5821 case NAND_ECC_PLACEMENT_UNKNOWN:
5822 case NAND_ECC_PLACEMENT_OOB:
5823 /* Use standard hwecc read page function? */
5824 if (!ecc->read_page)
5825 ecc->read_page = nand_read_page_hwecc;
5826 if (!ecc->write_page)
5827 ecc->write_page = nand_write_page_hwecc;
5828 if (!ecc->read_page_raw)
5829 ecc->read_page_raw = nand_read_page_raw;
5830 if (!ecc->write_page_raw)
5831 ecc->write_page_raw = nand_write_page_raw;
5833 ecc->read_oob = nand_read_oob_std;
5834 if (!ecc->write_oob)
5835 ecc->write_oob = nand_write_oob_std;
5836 if (!ecc->read_subpage)
5837 ecc->read_subpage = nand_read_subpage;
5838 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5839 ecc->write_subpage = nand_write_subpage_hwecc;
5842 case NAND_ECC_PLACEMENT_INTERLEAVED:
5843 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5845 ecc->read_page == nand_read_page_hwecc ||
5847 ecc->write_page == nand_write_page_hwecc)) {
5848 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5850 goto err_nand_manuf_cleanup;
5852 /* Use standard syndrome read/write page function? */
5853 if (!ecc->read_page)
5854 ecc->read_page = nand_read_page_syndrome;
5855 if (!ecc->write_page)
5856 ecc->write_page = nand_write_page_syndrome;
5857 if (!ecc->read_page_raw)
5858 ecc->read_page_raw = nand_read_page_raw_syndrome;
5859 if (!ecc->write_page_raw)
5860 ecc->write_page_raw = nand_write_page_raw_syndrome;
5862 ecc->read_oob = nand_read_oob_syndrome;
5863 if (!ecc->write_oob)
5864 ecc->write_oob = nand_write_oob_syndrome;
5868 pr_warn("Invalid NAND_ECC_PLACEMENT %d\n",
5871 goto err_nand_manuf_cleanup;
5874 if (mtd->writesize >= ecc->size) {
5875 if (!ecc->strength) {
5876 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
5878 goto err_nand_manuf_cleanup;
5882 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
5883 ecc->size, mtd->writesize);
5884 ecc->engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5885 ecc->algo = NAND_ECC_ALGO_HAMMING;
5888 case NAND_ECC_ENGINE_TYPE_SOFT:
5889 ret = nand_set_ecc_soft_ops(chip);
5892 goto err_nand_manuf_cleanup;
5896 case NAND_ECC_ENGINE_TYPE_ON_DIE:
5897 if (!ecc->read_page || !ecc->write_page) {
5898 WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
5900 goto err_nand_manuf_cleanup;
5903 ecc->read_oob = nand_read_oob_std;
5904 if (!ecc->write_oob)
5905 ecc->write_oob = nand_write_oob_std;
5908 case NAND_ECC_ENGINE_TYPE_NONE:
5909 pr_warn("NAND_ECC_ENGINE_TYPE_NONE selected by board driver. This is not recommended!\n");
5910 ecc->read_page = nand_read_page_raw;
5911 ecc->write_page = nand_write_page_raw;
5912 ecc->read_oob = nand_read_oob_std;
5913 ecc->read_page_raw = nand_read_page_raw;
5914 ecc->write_page_raw = nand_write_page_raw;
5915 ecc->write_oob = nand_write_oob_std;
5916 ecc->size = mtd->writesize;
5922 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->engine_type);
5924 goto err_nand_manuf_cleanup;
5927 if (ecc->correct || ecc->calculate) {
5928 ecc->calc_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
5929 ecc->code_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
5930 if (!ecc->calc_buf || !ecc->code_buf) {
5932 goto err_nand_manuf_cleanup;
5936 /* For many systems, the standard OOB write also works for raw */
5937 if (!ecc->read_oob_raw)
5938 ecc->read_oob_raw = ecc->read_oob;
5939 if (!ecc->write_oob_raw)
5940 ecc->write_oob_raw = ecc->write_oob;
5942 /* propagate ecc info to mtd_info */
5943 mtd->ecc_strength = ecc->strength;
5944 mtd->ecc_step_size = ecc->size;
5947 * Set the number of read / write steps for one page depending on ECC
5950 ecc->steps = mtd->writesize / ecc->size;
5951 if (ecc->steps * ecc->size != mtd->writesize) {
5952 WARN(1, "Invalid ECC parameters\n");
5954 goto err_nand_manuf_cleanup;
5956 ecc->total = ecc->steps * ecc->bytes;
5957 if (ecc->total > mtd->oobsize) {
5958 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
5960 goto err_nand_manuf_cleanup;
5964 * The number of bytes available for a client to place data into
5965 * the out of band area.
5967 ret = mtd_ooblayout_count_freebytes(mtd);
5971 mtd->oobavail = ret;
5973 /* ECC sanity check: warn if it's too weak */
5974 if (!nand_ecc_strength_good(chip))
5975 pr_warn("WARNING: %s: the ECC used on your system (%db/%dB) is too weak compared to the one required by the NAND chip (%db/%dB)\n",
5976 mtd->name, chip->ecc.strength, chip->ecc.size,
5977 nanddev_get_ecc_requirements(&chip->base)->strength,
5978 nanddev_get_ecc_requirements(&chip->base)->step_size);
5980 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
5981 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
5982 switch (ecc->steps) {
5984 mtd->subpage_sft = 1;
5989 mtd->subpage_sft = 2;
5993 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
5995 /* Invalidate the pagebuffer reference */
5996 chip->pagecache.page = -1;
5998 /* Large page NAND with SOFT_ECC should support subpage reads */
5999 switch (ecc->engine_type) {
6000 case NAND_ECC_ENGINE_TYPE_SOFT:
6001 if (chip->page_shift > 9)
6002 chip->options |= NAND_SUBPAGE_READ;
6009 ret = nanddev_init(&chip->base, &rawnand_ops, mtd->owner);
6011 goto err_nand_manuf_cleanup;
6013 /* Adjust the MTD_CAP_ flags when NAND_ROM is set. */
6014 if (chip->options & NAND_ROM)
6015 mtd->flags = MTD_CAP_ROM;
6017 /* Fill in remaining MTD driver data */
6018 mtd->_erase = nand_erase;
6020 mtd->_unpoint = NULL;
6021 mtd->_panic_write = panic_nand_write;
6022 mtd->_read_oob = nand_read_oob;
6023 mtd->_write_oob = nand_write_oob;
6024 mtd->_sync = nand_sync;
6025 mtd->_lock = nand_lock;
6026 mtd->_unlock = nand_unlock;
6027 mtd->_suspend = nand_suspend;
6028 mtd->_resume = nand_resume;
6029 mtd->_reboot = nand_shutdown;
6030 mtd->_block_isreserved = nand_block_isreserved;
6031 mtd->_block_isbad = nand_block_isbad;
6032 mtd->_block_markbad = nand_block_markbad;
6033 mtd->_max_bad_blocks = nanddev_mtd_max_bad_blocks;
6036 * Initialize bitflip_threshold to its default prior scan_bbt() call.
6037 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
6040 if (!mtd->bitflip_threshold)
6041 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
6043 /* Find the fastest data interface for this chip */
6044 ret = nand_choose_interface_config(chip);
6046 goto err_nanddev_cleanup;
6048 /* Enter fastest possible mode on all dies. */
6049 for (i = 0; i < nanddev_ntargets(&chip->base); i++) {
6050 ret = nand_setup_interface(chip, i);
6052 goto err_free_interface_config;
6055 /* Check, if we should skip the bad block table scan */
6056 if (chip->options & NAND_SKIP_BBTSCAN)
6059 /* Build bad block table */
6060 ret = nand_create_bbt(chip);
6062 goto err_free_interface_config;
6066 err_free_interface_config:
6067 kfree(chip->best_interface_config);
6069 err_nanddev_cleanup:
6070 nanddev_cleanup(&chip->base);
6072 err_nand_manuf_cleanup:
6073 nand_manufacturer_cleanup(chip);
6076 kfree(chip->data_buf);
6077 kfree(ecc->code_buf);
6078 kfree(ecc->calc_buf);
6083 static int nand_attach(struct nand_chip *chip)
6085 if (chip->controller->ops && chip->controller->ops->attach_chip)
6086 return chip->controller->ops->attach_chip(chip);
6091 static void nand_detach(struct nand_chip *chip)
6093 if (chip->controller->ops && chip->controller->ops->detach_chip)
6094 chip->controller->ops->detach_chip(chip);
6098 * nand_scan_with_ids - [NAND Interface] Scan for the NAND device
6099 * @chip: NAND chip object
6100 * @maxchips: number of chips to scan for.
6101 * @ids: optional flash IDs table
6103 * This fills out all the uninitialized function pointers with the defaults.
6104 * The flash ID is read and the mtd/chip structures are filled with the
6105 * appropriate values.
6107 int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips,
6108 struct nand_flash_dev *ids)
6115 ret = nand_scan_ident(chip, maxchips, ids);
6119 ret = nand_attach(chip);
6123 ret = nand_scan_tail(chip);
6132 nand_scan_ident_cleanup(chip);
6136 EXPORT_SYMBOL(nand_scan_with_ids);
6139 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
6140 * @chip: NAND chip object
6142 void nand_cleanup(struct nand_chip *chip)
6144 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
6145 chip->ecc.algo == NAND_ECC_ALGO_BCH)
6146 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
6148 nanddev_cleanup(&chip->base);
6150 /* Free bad block table memory */
6152 kfree(chip->data_buf);
6153 kfree(chip->ecc.code_buf);
6154 kfree(chip->ecc.calc_buf);
6156 /* Free bad block descriptor memory */
6157 if (chip->badblock_pattern && chip->badblock_pattern->options
6158 & NAND_BBT_DYNAMICSTRUCT)
6159 kfree(chip->badblock_pattern);
6161 /* Free the data interface */
6162 kfree(chip->best_interface_config);
6164 /* Free manufacturer priv data. */
6165 nand_manufacturer_cleanup(chip);
6167 /* Free controller specific allocations after chip identification */
6170 /* Free identification phase allocations */
6171 nand_scan_ident_cleanup(chip);
6174 EXPORT_SYMBOL_GPL(nand_cleanup);
6176 MODULE_LICENSE("GPL");
6177 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
6178 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
6179 MODULE_DESCRIPTION("Generic NAND flash driver code");