1 // SPDX-License-Identifier: GPL-2.0-only
4 * This is the generic MTD driver for NAND flash devices. It should be
5 * capable of working with almost all NAND chips currently available.
7 * Additional technical information is available on
8 * http://www.linux-mtd.infradead.org/doc/nand.html
10 * Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
11 * 2002-2006 Thomas Gleixner (tglx@linutronix.de)
14 * David Woodhouse for adding multichip support
16 * Aleph One Ltd. and Toby Churchill Ltd. for supporting the
17 * rework for 2K page size chips
20 * Enable cached programming for 2k page size chips
21 * Check, if mtd->ecctype should be set to MTD_ECC_HW
22 * if we have HW ECC support.
23 * BBT table is not serialized, has to be fixed
26 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
28 #include <linux/module.h>
29 #include <linux/delay.h>
30 #include <linux/errno.h>
31 #include <linux/err.h>
32 #include <linux/sched.h>
33 #include <linux/slab.h>
35 #include <linux/types.h>
36 #include <linux/mtd/mtd.h>
37 #include <linux/mtd/nand.h>
38 #include <linux/mtd/nand-ecc-sw-hamming.h>
39 #include <linux/mtd/nand-ecc-sw-bch.h>
40 #include <linux/interrupt.h>
41 #include <linux/bitops.h>
43 #include <linux/mtd/partitions.h>
45 #include <linux/gpio/consumer.h>
47 #include "internals.h"
49 static int nand_pairing_dist3_get_info(struct mtd_info *mtd, int page,
50 struct mtd_pairing_info *info)
52 int lastpage = (mtd->erasesize / mtd->writesize) - 1;
58 if (!page || (page & 1)) {
60 info->pair = (page + 1) / 2;
63 info->pair = (page + 1 - dist) / 2;
69 static int nand_pairing_dist3_get_wunit(struct mtd_info *mtd,
70 const struct mtd_pairing_info *info)
72 int lastpair = ((mtd->erasesize / mtd->writesize) - 1) / 2;
73 int page = info->pair * 2;
76 if (!info->group && !info->pair)
79 if (info->pair == lastpair && info->group)
87 if (page >= mtd->erasesize / mtd->writesize)
93 const struct mtd_pairing_scheme dist3_pairing_scheme = {
95 .get_info = nand_pairing_dist3_get_info,
96 .get_wunit = nand_pairing_dist3_get_wunit,
99 static int check_offs_len(struct nand_chip *chip, loff_t ofs, uint64_t len)
103 /* Start address must align on block boundary */
104 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
105 pr_debug("%s: unaligned address\n", __func__);
109 /* Length must align on block boundary */
110 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
111 pr_debug("%s: length not block aligned\n", __func__);
119 * nand_extract_bits - Copy unaligned bits from one buffer to another one
120 * @dst: destination buffer
121 * @dst_off: bit offset at which the writing starts
122 * @src: source buffer
123 * @src_off: bit offset at which the reading starts
124 * @nbits: number of bits to copy from @src to @dst
126 * Copy bits from one memory region to another (overlap authorized).
128 void nand_extract_bits(u8 *dst, unsigned int dst_off, const u8 *src,
129 unsigned int src_off, unsigned int nbits)
139 n = min3(8 - dst_off, 8 - src_off, nbits);
141 tmp = (*src >> src_off) & GENMASK(n - 1, 0);
142 *dst &= ~GENMASK(n - 1 + dst_off, dst_off);
143 *dst |= tmp << dst_off;
160 EXPORT_SYMBOL_GPL(nand_extract_bits);
163 * nand_select_target() - Select a NAND target (A.K.A. die)
164 * @chip: NAND chip object
165 * @cs: the CS line to select. Note that this CS id is always from the chip
166 * PoV, not the controller one
168 * Select a NAND target so that further operations executed on @chip go to the
169 * selected NAND target.
171 void nand_select_target(struct nand_chip *chip, unsigned int cs)
174 * cs should always lie between 0 and nanddev_ntargets(), when that's
175 * not the case it's a bug and the caller should be fixed.
177 if (WARN_ON(cs > nanddev_ntargets(&chip->base)))
182 if (chip->legacy.select_chip)
183 chip->legacy.select_chip(chip, cs);
185 EXPORT_SYMBOL_GPL(nand_select_target);
188 * nand_deselect_target() - Deselect the currently selected target
189 * @chip: NAND chip object
191 * Deselect the currently selected NAND target. The result of operations
192 * executed on @chip after the target has been deselected is undefined.
194 void nand_deselect_target(struct nand_chip *chip)
196 if (chip->legacy.select_chip)
197 chip->legacy.select_chip(chip, -1);
201 EXPORT_SYMBOL_GPL(nand_deselect_target);
204 * nand_release_device - [GENERIC] release chip
205 * @chip: NAND chip object
207 * Release chip lock and wake up anyone waiting on the device.
209 static void nand_release_device(struct nand_chip *chip)
211 /* Release the controller and the chip */
212 mutex_unlock(&chip->controller->lock);
213 mutex_unlock(&chip->lock);
217 * nand_bbm_get_next_page - Get the next page for bad block markers
218 * @chip: NAND chip object
219 * @page: First page to start checking for bad block marker usage
221 * Returns an integer that corresponds to the page offset within a block, for
222 * a page that is used to store bad block markers. If no more pages are
223 * available, -EINVAL is returned.
225 int nand_bbm_get_next_page(struct nand_chip *chip, int page)
227 struct mtd_info *mtd = nand_to_mtd(chip);
228 int last_page = ((mtd->erasesize - mtd->writesize) >>
229 chip->page_shift) & chip->pagemask;
230 unsigned int bbm_flags = NAND_BBM_FIRSTPAGE | NAND_BBM_SECONDPAGE
233 if (page == 0 && !(chip->options & bbm_flags))
235 if (page == 0 && chip->options & NAND_BBM_FIRSTPAGE)
237 if (page <= 1 && chip->options & NAND_BBM_SECONDPAGE)
239 if (page <= last_page && chip->options & NAND_BBM_LASTPAGE)
246 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
247 * @chip: NAND chip object
248 * @ofs: offset from device start
250 * Check, if the block is bad.
252 static int nand_block_bad(struct nand_chip *chip, loff_t ofs)
254 int first_page, page_offset;
258 first_page = (int)(ofs >> chip->page_shift) & chip->pagemask;
259 page_offset = nand_bbm_get_next_page(chip, 0);
261 while (page_offset >= 0) {
262 res = chip->ecc.read_oob(chip, first_page + page_offset);
266 bad = chip->oob_poi[chip->badblockpos];
268 if (likely(chip->badblockbits == 8))
271 res = hweight8(bad) < chip->badblockbits;
275 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
281 static int nand_isbad_bbm(struct nand_chip *chip, loff_t ofs)
283 if (chip->options & NAND_NO_BBM_QUIRK)
286 if (chip->legacy.block_bad)
287 return chip->legacy.block_bad(chip, ofs);
289 return nand_block_bad(chip, ofs);
293 * nand_get_device - [GENERIC] Get chip for selected access
294 * @chip: NAND chip structure
296 * Lock the device and its controller for exclusive access
298 * Return: -EBUSY if the chip has been suspended, 0 otherwise
300 static int nand_get_device(struct nand_chip *chip)
302 mutex_lock(&chip->lock);
303 if (chip->suspended) {
304 mutex_unlock(&chip->lock);
307 mutex_lock(&chip->controller->lock);
313 * nand_check_wp - [GENERIC] check if the chip is write protected
314 * @chip: NAND chip object
316 * Check, if the device is write protected. The function expects, that the
317 * device is already selected.
319 static int nand_check_wp(struct nand_chip *chip)
324 /* Broken xD cards report WP despite being writable */
325 if (chip->options & NAND_BROKEN_XD)
328 /* Check the WP bit */
329 ret = nand_status_op(chip, &status);
333 return status & NAND_STATUS_WP ? 0 : 1;
337 * nand_fill_oob - [INTERN] Transfer client buffer to oob
338 * @chip: NAND chip object
339 * @oob: oob data buffer
340 * @len: oob data write length
341 * @ops: oob ops structure
343 static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len,
344 struct mtd_oob_ops *ops)
346 struct mtd_info *mtd = nand_to_mtd(chip);
350 * Initialise to all 0xFF, to avoid the possibility of left over OOB
351 * data from a previous OOB read.
353 memset(chip->oob_poi, 0xff, mtd->oobsize);
357 case MTD_OPS_PLACE_OOB:
359 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
362 case MTD_OPS_AUTO_OOB:
363 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
375 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
376 * @chip: NAND chip object
377 * @to: offset to write to
378 * @ops: oob operation description structure
380 * NAND write out-of-band.
382 static int nand_do_write_oob(struct nand_chip *chip, loff_t to,
383 struct mtd_oob_ops *ops)
385 struct mtd_info *mtd = nand_to_mtd(chip);
386 int chipnr, page, status, len, ret;
388 pr_debug("%s: to = 0x%08x, len = %i\n",
389 __func__, (unsigned int)to, (int)ops->ooblen);
391 len = mtd_oobavail(mtd, ops);
393 /* Do not allow write past end of page */
394 if ((ops->ooboffs + ops->ooblen) > len) {
395 pr_debug("%s: attempt to write past end of page\n",
400 chipnr = (int)(to >> chip->chip_shift);
403 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
404 * of my DiskOnChip 2000 test units) will clear the whole data page too
405 * if we don't do this. I have no clue why, but I seem to have 'fixed'
406 * it in the doc2000 driver in August 1999. dwmw2.
408 ret = nand_reset(chip, chipnr);
412 nand_select_target(chip, chipnr);
414 /* Shift to get page */
415 page = (int)(to >> chip->page_shift);
417 /* Check, if it is write protected */
418 if (nand_check_wp(chip)) {
419 nand_deselect_target(chip);
423 /* Invalidate the page cache, if we write to the cached page */
424 if (page == chip->pagecache.page)
425 chip->pagecache.page = -1;
427 nand_fill_oob(chip, ops->oobbuf, ops->ooblen, ops);
429 if (ops->mode == MTD_OPS_RAW)
430 status = chip->ecc.write_oob_raw(chip, page & chip->pagemask);
432 status = chip->ecc.write_oob(chip, page & chip->pagemask);
434 nand_deselect_target(chip);
439 ops->oobretlen = ops->ooblen;
445 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
446 * @chip: NAND chip object
447 * @ofs: offset from device start
449 * This is the default implementation, which can be overridden by a hardware
450 * specific driver. It provides the details for writing a bad block marker to a
453 static int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
455 struct mtd_info *mtd = nand_to_mtd(chip);
456 struct mtd_oob_ops ops;
457 uint8_t buf[2] = { 0, 0 };
458 int ret = 0, res, page_offset;
460 memset(&ops, 0, sizeof(ops));
462 ops.ooboffs = chip->badblockpos;
463 if (chip->options & NAND_BUSWIDTH_16) {
464 ops.ooboffs &= ~0x01;
465 ops.len = ops.ooblen = 2;
467 ops.len = ops.ooblen = 1;
469 ops.mode = MTD_OPS_PLACE_OOB;
471 page_offset = nand_bbm_get_next_page(chip, 0);
473 while (page_offset >= 0) {
474 res = nand_do_write_oob(chip,
475 ofs + (page_offset * mtd->writesize),
481 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
488 * nand_markbad_bbm - mark a block by updating the BBM
489 * @chip: NAND chip object
490 * @ofs: offset of the block to mark bad
492 int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
494 if (chip->legacy.block_markbad)
495 return chip->legacy.block_markbad(chip, ofs);
497 return nand_default_block_markbad(chip, ofs);
501 * nand_block_markbad_lowlevel - mark a block bad
502 * @chip: NAND chip object
503 * @ofs: offset from device start
505 * This function performs the generic NAND bad block marking steps (i.e., bad
506 * block table(s) and/or marker(s)). We only allow the hardware driver to
507 * specify how to write bad block markers to OOB (chip->legacy.block_markbad).
509 * We try operations in the following order:
511 * (1) erase the affected block, to allow OOB marker to be written cleanly
512 * (2) write bad block marker to OOB area of affected block (unless flag
513 * NAND_BBT_NO_OOB_BBM is present)
516 * Note that we retain the first error encountered in (2) or (3), finish the
517 * procedures, and dump the error in the end.
519 static int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
521 struct mtd_info *mtd = nand_to_mtd(chip);
524 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
525 struct erase_info einfo;
527 /* Attempt erase before marking OOB */
528 memset(&einfo, 0, sizeof(einfo));
530 einfo.len = 1ULL << chip->phys_erase_shift;
531 nand_erase_nand(chip, &einfo, 0);
533 /* Write bad block marker to OOB */
534 ret = nand_get_device(chip);
538 ret = nand_markbad_bbm(chip, ofs);
539 nand_release_device(chip);
542 /* Mark block bad in BBT */
544 res = nand_markbad_bbt(chip, ofs);
550 mtd->ecc_stats.badblocks++;
556 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
557 * @mtd: MTD device structure
558 * @ofs: offset from device start
560 * Check if the block is marked as reserved.
562 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
564 struct nand_chip *chip = mtd_to_nand(mtd);
568 /* Return info from the table */
569 return nand_isreserved_bbt(chip, ofs);
573 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
574 * @chip: NAND chip object
575 * @ofs: offset from device start
576 * @allowbbt: 1, if its allowed to access the bbt area
578 * Check, if the block is bad. Either by reading the bad block table or
579 * calling of the scan function.
581 static int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
583 /* Return info from the table */
585 return nand_isbad_bbt(chip, ofs, allowbbt);
587 return nand_isbad_bbm(chip, ofs);
591 * nand_soft_waitrdy - Poll STATUS reg until RDY bit is set to 1
592 * @chip: NAND chip structure
593 * @timeout_ms: Timeout in ms
595 * Poll the STATUS register using ->exec_op() until the RDY bit becomes 1.
596 * If that does not happen whitin the specified timeout, -ETIMEDOUT is
599 * This helper is intended to be used when the controller does not have access
600 * to the NAND R/B pin.
602 * Be aware that calling this helper from an ->exec_op() implementation means
603 * ->exec_op() must be re-entrant.
605 * Return 0 if the NAND chip is ready, a negative error otherwise.
607 int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
609 const struct nand_sdr_timings *timings;
613 if (!nand_has_exec_op(chip))
616 /* Wait tWB before polling the STATUS reg. */
617 timings = nand_get_sdr_timings(nand_get_interface_config(chip));
618 ndelay(PSEC_TO_NSEC(timings->tWB_max));
620 ret = nand_status_op(chip, NULL);
625 * +1 below is necessary because if we are now in the last fraction
626 * of jiffy and msecs_to_jiffies is 1 then we will wait only that
627 * small jiffy fraction - possibly leading to false timeout
629 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
631 ret = nand_read_data_op(chip, &status, sizeof(status), true,
636 if (status & NAND_STATUS_READY)
640 * Typical lowest execution time for a tR on most NANDs is 10us,
641 * use this as polling delay before doing something smarter (ie.
642 * deriving a delay from the timeout value, timeout_ms/ratio).
645 } while (time_before(jiffies, timeout_ms));
648 * We have to exit READ_STATUS mode in order to read real data on the
649 * bus in case the WAITRDY instruction is preceding a DATA_IN
652 nand_exit_status_op(chip);
657 return status & NAND_STATUS_READY ? 0 : -ETIMEDOUT;
659 EXPORT_SYMBOL_GPL(nand_soft_waitrdy);
662 * nand_gpio_waitrdy - Poll R/B GPIO pin until ready
663 * @chip: NAND chip structure
664 * @gpiod: GPIO descriptor of R/B pin
665 * @timeout_ms: Timeout in ms
667 * Poll the R/B GPIO pin until it becomes ready. If that does not happen
668 * whitin the specified timeout, -ETIMEDOUT is returned.
670 * This helper is intended to be used when the controller has access to the
671 * NAND R/B pin over GPIO.
673 * Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.
675 int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
676 unsigned long timeout_ms)
680 * Wait until R/B pin indicates chip is ready or timeout occurs.
681 * +1 below is necessary because if we are now in the last fraction
682 * of jiffy and msecs_to_jiffies is 1 then we will wait only that
683 * small jiffy fraction - possibly leading to false timeout.
685 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
687 if (gpiod_get_value_cansleep(gpiod))
691 } while (time_before(jiffies, timeout_ms));
693 return gpiod_get_value_cansleep(gpiod) ? 0 : -ETIMEDOUT;
695 EXPORT_SYMBOL_GPL(nand_gpio_waitrdy);
698 * panic_nand_wait - [GENERIC] wait until the command is done
699 * @chip: NAND chip structure
702 * Wait for command done. This is a helper function for nand_wait used when
703 * we are in interrupt context. May happen when in panic and trying to write
704 * an oops through mtdoops.
706 void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
709 for (i = 0; i < timeo; i++) {
710 if (chip->legacy.dev_ready) {
711 if (chip->legacy.dev_ready(chip))
717 ret = nand_read_data_op(chip, &status, sizeof(status),
722 if (status & NAND_STATUS_READY)
729 static bool nand_supports_get_features(struct nand_chip *chip, int addr)
731 return (chip->parameters.supports_set_get_features &&
732 test_bit(addr, chip->parameters.get_feature_list));
735 static bool nand_supports_set_features(struct nand_chip *chip, int addr)
737 return (chip->parameters.supports_set_get_features &&
738 test_bit(addr, chip->parameters.set_feature_list));
742 * nand_reset_interface - Reset data interface and timings
743 * @chip: The NAND chip
744 * @chipnr: Internal die id
746 * Reset the Data interface and timings to ONFI mode 0.
748 * Returns 0 for success or negative error code otherwise.
750 static int nand_reset_interface(struct nand_chip *chip, int chipnr)
752 const struct nand_controller_ops *ops = chip->controller->ops;
755 if (!nand_controller_can_setup_interface(chip))
759 * The ONFI specification says:
761 * To transition from NV-DDR or NV-DDR2 to the SDR data
762 * interface, the host shall use the Reset (FFh) command
763 * using SDR timing mode 0. A device in any timing mode is
764 * required to recognize Reset (FFh) command issued in SDR
768 * Configure the data interface in SDR mode and set the
769 * timings to timing mode 0.
772 chip->current_interface_config = nand_get_reset_interface_config();
773 ret = ops->setup_interface(chip, chipnr,
774 chip->current_interface_config);
776 pr_err("Failed to configure data interface to SDR timing mode 0\n");
782 * nand_setup_interface - Setup the best data interface and timings
783 * @chip: The NAND chip
784 * @chipnr: Internal die id
786 * Configure what has been reported to be the best data interface and NAND
787 * timings supported by the chip and the driver.
789 * Returns 0 for success or negative error code otherwise.
791 static int nand_setup_interface(struct nand_chip *chip, int chipnr)
793 const struct nand_controller_ops *ops = chip->controller->ops;
794 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = { };
797 if (!nand_controller_can_setup_interface(chip))
801 * A nand_reset_interface() put both the NAND chip and the NAND
802 * controller in timings mode 0. If the default mode for this chip is
803 * also 0, no need to proceed to the change again. Plus, at probe time,
804 * nand_setup_interface() uses ->set/get_features() which would
805 * fail anyway as the parameter page is not available yet.
807 if (!chip->best_interface_config)
810 tmode_param[0] = chip->best_interface_config->timings.mode;
812 /* Change the mode on the chip side (if supported by the NAND chip) */
813 if (nand_supports_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE)) {
814 nand_select_target(chip, chipnr);
815 ret = nand_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
817 nand_deselect_target(chip);
822 /* Change the mode on the controller side */
823 ret = ops->setup_interface(chip, chipnr, chip->best_interface_config);
827 /* Check the mode has been accepted by the chip, if supported */
828 if (!nand_supports_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE))
829 goto update_interface_config;
831 memset(tmode_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
832 nand_select_target(chip, chipnr);
833 ret = nand_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
835 nand_deselect_target(chip);
839 if (tmode_param[0] != chip->best_interface_config->timings.mode) {
840 pr_warn("timing mode %d not acknowledged by the NAND chip\n",
841 chip->best_interface_config->timings.mode);
845 update_interface_config:
846 chip->current_interface_config = chip->best_interface_config;
852 * Fallback to mode 0 if the chip explicitly did not ack the chosen
855 nand_reset_interface(chip, chipnr);
856 nand_select_target(chip, chipnr);
858 nand_deselect_target(chip);
864 * nand_choose_best_sdr_timings - Pick up the best SDR timings that both the
865 * NAND controller and the NAND chip support
866 * @chip: the NAND chip
867 * @iface: the interface configuration (can eventually be updated)
868 * @spec_timings: specific timings, when not fitting the ONFI specification
870 * If specific timings are provided, use them. Otherwise, retrieve supported
871 * timing modes from ONFI information.
873 int nand_choose_best_sdr_timings(struct nand_chip *chip,
874 struct nand_interface_config *iface,
875 struct nand_sdr_timings *spec_timings)
877 const struct nand_controller_ops *ops = chip->controller->ops;
878 int best_mode = 0, mode, ret;
880 iface->type = NAND_SDR_IFACE;
883 iface->timings.sdr = *spec_timings;
884 iface->timings.mode = onfi_find_closest_sdr_mode(spec_timings);
886 /* Verify the controller supports the requested interface */
887 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
890 chip->best_interface_config = iface;
894 /* Fallback to slower modes */
895 best_mode = iface->timings.mode;
896 } else if (chip->parameters.onfi) {
897 best_mode = fls(chip->parameters.onfi->async_timing_mode) - 1;
900 for (mode = best_mode; mode >= 0; mode--) {
901 onfi_fill_interface_config(chip, iface, NAND_SDR_IFACE, mode);
903 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
909 chip->best_interface_config = iface;
915 * nand_choose_interface_config - find the best data interface and timings
916 * @chip: The NAND chip
918 * Find the best data interface and NAND timings supported by the chip
919 * and the driver. Eventually let the NAND manufacturer driver propose his own
922 * After this function nand_chip->interface_config is initialized with the best
923 * timing mode available.
925 * Returns 0 for success or negative error code otherwise.
927 static int nand_choose_interface_config(struct nand_chip *chip)
929 struct nand_interface_config *iface;
932 if (!nand_controller_can_setup_interface(chip))
935 iface = kzalloc(sizeof(*iface), GFP_KERNEL);
939 if (chip->ops.choose_interface_config)
940 ret = chip->ops.choose_interface_config(chip, iface);
942 ret = nand_choose_best_sdr_timings(chip, iface, NULL);
951 * nand_fill_column_cycles - fill the column cycles of an address
952 * @chip: The NAND chip
953 * @addrs: Array of address cycles to fill
954 * @offset_in_page: The offset in the page
956 * Fills the first or the first two bytes of the @addrs field depending
957 * on the NAND bus width and the page size.
959 * Returns the number of cycles needed to encode the column, or a negative
960 * error code in case one of the arguments is invalid.
962 static int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs,
963 unsigned int offset_in_page)
965 struct mtd_info *mtd = nand_to_mtd(chip);
967 /* Make sure the offset is less than the actual page size. */
968 if (offset_in_page > mtd->writesize + mtd->oobsize)
972 * On small page NANDs, there's a dedicated command to access the OOB
973 * area, and the column address is relative to the start of the OOB
974 * area, not the start of the page. Asjust the address accordingly.
976 if (mtd->writesize <= 512 && offset_in_page >= mtd->writesize)
977 offset_in_page -= mtd->writesize;
980 * The offset in page is expressed in bytes, if the NAND bus is 16-bit
981 * wide, then it must be divided by 2.
983 if (chip->options & NAND_BUSWIDTH_16) {
984 if (WARN_ON(offset_in_page % 2))
990 addrs[0] = offset_in_page;
993 * Small page NANDs use 1 cycle for the columns, while large page NANDs
996 if (mtd->writesize <= 512)
999 addrs[1] = offset_in_page >> 8;
1004 static int nand_sp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1005 unsigned int offset_in_page, void *buf,
1008 const struct nand_sdr_timings *sdr =
1009 nand_get_sdr_timings(nand_get_interface_config(chip));
1010 struct mtd_info *mtd = nand_to_mtd(chip);
1012 struct nand_op_instr instrs[] = {
1013 NAND_OP_CMD(NAND_CMD_READ0, 0),
1014 NAND_OP_ADDR(3, addrs, PSEC_TO_NSEC(sdr->tWB_max)),
1015 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1016 PSEC_TO_NSEC(sdr->tRR_min)),
1017 NAND_OP_DATA_IN(len, buf, 0),
1019 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1022 /* Drop the DATA_IN instruction if len is set to 0. */
1026 if (offset_in_page >= mtd->writesize)
1027 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1028 else if (offset_in_page >= 256 &&
1029 !(chip->options & NAND_BUSWIDTH_16))
1030 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1032 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1037 addrs[2] = page >> 8;
1039 if (chip->options & NAND_ROW_ADDR_3) {
1040 addrs[3] = page >> 16;
1041 instrs[1].ctx.addr.naddrs++;
1044 return nand_exec_op(chip, &op);
1047 static int nand_lp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1048 unsigned int offset_in_page, void *buf,
1051 const struct nand_sdr_timings *sdr =
1052 nand_get_sdr_timings(nand_get_interface_config(chip));
1054 struct nand_op_instr instrs[] = {
1055 NAND_OP_CMD(NAND_CMD_READ0, 0),
1056 NAND_OP_ADDR(4, addrs, 0),
1057 NAND_OP_CMD(NAND_CMD_READSTART, PSEC_TO_NSEC(sdr->tWB_max)),
1058 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1059 PSEC_TO_NSEC(sdr->tRR_min)),
1060 NAND_OP_DATA_IN(len, buf, 0),
1062 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1065 /* Drop the DATA_IN instruction if len is set to 0. */
1069 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1074 addrs[3] = page >> 8;
1076 if (chip->options & NAND_ROW_ADDR_3) {
1077 addrs[4] = page >> 16;
1078 instrs[1].ctx.addr.naddrs++;
1081 return nand_exec_op(chip, &op);
1085 * nand_read_page_op - Do a READ PAGE operation
1086 * @chip: The NAND chip
1087 * @page: page to read
1088 * @offset_in_page: offset within the page
1089 * @buf: buffer used to store the data
1090 * @len: length of the buffer
1092 * This function issues a READ PAGE operation.
1093 * This function does not select/unselect the CS line.
1095 * Returns 0 on success, a negative error code otherwise.
1097 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1098 unsigned int offset_in_page, void *buf, unsigned int len)
1100 struct mtd_info *mtd = nand_to_mtd(chip);
1105 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1108 if (nand_has_exec_op(chip)) {
1109 if (mtd->writesize > 512)
1110 return nand_lp_exec_read_page_op(chip, page,
1111 offset_in_page, buf,
1114 return nand_sp_exec_read_page_op(chip, page, offset_in_page,
1118 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, offset_in_page, page);
1120 chip->legacy.read_buf(chip, buf, len);
1124 EXPORT_SYMBOL_GPL(nand_read_page_op);
1127 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1128 * @chip: The NAND chip
1129 * @page: parameter page to read
1130 * @buf: buffer used to store the data
1131 * @len: length of the buffer
1133 * This function issues a READ PARAMETER PAGE operation.
1134 * This function does not select/unselect the CS line.
1136 * Returns 0 on success, a negative error code otherwise.
1138 int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1147 if (nand_has_exec_op(chip)) {
1148 const struct nand_sdr_timings *sdr =
1149 nand_get_sdr_timings(nand_get_interface_config(chip));
1150 struct nand_op_instr instrs[] = {
1151 NAND_OP_CMD(NAND_CMD_PARAM, 0),
1152 NAND_OP_ADDR(1, &page, PSEC_TO_NSEC(sdr->tWB_max)),
1153 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1154 PSEC_TO_NSEC(sdr->tRR_min)),
1155 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1157 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1159 /* Drop the DATA_IN instruction if len is set to 0. */
1163 return nand_exec_op(chip, &op);
1166 chip->legacy.cmdfunc(chip, NAND_CMD_PARAM, page, -1);
1167 for (i = 0; i < len; i++)
1168 p[i] = chip->legacy.read_byte(chip);
1174 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1175 * @chip: The NAND chip
1176 * @offset_in_page: offset within the page
1177 * @buf: buffer used to store the data
1178 * @len: length of the buffer
1179 * @force_8bit: force 8-bit bus access
1181 * This function issues a CHANGE READ COLUMN operation.
1182 * This function does not select/unselect the CS line.
1184 * Returns 0 on success, a negative error code otherwise.
1186 int nand_change_read_column_op(struct nand_chip *chip,
1187 unsigned int offset_in_page, void *buf,
1188 unsigned int len, bool force_8bit)
1190 struct mtd_info *mtd = nand_to_mtd(chip);
1195 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1198 /* Small page NANDs do not support column change. */
1199 if (mtd->writesize <= 512)
1202 if (nand_has_exec_op(chip)) {
1203 const struct nand_sdr_timings *sdr =
1204 nand_get_sdr_timings(nand_get_interface_config(chip));
1206 struct nand_op_instr instrs[] = {
1207 NAND_OP_CMD(NAND_CMD_RNDOUT, 0),
1208 NAND_OP_ADDR(2, addrs, 0),
1209 NAND_OP_CMD(NAND_CMD_RNDOUTSTART,
1210 PSEC_TO_NSEC(sdr->tCCS_min)),
1211 NAND_OP_DATA_IN(len, buf, 0),
1213 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1216 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1220 /* Drop the DATA_IN instruction if len is set to 0. */
1224 instrs[3].ctx.data.force_8bit = force_8bit;
1226 return nand_exec_op(chip, &op);
1229 chip->legacy.cmdfunc(chip, NAND_CMD_RNDOUT, offset_in_page, -1);
1231 chip->legacy.read_buf(chip, buf, len);
1235 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1238 * nand_read_oob_op - Do a READ OOB operation
1239 * @chip: The NAND chip
1240 * @page: page to read
1241 * @offset_in_oob: offset within the OOB area
1242 * @buf: buffer used to store the data
1243 * @len: length of the buffer
1245 * This function issues a READ OOB operation.
1246 * This function does not select/unselect the CS line.
1248 * Returns 0 on success, a negative error code otherwise.
1250 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1251 unsigned int offset_in_oob, void *buf, unsigned int len)
1253 struct mtd_info *mtd = nand_to_mtd(chip);
1258 if (offset_in_oob + len > mtd->oobsize)
1261 if (nand_has_exec_op(chip))
1262 return nand_read_page_op(chip, page,
1263 mtd->writesize + offset_in_oob,
1266 chip->legacy.cmdfunc(chip, NAND_CMD_READOOB, offset_in_oob, page);
1268 chip->legacy.read_buf(chip, buf, len);
1272 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1274 static int nand_exec_prog_page_op(struct nand_chip *chip, unsigned int page,
1275 unsigned int offset_in_page, const void *buf,
1276 unsigned int len, bool prog)
1278 const struct nand_sdr_timings *sdr =
1279 nand_get_sdr_timings(nand_get_interface_config(chip));
1280 struct mtd_info *mtd = nand_to_mtd(chip);
1282 struct nand_op_instr instrs[] = {
1284 * The first instruction will be dropped if we're dealing
1285 * with a large page NAND and adjusted if we're dealing
1286 * with a small page NAND and the page offset is > 255.
1288 NAND_OP_CMD(NAND_CMD_READ0, 0),
1289 NAND_OP_CMD(NAND_CMD_SEQIN, 0),
1290 NAND_OP_ADDR(0, addrs, PSEC_TO_NSEC(sdr->tADL_min)),
1291 NAND_OP_DATA_OUT(len, buf, 0),
1292 NAND_OP_CMD(NAND_CMD_PAGEPROG, PSEC_TO_NSEC(sdr->tWB_max)),
1293 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1295 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1296 int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
1303 addrs[naddrs++] = page;
1304 addrs[naddrs++] = page >> 8;
1305 if (chip->options & NAND_ROW_ADDR_3)
1306 addrs[naddrs++] = page >> 16;
1308 instrs[2].ctx.addr.naddrs = naddrs;
1310 /* Drop the last two instructions if we're not programming the page. */
1313 /* Also drop the DATA_OUT instruction if empty. */
1318 if (mtd->writesize <= 512) {
1320 * Small pages need some more tweaking: we have to adjust the
1321 * first instruction depending on the page offset we're trying
1324 if (offset_in_page >= mtd->writesize)
1325 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1326 else if (offset_in_page >= 256 &&
1327 !(chip->options & NAND_BUSWIDTH_16))
1328 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1331 * Drop the first command if we're dealing with a large page
1338 ret = nand_exec_op(chip, &op);
1342 ret = nand_status_op(chip, &status);
1350 * nand_prog_page_begin_op - starts a PROG PAGE operation
1351 * @chip: The NAND chip
1352 * @page: page to write
1353 * @offset_in_page: offset within the page
1354 * @buf: buffer containing the data to write to the page
1355 * @len: length of the buffer
1357 * This function issues the first half of a PROG PAGE operation.
1358 * This function does not select/unselect the CS line.
1360 * Returns 0 on success, a negative error code otherwise.
1362 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1363 unsigned int offset_in_page, const void *buf,
1366 struct mtd_info *mtd = nand_to_mtd(chip);
1371 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1374 if (nand_has_exec_op(chip))
1375 return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1378 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page, page);
1381 chip->legacy.write_buf(chip, buf, len);
1385 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1388 * nand_prog_page_end_op - ends a PROG PAGE operation
1389 * @chip: The NAND chip
1391 * This function issues the second half of a PROG PAGE operation.
1392 * This function does not select/unselect the CS line.
1394 * Returns 0 on success, a negative error code otherwise.
1396 int nand_prog_page_end_op(struct nand_chip *chip)
1401 if (nand_has_exec_op(chip)) {
1402 const struct nand_sdr_timings *sdr =
1403 nand_get_sdr_timings(nand_get_interface_config(chip));
1404 struct nand_op_instr instrs[] = {
1405 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1406 PSEC_TO_NSEC(sdr->tWB_max)),
1407 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1409 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1411 ret = nand_exec_op(chip, &op);
1415 ret = nand_status_op(chip, &status);
1419 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1420 ret = chip->legacy.waitfunc(chip);
1427 if (status & NAND_STATUS_FAIL)
1432 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1435 * nand_prog_page_op - Do a full PROG PAGE operation
1436 * @chip: The NAND chip
1437 * @page: page to write
1438 * @offset_in_page: offset within the page
1439 * @buf: buffer containing the data to write to the page
1440 * @len: length of the buffer
1442 * This function issues a full PROG PAGE operation.
1443 * This function does not select/unselect the CS line.
1445 * Returns 0 on success, a negative error code otherwise.
1447 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1448 unsigned int offset_in_page, const void *buf,
1451 struct mtd_info *mtd = nand_to_mtd(chip);
1457 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1460 if (nand_has_exec_op(chip)) {
1461 status = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1464 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page,
1466 chip->legacy.write_buf(chip, buf, len);
1467 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1468 status = chip->legacy.waitfunc(chip);
1471 if (status & NAND_STATUS_FAIL)
1476 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1479 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1480 * @chip: The NAND chip
1481 * @offset_in_page: offset within the page
1482 * @buf: buffer containing the data to send to the NAND
1483 * @len: length of the buffer
1484 * @force_8bit: force 8-bit bus access
1486 * This function issues a CHANGE WRITE COLUMN operation.
1487 * This function does not select/unselect the CS line.
1489 * Returns 0 on success, a negative error code otherwise.
1491 int nand_change_write_column_op(struct nand_chip *chip,
1492 unsigned int offset_in_page,
1493 const void *buf, unsigned int len,
1496 struct mtd_info *mtd = nand_to_mtd(chip);
1501 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1504 /* Small page NANDs do not support column change. */
1505 if (mtd->writesize <= 512)
1508 if (nand_has_exec_op(chip)) {
1509 const struct nand_sdr_timings *sdr =
1510 nand_get_sdr_timings(nand_get_interface_config(chip));
1512 struct nand_op_instr instrs[] = {
1513 NAND_OP_CMD(NAND_CMD_RNDIN, 0),
1514 NAND_OP_ADDR(2, addrs, PSEC_TO_NSEC(sdr->tCCS_min)),
1515 NAND_OP_DATA_OUT(len, buf, 0),
1517 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1520 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1524 instrs[2].ctx.data.force_8bit = force_8bit;
1526 /* Drop the DATA_OUT instruction if len is set to 0. */
1530 return nand_exec_op(chip, &op);
1533 chip->legacy.cmdfunc(chip, NAND_CMD_RNDIN, offset_in_page, -1);
1535 chip->legacy.write_buf(chip, buf, len);
1539 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1542 * nand_readid_op - Do a READID operation
1543 * @chip: The NAND chip
1544 * @addr: address cycle to pass after the READID command
1545 * @buf: buffer used to store the ID
1546 * @len: length of the buffer
1548 * This function sends a READID command and reads back the ID returned by the
1550 * This function does not select/unselect the CS line.
1552 * Returns 0 on success, a negative error code otherwise.
1554 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1563 if (nand_has_exec_op(chip)) {
1564 const struct nand_sdr_timings *sdr =
1565 nand_get_sdr_timings(nand_get_interface_config(chip));
1566 struct nand_op_instr instrs[] = {
1567 NAND_OP_CMD(NAND_CMD_READID, 0),
1568 NAND_OP_ADDR(1, &addr, PSEC_TO_NSEC(sdr->tADL_min)),
1569 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1571 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1573 /* Drop the DATA_IN instruction if len is set to 0. */
1577 return nand_exec_op(chip, &op);
1580 chip->legacy.cmdfunc(chip, NAND_CMD_READID, addr, -1);
1582 for (i = 0; i < len; i++)
1583 id[i] = chip->legacy.read_byte(chip);
1587 EXPORT_SYMBOL_GPL(nand_readid_op);
1590 * nand_status_op - Do a STATUS operation
1591 * @chip: The NAND chip
1592 * @status: out variable to store the NAND status
1594 * This function sends a STATUS command and reads back the status returned by
1596 * This function does not select/unselect the CS line.
1598 * Returns 0 on success, a negative error code otherwise.
1600 int nand_status_op(struct nand_chip *chip, u8 *status)
1602 if (nand_has_exec_op(chip)) {
1603 const struct nand_sdr_timings *sdr =
1604 nand_get_sdr_timings(nand_get_interface_config(chip));
1605 struct nand_op_instr instrs[] = {
1606 NAND_OP_CMD(NAND_CMD_STATUS,
1607 PSEC_TO_NSEC(sdr->tADL_min)),
1608 NAND_OP_8BIT_DATA_IN(1, status, 0),
1610 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1615 return nand_exec_op(chip, &op);
1618 chip->legacy.cmdfunc(chip, NAND_CMD_STATUS, -1, -1);
1620 *status = chip->legacy.read_byte(chip);
1624 EXPORT_SYMBOL_GPL(nand_status_op);
1627 * nand_exit_status_op - Exit a STATUS operation
1628 * @chip: The NAND chip
1630 * This function sends a READ0 command to cancel the effect of the STATUS
1631 * command to avoid reading only the status until a new read command is sent.
1633 * This function does not select/unselect the CS line.
1635 * Returns 0 on success, a negative error code otherwise.
1637 int nand_exit_status_op(struct nand_chip *chip)
1639 if (nand_has_exec_op(chip)) {
1640 struct nand_op_instr instrs[] = {
1641 NAND_OP_CMD(NAND_CMD_READ0, 0),
1643 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1645 return nand_exec_op(chip, &op);
1648 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, -1, -1);
1654 * nand_erase_op - Do an erase operation
1655 * @chip: The NAND chip
1656 * @eraseblock: block to erase
1658 * This function sends an ERASE command and waits for the NAND to be ready
1660 * This function does not select/unselect the CS line.
1662 * Returns 0 on success, a negative error code otherwise.
1664 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1666 unsigned int page = eraseblock <<
1667 (chip->phys_erase_shift - chip->page_shift);
1671 if (nand_has_exec_op(chip)) {
1672 const struct nand_sdr_timings *sdr =
1673 nand_get_sdr_timings(nand_get_interface_config(chip));
1674 u8 addrs[3] = { page, page >> 8, page >> 16 };
1675 struct nand_op_instr instrs[] = {
1676 NAND_OP_CMD(NAND_CMD_ERASE1, 0),
1677 NAND_OP_ADDR(2, addrs, 0),
1678 NAND_OP_CMD(NAND_CMD_ERASE2,
1679 PSEC_TO_MSEC(sdr->tWB_max)),
1680 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tBERS_max), 0),
1682 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1684 if (chip->options & NAND_ROW_ADDR_3)
1685 instrs[1].ctx.addr.naddrs++;
1687 ret = nand_exec_op(chip, &op);
1691 ret = nand_status_op(chip, &status);
1695 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE1, -1, page);
1696 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE2, -1, -1);
1698 ret = chip->legacy.waitfunc(chip);
1705 if (status & NAND_STATUS_FAIL)
1710 EXPORT_SYMBOL_GPL(nand_erase_op);
1713 * nand_set_features_op - Do a SET FEATURES operation
1714 * @chip: The NAND chip
1715 * @feature: feature id
1716 * @data: 4 bytes of data
1718 * This function sends a SET FEATURES command and waits for the NAND to be
1719 * ready before returning.
1720 * This function does not select/unselect the CS line.
1722 * Returns 0 on success, a negative error code otherwise.
1724 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1727 const u8 *params = data;
1730 if (nand_has_exec_op(chip)) {
1731 const struct nand_sdr_timings *sdr =
1732 nand_get_sdr_timings(nand_get_interface_config(chip));
1733 struct nand_op_instr instrs[] = {
1734 NAND_OP_CMD(NAND_CMD_SET_FEATURES, 0),
1735 NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tADL_min)),
1736 NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
1737 PSEC_TO_NSEC(sdr->tWB_max)),
1738 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max), 0),
1740 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1742 return nand_exec_op(chip, &op);
1745 chip->legacy.cmdfunc(chip, NAND_CMD_SET_FEATURES, feature, -1);
1746 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1747 chip->legacy.write_byte(chip, params[i]);
1749 ret = chip->legacy.waitfunc(chip);
1753 if (ret & NAND_STATUS_FAIL)
1760 * nand_get_features_op - Do a GET FEATURES operation
1761 * @chip: The NAND chip
1762 * @feature: feature id
1763 * @data: 4 bytes of data
1765 * This function sends a GET FEATURES command and waits for the NAND to be
1766 * ready before returning.
1767 * This function does not select/unselect the CS line.
1769 * Returns 0 on success, a negative error code otherwise.
1771 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1777 if (nand_has_exec_op(chip)) {
1778 const struct nand_sdr_timings *sdr =
1779 nand_get_sdr_timings(nand_get_interface_config(chip));
1780 struct nand_op_instr instrs[] = {
1781 NAND_OP_CMD(NAND_CMD_GET_FEATURES, 0),
1782 NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tWB_max)),
1783 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max),
1784 PSEC_TO_NSEC(sdr->tRR_min)),
1785 NAND_OP_8BIT_DATA_IN(ONFI_SUBFEATURE_PARAM_LEN,
1788 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1790 return nand_exec_op(chip, &op);
1793 chip->legacy.cmdfunc(chip, NAND_CMD_GET_FEATURES, feature, -1);
1794 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1795 params[i] = chip->legacy.read_byte(chip);
1800 static int nand_wait_rdy_op(struct nand_chip *chip, unsigned int timeout_ms,
1801 unsigned int delay_ns)
1803 if (nand_has_exec_op(chip)) {
1804 struct nand_op_instr instrs[] = {
1805 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(timeout_ms),
1806 PSEC_TO_NSEC(delay_ns)),
1808 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1810 return nand_exec_op(chip, &op);
1813 /* Apply delay or wait for ready/busy pin */
1814 if (!chip->legacy.dev_ready)
1815 udelay(chip->legacy.chip_delay);
1817 nand_wait_ready(chip);
1823 * nand_reset_op - Do a reset operation
1824 * @chip: The NAND chip
1826 * This function sends a RESET command and waits for the NAND to be ready
1828 * This function does not select/unselect the CS line.
1830 * Returns 0 on success, a negative error code otherwise.
1832 int nand_reset_op(struct nand_chip *chip)
1834 if (nand_has_exec_op(chip)) {
1835 const struct nand_sdr_timings *sdr =
1836 nand_get_sdr_timings(nand_get_interface_config(chip));
1837 struct nand_op_instr instrs[] = {
1838 NAND_OP_CMD(NAND_CMD_RESET, PSEC_TO_NSEC(sdr->tWB_max)),
1839 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tRST_max), 0),
1841 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1843 return nand_exec_op(chip, &op);
1846 chip->legacy.cmdfunc(chip, NAND_CMD_RESET, -1, -1);
1850 EXPORT_SYMBOL_GPL(nand_reset_op);
1853 * nand_read_data_op - Read data from the NAND
1854 * @chip: The NAND chip
1855 * @buf: buffer used to store the data
1856 * @len: length of the buffer
1857 * @force_8bit: force 8-bit bus access
1858 * @check_only: do not actually run the command, only checks if the
1859 * controller driver supports it
1861 * This function does a raw data read on the bus. Usually used after launching
1862 * another NAND operation like nand_read_page_op().
1863 * This function does not select/unselect the CS line.
1865 * Returns 0 on success, a negative error code otherwise.
1867 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
1868 bool force_8bit, bool check_only)
1873 if (nand_has_exec_op(chip)) {
1874 struct nand_op_instr instrs[] = {
1875 NAND_OP_DATA_IN(len, buf, 0),
1877 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1879 instrs[0].ctx.data.force_8bit = force_8bit;
1882 return nand_check_op(chip, &op);
1884 return nand_exec_op(chip, &op);
1894 for (i = 0; i < len; i++)
1895 p[i] = chip->legacy.read_byte(chip);
1897 chip->legacy.read_buf(chip, buf, len);
1902 EXPORT_SYMBOL_GPL(nand_read_data_op);
1905 * nand_write_data_op - Write data from the NAND
1906 * @chip: The NAND chip
1907 * @buf: buffer containing the data to send on the bus
1908 * @len: length of the buffer
1909 * @force_8bit: force 8-bit bus access
1911 * This function does a raw data write on the bus. Usually used after launching
1912 * another NAND operation like nand_write_page_begin_op().
1913 * This function does not select/unselect the CS line.
1915 * Returns 0 on success, a negative error code otherwise.
1917 int nand_write_data_op(struct nand_chip *chip, const void *buf,
1918 unsigned int len, bool force_8bit)
1923 if (nand_has_exec_op(chip)) {
1924 struct nand_op_instr instrs[] = {
1925 NAND_OP_DATA_OUT(len, buf, 0),
1927 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1929 instrs[0].ctx.data.force_8bit = force_8bit;
1931 return nand_exec_op(chip, &op);
1938 for (i = 0; i < len; i++)
1939 chip->legacy.write_byte(chip, p[i]);
1941 chip->legacy.write_buf(chip, buf, len);
1946 EXPORT_SYMBOL_GPL(nand_write_data_op);
1949 * struct nand_op_parser_ctx - Context used by the parser
1950 * @instrs: array of all the instructions that must be addressed
1951 * @ninstrs: length of the @instrs array
1952 * @subop: Sub-operation to be passed to the NAND controller
1954 * This structure is used by the core to split NAND operations into
1955 * sub-operations that can be handled by the NAND controller.
1957 struct nand_op_parser_ctx {
1958 const struct nand_op_instr *instrs;
1959 unsigned int ninstrs;
1960 struct nand_subop subop;
1964 * nand_op_parser_must_split_instr - Checks if an instruction must be split
1965 * @pat: the parser pattern element that matches @instr
1966 * @instr: pointer to the instruction to check
1967 * @start_offset: this is an in/out parameter. If @instr has already been
1968 * split, then @start_offset is the offset from which to start
1969 * (either an address cycle or an offset in the data buffer).
1970 * Conversely, if the function returns true (ie. instr must be
1971 * split), this parameter is updated to point to the first
1972 * data/address cycle that has not been taken care of.
1974 * Some NAND controllers are limited and cannot send X address cycles with a
1975 * unique operation, or cannot read/write more than Y bytes at the same time.
1976 * In this case, split the instruction that does not fit in a single
1977 * controller-operation into two or more chunks.
1979 * Returns true if the instruction must be split, false otherwise.
1980 * The @start_offset parameter is also updated to the offset at which the next
1981 * bundle of instruction must start (if an address or a data instruction).
1984 nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat,
1985 const struct nand_op_instr *instr,
1986 unsigned int *start_offset)
1988 switch (pat->type) {
1989 case NAND_OP_ADDR_INSTR:
1990 if (!pat->ctx.addr.maxcycles)
1993 if (instr->ctx.addr.naddrs - *start_offset >
1994 pat->ctx.addr.maxcycles) {
1995 *start_offset += pat->ctx.addr.maxcycles;
2000 case NAND_OP_DATA_IN_INSTR:
2001 case NAND_OP_DATA_OUT_INSTR:
2002 if (!pat->ctx.data.maxlen)
2005 if (instr->ctx.data.len - *start_offset >
2006 pat->ctx.data.maxlen) {
2007 *start_offset += pat->ctx.data.maxlen;
2020 * nand_op_parser_match_pat - Checks if a pattern matches the instructions
2021 * remaining in the parser context
2022 * @pat: the pattern to test
2023 * @ctx: the parser context structure to match with the pattern @pat
2025 * Check if @pat matches the set or a sub-set of instructions remaining in @ctx.
2026 * Returns true if this is the case, false ortherwise. When true is returned,
2027 * @ctx->subop is updated with the set of instructions to be passed to the
2028 * controller driver.
2031 nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
2032 struct nand_op_parser_ctx *ctx)
2034 unsigned int instr_offset = ctx->subop.first_instr_start_off;
2035 const struct nand_op_instr *end = ctx->instrs + ctx->ninstrs;
2036 const struct nand_op_instr *instr = ctx->subop.instrs;
2037 unsigned int i, ninstrs;
2039 for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
2041 * The pattern instruction does not match the operation
2042 * instruction. If the instruction is marked optional in the
2043 * pattern definition, we skip the pattern element and continue
2044 * to the next one. If the element is mandatory, there's no
2045 * match and we can return false directly.
2047 if (instr->type != pat->elems[i].type) {
2048 if (!pat->elems[i].optional)
2055 * Now check the pattern element constraints. If the pattern is
2056 * not able to handle the whole instruction in a single step,
2057 * we have to split it.
2058 * The last_instr_end_off value comes back updated to point to
2059 * the position where we have to split the instruction (the
2060 * start of the next subop chunk).
2062 if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
2075 * This can happen if all instructions of a pattern are optional.
2076 * Still, if there's not at least one instruction handled by this
2077 * pattern, this is not a match, and we should try the next one (if
2084 * We had a match on the pattern head, but the pattern may be longer
2085 * than the instructions we're asked to execute. We need to make sure
2086 * there's no mandatory elements in the pattern tail.
2088 for (; i < pat->nelems; i++) {
2089 if (!pat->elems[i].optional)
2094 * We have a match: update the subop structure accordingly and return
2097 ctx->subop.ninstrs = ninstrs;
2098 ctx->subop.last_instr_end_off = instr_offset;
2103 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
2104 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2106 const struct nand_op_instr *instr;
2110 pr_debug("executing subop (CS%d):\n", ctx->subop.cs);
2112 for (i = 0; i < ctx->ninstrs; i++) {
2113 instr = &ctx->instrs[i];
2115 if (instr == &ctx->subop.instrs[0])
2118 nand_op_trace(prefix, instr);
2120 if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
2125 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2131 static int nand_op_parser_cmp_ctx(const struct nand_op_parser_ctx *a,
2132 const struct nand_op_parser_ctx *b)
2134 if (a->subop.ninstrs < b->subop.ninstrs)
2136 else if (a->subop.ninstrs > b->subop.ninstrs)
2139 if (a->subop.last_instr_end_off < b->subop.last_instr_end_off)
2141 else if (a->subop.last_instr_end_off > b->subop.last_instr_end_off)
2148 * nand_op_parser_exec_op - exec_op parser
2149 * @chip: the NAND chip
2150 * @parser: patterns description provided by the controller driver
2151 * @op: the NAND operation to address
2152 * @check_only: when true, the function only checks if @op can be handled but
2153 * does not execute the operation
2155 * Helper function designed to ease integration of NAND controller drivers that
2156 * only support a limited set of instruction sequences. The supported sequences
2157 * are described in @parser, and the framework takes care of splitting @op into
2158 * multiple sub-operations (if required) and pass them back to the ->exec()
2159 * callback of the matching pattern if @check_only is set to false.
2161 * NAND controller drivers should call this function from their own ->exec_op()
2164 * Returns 0 on success, a negative error code otherwise. A failure can be
2165 * caused by an unsupported operation (none of the supported patterns is able
2166 * to handle the requested operation), or an error returned by one of the
2167 * matching pattern->exec() hook.
2169 int nand_op_parser_exec_op(struct nand_chip *chip,
2170 const struct nand_op_parser *parser,
2171 const struct nand_operation *op, bool check_only)
2173 struct nand_op_parser_ctx ctx = {
2175 .subop.instrs = op->instrs,
2176 .instrs = op->instrs,
2177 .ninstrs = op->ninstrs,
2181 while (ctx.subop.instrs < op->instrs + op->ninstrs) {
2182 const struct nand_op_parser_pattern *pattern;
2183 struct nand_op_parser_ctx best_ctx;
2184 int ret, best_pattern = -1;
2186 for (i = 0; i < parser->npatterns; i++) {
2187 struct nand_op_parser_ctx test_ctx = ctx;
2189 pattern = &parser->patterns[i];
2190 if (!nand_op_parser_match_pat(pattern, &test_ctx))
2193 if (best_pattern >= 0 &&
2194 nand_op_parser_cmp_ctx(&test_ctx, &best_ctx) <= 0)
2198 best_ctx = test_ctx;
2201 if (best_pattern < 0) {
2202 pr_debug("->exec_op() parser: pattern not found!\n");
2207 nand_op_parser_trace(&ctx);
2210 pattern = &parser->patterns[best_pattern];
2211 ret = pattern->exec(chip, &ctx.subop);
2217 * Update the context structure by pointing to the start of the
2220 ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
2221 if (ctx.subop.last_instr_end_off)
2222 ctx.subop.instrs -= 1;
2224 ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
2229 EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
2231 static bool nand_instr_is_data(const struct nand_op_instr *instr)
2233 return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
2234 instr->type == NAND_OP_DATA_OUT_INSTR);
2237 static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
2238 unsigned int instr_idx)
2240 return subop && instr_idx < subop->ninstrs;
2243 static unsigned int nand_subop_get_start_off(const struct nand_subop *subop,
2244 unsigned int instr_idx)
2249 return subop->first_instr_start_off;
2253 * nand_subop_get_addr_start_off - Get the start offset in an address array
2254 * @subop: The entire sub-operation
2255 * @instr_idx: Index of the instruction inside the sub-operation
2257 * During driver development, one could be tempted to directly use the
2258 * ->addr.addrs field of address instructions. This is wrong as address
2259 * instructions might be split.
2261 * Given an address instruction, returns the offset of the first cycle to issue.
2263 unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
2264 unsigned int instr_idx)
2266 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2267 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2270 return nand_subop_get_start_off(subop, instr_idx);
2272 EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
2275 * nand_subop_get_num_addr_cyc - Get the remaining address cycles to assert
2276 * @subop: The entire sub-operation
2277 * @instr_idx: Index of the instruction inside the sub-operation
2279 * During driver development, one could be tempted to directly use the
2280 * ->addr->naddrs field of a data instruction. This is wrong as instructions
2283 * Given an address instruction, returns the number of address cycle to issue.
2285 unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
2286 unsigned int instr_idx)
2288 int start_off, end_off;
2290 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2291 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2294 start_off = nand_subop_get_addr_start_off(subop, instr_idx);
2296 if (instr_idx == subop->ninstrs - 1 &&
2297 subop->last_instr_end_off)
2298 end_off = subop->last_instr_end_off;
2300 end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
2302 return end_off - start_off;
2304 EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
2307 * nand_subop_get_data_start_off - Get the start offset in a data array
2308 * @subop: The entire sub-operation
2309 * @instr_idx: Index of the instruction inside the sub-operation
2311 * During driver development, one could be tempted to directly use the
2312 * ->data->buf.{in,out} field of data instructions. This is wrong as data
2313 * instructions might be split.
2315 * Given a data instruction, returns the offset to start from.
2317 unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
2318 unsigned int instr_idx)
2320 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2321 !nand_instr_is_data(&subop->instrs[instr_idx])))
2324 return nand_subop_get_start_off(subop, instr_idx);
2326 EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
2329 * nand_subop_get_data_len - Get the number of bytes to retrieve
2330 * @subop: The entire sub-operation
2331 * @instr_idx: Index of the instruction inside the sub-operation
2333 * During driver development, one could be tempted to directly use the
2334 * ->data->len field of a data instruction. This is wrong as data instructions
2337 * Returns the length of the chunk of data to send/receive.
2339 unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
2340 unsigned int instr_idx)
2342 int start_off = 0, end_off;
2344 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2345 !nand_instr_is_data(&subop->instrs[instr_idx])))
2348 start_off = nand_subop_get_data_start_off(subop, instr_idx);
2350 if (instr_idx == subop->ninstrs - 1 &&
2351 subop->last_instr_end_off)
2352 end_off = subop->last_instr_end_off;
2354 end_off = subop->instrs[instr_idx].ctx.data.len;
2356 return end_off - start_off;
2358 EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
2361 * nand_reset - Reset and initialize a NAND device
2362 * @chip: The NAND chip
2363 * @chipnr: Internal die id
2365 * Save the timings data structure, then apply SDR timings mode 0 (see
2366 * nand_reset_interface for details), do the reset operation, and apply
2367 * back the previous timings.
2369 * Returns 0 on success, a negative error code otherwise.
2371 int nand_reset(struct nand_chip *chip, int chipnr)
2375 ret = nand_reset_interface(chip, chipnr);
2380 * The CS line has to be released before we can apply the new NAND
2381 * interface settings, hence this weird nand_select_target()
2382 * nand_deselect_target() dance.
2384 nand_select_target(chip, chipnr);
2385 ret = nand_reset_op(chip);
2386 nand_deselect_target(chip);
2390 ret = nand_setup_interface(chip, chipnr);
2396 EXPORT_SYMBOL_GPL(nand_reset);
2399 * nand_get_features - wrapper to perform a GET_FEATURE
2400 * @chip: NAND chip info structure
2401 * @addr: feature address
2402 * @subfeature_param: the subfeature parameters, a four bytes array
2404 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2405 * operation cannot be handled.
2407 int nand_get_features(struct nand_chip *chip, int addr,
2408 u8 *subfeature_param)
2410 if (!nand_supports_get_features(chip, addr))
2413 if (chip->legacy.get_features)
2414 return chip->legacy.get_features(chip, addr, subfeature_param);
2416 return nand_get_features_op(chip, addr, subfeature_param);
2420 * nand_set_features - wrapper to perform a SET_FEATURE
2421 * @chip: NAND chip info structure
2422 * @addr: feature address
2423 * @subfeature_param: the subfeature parameters, a four bytes array
2425 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2426 * operation cannot be handled.
2428 int nand_set_features(struct nand_chip *chip, int addr,
2429 u8 *subfeature_param)
2431 if (!nand_supports_set_features(chip, addr))
2434 if (chip->legacy.set_features)
2435 return chip->legacy.set_features(chip, addr, subfeature_param);
2437 return nand_set_features_op(chip, addr, subfeature_param);
2441 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
2442 * @buf: buffer to test
2443 * @len: buffer length
2444 * @bitflips_threshold: maximum number of bitflips
2446 * Check if a buffer contains only 0xff, which means the underlying region
2447 * has been erased and is ready to be programmed.
2448 * The bitflips_threshold specify the maximum number of bitflips before
2449 * considering the region is not erased.
2450 * Note: The logic of this function has been extracted from the memweight
2451 * implementation, except that nand_check_erased_buf function exit before
2452 * testing the whole buffer if the number of bitflips exceed the
2453 * bitflips_threshold value.
2455 * Returns a positive number of bitflips less than or equal to
2456 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2459 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
2461 const unsigned char *bitmap = buf;
2465 for (; len && ((uintptr_t)bitmap) % sizeof(long);
2467 weight = hweight8(*bitmap);
2468 bitflips += BITS_PER_BYTE - weight;
2469 if (unlikely(bitflips > bitflips_threshold))
2473 for (; len >= sizeof(long);
2474 len -= sizeof(long), bitmap += sizeof(long)) {
2475 unsigned long d = *((unsigned long *)bitmap);
2478 weight = hweight_long(d);
2479 bitflips += BITS_PER_LONG - weight;
2480 if (unlikely(bitflips > bitflips_threshold))
2484 for (; len > 0; len--, bitmap++) {
2485 weight = hweight8(*bitmap);
2486 bitflips += BITS_PER_BYTE - weight;
2487 if (unlikely(bitflips > bitflips_threshold))
2495 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
2497 * @data: data buffer to test
2498 * @datalen: data length
2500 * @ecclen: ECC length
2501 * @extraoob: extra OOB buffer
2502 * @extraooblen: extra OOB length
2503 * @bitflips_threshold: maximum number of bitflips
2505 * Check if a data buffer and its associated ECC and OOB data contains only
2506 * 0xff pattern, which means the underlying region has been erased and is
2507 * ready to be programmed.
2508 * The bitflips_threshold specify the maximum number of bitflips before
2509 * considering the region as not erased.
2512 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
2513 * different from the NAND page size. When fixing bitflips, ECC engines will
2514 * report the number of errors per chunk, and the NAND core infrastructure
2515 * expect you to return the maximum number of bitflips for the whole page.
2516 * This is why you should always use this function on a single chunk and
2517 * not on the whole page. After checking each chunk you should update your
2518 * max_bitflips value accordingly.
2519 * 2/ When checking for bitflips in erased pages you should not only check
2520 * the payload data but also their associated ECC data, because a user might
2521 * have programmed almost all bits to 1 but a few. In this case, we
2522 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
2524 * 3/ The extraoob argument is optional, and should be used if some of your OOB
2525 * data are protected by the ECC engine.
2526 * It could also be used if you support subpages and want to attach some
2527 * extra OOB data to an ECC chunk.
2529 * Returns a positive number of bitflips less than or equal to
2530 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2531 * threshold. In case of success, the passed buffers are filled with 0xff.
2533 int nand_check_erased_ecc_chunk(void *data, int datalen,
2534 void *ecc, int ecclen,
2535 void *extraoob, int extraooblen,
2536 int bitflips_threshold)
2538 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
2540 data_bitflips = nand_check_erased_buf(data, datalen,
2541 bitflips_threshold);
2542 if (data_bitflips < 0)
2543 return data_bitflips;
2545 bitflips_threshold -= data_bitflips;
2547 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
2548 if (ecc_bitflips < 0)
2549 return ecc_bitflips;
2551 bitflips_threshold -= ecc_bitflips;
2553 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
2554 bitflips_threshold);
2555 if (extraoob_bitflips < 0)
2556 return extraoob_bitflips;
2559 memset(data, 0xff, datalen);
2562 memset(ecc, 0xff, ecclen);
2564 if (extraoob_bitflips)
2565 memset(extraoob, 0xff, extraooblen);
2567 return data_bitflips + ecc_bitflips + extraoob_bitflips;
2569 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
2572 * nand_read_page_raw_notsupp - dummy read raw page function
2573 * @chip: nand chip info structure
2574 * @buf: buffer to store read data
2575 * @oob_required: caller requires OOB data read to chip->oob_poi
2576 * @page: page number to read
2578 * Returns -ENOTSUPP unconditionally.
2580 int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf,
2581 int oob_required, int page)
2587 * nand_read_page_raw - [INTERN] read raw page data without ecc
2588 * @chip: nand chip info structure
2589 * @buf: buffer to store read data
2590 * @oob_required: caller requires OOB data read to chip->oob_poi
2591 * @page: page number to read
2593 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2595 int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
2598 struct mtd_info *mtd = nand_to_mtd(chip);
2601 ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
2606 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
2614 EXPORT_SYMBOL(nand_read_page_raw);
2617 * nand_monolithic_read_page_raw - Monolithic page read in raw mode
2618 * @chip: NAND chip info structure
2619 * @buf: buffer to store read data
2620 * @oob_required: caller requires OOB data read to chip->oob_poi
2621 * @page: page number to read
2623 * This is a raw page read, ie. without any error detection/correction.
2624 * Monolithic means we are requesting all the relevant data (main plus
2625 * eventually OOB) to be loaded in the NAND cache and sent over the
2626 * bus (from the NAND chip to the NAND controller) in a single
2627 * operation. This is an alternative to nand_read_page_raw(), which
2628 * first reads the main data, and if the OOB data is requested too,
2629 * then reads more data on the bus.
2631 int nand_monolithic_read_page_raw(struct nand_chip *chip, u8 *buf,
2632 int oob_required, int page)
2634 struct mtd_info *mtd = nand_to_mtd(chip);
2635 unsigned int size = mtd->writesize;
2640 size += mtd->oobsize;
2642 if (buf != chip->data_buf)
2643 read_buf = nand_get_data_buf(chip);
2646 ret = nand_read_page_op(chip, page, 0, read_buf, size);
2650 if (buf != chip->data_buf)
2651 memcpy(buf, read_buf, mtd->writesize);
2655 EXPORT_SYMBOL(nand_monolithic_read_page_raw);
2658 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
2659 * @chip: nand chip info structure
2660 * @buf: buffer to store read data
2661 * @oob_required: caller requires OOB data read to chip->oob_poi
2662 * @page: page number to read
2664 * We need a special oob layout and handling even when OOB isn't used.
2666 static int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf,
2667 int oob_required, int page)
2669 struct mtd_info *mtd = nand_to_mtd(chip);
2670 int eccsize = chip->ecc.size;
2671 int eccbytes = chip->ecc.bytes;
2672 uint8_t *oob = chip->oob_poi;
2673 int steps, size, ret;
2675 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2679 for (steps = chip->ecc.steps; steps > 0; steps--) {
2680 ret = nand_read_data_op(chip, buf, eccsize, false, false);
2686 if (chip->ecc.prepad) {
2687 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2692 oob += chip->ecc.prepad;
2695 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
2701 if (chip->ecc.postpad) {
2702 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2707 oob += chip->ecc.postpad;
2711 size = mtd->oobsize - (oob - chip->oob_poi);
2713 ret = nand_read_data_op(chip, oob, size, false, false);
2722 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
2723 * @chip: nand chip info structure
2724 * @buf: buffer to store read data
2725 * @oob_required: caller requires OOB data read to chip->oob_poi
2726 * @page: page number to read
2728 static int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf,
2729 int oob_required, int page)
2731 struct mtd_info *mtd = nand_to_mtd(chip);
2732 int i, eccsize = chip->ecc.size, ret;
2733 int eccbytes = chip->ecc.bytes;
2734 int eccsteps = chip->ecc.steps;
2736 uint8_t *ecc_calc = chip->ecc.calc_buf;
2737 uint8_t *ecc_code = chip->ecc.code_buf;
2738 unsigned int max_bitflips = 0;
2740 chip->ecc.read_page_raw(chip, buf, 1, page);
2742 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2743 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2745 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2750 eccsteps = chip->ecc.steps;
2753 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2756 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
2758 mtd->ecc_stats.failed++;
2760 mtd->ecc_stats.corrected += stat;
2761 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2764 return max_bitflips;
2768 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
2769 * @chip: nand chip info structure
2770 * @data_offs: offset of requested data within the page
2771 * @readlen: data length
2772 * @bufpoi: buffer to store read data
2773 * @page: page number to read
2775 static int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs,
2776 uint32_t readlen, uint8_t *bufpoi, int page)
2778 struct mtd_info *mtd = nand_to_mtd(chip);
2779 int start_step, end_step, num_steps, ret;
2781 int data_col_addr, i, gaps = 0;
2782 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
2783 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
2784 int index, section = 0;
2785 unsigned int max_bitflips = 0;
2786 struct mtd_oob_region oobregion = { };
2788 /* Column address within the page aligned to ECC size (256bytes) */
2789 start_step = data_offs / chip->ecc.size;
2790 end_step = (data_offs + readlen - 1) / chip->ecc.size;
2791 num_steps = end_step - start_step + 1;
2792 index = start_step * chip->ecc.bytes;
2794 /* Data size aligned to ECC ecc.size */
2795 datafrag_len = num_steps * chip->ecc.size;
2796 eccfrag_len = num_steps * chip->ecc.bytes;
2798 data_col_addr = start_step * chip->ecc.size;
2799 /* If we read not a page aligned data */
2800 p = bufpoi + data_col_addr;
2801 ret = nand_read_page_op(chip, page, data_col_addr, p, datafrag_len);
2806 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
2807 chip->ecc.calculate(chip, p, &chip->ecc.calc_buf[i]);
2810 * The performance is faster if we position offsets according to
2811 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
2813 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
2817 if (oobregion.length < eccfrag_len)
2821 ret = nand_change_read_column_op(chip, mtd->writesize,
2822 chip->oob_poi, mtd->oobsize,
2828 * Send the command to read the particular ECC bytes take care
2829 * about buswidth alignment in read_buf.
2831 aligned_pos = oobregion.offset & ~(busw - 1);
2832 aligned_len = eccfrag_len;
2833 if (oobregion.offset & (busw - 1))
2835 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
2839 ret = nand_change_read_column_op(chip,
2840 mtd->writesize + aligned_pos,
2841 &chip->oob_poi[aligned_pos],
2842 aligned_len, false);
2847 ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
2848 chip->oob_poi, index, eccfrag_len);
2852 p = bufpoi + data_col_addr;
2853 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
2856 stat = chip->ecc.correct(chip, p, &chip->ecc.code_buf[i],
2857 &chip->ecc.calc_buf[i]);
2858 if (stat == -EBADMSG &&
2859 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2860 /* check for empty pages with bitflips */
2861 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
2862 &chip->ecc.code_buf[i],
2865 chip->ecc.strength);
2869 mtd->ecc_stats.failed++;
2871 mtd->ecc_stats.corrected += stat;
2872 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2875 return max_bitflips;
2879 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
2880 * @chip: nand chip info structure
2881 * @buf: buffer to store read data
2882 * @oob_required: caller requires OOB data read to chip->oob_poi
2883 * @page: page number to read
2885 * Not for syndrome calculating ECC controllers which need a special oob layout.
2887 static int nand_read_page_hwecc(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 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2903 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2904 chip->ecc.hwctl(chip, NAND_ECC_READ);
2906 ret = nand_read_data_op(chip, p, eccsize, false, false);
2910 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2913 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false,
2918 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2923 eccsteps = chip->ecc.steps;
2926 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2929 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
2930 if (stat == -EBADMSG &&
2931 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2932 /* check for empty pages with bitflips */
2933 stat = nand_check_erased_ecc_chunk(p, eccsize,
2934 &ecc_code[i], eccbytes,
2936 chip->ecc.strength);
2940 mtd->ecc_stats.failed++;
2942 mtd->ecc_stats.corrected += stat;
2943 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2946 return max_bitflips;
2950 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
2951 * @chip: nand chip info structure
2952 * @buf: buffer to store read data
2953 * @oob_required: caller requires OOB data read to chip->oob_poi
2954 * @page: page number to read
2956 * The hw generator calculates the error syndrome automatically. Therefore we
2957 * need a special oob layout and handling.
2959 static int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf,
2960 int oob_required, int page)
2962 struct mtd_info *mtd = nand_to_mtd(chip);
2963 int ret, i, eccsize = chip->ecc.size;
2964 int eccbytes = chip->ecc.bytes;
2965 int eccsteps = chip->ecc.steps;
2966 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
2968 uint8_t *oob = chip->oob_poi;
2969 unsigned int max_bitflips = 0;
2971 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2975 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2978 chip->ecc.hwctl(chip, NAND_ECC_READ);
2980 ret = nand_read_data_op(chip, p, eccsize, false, false);
2984 if (chip->ecc.prepad) {
2985 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2990 oob += chip->ecc.prepad;
2993 chip->ecc.hwctl(chip, NAND_ECC_READSYN);
2995 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
2999 stat = chip->ecc.correct(chip, p, oob, NULL);
3003 if (chip->ecc.postpad) {
3004 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3009 oob += chip->ecc.postpad;
3012 if (stat == -EBADMSG &&
3013 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3014 /* check for empty pages with bitflips */
3015 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3019 chip->ecc.strength);
3023 mtd->ecc_stats.failed++;
3025 mtd->ecc_stats.corrected += stat;
3026 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3030 /* Calculate remaining oob bytes */
3031 i = mtd->oobsize - (oob - chip->oob_poi);
3033 ret = nand_read_data_op(chip, oob, i, false, false);
3038 return max_bitflips;
3042 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
3043 * @chip: NAND chip object
3044 * @oob: oob destination address
3045 * @ops: oob ops structure
3046 * @len: size of oob to transfer
3048 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
3049 struct mtd_oob_ops *ops, size_t len)
3051 struct mtd_info *mtd = nand_to_mtd(chip);
3054 switch (ops->mode) {
3056 case MTD_OPS_PLACE_OOB:
3058 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
3061 case MTD_OPS_AUTO_OOB:
3062 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
3074 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
3075 * @chip: NAND chip object
3076 * @retry_mode: the retry mode to use
3078 * Some vendors supply a special command to shift the Vt threshold, to be used
3079 * when there are too many bitflips in a page (i.e., ECC error). After setting
3080 * a new threshold, the host should retry reading the page.
3082 static int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
3084 pr_debug("setting READ RETRY mode %d\n", retry_mode);
3086 if (retry_mode >= chip->read_retries)
3089 if (!chip->ops.setup_read_retry)
3092 return chip->ops.setup_read_retry(chip, retry_mode);
3095 static void nand_wait_readrdy(struct nand_chip *chip)
3097 const struct nand_sdr_timings *sdr;
3099 if (!(chip->options & NAND_NEED_READRDY))
3102 sdr = nand_get_sdr_timings(nand_get_interface_config(chip));
3103 WARN_ON(nand_wait_rdy_op(chip, PSEC_TO_MSEC(sdr->tR_max), 0));
3107 * nand_do_read_ops - [INTERN] Read data with ECC
3108 * @chip: NAND chip object
3109 * @from: offset to read from
3110 * @ops: oob ops structure
3112 * Internal function. Called with chip held.
3114 static int nand_do_read_ops(struct nand_chip *chip, loff_t from,
3115 struct mtd_oob_ops *ops)
3117 int chipnr, page, realpage, col, bytes, aligned, oob_required;
3118 struct mtd_info *mtd = nand_to_mtd(chip);
3120 uint32_t readlen = ops->len;
3121 uint32_t oobreadlen = ops->ooblen;
3122 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
3124 uint8_t *bufpoi, *oob, *buf;
3126 unsigned int max_bitflips = 0;
3128 bool ecc_fail = false;
3130 chipnr = (int)(from >> chip->chip_shift);
3131 nand_select_target(chip, chipnr);
3133 realpage = (int)(from >> chip->page_shift);
3134 page = realpage & chip->pagemask;
3136 col = (int)(from & (mtd->writesize - 1));
3140 oob_required = oob ? 1 : 0;
3143 struct mtd_ecc_stats ecc_stats = mtd->ecc_stats;
3145 bytes = min(mtd->writesize - col, readlen);
3146 aligned = (bytes == mtd->writesize);
3150 else if (chip->options & NAND_USES_DMA)
3151 use_bounce_buf = !virt_addr_valid(buf) ||
3152 !IS_ALIGNED((unsigned long)buf,
3157 /* Is the current page in the buffer? */
3158 if (realpage != chip->pagecache.page || oob) {
3159 bufpoi = use_bounce_buf ? chip->data_buf : buf;
3161 if (use_bounce_buf && aligned)
3162 pr_debug("%s: using read bounce buffer for buf@%p\n",
3167 * Now read the page into the buffer. Absent an error,
3168 * the read methods return max bitflips per ecc step.
3170 if (unlikely(ops->mode == MTD_OPS_RAW))
3171 ret = chip->ecc.read_page_raw(chip, bufpoi,
3174 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
3176 ret = chip->ecc.read_subpage(chip, col, bytes,
3179 ret = chip->ecc.read_page(chip, bufpoi,
3180 oob_required, page);
3183 /* Invalidate page cache */
3184 chip->pagecache.page = -1;
3189 * Copy back the data in the initial buffer when reading
3190 * partial pages or when a bounce buffer is required.
3192 if (use_bounce_buf) {
3193 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
3194 !(mtd->ecc_stats.failed - ecc_stats.failed) &&
3195 (ops->mode != MTD_OPS_RAW)) {
3196 chip->pagecache.page = realpage;
3197 chip->pagecache.bitflips = ret;
3199 /* Invalidate page cache */
3200 chip->pagecache.page = -1;
3202 memcpy(buf, bufpoi + col, bytes);
3205 if (unlikely(oob)) {
3206 int toread = min(oobreadlen, max_oobsize);
3209 oob = nand_transfer_oob(chip, oob, ops,
3211 oobreadlen -= toread;
3215 nand_wait_readrdy(chip);
3217 if (mtd->ecc_stats.failed - ecc_stats.failed) {
3218 if (retry_mode + 1 < chip->read_retries) {
3220 ret = nand_setup_read_retry(chip,
3225 /* Reset ecc_stats; retry */
3226 mtd->ecc_stats = ecc_stats;
3229 /* No more retry modes; real failure */
3235 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3237 memcpy(buf, chip->data_buf + col, bytes);
3239 max_bitflips = max_t(unsigned int, max_bitflips,
3240 chip->pagecache.bitflips);
3245 /* Reset to retry mode 0 */
3247 ret = nand_setup_read_retry(chip, 0);
3256 /* For subsequent reads align to page boundary */
3258 /* Increment page address */
3261 page = realpage & chip->pagemask;
3262 /* Check, if we cross a chip boundary */
3265 nand_deselect_target(chip);
3266 nand_select_target(chip, chipnr);
3269 nand_deselect_target(chip);
3271 ops->retlen = ops->len - (size_t) readlen;
3273 ops->oobretlen = ops->ooblen - oobreadlen;
3281 return max_bitflips;
3285 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
3286 * @chip: nand chip info structure
3287 * @page: page number to read
3289 int nand_read_oob_std(struct nand_chip *chip, int page)
3291 struct mtd_info *mtd = nand_to_mtd(chip);
3293 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3295 EXPORT_SYMBOL(nand_read_oob_std);
3298 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
3300 * @chip: nand chip info structure
3301 * @page: page number to read
3303 static int nand_read_oob_syndrome(struct nand_chip *chip, int page)
3305 struct mtd_info *mtd = nand_to_mtd(chip);
3306 int length = mtd->oobsize;
3307 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3308 int eccsize = chip->ecc.size;
3309 uint8_t *bufpoi = chip->oob_poi;
3310 int i, toread, sndrnd = 0, pos, ret;
3312 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
3316 for (i = 0; i < chip->ecc.steps; i++) {
3320 pos = eccsize + i * (eccsize + chunk);
3321 if (mtd->writesize > 512)
3322 ret = nand_change_read_column_op(chip, pos,
3326 ret = nand_read_page_op(chip, page, pos, NULL,
3333 toread = min_t(int, length, chunk);
3335 ret = nand_read_data_op(chip, bufpoi, toread, false, false);
3343 ret = nand_read_data_op(chip, bufpoi, length, false, false);
3352 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
3353 * @chip: nand chip info structure
3354 * @page: page number to write
3356 int nand_write_oob_std(struct nand_chip *chip, int page)
3358 struct mtd_info *mtd = nand_to_mtd(chip);
3360 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
3363 EXPORT_SYMBOL(nand_write_oob_std);
3366 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
3367 * with syndrome - only for large page flash
3368 * @chip: nand chip info structure
3369 * @page: page number to write
3371 static int nand_write_oob_syndrome(struct nand_chip *chip, int page)
3373 struct mtd_info *mtd = nand_to_mtd(chip);
3374 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3375 int eccsize = chip->ecc.size, length = mtd->oobsize;
3376 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
3377 const uint8_t *bufpoi = chip->oob_poi;
3380 * data-ecc-data-ecc ... ecc-oob
3382 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
3384 if (!chip->ecc.prepad && !chip->ecc.postpad) {
3385 pos = steps * (eccsize + chunk);
3390 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
3394 for (i = 0; i < steps; i++) {
3396 if (mtd->writesize <= 512) {
3397 uint32_t fill = 0xFFFFFFFF;
3401 int num = min_t(int, len, 4);
3403 ret = nand_write_data_op(chip, &fill,
3411 pos = eccsize + i * (eccsize + chunk);
3412 ret = nand_change_write_column_op(chip, pos,
3420 len = min_t(int, length, chunk);
3422 ret = nand_write_data_op(chip, bufpoi, len, false);
3430 ret = nand_write_data_op(chip, bufpoi, length, false);
3435 return nand_prog_page_end_op(chip);
3439 * nand_do_read_oob - [INTERN] NAND read out-of-band
3440 * @chip: NAND chip object
3441 * @from: offset to read from
3442 * @ops: oob operations description structure
3444 * NAND read out-of-band data from the spare area.
3446 static int nand_do_read_oob(struct nand_chip *chip, loff_t from,
3447 struct mtd_oob_ops *ops)
3449 struct mtd_info *mtd = nand_to_mtd(chip);
3450 unsigned int max_bitflips = 0;
3451 int page, realpage, chipnr;
3452 struct mtd_ecc_stats stats;
3453 int readlen = ops->ooblen;
3455 uint8_t *buf = ops->oobbuf;
3458 pr_debug("%s: from = 0x%08Lx, len = %i\n",
3459 __func__, (unsigned long long)from, readlen);
3461 stats = mtd->ecc_stats;
3463 len = mtd_oobavail(mtd, ops);
3465 chipnr = (int)(from >> chip->chip_shift);
3466 nand_select_target(chip, chipnr);
3468 /* Shift to get page */
3469 realpage = (int)(from >> chip->page_shift);
3470 page = realpage & chip->pagemask;
3473 if (ops->mode == MTD_OPS_RAW)
3474 ret = chip->ecc.read_oob_raw(chip, page);
3476 ret = chip->ecc.read_oob(chip, page);
3481 len = min(len, readlen);
3482 buf = nand_transfer_oob(chip, buf, ops, len);
3484 nand_wait_readrdy(chip);
3486 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3492 /* Increment page address */
3495 page = realpage & chip->pagemask;
3496 /* Check, if we cross a chip boundary */
3499 nand_deselect_target(chip);
3500 nand_select_target(chip, chipnr);
3503 nand_deselect_target(chip);
3505 ops->oobretlen = ops->ooblen - readlen;
3510 if (mtd->ecc_stats.failed - stats.failed)
3513 return max_bitflips;
3517 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
3518 * @mtd: MTD device structure
3519 * @from: offset to read from
3520 * @ops: oob operation description structure
3522 * NAND read data and/or out-of-band data.
3524 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
3525 struct mtd_oob_ops *ops)
3527 struct nand_chip *chip = mtd_to_nand(mtd);
3532 if (ops->mode != MTD_OPS_PLACE_OOB &&
3533 ops->mode != MTD_OPS_AUTO_OOB &&
3534 ops->mode != MTD_OPS_RAW)
3537 ret = nand_get_device(chip);
3542 ret = nand_do_read_oob(chip, from, ops);
3544 ret = nand_do_read_ops(chip, from, ops);
3546 nand_release_device(chip);
3551 * nand_write_page_raw_notsupp - dummy raw page write function
3552 * @chip: nand chip info structure
3554 * @oob_required: must write chip->oob_poi to OOB
3555 * @page: page number to write
3557 * Returns -ENOTSUPP unconditionally.
3559 int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf,
3560 int oob_required, int page)
3566 * nand_write_page_raw - [INTERN] raw page write function
3567 * @chip: nand chip info structure
3569 * @oob_required: must write chip->oob_poi to OOB
3570 * @page: page number to write
3572 * Not for syndrome calculating ECC controllers, which use a special oob layout.
3574 int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
3575 int oob_required, int page)
3577 struct mtd_info *mtd = nand_to_mtd(chip);
3580 ret = nand_prog_page_begin_op(chip, page, 0, buf, mtd->writesize);
3585 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
3591 return nand_prog_page_end_op(chip);
3593 EXPORT_SYMBOL(nand_write_page_raw);
3596 * nand_monolithic_write_page_raw - Monolithic page write in raw mode
3597 * @chip: NAND chip info structure
3598 * @buf: data buffer to write
3599 * @oob_required: must write chip->oob_poi to OOB
3600 * @page: page number to write
3602 * This is a raw page write, ie. without any error detection/correction.
3603 * Monolithic means we are requesting all the relevant data (main plus
3604 * eventually OOB) to be sent over the bus and effectively programmed
3605 * into the NAND chip arrays in a single operation. This is an
3606 * alternative to nand_write_page_raw(), which first sends the main
3607 * data, then eventually send the OOB data by latching more data
3608 * cycles on the NAND bus, and finally sends the program command to
3609 * synchronyze the NAND chip cache.
3611 int nand_monolithic_write_page_raw(struct nand_chip *chip, const u8 *buf,
3612 int oob_required, int page)
3614 struct mtd_info *mtd = nand_to_mtd(chip);
3615 unsigned int size = mtd->writesize;
3616 u8 *write_buf = (u8 *)buf;
3619 size += mtd->oobsize;
3621 if (buf != chip->data_buf) {
3622 write_buf = nand_get_data_buf(chip);
3623 memcpy(write_buf, buf, mtd->writesize);
3627 return nand_prog_page_op(chip, page, 0, write_buf, size);
3629 EXPORT_SYMBOL(nand_monolithic_write_page_raw);
3632 * nand_write_page_raw_syndrome - [INTERN] raw page write function
3633 * @chip: nand chip info structure
3635 * @oob_required: must write chip->oob_poi to OOB
3636 * @page: page number to write
3638 * We need a special oob layout and handling even when ECC isn't checked.
3640 static int nand_write_page_raw_syndrome(struct nand_chip *chip,
3641 const uint8_t *buf, int oob_required,
3644 struct mtd_info *mtd = nand_to_mtd(chip);
3645 int eccsize = chip->ecc.size;
3646 int eccbytes = chip->ecc.bytes;
3647 uint8_t *oob = chip->oob_poi;
3648 int steps, size, ret;
3650 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3654 for (steps = chip->ecc.steps; steps > 0; steps--) {
3655 ret = nand_write_data_op(chip, buf, eccsize, false);
3661 if (chip->ecc.prepad) {
3662 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3667 oob += chip->ecc.prepad;
3670 ret = nand_write_data_op(chip, oob, eccbytes, false);
3676 if (chip->ecc.postpad) {
3677 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3682 oob += chip->ecc.postpad;
3686 size = mtd->oobsize - (oob - chip->oob_poi);
3688 ret = nand_write_data_op(chip, oob, size, false);
3693 return nand_prog_page_end_op(chip);
3696 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
3697 * @chip: nand chip info structure
3699 * @oob_required: must write chip->oob_poi to OOB
3700 * @page: page number to write
3702 static int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf,
3703 int oob_required, int page)
3705 struct mtd_info *mtd = nand_to_mtd(chip);
3706 int i, eccsize = chip->ecc.size, ret;
3707 int eccbytes = chip->ecc.bytes;
3708 int eccsteps = chip->ecc.steps;
3709 uint8_t *ecc_calc = chip->ecc.calc_buf;
3710 const uint8_t *p = buf;
3712 /* Software ECC calculation */
3713 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
3714 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3716 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3721 return chip->ecc.write_page_raw(chip, buf, 1, page);
3725 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
3726 * @chip: nand chip info structure
3728 * @oob_required: must write chip->oob_poi to OOB
3729 * @page: page number to write
3731 static int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf,
3732 int oob_required, int page)
3734 struct mtd_info *mtd = nand_to_mtd(chip);
3735 int i, eccsize = chip->ecc.size, ret;
3736 int eccbytes = chip->ecc.bytes;
3737 int eccsteps = chip->ecc.steps;
3738 uint8_t *ecc_calc = chip->ecc.calc_buf;
3739 const uint8_t *p = buf;
3741 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3745 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3746 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3748 ret = nand_write_data_op(chip, p, eccsize, false);
3752 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3755 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3760 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3764 return nand_prog_page_end_op(chip);
3769 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
3770 * @chip: nand chip info structure
3771 * @offset: column address of subpage within the page
3772 * @data_len: data length
3774 * @oob_required: must write chip->oob_poi to OOB
3775 * @page: page number to write
3777 static int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset,
3778 uint32_t data_len, const uint8_t *buf,
3779 int oob_required, int page)
3781 struct mtd_info *mtd = nand_to_mtd(chip);
3782 uint8_t *oob_buf = chip->oob_poi;
3783 uint8_t *ecc_calc = chip->ecc.calc_buf;
3784 int ecc_size = chip->ecc.size;
3785 int ecc_bytes = chip->ecc.bytes;
3786 int ecc_steps = chip->ecc.steps;
3787 uint32_t start_step = offset / ecc_size;
3788 uint32_t end_step = (offset + data_len - 1) / ecc_size;
3789 int oob_bytes = mtd->oobsize / ecc_steps;
3792 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3796 for (step = 0; step < ecc_steps; step++) {
3797 /* configure controller for WRITE access */
3798 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3800 /* write data (untouched subpages already masked by 0xFF) */
3801 ret = nand_write_data_op(chip, buf, ecc_size, false);
3805 /* mask ECC of un-touched subpages by padding 0xFF */
3806 if ((step < start_step) || (step > end_step))
3807 memset(ecc_calc, 0xff, ecc_bytes);
3809 chip->ecc.calculate(chip, buf, ecc_calc);
3811 /* mask OOB of un-touched subpages by padding 0xFF */
3812 /* if oob_required, preserve OOB metadata of written subpage */
3813 if (!oob_required || (step < start_step) || (step > end_step))
3814 memset(oob_buf, 0xff, oob_bytes);
3817 ecc_calc += ecc_bytes;
3818 oob_buf += oob_bytes;
3821 /* copy calculated ECC for whole page to chip->buffer->oob */
3822 /* this include masked-value(0xFF) for unwritten subpages */
3823 ecc_calc = chip->ecc.calc_buf;
3824 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3829 /* write OOB buffer to NAND device */
3830 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3834 return nand_prog_page_end_op(chip);
3839 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
3840 * @chip: nand chip info structure
3842 * @oob_required: must write chip->oob_poi to OOB
3843 * @page: page number to write
3845 * The hw generator calculates the error syndrome automatically. Therefore we
3846 * need a special oob layout and handling.
3848 static int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf,
3849 int oob_required, int page)
3851 struct mtd_info *mtd = nand_to_mtd(chip);
3852 int i, eccsize = chip->ecc.size;
3853 int eccbytes = chip->ecc.bytes;
3854 int eccsteps = chip->ecc.steps;
3855 const uint8_t *p = buf;
3856 uint8_t *oob = chip->oob_poi;
3859 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3863 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3864 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3866 ret = nand_write_data_op(chip, p, eccsize, false);
3870 if (chip->ecc.prepad) {
3871 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3876 oob += chip->ecc.prepad;
3879 chip->ecc.calculate(chip, p, oob);
3881 ret = nand_write_data_op(chip, oob, eccbytes, false);
3887 if (chip->ecc.postpad) {
3888 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3893 oob += chip->ecc.postpad;
3897 /* Calculate remaining oob bytes */
3898 i = mtd->oobsize - (oob - chip->oob_poi);
3900 ret = nand_write_data_op(chip, oob, i, false);
3905 return nand_prog_page_end_op(chip);
3909 * nand_write_page - write one page
3910 * @chip: NAND chip descriptor
3911 * @offset: address offset within the page
3912 * @data_len: length of actual data to be written
3913 * @buf: the data to write
3914 * @oob_required: must write chip->oob_poi to OOB
3915 * @page: page number to write
3916 * @raw: use _raw version of write_page
3918 static int nand_write_page(struct nand_chip *chip, uint32_t offset,
3919 int data_len, const uint8_t *buf, int oob_required,
3922 struct mtd_info *mtd = nand_to_mtd(chip);
3923 int status, subpage;
3925 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
3926 chip->ecc.write_subpage)
3927 subpage = offset || (data_len < mtd->writesize);
3932 status = chip->ecc.write_page_raw(chip, buf, oob_required,
3935 status = chip->ecc.write_subpage(chip, offset, data_len, buf,
3936 oob_required, page);
3938 status = chip->ecc.write_page(chip, buf, oob_required, page);
3946 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
3949 * nand_do_write_ops - [INTERN] NAND write with ECC
3950 * @chip: NAND chip object
3951 * @to: offset to write to
3952 * @ops: oob operations description structure
3954 * NAND write with ECC.
3956 static int nand_do_write_ops(struct nand_chip *chip, loff_t to,
3957 struct mtd_oob_ops *ops)
3959 struct mtd_info *mtd = nand_to_mtd(chip);
3960 int chipnr, realpage, page, column;
3961 uint32_t writelen = ops->len;
3963 uint32_t oobwritelen = ops->ooblen;
3964 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
3966 uint8_t *oob = ops->oobbuf;
3967 uint8_t *buf = ops->datbuf;
3969 int oob_required = oob ? 1 : 0;
3975 /* Reject writes, which are not page aligned */
3976 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
3977 pr_notice("%s: attempt to write non page aligned data\n",
3982 column = to & (mtd->writesize - 1);
3984 chipnr = (int)(to >> chip->chip_shift);
3985 nand_select_target(chip, chipnr);
3987 /* Check, if it is write protected */
3988 if (nand_check_wp(chip)) {
3993 realpage = (int)(to >> chip->page_shift);
3994 page = realpage & chip->pagemask;
3996 /* Invalidate the page cache, when we write to the cached page */
3997 if (to <= ((loff_t)chip->pagecache.page << chip->page_shift) &&
3998 ((loff_t)chip->pagecache.page << chip->page_shift) < (to + ops->len))
3999 chip->pagecache.page = -1;
4001 /* Don't allow multipage oob writes with offset */
4002 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
4008 int bytes = mtd->writesize;
4009 uint8_t *wbuf = buf;
4011 int part_pagewr = (column || writelen < mtd->writesize);
4015 else if (chip->options & NAND_USES_DMA)
4016 use_bounce_buf = !virt_addr_valid(buf) ||
4017 !IS_ALIGNED((unsigned long)buf,
4023 * Copy the data from the initial buffer when doing partial page
4024 * writes or when a bounce buffer is required.
4026 if (use_bounce_buf) {
4027 pr_debug("%s: using write bounce buffer for buf@%p\n",
4030 bytes = min_t(int, bytes - column, writelen);
4031 wbuf = nand_get_data_buf(chip);
4032 memset(wbuf, 0xff, mtd->writesize);
4033 memcpy(&wbuf[column], buf, bytes);
4036 if (unlikely(oob)) {
4037 size_t len = min(oobwritelen, oobmaxlen);
4038 oob = nand_fill_oob(chip, oob, len, ops);
4041 /* We still need to erase leftover OOB data */
4042 memset(chip->oob_poi, 0xff, mtd->oobsize);
4045 ret = nand_write_page(chip, column, bytes, wbuf,
4047 (ops->mode == MTD_OPS_RAW));
4059 page = realpage & chip->pagemask;
4060 /* Check, if we cross a chip boundary */
4063 nand_deselect_target(chip);
4064 nand_select_target(chip, chipnr);
4068 ops->retlen = ops->len - writelen;
4070 ops->oobretlen = ops->ooblen;
4073 nand_deselect_target(chip);
4078 * panic_nand_write - [MTD Interface] NAND write with ECC
4079 * @mtd: MTD device structure
4080 * @to: offset to write to
4081 * @len: number of bytes to write
4082 * @retlen: pointer to variable to store the number of written bytes
4083 * @buf: the data to write
4085 * NAND write with ECC. Used when performing writes in interrupt context, this
4086 * may for example be called by mtdoops when writing an oops while in panic.
4088 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
4089 size_t *retlen, const uint8_t *buf)
4091 struct nand_chip *chip = mtd_to_nand(mtd);
4092 int chipnr = (int)(to >> chip->chip_shift);
4093 struct mtd_oob_ops ops;
4096 nand_select_target(chip, chipnr);
4098 /* Wait for the device to get ready */
4099 panic_nand_wait(chip, 400);
4101 memset(&ops, 0, sizeof(ops));
4103 ops.datbuf = (uint8_t *)buf;
4104 ops.mode = MTD_OPS_PLACE_OOB;
4106 ret = nand_do_write_ops(chip, to, &ops);
4108 *retlen = ops.retlen;
4113 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
4114 * @mtd: MTD device structure
4115 * @to: offset to write to
4116 * @ops: oob operation description structure
4118 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
4119 struct mtd_oob_ops *ops)
4121 struct nand_chip *chip = mtd_to_nand(mtd);
4126 ret = nand_get_device(chip);
4130 switch (ops->mode) {
4131 case MTD_OPS_PLACE_OOB:
4132 case MTD_OPS_AUTO_OOB:
4141 ret = nand_do_write_oob(chip, to, ops);
4143 ret = nand_do_write_ops(chip, to, ops);
4146 nand_release_device(chip);
4151 * nand_erase - [MTD Interface] erase block(s)
4152 * @mtd: MTD device structure
4153 * @instr: erase instruction
4155 * Erase one ore more blocks.
4157 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
4159 return nand_erase_nand(mtd_to_nand(mtd), instr, 0);
4163 * nand_erase_nand - [INTERN] erase block(s)
4164 * @chip: NAND chip object
4165 * @instr: erase instruction
4166 * @allowbbt: allow erasing the bbt area
4168 * Erase one ore more blocks.
4170 int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr,
4173 int page, pages_per_block, ret, chipnr;
4176 pr_debug("%s: start = 0x%012llx, len = %llu\n",
4177 __func__, (unsigned long long)instr->addr,
4178 (unsigned long long)instr->len);
4180 if (check_offs_len(chip, instr->addr, instr->len))
4183 /* Grab the lock and see if the device is available */
4184 ret = nand_get_device(chip);
4188 /* Shift to get first page */
4189 page = (int)(instr->addr >> chip->page_shift);
4190 chipnr = (int)(instr->addr >> chip->chip_shift);
4192 /* Calculate pages in each block */
4193 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
4195 /* Select the NAND device */
4196 nand_select_target(chip, chipnr);
4198 /* Check, if it is write protected */
4199 if (nand_check_wp(chip)) {
4200 pr_debug("%s: device is write protected!\n",
4206 /* Loop through the pages */
4210 /* Check if we have a bad block, we do not erase bad blocks! */
4211 if (nand_block_checkbad(chip, ((loff_t) page) <<
4212 chip->page_shift, allowbbt)) {
4213 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
4220 * Invalidate the page cache, if we erase the block which
4221 * contains the current cached page.
4223 if (page <= chip->pagecache.page && chip->pagecache.page <
4224 (page + pages_per_block))
4225 chip->pagecache.page = -1;
4227 ret = nand_erase_op(chip, (page & chip->pagemask) >>
4228 (chip->phys_erase_shift - chip->page_shift));
4230 pr_debug("%s: failed erase, page 0x%08x\n",
4233 ((loff_t)page << chip->page_shift);
4237 /* Increment page address and decrement length */
4238 len -= (1ULL << chip->phys_erase_shift);
4239 page += pages_per_block;
4241 /* Check, if we cross a chip boundary */
4242 if (len && !(page & chip->pagemask)) {
4244 nand_deselect_target(chip);
4245 nand_select_target(chip, chipnr);
4252 /* Deselect and wake up anyone waiting on the device */
4253 nand_deselect_target(chip);
4254 nand_release_device(chip);
4256 /* Return more or less happy */
4261 * nand_sync - [MTD Interface] sync
4262 * @mtd: MTD device structure
4264 * Sync is actually a wait for chip ready function.
4266 static void nand_sync(struct mtd_info *mtd)
4268 struct nand_chip *chip = mtd_to_nand(mtd);
4270 pr_debug("%s: called\n", __func__);
4272 /* Grab the lock and see if the device is available */
4273 WARN_ON(nand_get_device(chip));
4274 /* Release it and go back */
4275 nand_release_device(chip);
4279 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
4280 * @mtd: MTD device structure
4281 * @offs: offset relative to mtd start
4283 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
4285 struct nand_chip *chip = mtd_to_nand(mtd);
4286 int chipnr = (int)(offs >> chip->chip_shift);
4289 /* Select the NAND device */
4290 ret = nand_get_device(chip);
4294 nand_select_target(chip, chipnr);
4296 ret = nand_block_checkbad(chip, offs, 0);
4298 nand_deselect_target(chip);
4299 nand_release_device(chip);
4305 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
4306 * @mtd: MTD device structure
4307 * @ofs: offset relative to mtd start
4309 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
4313 ret = nand_block_isbad(mtd, ofs);
4315 /* If it was bad already, return success and do nothing */
4321 return nand_block_markbad_lowlevel(mtd_to_nand(mtd), ofs);
4325 * nand_suspend - [MTD Interface] Suspend the NAND flash
4326 * @mtd: MTD device structure
4328 * Returns 0 for success or negative error code otherwise.
4330 static int nand_suspend(struct mtd_info *mtd)
4332 struct nand_chip *chip = mtd_to_nand(mtd);
4335 mutex_lock(&chip->lock);
4336 if (chip->ops.suspend)
4337 ret = chip->ops.suspend(chip);
4339 chip->suspended = 1;
4340 mutex_unlock(&chip->lock);
4346 * nand_resume - [MTD Interface] Resume the NAND flash
4347 * @mtd: MTD device structure
4349 static void nand_resume(struct mtd_info *mtd)
4351 struct nand_chip *chip = mtd_to_nand(mtd);
4353 mutex_lock(&chip->lock);
4354 if (chip->suspended) {
4355 if (chip->ops.resume)
4356 chip->ops.resume(chip);
4357 chip->suspended = 0;
4359 pr_err("%s called for a chip which is not in suspended state\n",
4362 mutex_unlock(&chip->lock);
4366 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
4367 * prevent further operations
4368 * @mtd: MTD device structure
4370 static void nand_shutdown(struct mtd_info *mtd)
4376 * nand_lock - [MTD Interface] Lock the NAND flash
4377 * @mtd: MTD device structure
4378 * @ofs: offset byte address
4379 * @len: number of bytes to lock (must be a multiple of block/page size)
4381 static int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4383 struct nand_chip *chip = mtd_to_nand(mtd);
4385 if (!chip->ops.lock_area)
4388 return chip->ops.lock_area(chip, ofs, len);
4392 * nand_unlock - [MTD Interface] Unlock the NAND flash
4393 * @mtd: MTD device structure
4394 * @ofs: offset byte address
4395 * @len: number of bytes to unlock (must be a multiple of block/page size)
4397 static int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4399 struct nand_chip *chip = mtd_to_nand(mtd);
4401 if (!chip->ops.unlock_area)
4404 return chip->ops.unlock_area(chip, ofs, len);
4407 /* Set default functions */
4408 static void nand_set_defaults(struct nand_chip *chip)
4410 /* If no controller is provided, use the dummy, legacy one. */
4411 if (!chip->controller) {
4412 chip->controller = &chip->legacy.dummy_controller;
4413 nand_controller_init(chip->controller);
4416 nand_legacy_set_defaults(chip);
4418 if (!chip->buf_align)
4419 chip->buf_align = 1;
4422 /* Sanitize ONFI strings so we can safely print them */
4423 void sanitize_string(uint8_t *s, size_t len)
4427 /* Null terminate */
4430 /* Remove non printable chars */
4431 for (i = 0; i < len - 1; i++) {
4432 if (s[i] < ' ' || s[i] > 127)
4436 /* Remove trailing spaces */
4441 * nand_id_has_period - Check if an ID string has a given wraparound period
4442 * @id_data: the ID string
4443 * @arrlen: the length of the @id_data array
4444 * @period: the period of repitition
4446 * Check if an ID string is repeated within a given sequence of bytes at
4447 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4448 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4449 * if the repetition has a period of @period; otherwise, returns zero.
4451 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4454 for (i = 0; i < period; i++)
4455 for (j = i + period; j < arrlen; j += period)
4456 if (id_data[i] != id_data[j])
4462 * nand_id_len - Get the length of an ID string returned by CMD_READID
4463 * @id_data: the ID string
4464 * @arrlen: the length of the @id_data array
4466 * Returns the length of the ID string, according to known wraparound/trailing
4467 * zero patterns. If no pattern exists, returns the length of the array.
4469 static int nand_id_len(u8 *id_data, int arrlen)
4471 int last_nonzero, period;
4473 /* Find last non-zero byte */
4474 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4475 if (id_data[last_nonzero])
4479 if (last_nonzero < 0)
4482 /* Calculate wraparound period */
4483 for (period = 1; period < arrlen; period++)
4484 if (nand_id_has_period(id_data, arrlen, period))
4487 /* There's a repeated pattern */
4488 if (period < arrlen)
4491 /* There are trailing zeros */
4492 if (last_nonzero < arrlen - 1)
4493 return last_nonzero + 1;
4495 /* No pattern detected */
4499 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4500 static int nand_get_bits_per_cell(u8 cellinfo)
4504 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4505 bits >>= NAND_CI_CELLTYPE_SHIFT;
4510 * Many new NAND share similar device ID codes, which represent the size of the
4511 * chip. The rest of the parameters must be decoded according to generic or
4512 * manufacturer-specific "extended ID" decoding patterns.
4514 void nand_decode_ext_id(struct nand_chip *chip)
4516 struct nand_memory_organization *memorg;
4517 struct mtd_info *mtd = nand_to_mtd(chip);
4519 u8 *id_data = chip->id.data;
4521 memorg = nanddev_get_memorg(&chip->base);
4523 /* The 3rd id byte holds MLC / multichip data */
4524 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4525 /* The 4th id byte is the important one */
4529 memorg->pagesize = 1024 << (extid & 0x03);
4530 mtd->writesize = memorg->pagesize;
4533 memorg->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
4534 mtd->oobsize = memorg->oobsize;
4536 /* Calc blocksize. Blocksize is multiples of 64KiB */
4537 memorg->pages_per_eraseblock = ((64 * 1024) << (extid & 0x03)) /
4539 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4541 /* Get buswidth information */
4543 chip->options |= NAND_BUSWIDTH_16;
4545 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
4548 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4549 * decodes a matching ID table entry and assigns the MTD size parameters for
4552 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
4554 struct mtd_info *mtd = nand_to_mtd(chip);
4555 struct nand_memory_organization *memorg;
4557 memorg = nanddev_get_memorg(&chip->base);
4559 memorg->pages_per_eraseblock = type->erasesize / type->pagesize;
4560 mtd->erasesize = type->erasesize;
4561 memorg->pagesize = type->pagesize;
4562 mtd->writesize = memorg->pagesize;
4563 memorg->oobsize = memorg->pagesize / 32;
4564 mtd->oobsize = memorg->oobsize;
4566 /* All legacy ID NAND are small-page, SLC */
4567 memorg->bits_per_cell = 1;
4571 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4572 * heuristic patterns using various detected parameters (e.g., manufacturer,
4573 * page size, cell-type information).
4575 static void nand_decode_bbm_options(struct nand_chip *chip)
4577 struct mtd_info *mtd = nand_to_mtd(chip);
4579 /* Set the bad block position */
4580 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4581 chip->badblockpos = NAND_BBM_POS_LARGE;
4583 chip->badblockpos = NAND_BBM_POS_SMALL;
4586 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4588 return type->id_len;
4591 static bool find_full_id_nand(struct nand_chip *chip,
4592 struct nand_flash_dev *type)
4594 struct nand_device *base = &chip->base;
4595 struct nand_ecc_props requirements;
4596 struct mtd_info *mtd = nand_to_mtd(chip);
4597 struct nand_memory_organization *memorg;
4598 u8 *id_data = chip->id.data;
4600 memorg = nanddev_get_memorg(&chip->base);
4602 if (!strncmp(type->id, id_data, type->id_len)) {
4603 memorg->pagesize = type->pagesize;
4604 mtd->writesize = memorg->pagesize;
4605 memorg->pages_per_eraseblock = type->erasesize /
4607 mtd->erasesize = type->erasesize;
4608 memorg->oobsize = type->oobsize;
4609 mtd->oobsize = memorg->oobsize;
4611 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4612 memorg->eraseblocks_per_lun =
4613 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4615 memorg->pages_per_eraseblock);
4616 chip->options |= type->options;
4617 requirements.strength = NAND_ECC_STRENGTH(type);
4618 requirements.step_size = NAND_ECC_STEP(type);
4619 nanddev_set_ecc_requirements(base, &requirements);
4621 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4622 if (!chip->parameters.model)
4631 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
4632 * compliant and does not have a full-id or legacy-id entry in the nand_ids
4635 static void nand_manufacturer_detect(struct nand_chip *chip)
4638 * Try manufacturer detection if available and use
4639 * nand_decode_ext_id() otherwise.
4641 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4642 chip->manufacturer.desc->ops->detect) {
4643 struct nand_memory_organization *memorg;
4645 memorg = nanddev_get_memorg(&chip->base);
4647 /* The 3rd id byte holds MLC / multichip data */
4648 memorg->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
4649 chip->manufacturer.desc->ops->detect(chip);
4651 nand_decode_ext_id(chip);
4656 * Manufacturer initialization. This function is called for all NANDs including
4657 * ONFI and JEDEC compliant ones.
4658 * Manufacturer drivers should put all their specific initialization code in
4659 * their ->init() hook.
4661 static int nand_manufacturer_init(struct nand_chip *chip)
4663 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
4664 !chip->manufacturer.desc->ops->init)
4667 return chip->manufacturer.desc->ops->init(chip);
4671 * Manufacturer cleanup. This function is called for all NANDs including
4672 * ONFI and JEDEC compliant ones.
4673 * Manufacturer drivers should put all their specific cleanup code in their
4676 static void nand_manufacturer_cleanup(struct nand_chip *chip)
4678 /* Release manufacturer private data */
4679 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4680 chip->manufacturer.desc->ops->cleanup)
4681 chip->manufacturer.desc->ops->cleanup(chip);
4685 nand_manufacturer_name(const struct nand_manufacturer_desc *manufacturer_desc)
4687 return manufacturer_desc ? manufacturer_desc->name : "Unknown";
4691 * Get the flash and manufacturer id and lookup if the type is supported.
4693 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
4695 const struct nand_manufacturer_desc *manufacturer_desc;
4696 struct mtd_info *mtd = nand_to_mtd(chip);
4697 struct nand_memory_organization *memorg;
4699 u8 *id_data = chip->id.data;
4704 * Let's start by initializing memorg fields that might be left
4705 * unassigned by the ID-based detection logic.
4707 memorg = nanddev_get_memorg(&chip->base);
4708 memorg->planes_per_lun = 1;
4709 memorg->luns_per_target = 1;
4712 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4715 ret = nand_reset(chip, 0);
4719 /* Select the device */
4720 nand_select_target(chip, 0);
4722 /* Send the command for reading device ID */
4723 ret = nand_readid_op(chip, 0, id_data, 2);
4727 /* Read manufacturer and device IDs */
4728 maf_id = id_data[0];
4729 dev_id = id_data[1];
4732 * Try again to make sure, as some systems the bus-hold or other
4733 * interface concerns can cause random data which looks like a
4734 * possibly credible NAND flash to appear. If the two results do
4735 * not match, ignore the device completely.
4738 /* Read entire ID string */
4739 ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
4743 if (id_data[0] != maf_id || id_data[1] != dev_id) {
4744 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4745 maf_id, dev_id, id_data[0], id_data[1]);
4749 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
4751 /* Try to identify manufacturer */
4752 manufacturer_desc = nand_get_manufacturer_desc(maf_id);
4753 chip->manufacturer.desc = manufacturer_desc;
4756 type = nand_flash_ids;
4759 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
4761 * This is required to make sure initial NAND bus width set by the
4762 * NAND controller driver is coherent with the real NAND bus width
4763 * (extracted by auto-detection code).
4765 busw = chip->options & NAND_BUSWIDTH_16;
4768 * The flag is only set (never cleared), reset it to its default value
4769 * before starting auto-detection.
4771 chip->options &= ~NAND_BUSWIDTH_16;
4773 for (; type->name != NULL; type++) {
4774 if (is_full_id_nand(type)) {
4775 if (find_full_id_nand(chip, type))
4777 } else if (dev_id == type->dev_id) {
4782 if (!type->name || !type->pagesize) {
4783 /* Check if the chip is ONFI compliant */
4784 ret = nand_onfi_detect(chip);
4790 /* Check if the chip is JEDEC compliant */
4791 ret = nand_jedec_detect(chip);
4801 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4802 if (!chip->parameters.model)
4805 if (!type->pagesize)
4806 nand_manufacturer_detect(chip);
4808 nand_decode_id(chip, type);
4810 /* Get chip options */
4811 chip->options |= type->options;
4813 memorg->eraseblocks_per_lun =
4814 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4816 memorg->pages_per_eraseblock);
4820 mtd->name = chip->parameters.model;
4822 if (chip->options & NAND_BUSWIDTH_AUTO) {
4823 WARN_ON(busw & NAND_BUSWIDTH_16);
4824 nand_set_defaults(chip);
4825 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4827 * Check, if buswidth is correct. Hardware drivers should set
4830 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4832 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
4834 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
4835 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
4838 goto free_detect_allocation;
4841 nand_decode_bbm_options(chip);
4843 /* Calculate the address shift from the page size */
4844 chip->page_shift = ffs(mtd->writesize) - 1;
4845 /* Convert chipsize to number of pages per chip -1 */
4846 targetsize = nanddev_target_size(&chip->base);
4847 chip->pagemask = (targetsize >> chip->page_shift) - 1;
4849 chip->bbt_erase_shift = chip->phys_erase_shift =
4850 ffs(mtd->erasesize) - 1;
4851 if (targetsize & 0xffffffff)
4852 chip->chip_shift = ffs((unsigned)targetsize) - 1;
4854 chip->chip_shift = ffs((unsigned)(targetsize >> 32));
4855 chip->chip_shift += 32 - 1;
4858 if (chip->chip_shift - chip->page_shift > 16)
4859 chip->options |= NAND_ROW_ADDR_3;
4861 chip->badblockbits = 8;
4863 nand_legacy_adjust_cmdfunc(chip);
4865 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4867 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
4868 chip->parameters.model);
4869 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4870 (int)(targetsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4871 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4874 free_detect_allocation:
4875 kfree(chip->parameters.model);
4880 static enum nand_ecc_engine_type
4881 of_get_rawnand_ecc_engine_type_legacy(struct device_node *np)
4883 enum nand_ecc_legacy_mode {
4889 NAND_ECC_HW_SYNDROME,
4892 const char * const nand_ecc_legacy_modes[] = {
4893 [NAND_ECC_NONE] = "none",
4894 [NAND_ECC_SOFT] = "soft",
4895 [NAND_ECC_SOFT_BCH] = "soft_bch",
4896 [NAND_ECC_HW] = "hw",
4897 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
4898 [NAND_ECC_ON_DIE] = "on-die",
4900 enum nand_ecc_legacy_mode eng_type;
4904 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4906 return NAND_ECC_ENGINE_TYPE_INVALID;
4908 for (eng_type = NAND_ECC_NONE;
4909 eng_type < ARRAY_SIZE(nand_ecc_legacy_modes); eng_type++) {
4910 if (!strcasecmp(pm, nand_ecc_legacy_modes[eng_type])) {
4913 return NAND_ECC_ENGINE_TYPE_NONE;
4915 case NAND_ECC_SOFT_BCH:
4916 return NAND_ECC_ENGINE_TYPE_SOFT;
4918 case NAND_ECC_HW_SYNDROME:
4919 return NAND_ECC_ENGINE_TYPE_ON_HOST;
4920 case NAND_ECC_ON_DIE:
4921 return NAND_ECC_ENGINE_TYPE_ON_DIE;
4928 return NAND_ECC_ENGINE_TYPE_INVALID;
4931 static enum nand_ecc_placement
4932 of_get_rawnand_ecc_placement_legacy(struct device_node *np)
4937 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4939 if (!strcasecmp(pm, "hw_syndrome"))
4940 return NAND_ECC_PLACEMENT_INTERLEAVED;
4943 return NAND_ECC_PLACEMENT_UNKNOWN;
4946 static enum nand_ecc_algo of_get_rawnand_ecc_algo_legacy(struct device_node *np)
4951 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4953 if (!strcasecmp(pm, "soft"))
4954 return NAND_ECC_ALGO_HAMMING;
4955 else if (!strcasecmp(pm, "soft_bch"))
4956 return NAND_ECC_ALGO_BCH;
4959 return NAND_ECC_ALGO_UNKNOWN;
4962 static void of_get_nand_ecc_legacy_user_config(struct nand_chip *chip)
4964 struct device_node *dn = nand_get_flash_node(chip);
4965 struct nand_ecc_props *user_conf = &chip->base.ecc.user_conf;
4967 if (user_conf->engine_type == NAND_ECC_ENGINE_TYPE_INVALID)
4968 user_conf->engine_type = of_get_rawnand_ecc_engine_type_legacy(dn);
4970 if (user_conf->algo == NAND_ECC_ALGO_UNKNOWN)
4971 user_conf->algo = of_get_rawnand_ecc_algo_legacy(dn);
4973 if (user_conf->placement == NAND_ECC_PLACEMENT_UNKNOWN)
4974 user_conf->placement = of_get_rawnand_ecc_placement_legacy(dn);
4977 static int of_get_nand_bus_width(struct device_node *np)
4981 if (of_property_read_u32(np, "nand-bus-width", &val))
4993 static bool of_get_nand_on_flash_bbt(struct device_node *np)
4995 return of_property_read_bool(np, "nand-on-flash-bbt");
4998 static int rawnand_dt_init(struct nand_chip *chip)
5000 struct nand_device *nand = mtd_to_nanddev(nand_to_mtd(chip));
5001 struct device_node *dn = nand_get_flash_node(chip);
5006 if (of_get_nand_bus_width(dn) == 16)
5007 chip->options |= NAND_BUSWIDTH_16;
5009 if (of_property_read_bool(dn, "nand-is-boot-medium"))
5010 chip->options |= NAND_IS_BOOT_MEDIUM;
5012 if (of_get_nand_on_flash_bbt(dn))
5013 chip->bbt_options |= NAND_BBT_USE_FLASH;
5015 of_get_nand_ecc_user_config(nand);
5016 of_get_nand_ecc_legacy_user_config(chip);
5019 * If neither the user nor the NAND controller have requested a specific
5020 * ECC engine type, we will default to NAND_ECC_ENGINE_TYPE_ON_HOST.
5022 nand->ecc.defaults.engine_type = NAND_ECC_ENGINE_TYPE_ON_HOST;
5025 * Use the user requested engine type, unless there is none, in this
5026 * case default to the NAND controller choice, otherwise fallback to
5027 * the raw NAND default one.
5029 if (nand->ecc.user_conf.engine_type != NAND_ECC_ENGINE_TYPE_INVALID)
5030 chip->ecc.engine_type = nand->ecc.user_conf.engine_type;
5031 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_INVALID)
5032 chip->ecc.engine_type = nand->ecc.defaults.engine_type;
5034 chip->ecc.placement = nand->ecc.user_conf.placement;
5035 chip->ecc.algo = nand->ecc.user_conf.algo;
5036 chip->ecc.strength = nand->ecc.user_conf.strength;
5037 chip->ecc.size = nand->ecc.user_conf.step_size;
5043 * nand_scan_ident - Scan for the NAND device
5044 * @chip: NAND chip object
5045 * @maxchips: number of chips to scan for
5046 * @table: alternative NAND ID table
5048 * This is the first phase of the normal nand_scan() function. It reads the
5049 * flash ID and sets up MTD fields accordingly.
5051 * This helper used to be called directly from controller drivers that needed
5052 * to tweak some ECC-related parameters before nand_scan_tail(). This separation
5053 * prevented dynamic allocations during this phase which was unconvenient and
5054 * as been banned for the benefit of the ->init_ecc()/cleanup_ecc() hooks.
5056 static int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips,
5057 struct nand_flash_dev *table)
5059 struct mtd_info *mtd = nand_to_mtd(chip);
5060 struct nand_memory_organization *memorg;
5061 int nand_maf_id, nand_dev_id;
5065 memorg = nanddev_get_memorg(&chip->base);
5067 /* Assume all dies are deselected when we enter nand_scan_ident(). */
5070 mutex_init(&chip->lock);
5072 /* Enforce the right timings for reset/detection */
5073 chip->current_interface_config = nand_get_reset_interface_config();
5075 ret = rawnand_dt_init(chip);
5079 if (!mtd->name && mtd->dev.parent)
5080 mtd->name = dev_name(mtd->dev.parent);
5082 /* Set the default functions */
5083 nand_set_defaults(chip);
5085 ret = nand_legacy_check_hooks(chip);
5089 memorg->ntargets = maxchips;
5091 /* Read the flash type */
5092 ret = nand_detect(chip, table);
5094 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
5095 pr_warn("No NAND device found\n");
5096 nand_deselect_target(chip);
5100 nand_maf_id = chip->id.data[0];
5101 nand_dev_id = chip->id.data[1];
5103 nand_deselect_target(chip);
5105 /* Check for a chip array */
5106 for (i = 1; i < maxchips; i++) {
5109 /* See comment in nand_get_flash_type for reset */
5110 ret = nand_reset(chip, i);
5114 nand_select_target(chip, i);
5115 /* Send the command for reading device ID */
5116 ret = nand_readid_op(chip, 0, id, sizeof(id));
5119 /* Read manufacturer and device IDs */
5120 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
5121 nand_deselect_target(chip);
5124 nand_deselect_target(chip);
5127 pr_info("%d chips detected\n", i);
5129 /* Store the number of chips and calc total size for mtd */
5130 memorg->ntargets = i;
5131 mtd->size = i * nanddev_target_size(&chip->base);
5136 static void nand_scan_ident_cleanup(struct nand_chip *chip)
5138 kfree(chip->parameters.model);
5139 kfree(chip->parameters.onfi);
5142 int rawnand_sw_hamming_calculate(struct nand_chip *chip,
5143 const unsigned char *buf,
5144 unsigned char *code)
5146 struct nand_device *base = &chip->base;
5148 return nand_ecc_sw_hamming_calculate(base, buf, code);
5150 EXPORT_SYMBOL(rawnand_sw_hamming_calculate);
5152 int rawnand_sw_hamming_correct(struct nand_chip *chip,
5154 unsigned char *read_ecc,
5155 unsigned char *calc_ecc)
5157 struct nand_device *base = &chip->base;
5159 return nand_ecc_sw_hamming_correct(base, buf, read_ecc, calc_ecc);
5161 EXPORT_SYMBOL(rawnand_sw_hamming_correct);
5163 int rawnand_sw_bch_init(struct nand_chip *chip)
5165 struct nand_device *base = &chip->base;
5166 struct nand_ecc_sw_bch_conf *engine_conf;
5169 base->ecc.user_conf.engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5170 base->ecc.user_conf.algo = NAND_ECC_ALGO_BCH;
5171 base->ecc.user_conf.step_size = chip->ecc.size;
5172 base->ecc.user_conf.strength = chip->ecc.strength;
5174 ret = nand_ecc_sw_bch_init_ctx(base);
5178 engine_conf = base->ecc.ctx.priv;
5180 chip->ecc.size = base->ecc.ctx.conf.step_size;
5181 chip->ecc.strength = base->ecc.ctx.conf.strength;
5182 chip->ecc.total = base->ecc.ctx.total;
5183 chip->ecc.steps = engine_conf->nsteps;
5184 chip->ecc.bytes = engine_conf->code_size;
5188 EXPORT_SYMBOL(rawnand_sw_bch_init);
5190 static int rawnand_sw_bch_calculate(struct nand_chip *chip,
5191 const unsigned char *buf,
5192 unsigned char *code)
5194 struct nand_device *base = &chip->base;
5196 return nand_ecc_sw_bch_calculate(base, buf, code);
5199 int rawnand_sw_bch_correct(struct nand_chip *chip, unsigned char *buf,
5200 unsigned char *read_ecc, unsigned char *calc_ecc)
5202 struct nand_device *base = &chip->base;
5204 return nand_ecc_sw_bch_correct(base, buf, read_ecc, calc_ecc);
5206 EXPORT_SYMBOL(rawnand_sw_bch_correct);
5208 void rawnand_sw_bch_cleanup(struct nand_chip *chip)
5210 struct nand_device *base = &chip->base;
5212 nand_ecc_sw_bch_cleanup_ctx(base);
5214 EXPORT_SYMBOL(rawnand_sw_bch_cleanup);
5216 static int nand_set_ecc_on_host_ops(struct nand_chip *chip)
5218 struct nand_ecc_ctrl *ecc = &chip->ecc;
5220 switch (ecc->placement) {
5221 case NAND_ECC_PLACEMENT_UNKNOWN:
5222 case NAND_ECC_PLACEMENT_OOB:
5223 /* Use standard hwecc read page function? */
5224 if (!ecc->read_page)
5225 ecc->read_page = nand_read_page_hwecc;
5226 if (!ecc->write_page)
5227 ecc->write_page = nand_write_page_hwecc;
5228 if (!ecc->read_page_raw)
5229 ecc->read_page_raw = nand_read_page_raw;
5230 if (!ecc->write_page_raw)
5231 ecc->write_page_raw = nand_write_page_raw;
5233 ecc->read_oob = nand_read_oob_std;
5234 if (!ecc->write_oob)
5235 ecc->write_oob = nand_write_oob_std;
5236 if (!ecc->read_subpage)
5237 ecc->read_subpage = nand_read_subpage;
5238 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5239 ecc->write_subpage = nand_write_subpage_hwecc;
5242 case NAND_ECC_PLACEMENT_INTERLEAVED:
5243 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5245 ecc->read_page == nand_read_page_hwecc ||
5247 ecc->write_page == nand_write_page_hwecc)) {
5248 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5251 /* Use standard syndrome read/write page function? */
5252 if (!ecc->read_page)
5253 ecc->read_page = nand_read_page_syndrome;
5254 if (!ecc->write_page)
5255 ecc->write_page = nand_write_page_syndrome;
5256 if (!ecc->read_page_raw)
5257 ecc->read_page_raw = nand_read_page_raw_syndrome;
5258 if (!ecc->write_page_raw)
5259 ecc->write_page_raw = nand_write_page_raw_syndrome;
5261 ecc->read_oob = nand_read_oob_syndrome;
5262 if (!ecc->write_oob)
5263 ecc->write_oob = nand_write_oob_syndrome;
5267 pr_warn("Invalid NAND_ECC_PLACEMENT %d\n",
5275 static int nand_set_ecc_soft_ops(struct nand_chip *chip)
5277 struct mtd_info *mtd = nand_to_mtd(chip);
5278 struct nand_device *nanddev = mtd_to_nanddev(mtd);
5279 struct nand_ecc_ctrl *ecc = &chip->ecc;
5282 if (WARN_ON(ecc->engine_type != NAND_ECC_ENGINE_TYPE_SOFT))
5285 switch (ecc->algo) {
5286 case NAND_ECC_ALGO_HAMMING:
5287 ecc->calculate = rawnand_sw_hamming_calculate;
5288 ecc->correct = rawnand_sw_hamming_correct;
5289 ecc->read_page = nand_read_page_swecc;
5290 ecc->read_subpage = nand_read_subpage;
5291 ecc->write_page = nand_write_page_swecc;
5292 if (!ecc->read_page_raw)
5293 ecc->read_page_raw = nand_read_page_raw;
5294 if (!ecc->write_page_raw)
5295 ecc->write_page_raw = nand_write_page_raw;
5296 ecc->read_oob = nand_read_oob_std;
5297 ecc->write_oob = nand_write_oob_std;
5303 if (IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_HAMMING_SMC))
5304 ecc->options |= NAND_ECC_SOFT_HAMMING_SM_ORDER;
5307 case NAND_ECC_ALGO_BCH:
5308 if (!IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_BCH)) {
5309 WARN(1, "CONFIG_MTD_NAND_ECC_SW_BCH not enabled\n");
5312 ecc->calculate = rawnand_sw_bch_calculate;
5313 ecc->correct = rawnand_sw_bch_correct;
5314 ecc->read_page = nand_read_page_swecc;
5315 ecc->read_subpage = nand_read_subpage;
5316 ecc->write_page = nand_write_page_swecc;
5317 if (!ecc->read_page_raw)
5318 ecc->read_page_raw = nand_read_page_raw;
5319 if (!ecc->write_page_raw)
5320 ecc->write_page_raw = nand_write_page_raw;
5321 ecc->read_oob = nand_read_oob_std;
5322 ecc->write_oob = nand_write_oob_std;
5325 * We can only maximize ECC config when the default layout is
5326 * used, otherwise we don't know how many bytes can really be
5329 if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH &&
5330 mtd->ooblayout != nand_get_large_page_ooblayout())
5331 nanddev->ecc.user_conf.flags &= ~NAND_ECC_MAXIMIZE_STRENGTH;
5333 ret = rawnand_sw_bch_init(chip);
5335 WARN(1, "BCH ECC initialization failed!\n");
5341 WARN(1, "Unsupported ECC algorithm!\n");
5347 * nand_check_ecc_caps - check the sanity of preset ECC settings
5348 * @chip: nand chip info structure
5349 * @caps: ECC caps info structure
5350 * @oobavail: OOB size that the ECC engine can use
5352 * When ECC step size and strength are already set, check if they are supported
5353 * by the controller and the calculated ECC bytes fit within the chip's OOB.
5354 * On success, the calculated ECC bytes is set.
5357 nand_check_ecc_caps(struct nand_chip *chip,
5358 const struct nand_ecc_caps *caps, int oobavail)
5360 struct mtd_info *mtd = nand_to_mtd(chip);
5361 const struct nand_ecc_step_info *stepinfo;
5362 int preset_step = chip->ecc.size;
5363 int preset_strength = chip->ecc.strength;
5364 int ecc_bytes, nsteps = mtd->writesize / preset_step;
5367 for (i = 0; i < caps->nstepinfos; i++) {
5368 stepinfo = &caps->stepinfos[i];
5370 if (stepinfo->stepsize != preset_step)
5373 for (j = 0; j < stepinfo->nstrengths; j++) {
5374 if (stepinfo->strengths[j] != preset_strength)
5377 ecc_bytes = caps->calc_ecc_bytes(preset_step,
5379 if (WARN_ON_ONCE(ecc_bytes < 0))
5382 if (ecc_bytes * nsteps > oobavail) {
5383 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
5384 preset_step, preset_strength);
5388 chip->ecc.bytes = ecc_bytes;
5394 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
5395 preset_step, preset_strength);
5401 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
5402 * @chip: nand chip info structure
5403 * @caps: ECC engine caps info structure
5404 * @oobavail: OOB size that the ECC engine can use
5406 * If a chip's ECC requirement is provided, try to meet it with the least
5407 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
5408 * On success, the chosen ECC settings are set.
5411 nand_match_ecc_req(struct nand_chip *chip,
5412 const struct nand_ecc_caps *caps, int oobavail)
5414 const struct nand_ecc_props *requirements =
5415 nanddev_get_ecc_requirements(&chip->base);
5416 struct mtd_info *mtd = nand_to_mtd(chip);
5417 const struct nand_ecc_step_info *stepinfo;
5418 int req_step = requirements->step_size;
5419 int req_strength = requirements->strength;
5420 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
5421 int best_step, best_strength, best_ecc_bytes;
5422 int best_ecc_bytes_total = INT_MAX;
5425 /* No information provided by the NAND chip */
5426 if (!req_step || !req_strength)
5429 /* number of correctable bits the chip requires in a page */
5430 req_corr = mtd->writesize / req_step * req_strength;
5432 for (i = 0; i < caps->nstepinfos; i++) {
5433 stepinfo = &caps->stepinfos[i];
5434 step_size = stepinfo->stepsize;
5436 for (j = 0; j < stepinfo->nstrengths; j++) {
5437 strength = stepinfo->strengths[j];
5440 * If both step size and strength are smaller than the
5441 * chip's requirement, it is not easy to compare the
5442 * resulted reliability.
5444 if (step_size < req_step && strength < req_strength)
5447 if (mtd->writesize % step_size)
5450 nsteps = mtd->writesize / step_size;
5452 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5453 if (WARN_ON_ONCE(ecc_bytes < 0))
5455 ecc_bytes_total = ecc_bytes * nsteps;
5457 if (ecc_bytes_total > oobavail ||
5458 strength * nsteps < req_corr)
5462 * We assume the best is to meet the chip's requrement
5463 * with the least number of ECC bytes.
5465 if (ecc_bytes_total < best_ecc_bytes_total) {
5466 best_ecc_bytes_total = ecc_bytes_total;
5467 best_step = step_size;
5468 best_strength = strength;
5469 best_ecc_bytes = ecc_bytes;
5474 if (best_ecc_bytes_total == INT_MAX)
5477 chip->ecc.size = best_step;
5478 chip->ecc.strength = best_strength;
5479 chip->ecc.bytes = best_ecc_bytes;
5485 * nand_maximize_ecc - choose the max ECC strength available
5486 * @chip: nand chip info structure
5487 * @caps: ECC engine caps info structure
5488 * @oobavail: OOB size that the ECC engine can use
5490 * Choose the max ECC strength that is supported on the controller, and can fit
5491 * within the chip's OOB. On success, the chosen ECC settings are set.
5494 nand_maximize_ecc(struct nand_chip *chip,
5495 const struct nand_ecc_caps *caps, int oobavail)
5497 struct mtd_info *mtd = nand_to_mtd(chip);
5498 const struct nand_ecc_step_info *stepinfo;
5499 int step_size, strength, nsteps, ecc_bytes, corr;
5502 int best_strength, best_ecc_bytes;
5505 for (i = 0; i < caps->nstepinfos; i++) {
5506 stepinfo = &caps->stepinfos[i];
5507 step_size = stepinfo->stepsize;
5509 /* If chip->ecc.size is already set, respect it */
5510 if (chip->ecc.size && step_size != chip->ecc.size)
5513 for (j = 0; j < stepinfo->nstrengths; j++) {
5514 strength = stepinfo->strengths[j];
5516 if (mtd->writesize % step_size)
5519 nsteps = mtd->writesize / step_size;
5521 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5522 if (WARN_ON_ONCE(ecc_bytes < 0))
5525 if (ecc_bytes * nsteps > oobavail)
5528 corr = strength * nsteps;
5531 * If the number of correctable bits is the same,
5532 * bigger step_size has more reliability.
5534 if (corr > best_corr ||
5535 (corr == best_corr && step_size > best_step)) {
5537 best_step = step_size;
5538 best_strength = strength;
5539 best_ecc_bytes = ecc_bytes;
5547 chip->ecc.size = best_step;
5548 chip->ecc.strength = best_strength;
5549 chip->ecc.bytes = best_ecc_bytes;
5555 * nand_ecc_choose_conf - Set the ECC strength and ECC step size
5556 * @chip: nand chip info structure
5557 * @caps: ECC engine caps info structure
5558 * @oobavail: OOB size that the ECC engine can use
5560 * Choose the ECC configuration according to following logic.
5562 * 1. If both ECC step size and ECC strength are already set (usually by DT)
5563 * then check if it is supported by this controller.
5564 * 2. If the user provided the nand-ecc-maximize property, then select maximum
5566 * 3. Otherwise, try to match the ECC step size and ECC strength closest
5567 * to the chip's requirement. If available OOB size can't fit the chip
5568 * requirement then fallback to the maximum ECC step size and ECC strength.
5570 * On success, the chosen ECC settings are set.
5572 int nand_ecc_choose_conf(struct nand_chip *chip,
5573 const struct nand_ecc_caps *caps, int oobavail)
5575 struct mtd_info *mtd = nand_to_mtd(chip);
5576 struct nand_device *nanddev = mtd_to_nanddev(mtd);
5578 if (WARN_ON(oobavail < 0 || oobavail > mtd->oobsize))
5581 if (chip->ecc.size && chip->ecc.strength)
5582 return nand_check_ecc_caps(chip, caps, oobavail);
5584 if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH)
5585 return nand_maximize_ecc(chip, caps, oobavail);
5587 if (!nand_match_ecc_req(chip, caps, oobavail))
5590 return nand_maximize_ecc(chip, caps, oobavail);
5592 EXPORT_SYMBOL_GPL(nand_ecc_choose_conf);
5594 static int rawnand_erase(struct nand_device *nand, const struct nand_pos *pos)
5596 struct nand_chip *chip = container_of(nand, struct nand_chip,
5598 unsigned int eb = nanddev_pos_to_row(nand, pos);
5601 eb >>= nand->rowconv.eraseblock_addr_shift;
5603 nand_select_target(chip, pos->target);
5604 ret = nand_erase_op(chip, eb);
5605 nand_deselect_target(chip);
5610 static int rawnand_markbad(struct nand_device *nand,
5611 const struct nand_pos *pos)
5613 struct nand_chip *chip = container_of(nand, struct nand_chip,
5616 return nand_markbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5619 static bool rawnand_isbad(struct nand_device *nand, const struct nand_pos *pos)
5621 struct nand_chip *chip = container_of(nand, struct nand_chip,
5625 nand_select_target(chip, pos->target);
5626 ret = nand_isbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5627 nand_deselect_target(chip);
5632 static const struct nand_ops rawnand_ops = {
5633 .erase = rawnand_erase,
5634 .markbad = rawnand_markbad,
5635 .isbad = rawnand_isbad,
5639 * nand_scan_tail - Scan for the NAND device
5640 * @chip: NAND chip object
5642 * This is the second phase of the normal nand_scan() function. It fills out
5643 * all the uninitialized function pointers with the defaults and scans for a
5644 * bad block table if appropriate.
5646 static int nand_scan_tail(struct nand_chip *chip)
5648 struct mtd_info *mtd = nand_to_mtd(chip);
5649 struct nand_ecc_ctrl *ecc = &chip->ecc;
5652 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
5653 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
5654 !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
5658 chip->data_buf = kmalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
5659 if (!chip->data_buf)
5663 * FIXME: some NAND manufacturer drivers expect the first die to be
5664 * selected when manufacturer->init() is called. They should be fixed
5665 * to explictly select the relevant die when interacting with the NAND
5668 nand_select_target(chip, 0);
5669 ret = nand_manufacturer_init(chip);
5670 nand_deselect_target(chip);
5674 /* Set the internal oob buffer location, just after the page data */
5675 chip->oob_poi = chip->data_buf + mtd->writesize;
5678 * If no default placement scheme is given, select an appropriate one.
5680 if (!mtd->ooblayout &&
5681 !(ecc->engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
5682 ecc->algo == NAND_ECC_ALGO_BCH)) {
5683 switch (mtd->oobsize) {
5686 mtd_set_ooblayout(mtd, nand_get_small_page_ooblayout());
5690 mtd_set_ooblayout(mtd,
5691 nand_get_large_page_hamming_ooblayout());
5695 * Expose the whole OOB area to users if ECC_NONE
5696 * is passed. We could do that for all kind of
5697 * ->oobsize, but we must keep the old large/small
5698 * page with ECC layout when ->oobsize <= 128 for
5699 * compatibility reasons.
5701 if (ecc->engine_type == NAND_ECC_ENGINE_TYPE_NONE) {
5702 mtd_set_ooblayout(mtd,
5703 nand_get_large_page_ooblayout());
5707 WARN(1, "No oob scheme defined for oobsize %d\n",
5710 goto err_nand_manuf_cleanup;
5715 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
5716 * selected and we have 256 byte pagesize fallback to software ECC
5719 switch (ecc->engine_type) {
5720 case NAND_ECC_ENGINE_TYPE_ON_HOST:
5721 ret = nand_set_ecc_on_host_ops(chip);
5723 goto err_nand_manuf_cleanup;
5725 if (mtd->writesize >= ecc->size) {
5726 if (!ecc->strength) {
5727 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
5729 goto err_nand_manuf_cleanup;
5733 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
5734 ecc->size, mtd->writesize);
5735 ecc->engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5736 ecc->algo = NAND_ECC_ALGO_HAMMING;
5739 case NAND_ECC_ENGINE_TYPE_SOFT:
5740 ret = nand_set_ecc_soft_ops(chip);
5742 goto err_nand_manuf_cleanup;
5745 case NAND_ECC_ENGINE_TYPE_ON_DIE:
5746 if (!ecc->read_page || !ecc->write_page) {
5747 WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
5749 goto err_nand_manuf_cleanup;
5752 ecc->read_oob = nand_read_oob_std;
5753 if (!ecc->write_oob)
5754 ecc->write_oob = nand_write_oob_std;
5757 case NAND_ECC_ENGINE_TYPE_NONE:
5758 pr_warn("NAND_ECC_ENGINE_TYPE_NONE selected by board driver. This is not recommended!\n");
5759 ecc->read_page = nand_read_page_raw;
5760 ecc->write_page = nand_write_page_raw;
5761 ecc->read_oob = nand_read_oob_std;
5762 ecc->read_page_raw = nand_read_page_raw;
5763 ecc->write_page_raw = nand_write_page_raw;
5764 ecc->write_oob = nand_write_oob_std;
5765 ecc->size = mtd->writesize;
5771 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->engine_type);
5773 goto err_nand_manuf_cleanup;
5776 if (ecc->correct || ecc->calculate) {
5777 ecc->calc_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
5778 ecc->code_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
5779 if (!ecc->calc_buf || !ecc->code_buf) {
5781 goto err_nand_manuf_cleanup;
5785 /* For many systems, the standard OOB write also works for raw */
5786 if (!ecc->read_oob_raw)
5787 ecc->read_oob_raw = ecc->read_oob;
5788 if (!ecc->write_oob_raw)
5789 ecc->write_oob_raw = ecc->write_oob;
5791 /* propagate ecc info to mtd_info */
5792 mtd->ecc_strength = ecc->strength;
5793 mtd->ecc_step_size = ecc->size;
5796 * Set the number of read / write steps for one page depending on ECC
5800 ecc->steps = mtd->writesize / ecc->size;
5801 if (ecc->steps * ecc->size != mtd->writesize) {
5802 WARN(1, "Invalid ECC parameters\n");
5804 goto err_nand_manuf_cleanup;
5808 ecc->total = ecc->steps * ecc->bytes;
5809 chip->base.ecc.ctx.total = ecc->total;
5812 if (ecc->total > mtd->oobsize) {
5813 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
5815 goto err_nand_manuf_cleanup;
5819 * The number of bytes available for a client to place data into
5820 * the out of band area.
5822 ret = mtd_ooblayout_count_freebytes(mtd);
5826 mtd->oobavail = ret;
5828 /* ECC sanity check: warn if it's too weak */
5829 if (!nand_ecc_is_strong_enough(&chip->base))
5830 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",
5831 mtd->name, chip->ecc.strength, chip->ecc.size,
5832 nanddev_get_ecc_requirements(&chip->base)->strength,
5833 nanddev_get_ecc_requirements(&chip->base)->step_size);
5835 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
5836 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
5837 switch (ecc->steps) {
5839 mtd->subpage_sft = 1;
5844 mtd->subpage_sft = 2;
5848 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
5850 /* Invalidate the pagebuffer reference */
5851 chip->pagecache.page = -1;
5853 /* Large page NAND with SOFT_ECC should support subpage reads */
5854 switch (ecc->engine_type) {
5855 case NAND_ECC_ENGINE_TYPE_SOFT:
5856 if (chip->page_shift > 9)
5857 chip->options |= NAND_SUBPAGE_READ;
5864 ret = nanddev_init(&chip->base, &rawnand_ops, mtd->owner);
5866 goto err_nand_manuf_cleanup;
5868 /* Adjust the MTD_CAP_ flags when NAND_ROM is set. */
5869 if (chip->options & NAND_ROM)
5870 mtd->flags = MTD_CAP_ROM;
5872 /* Fill in remaining MTD driver data */
5873 mtd->_erase = nand_erase;
5875 mtd->_unpoint = NULL;
5876 mtd->_panic_write = panic_nand_write;
5877 mtd->_read_oob = nand_read_oob;
5878 mtd->_write_oob = nand_write_oob;
5879 mtd->_sync = nand_sync;
5880 mtd->_lock = nand_lock;
5881 mtd->_unlock = nand_unlock;
5882 mtd->_suspend = nand_suspend;
5883 mtd->_resume = nand_resume;
5884 mtd->_reboot = nand_shutdown;
5885 mtd->_block_isreserved = nand_block_isreserved;
5886 mtd->_block_isbad = nand_block_isbad;
5887 mtd->_block_markbad = nand_block_markbad;
5888 mtd->_max_bad_blocks = nanddev_mtd_max_bad_blocks;
5891 * Initialize bitflip_threshold to its default prior scan_bbt() call.
5892 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
5895 if (!mtd->bitflip_threshold)
5896 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
5898 /* Find the fastest data interface for this chip */
5899 ret = nand_choose_interface_config(chip);
5901 goto err_nanddev_cleanup;
5903 /* Enter fastest possible mode on all dies. */
5904 for (i = 0; i < nanddev_ntargets(&chip->base); i++) {
5905 ret = nand_setup_interface(chip, i);
5907 goto err_free_interface_config;
5910 /* Check, if we should skip the bad block table scan */
5911 if (chip->options & NAND_SKIP_BBTSCAN)
5914 /* Build bad block table */
5915 ret = nand_create_bbt(chip);
5917 goto err_free_interface_config;
5921 err_free_interface_config:
5922 kfree(chip->best_interface_config);
5924 err_nanddev_cleanup:
5925 nanddev_cleanup(&chip->base);
5927 err_nand_manuf_cleanup:
5928 nand_manufacturer_cleanup(chip);
5931 kfree(chip->data_buf);
5932 kfree(ecc->code_buf);
5933 kfree(ecc->calc_buf);
5938 static int nand_attach(struct nand_chip *chip)
5940 if (chip->controller->ops && chip->controller->ops->attach_chip)
5941 return chip->controller->ops->attach_chip(chip);
5946 static void nand_detach(struct nand_chip *chip)
5948 if (chip->controller->ops && chip->controller->ops->detach_chip)
5949 chip->controller->ops->detach_chip(chip);
5953 * nand_scan_with_ids - [NAND Interface] Scan for the NAND device
5954 * @chip: NAND chip object
5955 * @maxchips: number of chips to scan for.
5956 * @ids: optional flash IDs table
5958 * This fills out all the uninitialized function pointers with the defaults.
5959 * The flash ID is read and the mtd/chip structures are filled with the
5960 * appropriate values.
5962 int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips,
5963 struct nand_flash_dev *ids)
5970 ret = nand_scan_ident(chip, maxchips, ids);
5974 ret = nand_attach(chip);
5978 ret = nand_scan_tail(chip);
5987 nand_scan_ident_cleanup(chip);
5991 EXPORT_SYMBOL(nand_scan_with_ids);
5994 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
5995 * @chip: NAND chip object
5997 void nand_cleanup(struct nand_chip *chip)
5999 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
6000 chip->ecc.algo == NAND_ECC_ALGO_BCH)
6001 rawnand_sw_bch_cleanup(chip);
6003 nanddev_cleanup(&chip->base);
6005 /* Free bad block table memory */
6007 kfree(chip->data_buf);
6008 kfree(chip->ecc.code_buf);
6009 kfree(chip->ecc.calc_buf);
6011 /* Free bad block descriptor memory */
6012 if (chip->badblock_pattern && chip->badblock_pattern->options
6013 & NAND_BBT_DYNAMICSTRUCT)
6014 kfree(chip->badblock_pattern);
6016 /* Free the data interface */
6017 kfree(chip->best_interface_config);
6019 /* Free manufacturer priv data. */
6020 nand_manufacturer_cleanup(chip);
6022 /* Free controller specific allocations after chip identification */
6025 /* Free identification phase allocations */
6026 nand_scan_ident_cleanup(chip);
6029 EXPORT_SYMBOL_GPL(nand_cleanup);
6031 MODULE_LICENSE("GPL");
6032 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
6033 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
6034 MODULE_DESCRIPTION("Generic NAND flash driver code");