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
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);
282 * nand_region_is_secured() - Check if the region is secured
283 * @chip: NAND chip object
284 * @offset: Offset of the region to check
285 * @size: Size of the region to check
287 * Checks if the region is secured by comparing the offset and size with the
288 * list of secure regions obtained from DT. Returns true if the region is
289 * secured else false.
291 static bool nand_region_is_secured(struct nand_chip *chip, loff_t offset, u64 size)
295 /* Skip touching the secure regions if present */
296 for (i = 0; i < chip->nr_secure_regions; i++) {
297 const struct nand_secure_region *region = &chip->secure_regions[i];
299 if (offset + size <= region->offset ||
300 offset >= region->offset + region->size)
303 pr_debug("%s: Region 0x%llx - 0x%llx is secured!",
304 __func__, offset, offset + size);
312 static int nand_isbad_bbm(struct nand_chip *chip, loff_t ofs)
314 struct mtd_info *mtd = nand_to_mtd(chip);
316 if (chip->options & NAND_NO_BBM_QUIRK)
319 /* Check if the region is secured */
320 if (nand_region_is_secured(chip, ofs, mtd->erasesize))
323 if (mtd_check_expert_analysis_mode())
326 if (chip->legacy.block_bad)
327 return chip->legacy.block_bad(chip, ofs);
329 return nand_block_bad(chip, ofs);
333 * nand_get_device - [GENERIC] Get chip for selected access
334 * @chip: NAND chip structure
336 * Lock the device and its controller for exclusive access
338 static void nand_get_device(struct nand_chip *chip)
340 /* Wait until the device is resumed. */
342 mutex_lock(&chip->lock);
343 if (!chip->suspended) {
344 mutex_lock(&chip->controller->lock);
347 mutex_unlock(&chip->lock);
349 wait_event(chip->resume_wq, !chip->suspended);
354 * nand_check_wp - [GENERIC] check if the chip is write protected
355 * @chip: NAND chip object
357 * Check, if the device is write protected. The function expects, that the
358 * device is already selected.
360 static int nand_check_wp(struct nand_chip *chip)
365 /* Broken xD cards report WP despite being writable */
366 if (chip->options & NAND_BROKEN_XD)
369 /* Check the WP bit */
370 ret = nand_status_op(chip, &status);
374 return status & NAND_STATUS_WP ? 0 : 1;
378 * nand_fill_oob - [INTERN] Transfer client buffer to oob
379 * @chip: NAND chip object
380 * @oob: oob data buffer
381 * @len: oob data write length
382 * @ops: oob ops structure
384 static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len,
385 struct mtd_oob_ops *ops)
387 struct mtd_info *mtd = nand_to_mtd(chip);
391 * Initialise to all 0xFF, to avoid the possibility of left over OOB
392 * data from a previous OOB read.
394 memset(chip->oob_poi, 0xff, mtd->oobsize);
398 case MTD_OPS_PLACE_OOB:
400 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
403 case MTD_OPS_AUTO_OOB:
404 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
416 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
417 * @chip: NAND chip object
418 * @to: offset to write to
419 * @ops: oob operation description structure
421 * NAND write out-of-band.
423 static int nand_do_write_oob(struct nand_chip *chip, loff_t to,
424 struct mtd_oob_ops *ops)
426 struct mtd_info *mtd = nand_to_mtd(chip);
427 int chipnr, page, status, len, ret;
429 pr_debug("%s: to = 0x%08x, len = %i\n",
430 __func__, (unsigned int)to, (int)ops->ooblen);
432 len = mtd_oobavail(mtd, ops);
434 /* Do not allow write past end of page */
435 if ((ops->ooboffs + ops->ooblen) > len) {
436 pr_debug("%s: attempt to write past end of page\n",
441 /* Check if the region is secured */
442 if (nand_region_is_secured(chip, to, ops->ooblen))
445 chipnr = (int)(to >> chip->chip_shift);
448 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
449 * of my DiskOnChip 2000 test units) will clear the whole data page too
450 * if we don't do this. I have no clue why, but I seem to have 'fixed'
451 * it in the doc2000 driver in August 1999. dwmw2.
453 ret = nand_reset(chip, chipnr);
457 nand_select_target(chip, chipnr);
459 /* Shift to get page */
460 page = (int)(to >> chip->page_shift);
462 /* Check, if it is write protected */
463 if (nand_check_wp(chip)) {
464 nand_deselect_target(chip);
468 /* Invalidate the page cache, if we write to the cached page */
469 if (page == chip->pagecache.page)
470 chip->pagecache.page = -1;
472 nand_fill_oob(chip, ops->oobbuf, ops->ooblen, ops);
474 if (ops->mode == MTD_OPS_RAW)
475 status = chip->ecc.write_oob_raw(chip, page & chip->pagemask);
477 status = chip->ecc.write_oob(chip, page & chip->pagemask);
479 nand_deselect_target(chip);
484 ops->oobretlen = ops->ooblen;
490 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
491 * @chip: NAND chip object
492 * @ofs: offset from device start
494 * This is the default implementation, which can be overridden by a hardware
495 * specific driver. It provides the details for writing a bad block marker to a
498 static int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
500 struct mtd_info *mtd = nand_to_mtd(chip);
501 struct mtd_oob_ops ops;
502 uint8_t buf[2] = { 0, 0 };
503 int ret = 0, res, page_offset;
505 memset(&ops, 0, sizeof(ops));
507 ops.ooboffs = chip->badblockpos;
508 if (chip->options & NAND_BUSWIDTH_16) {
509 ops.ooboffs &= ~0x01;
510 ops.len = ops.ooblen = 2;
512 ops.len = ops.ooblen = 1;
514 ops.mode = MTD_OPS_PLACE_OOB;
516 page_offset = nand_bbm_get_next_page(chip, 0);
518 while (page_offset >= 0) {
519 res = nand_do_write_oob(chip,
520 ofs + (page_offset * mtd->writesize),
526 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
533 * nand_markbad_bbm - mark a block by updating the BBM
534 * @chip: NAND chip object
535 * @ofs: offset of the block to mark bad
537 int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
539 if (chip->legacy.block_markbad)
540 return chip->legacy.block_markbad(chip, ofs);
542 return nand_default_block_markbad(chip, ofs);
546 * nand_block_markbad_lowlevel - mark a block bad
547 * @chip: NAND chip object
548 * @ofs: offset from device start
550 * This function performs the generic NAND bad block marking steps (i.e., bad
551 * block table(s) and/or marker(s)). We only allow the hardware driver to
552 * specify how to write bad block markers to OOB (chip->legacy.block_markbad).
554 * We try operations in the following order:
556 * (1) erase the affected block, to allow OOB marker to be written cleanly
557 * (2) write bad block marker to OOB area of affected block (unless flag
558 * NAND_BBT_NO_OOB_BBM is present)
561 * Note that we retain the first error encountered in (2) or (3), finish the
562 * procedures, and dump the error in the end.
564 static int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
566 struct mtd_info *mtd = nand_to_mtd(chip);
569 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
570 struct erase_info einfo;
572 /* Attempt erase before marking OOB */
573 memset(&einfo, 0, sizeof(einfo));
575 einfo.len = 1ULL << chip->phys_erase_shift;
576 nand_erase_nand(chip, &einfo, 0);
578 /* Write bad block marker to OOB */
579 nand_get_device(chip);
581 ret = nand_markbad_bbm(chip, ofs);
582 nand_release_device(chip);
585 /* Mark block bad in BBT */
587 res = nand_markbad_bbt(chip, ofs);
593 mtd->ecc_stats.badblocks++;
599 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
600 * @mtd: MTD device structure
601 * @ofs: offset from device start
603 * Check if the block is marked as reserved.
605 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
607 struct nand_chip *chip = mtd_to_nand(mtd);
611 /* Return info from the table */
612 return nand_isreserved_bbt(chip, ofs);
616 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
617 * @chip: NAND chip object
618 * @ofs: offset from device start
619 * @allowbbt: 1, if its allowed to access the bbt area
621 * Check, if the block is bad. Either by reading the bad block table or
622 * calling of the scan function.
624 static int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
626 /* Return info from the table */
628 return nand_isbad_bbt(chip, ofs, allowbbt);
630 return nand_isbad_bbm(chip, ofs);
634 * nand_soft_waitrdy - Poll STATUS reg until RDY bit is set to 1
635 * @chip: NAND chip structure
636 * @timeout_ms: Timeout in ms
638 * Poll the STATUS register using ->exec_op() until the RDY bit becomes 1.
639 * If that does not happen whitin the specified timeout, -ETIMEDOUT is
642 * This helper is intended to be used when the controller does not have access
643 * to the NAND R/B pin.
645 * Be aware that calling this helper from an ->exec_op() implementation means
646 * ->exec_op() must be re-entrant.
648 * Return 0 if the NAND chip is ready, a negative error otherwise.
650 int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
652 const struct nand_interface_config *conf;
656 if (!nand_has_exec_op(chip))
659 /* Wait tWB before polling the STATUS reg. */
660 conf = nand_get_interface_config(chip);
661 ndelay(NAND_COMMON_TIMING_NS(conf, tWB_max));
663 ret = nand_status_op(chip, NULL);
668 * +1 below is necessary because if we are now in the last fraction
669 * of jiffy and msecs_to_jiffies is 1 then we will wait only that
670 * small jiffy fraction - possibly leading to false timeout
672 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
674 ret = nand_read_data_op(chip, &status, sizeof(status), true,
679 if (status & NAND_STATUS_READY)
683 * Typical lowest execution time for a tR on most NANDs is 10us,
684 * use this as polling delay before doing something smarter (ie.
685 * deriving a delay from the timeout value, timeout_ms/ratio).
688 } while (time_before(jiffies, timeout_ms));
691 * We have to exit READ_STATUS mode in order to read real data on the
692 * bus in case the WAITRDY instruction is preceding a DATA_IN
695 nand_exit_status_op(chip);
700 return status & NAND_STATUS_READY ? 0 : -ETIMEDOUT;
702 EXPORT_SYMBOL_GPL(nand_soft_waitrdy);
705 * nand_gpio_waitrdy - Poll R/B GPIO pin until ready
706 * @chip: NAND chip structure
707 * @gpiod: GPIO descriptor of R/B pin
708 * @timeout_ms: Timeout in ms
710 * Poll the R/B GPIO pin until it becomes ready. If that does not happen
711 * whitin the specified timeout, -ETIMEDOUT is returned.
713 * This helper is intended to be used when the controller has access to the
714 * NAND R/B pin over GPIO.
716 * Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.
718 int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
719 unsigned long timeout_ms)
723 * Wait until R/B pin indicates chip is ready or timeout occurs.
724 * +1 below is necessary because if we are now in the last fraction
725 * of jiffy and msecs_to_jiffies is 1 then we will wait only that
726 * small jiffy fraction - possibly leading to false timeout.
728 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
730 if (gpiod_get_value_cansleep(gpiod))
734 } while (time_before(jiffies, timeout_ms));
736 return gpiod_get_value_cansleep(gpiod) ? 0 : -ETIMEDOUT;
738 EXPORT_SYMBOL_GPL(nand_gpio_waitrdy);
741 * panic_nand_wait - [GENERIC] wait until the command is done
742 * @chip: NAND chip structure
745 * Wait for command done. This is a helper function for nand_wait used when
746 * we are in interrupt context. May happen when in panic and trying to write
747 * an oops through mtdoops.
749 void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
752 for (i = 0; i < timeo; i++) {
753 if (chip->legacy.dev_ready) {
754 if (chip->legacy.dev_ready(chip))
760 ret = nand_read_data_op(chip, &status, sizeof(status),
765 if (status & NAND_STATUS_READY)
772 static bool nand_supports_get_features(struct nand_chip *chip, int addr)
774 return (chip->parameters.supports_set_get_features &&
775 test_bit(addr, chip->parameters.get_feature_list));
778 static bool nand_supports_set_features(struct nand_chip *chip, int addr)
780 return (chip->parameters.supports_set_get_features &&
781 test_bit(addr, chip->parameters.set_feature_list));
785 * nand_reset_interface - Reset data interface and timings
786 * @chip: The NAND chip
787 * @chipnr: Internal die id
789 * Reset the Data interface and timings to ONFI mode 0.
791 * Returns 0 for success or negative error code otherwise.
793 static int nand_reset_interface(struct nand_chip *chip, int chipnr)
795 const struct nand_controller_ops *ops = chip->controller->ops;
798 if (!nand_controller_can_setup_interface(chip))
802 * The ONFI specification says:
804 * To transition from NV-DDR or NV-DDR2 to the SDR data
805 * interface, the host shall use the Reset (FFh) command
806 * using SDR timing mode 0. A device in any timing mode is
807 * required to recognize Reset (FFh) command issued in SDR
811 * Configure the data interface in SDR mode and set the
812 * timings to timing mode 0.
815 chip->current_interface_config = nand_get_reset_interface_config();
816 ret = ops->setup_interface(chip, chipnr,
817 chip->current_interface_config);
819 pr_err("Failed to configure data interface to SDR timing mode 0\n");
825 * nand_setup_interface - Setup the best data interface and timings
826 * @chip: The NAND chip
827 * @chipnr: Internal die id
829 * Configure what has been reported to be the best data interface and NAND
830 * timings supported by the chip and the driver.
832 * Returns 0 for success or negative error code otherwise.
834 static int nand_setup_interface(struct nand_chip *chip, int chipnr)
836 const struct nand_controller_ops *ops = chip->controller->ops;
837 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = { }, request;
840 if (!nand_controller_can_setup_interface(chip))
844 * A nand_reset_interface() put both the NAND chip and the NAND
845 * controller in timings mode 0. If the default mode for this chip is
846 * also 0, no need to proceed to the change again. Plus, at probe time,
847 * nand_setup_interface() uses ->set/get_features() which would
848 * fail anyway as the parameter page is not available yet.
850 if (!chip->best_interface_config)
853 request = chip->best_interface_config->timings.mode;
854 if (nand_interface_is_sdr(chip->best_interface_config))
855 request |= ONFI_DATA_INTERFACE_SDR;
857 request |= ONFI_DATA_INTERFACE_NVDDR;
858 tmode_param[0] = request;
860 /* Change the mode on the chip side (if supported by the NAND chip) */
861 if (nand_supports_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE)) {
862 nand_select_target(chip, chipnr);
863 ret = nand_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
865 nand_deselect_target(chip);
870 /* Change the mode on the controller side */
871 ret = ops->setup_interface(chip, chipnr, chip->best_interface_config);
875 /* Check the mode has been accepted by the chip, if supported */
876 if (!nand_supports_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE))
877 goto update_interface_config;
879 memset(tmode_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
880 nand_select_target(chip, chipnr);
881 ret = nand_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
883 nand_deselect_target(chip);
887 if (request != tmode_param[0]) {
888 pr_warn("%s timing mode %d not acknowledged by the NAND chip\n",
889 nand_interface_is_nvddr(chip->best_interface_config) ? "NV-DDR" : "SDR",
890 chip->best_interface_config->timings.mode);
891 pr_debug("NAND chip would work in %s timing mode %d\n",
892 tmode_param[0] & ONFI_DATA_INTERFACE_NVDDR ? "NV-DDR" : "SDR",
893 (unsigned int)ONFI_TIMING_MODE_PARAM(tmode_param[0]));
897 update_interface_config:
898 chip->current_interface_config = chip->best_interface_config;
904 * Fallback to mode 0 if the chip explicitly did not ack the chosen
907 nand_reset_interface(chip, chipnr);
908 nand_select_target(chip, chipnr);
910 nand_deselect_target(chip);
916 * nand_choose_best_sdr_timings - Pick up the best SDR timings that both the
917 * NAND controller and the NAND chip support
918 * @chip: the NAND chip
919 * @iface: the interface configuration (can eventually be updated)
920 * @spec_timings: specific timings, when not fitting the ONFI specification
922 * If specific timings are provided, use them. Otherwise, retrieve supported
923 * timing modes from ONFI information.
925 int nand_choose_best_sdr_timings(struct nand_chip *chip,
926 struct nand_interface_config *iface,
927 struct nand_sdr_timings *spec_timings)
929 const struct nand_controller_ops *ops = chip->controller->ops;
930 int best_mode = 0, mode, ret = -EOPNOTSUPP;
932 iface->type = NAND_SDR_IFACE;
935 iface->timings.sdr = *spec_timings;
936 iface->timings.mode = onfi_find_closest_sdr_mode(spec_timings);
938 /* Verify the controller supports the requested interface */
939 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
942 chip->best_interface_config = iface;
946 /* Fallback to slower modes */
947 best_mode = iface->timings.mode;
948 } else if (chip->parameters.onfi) {
949 best_mode = fls(chip->parameters.onfi->sdr_timing_modes) - 1;
952 for (mode = best_mode; mode >= 0; mode--) {
953 onfi_fill_interface_config(chip, iface, NAND_SDR_IFACE, mode);
955 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
958 chip->best_interface_config = iface;
967 * nand_choose_best_nvddr_timings - Pick up the best NVDDR timings that both the
968 * NAND controller and the NAND chip support
969 * @chip: the NAND chip
970 * @iface: the interface configuration (can eventually be updated)
971 * @spec_timings: specific timings, when not fitting the ONFI specification
973 * If specific timings are provided, use them. Otherwise, retrieve supported
974 * timing modes from ONFI information.
976 int nand_choose_best_nvddr_timings(struct nand_chip *chip,
977 struct nand_interface_config *iface,
978 struct nand_nvddr_timings *spec_timings)
980 const struct nand_controller_ops *ops = chip->controller->ops;
981 int best_mode = 0, mode, ret = -EOPNOTSUPP;
983 iface->type = NAND_NVDDR_IFACE;
986 iface->timings.nvddr = *spec_timings;
987 iface->timings.mode = onfi_find_closest_nvddr_mode(spec_timings);
989 /* Verify the controller supports the requested interface */
990 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
993 chip->best_interface_config = iface;
997 /* Fallback to slower modes */
998 best_mode = iface->timings.mode;
999 } else if (chip->parameters.onfi) {
1000 best_mode = fls(chip->parameters.onfi->nvddr_timing_modes) - 1;
1003 for (mode = best_mode; mode >= 0; mode--) {
1004 onfi_fill_interface_config(chip, iface, NAND_NVDDR_IFACE, mode);
1006 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
1009 chip->best_interface_config = iface;
1018 * nand_choose_best_timings - Pick up the best NVDDR or SDR timings that both
1019 * NAND controller and the NAND chip support
1020 * @chip: the NAND chip
1021 * @iface: the interface configuration (can eventually be updated)
1023 * If specific timings are provided, use them. Otherwise, retrieve supported
1024 * timing modes from ONFI information.
1026 static int nand_choose_best_timings(struct nand_chip *chip,
1027 struct nand_interface_config *iface)
1031 /* Try the fastest timings: NV-DDR */
1032 ret = nand_choose_best_nvddr_timings(chip, iface, NULL);
1036 /* Fallback to SDR timings otherwise */
1037 return nand_choose_best_sdr_timings(chip, iface, NULL);
1041 * nand_choose_interface_config - find the best data interface and timings
1042 * @chip: The NAND chip
1044 * Find the best data interface and NAND timings supported by the chip
1045 * and the driver. Eventually let the NAND manufacturer driver propose his own
1048 * After this function nand_chip->interface_config is initialized with the best
1049 * timing mode available.
1051 * Returns 0 for success or negative error code otherwise.
1053 static int nand_choose_interface_config(struct nand_chip *chip)
1055 struct nand_interface_config *iface;
1058 if (!nand_controller_can_setup_interface(chip))
1061 iface = kzalloc(sizeof(*iface), GFP_KERNEL);
1065 if (chip->ops.choose_interface_config)
1066 ret = chip->ops.choose_interface_config(chip, iface);
1068 ret = nand_choose_best_timings(chip, iface);
1077 * nand_fill_column_cycles - fill the column cycles of an address
1078 * @chip: The NAND chip
1079 * @addrs: Array of address cycles to fill
1080 * @offset_in_page: The offset in the page
1082 * Fills the first or the first two bytes of the @addrs field depending
1083 * on the NAND bus width and the page size.
1085 * Returns the number of cycles needed to encode the column, or a negative
1086 * error code in case one of the arguments is invalid.
1088 static int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs,
1089 unsigned int offset_in_page)
1091 struct mtd_info *mtd = nand_to_mtd(chip);
1093 /* Make sure the offset is less than the actual page size. */
1094 if (offset_in_page > mtd->writesize + mtd->oobsize)
1098 * On small page NANDs, there's a dedicated command to access the OOB
1099 * area, and the column address is relative to the start of the OOB
1100 * area, not the start of the page. Asjust the address accordingly.
1102 if (mtd->writesize <= 512 && offset_in_page >= mtd->writesize)
1103 offset_in_page -= mtd->writesize;
1106 * The offset in page is expressed in bytes, if the NAND bus is 16-bit
1107 * wide, then it must be divided by 2.
1109 if (chip->options & NAND_BUSWIDTH_16) {
1110 if (WARN_ON(offset_in_page % 2))
1113 offset_in_page /= 2;
1116 addrs[0] = offset_in_page;
1119 * Small page NANDs use 1 cycle for the columns, while large page NANDs
1122 if (mtd->writesize <= 512)
1125 addrs[1] = offset_in_page >> 8;
1130 static int nand_sp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1131 unsigned int offset_in_page, void *buf,
1134 const struct nand_interface_config *conf =
1135 nand_get_interface_config(chip);
1136 struct mtd_info *mtd = nand_to_mtd(chip);
1138 struct nand_op_instr instrs[] = {
1139 NAND_OP_CMD(NAND_CMD_READ0, 0),
1140 NAND_OP_ADDR(3, addrs, NAND_COMMON_TIMING_NS(conf, tWB_max)),
1141 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1142 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1143 NAND_OP_DATA_IN(len, buf, 0),
1145 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1148 /* Drop the DATA_IN instruction if len is set to 0. */
1152 if (offset_in_page >= mtd->writesize)
1153 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1154 else if (offset_in_page >= 256 &&
1155 !(chip->options & NAND_BUSWIDTH_16))
1156 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1158 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1163 addrs[2] = page >> 8;
1165 if (chip->options & NAND_ROW_ADDR_3) {
1166 addrs[3] = page >> 16;
1167 instrs[1].ctx.addr.naddrs++;
1170 return nand_exec_op(chip, &op);
1173 static int nand_lp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1174 unsigned int offset_in_page, void *buf,
1177 const struct nand_interface_config *conf =
1178 nand_get_interface_config(chip);
1180 struct nand_op_instr instrs[] = {
1181 NAND_OP_CMD(NAND_CMD_READ0, 0),
1182 NAND_OP_ADDR(4, addrs, 0),
1183 NAND_OP_CMD(NAND_CMD_READSTART, NAND_COMMON_TIMING_NS(conf, tWB_max)),
1184 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1185 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1186 NAND_OP_DATA_IN(len, buf, 0),
1188 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1191 /* Drop the DATA_IN instruction if len is set to 0. */
1195 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1200 addrs[3] = page >> 8;
1202 if (chip->options & NAND_ROW_ADDR_3) {
1203 addrs[4] = page >> 16;
1204 instrs[1].ctx.addr.naddrs++;
1207 return nand_exec_op(chip, &op);
1210 static int nand_lp_exec_cont_read_page_op(struct nand_chip *chip, unsigned int page,
1211 unsigned int offset_in_page, void *buf,
1212 unsigned int len, bool check_only)
1214 const struct nand_interface_config *conf =
1215 nand_get_interface_config(chip);
1217 struct nand_op_instr start_instrs[] = {
1218 NAND_OP_CMD(NAND_CMD_READ0, 0),
1219 NAND_OP_ADDR(4, addrs, 0),
1220 NAND_OP_CMD(NAND_CMD_READSTART, NAND_COMMON_TIMING_NS(conf, tWB_max)),
1221 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max), 0),
1222 NAND_OP_CMD(NAND_CMD_READCACHESEQ, NAND_COMMON_TIMING_NS(conf, tWB_max)),
1223 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1224 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1225 NAND_OP_DATA_IN(len, buf, 0),
1227 struct nand_op_instr cont_instrs[] = {
1228 NAND_OP_CMD(page == chip->cont_read.last_page ?
1229 NAND_CMD_READCACHEEND : NAND_CMD_READCACHESEQ,
1230 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1231 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1232 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1233 NAND_OP_DATA_IN(len, buf, 0),
1235 struct nand_operation start_op = NAND_OPERATION(chip->cur_cs, start_instrs);
1236 struct nand_operation cont_op = NAND_OPERATION(chip->cur_cs, cont_instrs);
1244 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1249 addrs[3] = page >> 8;
1251 if (chip->options & NAND_ROW_ADDR_3) {
1252 addrs[4] = page >> 16;
1253 start_instrs[1].ctx.addr.naddrs++;
1256 /* Check if cache reads are supported */
1258 if (nand_check_op(chip, &start_op) || nand_check_op(chip, &cont_op))
1264 if (page == chip->cont_read.first_page)
1265 return nand_exec_op(chip, &start_op);
1267 return nand_exec_op(chip, &cont_op);
1270 static bool rawnand_cont_read_ongoing(struct nand_chip *chip, unsigned int page)
1272 return chip->cont_read.ongoing &&
1273 page >= chip->cont_read.first_page &&
1274 page <= chip->cont_read.last_page;
1278 * nand_read_page_op - Do a READ PAGE operation
1279 * @chip: The NAND chip
1280 * @page: page to read
1281 * @offset_in_page: offset within the page
1282 * @buf: buffer used to store the data
1283 * @len: length of the buffer
1285 * This function issues a READ PAGE operation.
1286 * This function does not select/unselect the CS line.
1288 * Returns 0 on success, a negative error code otherwise.
1290 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1291 unsigned int offset_in_page, void *buf, unsigned int len)
1293 struct mtd_info *mtd = nand_to_mtd(chip);
1298 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1301 if (nand_has_exec_op(chip)) {
1302 if (mtd->writesize > 512) {
1303 if (rawnand_cont_read_ongoing(chip, page))
1304 return nand_lp_exec_cont_read_page_op(chip, page,
1308 return nand_lp_exec_read_page_op(chip, page,
1309 offset_in_page, buf,
1313 return nand_sp_exec_read_page_op(chip, page, offset_in_page,
1317 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, offset_in_page, page);
1319 chip->legacy.read_buf(chip, buf, len);
1323 EXPORT_SYMBOL_GPL(nand_read_page_op);
1326 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1327 * @chip: The NAND chip
1328 * @page: parameter page to read
1329 * @buf: buffer used to store the data
1330 * @len: length of the buffer
1332 * This function issues a READ PARAMETER PAGE operation.
1333 * This function does not select/unselect the CS line.
1335 * Returns 0 on success, a negative error code otherwise.
1337 int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1346 if (nand_has_exec_op(chip)) {
1347 const struct nand_interface_config *conf =
1348 nand_get_interface_config(chip);
1349 struct nand_op_instr instrs[] = {
1350 NAND_OP_CMD(NAND_CMD_PARAM, 0),
1351 NAND_OP_ADDR(1, &page,
1352 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1353 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1354 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1355 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1357 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1359 /* Drop the DATA_IN instruction if len is set to 0. */
1363 return nand_exec_op(chip, &op);
1366 chip->legacy.cmdfunc(chip, NAND_CMD_PARAM, page, -1);
1367 for (i = 0; i < len; i++)
1368 p[i] = chip->legacy.read_byte(chip);
1374 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1375 * @chip: The NAND chip
1376 * @offset_in_page: offset within the page
1377 * @buf: buffer used to store the data
1378 * @len: length of the buffer
1379 * @force_8bit: force 8-bit bus access
1381 * This function issues a CHANGE READ COLUMN operation.
1382 * This function does not select/unselect the CS line.
1384 * Returns 0 on success, a negative error code otherwise.
1386 int nand_change_read_column_op(struct nand_chip *chip,
1387 unsigned int offset_in_page, void *buf,
1388 unsigned int len, bool force_8bit)
1390 struct mtd_info *mtd = nand_to_mtd(chip);
1395 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1398 /* Small page NANDs do not support column change. */
1399 if (mtd->writesize <= 512)
1402 if (nand_has_exec_op(chip)) {
1403 const struct nand_interface_config *conf =
1404 nand_get_interface_config(chip);
1406 struct nand_op_instr instrs[] = {
1407 NAND_OP_CMD(NAND_CMD_RNDOUT, 0),
1408 NAND_OP_ADDR(2, addrs, 0),
1409 NAND_OP_CMD(NAND_CMD_RNDOUTSTART,
1410 NAND_COMMON_TIMING_NS(conf, tCCS_min)),
1411 NAND_OP_DATA_IN(len, buf, 0),
1413 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1416 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1420 /* Drop the DATA_IN instruction if len is set to 0. */
1424 instrs[3].ctx.data.force_8bit = force_8bit;
1426 return nand_exec_op(chip, &op);
1429 chip->legacy.cmdfunc(chip, NAND_CMD_RNDOUT, offset_in_page, -1);
1431 chip->legacy.read_buf(chip, buf, len);
1435 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1438 * nand_read_oob_op - Do a READ OOB operation
1439 * @chip: The NAND chip
1440 * @page: page to read
1441 * @offset_in_oob: offset within the OOB area
1442 * @buf: buffer used to store the data
1443 * @len: length of the buffer
1445 * This function issues a READ OOB operation.
1446 * This function does not select/unselect the CS line.
1448 * Returns 0 on success, a negative error code otherwise.
1450 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1451 unsigned int offset_in_oob, void *buf, unsigned int len)
1453 struct mtd_info *mtd = nand_to_mtd(chip);
1458 if (offset_in_oob + len > mtd->oobsize)
1461 if (nand_has_exec_op(chip))
1462 return nand_read_page_op(chip, page,
1463 mtd->writesize + offset_in_oob,
1466 chip->legacy.cmdfunc(chip, NAND_CMD_READOOB, offset_in_oob, page);
1468 chip->legacy.read_buf(chip, buf, len);
1472 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1474 static int nand_exec_prog_page_op(struct nand_chip *chip, unsigned int page,
1475 unsigned int offset_in_page, const void *buf,
1476 unsigned int len, bool prog)
1478 const struct nand_interface_config *conf =
1479 nand_get_interface_config(chip);
1480 struct mtd_info *mtd = nand_to_mtd(chip);
1482 struct nand_op_instr instrs[] = {
1484 * The first instruction will be dropped if we're dealing
1485 * with a large page NAND and adjusted if we're dealing
1486 * with a small page NAND and the page offset is > 255.
1488 NAND_OP_CMD(NAND_CMD_READ0, 0),
1489 NAND_OP_CMD(NAND_CMD_SEQIN, 0),
1490 NAND_OP_ADDR(0, addrs, NAND_COMMON_TIMING_NS(conf, tADL_min)),
1491 NAND_OP_DATA_OUT(len, buf, 0),
1492 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1493 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1494 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tPROG_max), 0),
1496 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1497 int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
1502 addrs[naddrs++] = page;
1503 addrs[naddrs++] = page >> 8;
1504 if (chip->options & NAND_ROW_ADDR_3)
1505 addrs[naddrs++] = page >> 16;
1507 instrs[2].ctx.addr.naddrs = naddrs;
1509 /* Drop the last two instructions if we're not programming the page. */
1512 /* Also drop the DATA_OUT instruction if empty. */
1517 if (mtd->writesize <= 512) {
1519 * Small pages need some more tweaking: we have to adjust the
1520 * first instruction depending on the page offset we're trying
1523 if (offset_in_page >= mtd->writesize)
1524 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1525 else if (offset_in_page >= 256 &&
1526 !(chip->options & NAND_BUSWIDTH_16))
1527 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1530 * Drop the first command if we're dealing with a large page
1537 return nand_exec_op(chip, &op);
1541 * nand_prog_page_begin_op - starts a PROG PAGE operation
1542 * @chip: The NAND chip
1543 * @page: page to write
1544 * @offset_in_page: offset within the page
1545 * @buf: buffer containing the data to write to the page
1546 * @len: length of the buffer
1548 * This function issues the first half of a PROG PAGE operation.
1549 * This function does not select/unselect the CS line.
1551 * Returns 0 on success, a negative error code otherwise.
1553 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1554 unsigned int offset_in_page, const void *buf,
1557 struct mtd_info *mtd = nand_to_mtd(chip);
1562 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1565 if (nand_has_exec_op(chip))
1566 return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1569 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page, page);
1572 chip->legacy.write_buf(chip, buf, len);
1576 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1579 * nand_prog_page_end_op - ends a PROG PAGE operation
1580 * @chip: The NAND chip
1582 * This function issues the second half of a PROG PAGE operation.
1583 * This function does not select/unselect the CS line.
1585 * Returns 0 on success, a negative error code otherwise.
1587 int nand_prog_page_end_op(struct nand_chip *chip)
1592 if (nand_has_exec_op(chip)) {
1593 const struct nand_interface_config *conf =
1594 nand_get_interface_config(chip);
1595 struct nand_op_instr instrs[] = {
1596 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1597 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1598 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tPROG_max),
1601 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1603 ret = nand_exec_op(chip, &op);
1607 ret = nand_status_op(chip, &status);
1611 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1612 ret = chip->legacy.waitfunc(chip);
1619 if (status & NAND_STATUS_FAIL)
1624 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1627 * nand_prog_page_op - Do a full PROG PAGE operation
1628 * @chip: The NAND chip
1629 * @page: page to write
1630 * @offset_in_page: offset within the page
1631 * @buf: buffer containing the data to write to the page
1632 * @len: length of the buffer
1634 * This function issues a full PROG PAGE operation.
1635 * This function does not select/unselect the CS line.
1637 * Returns 0 on success, a negative error code otherwise.
1639 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1640 unsigned int offset_in_page, const void *buf,
1643 struct mtd_info *mtd = nand_to_mtd(chip);
1650 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1653 if (nand_has_exec_op(chip)) {
1654 ret = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1659 ret = nand_status_op(chip, &status);
1663 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page,
1665 chip->legacy.write_buf(chip, buf, len);
1666 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1667 ret = chip->legacy.waitfunc(chip);
1674 if (status & NAND_STATUS_FAIL)
1679 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1682 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1683 * @chip: The NAND chip
1684 * @offset_in_page: offset within the page
1685 * @buf: buffer containing the data to send to the NAND
1686 * @len: length of the buffer
1687 * @force_8bit: force 8-bit bus access
1689 * This function issues a CHANGE WRITE COLUMN operation.
1690 * This function does not select/unselect the CS line.
1692 * Returns 0 on success, a negative error code otherwise.
1694 int nand_change_write_column_op(struct nand_chip *chip,
1695 unsigned int offset_in_page,
1696 const void *buf, unsigned int len,
1699 struct mtd_info *mtd = nand_to_mtd(chip);
1704 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1707 /* Small page NANDs do not support column change. */
1708 if (mtd->writesize <= 512)
1711 if (nand_has_exec_op(chip)) {
1712 const struct nand_interface_config *conf =
1713 nand_get_interface_config(chip);
1715 struct nand_op_instr instrs[] = {
1716 NAND_OP_CMD(NAND_CMD_RNDIN, 0),
1717 NAND_OP_ADDR(2, addrs, NAND_COMMON_TIMING_NS(conf, tCCS_min)),
1718 NAND_OP_DATA_OUT(len, buf, 0),
1720 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1723 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1727 instrs[2].ctx.data.force_8bit = force_8bit;
1729 /* Drop the DATA_OUT instruction if len is set to 0. */
1733 return nand_exec_op(chip, &op);
1736 chip->legacy.cmdfunc(chip, NAND_CMD_RNDIN, offset_in_page, -1);
1738 chip->legacy.write_buf(chip, buf, len);
1742 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1745 * nand_readid_op - Do a READID operation
1746 * @chip: The NAND chip
1747 * @addr: address cycle to pass after the READID command
1748 * @buf: buffer used to store the ID
1749 * @len: length of the buffer
1751 * This function sends a READID command and reads back the ID returned by the
1753 * This function does not select/unselect the CS line.
1755 * Returns 0 on success, a negative error code otherwise.
1757 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1761 u8 *id = buf, *ddrbuf = NULL;
1766 if (nand_has_exec_op(chip)) {
1767 const struct nand_interface_config *conf =
1768 nand_get_interface_config(chip);
1769 struct nand_op_instr instrs[] = {
1770 NAND_OP_CMD(NAND_CMD_READID, 0),
1771 NAND_OP_ADDR(1, &addr,
1772 NAND_COMMON_TIMING_NS(conf, tADL_min)),
1773 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1775 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1778 /* READ_ID data bytes are received twice in NV-DDR mode */
1779 if (len && nand_interface_is_nvddr(conf)) {
1780 ddrbuf = kzalloc(len * 2, GFP_KERNEL);
1784 instrs[2].ctx.data.len *= 2;
1785 instrs[2].ctx.data.buf.in = ddrbuf;
1788 /* Drop the DATA_IN instruction if len is set to 0. */
1792 ret = nand_exec_op(chip, &op);
1793 if (!ret && len && nand_interface_is_nvddr(conf)) {
1794 for (i = 0; i < len; i++)
1795 id[i] = ddrbuf[i * 2];
1803 chip->legacy.cmdfunc(chip, NAND_CMD_READID, addr, -1);
1805 for (i = 0; i < len; i++)
1806 id[i] = chip->legacy.read_byte(chip);
1810 EXPORT_SYMBOL_GPL(nand_readid_op);
1813 * nand_status_op - Do a STATUS operation
1814 * @chip: The NAND chip
1815 * @status: out variable to store the NAND status
1817 * This function sends a STATUS command and reads back the status returned by
1819 * This function does not select/unselect the CS line.
1821 * Returns 0 on success, a negative error code otherwise.
1823 int nand_status_op(struct nand_chip *chip, u8 *status)
1825 if (nand_has_exec_op(chip)) {
1826 const struct nand_interface_config *conf =
1827 nand_get_interface_config(chip);
1829 struct nand_op_instr instrs[] = {
1830 NAND_OP_CMD(NAND_CMD_STATUS,
1831 NAND_COMMON_TIMING_NS(conf, tADL_min)),
1832 NAND_OP_8BIT_DATA_IN(1, status, 0),
1834 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1837 /* The status data byte will be received twice in NV-DDR mode */
1838 if (status && nand_interface_is_nvddr(conf)) {
1839 instrs[1].ctx.data.len *= 2;
1840 instrs[1].ctx.data.buf.in = ddrstatus;
1846 ret = nand_exec_op(chip, &op);
1847 if (!ret && status && nand_interface_is_nvddr(conf))
1848 *status = ddrstatus[0];
1853 chip->legacy.cmdfunc(chip, NAND_CMD_STATUS, -1, -1);
1855 *status = chip->legacy.read_byte(chip);
1859 EXPORT_SYMBOL_GPL(nand_status_op);
1862 * nand_exit_status_op - Exit a STATUS operation
1863 * @chip: The NAND chip
1865 * This function sends a READ0 command to cancel the effect of the STATUS
1866 * command to avoid reading only the status until a new read command is sent.
1868 * This function does not select/unselect the CS line.
1870 * Returns 0 on success, a negative error code otherwise.
1872 int nand_exit_status_op(struct nand_chip *chip)
1874 if (nand_has_exec_op(chip)) {
1875 struct nand_op_instr instrs[] = {
1876 NAND_OP_CMD(NAND_CMD_READ0, 0),
1878 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1880 return nand_exec_op(chip, &op);
1883 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, -1, -1);
1887 EXPORT_SYMBOL_GPL(nand_exit_status_op);
1890 * nand_erase_op - Do an erase operation
1891 * @chip: The NAND chip
1892 * @eraseblock: block to erase
1894 * This function sends an ERASE command and waits for the NAND to be ready
1896 * This function does not select/unselect the CS line.
1898 * Returns 0 on success, a negative error code otherwise.
1900 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1902 unsigned int page = eraseblock <<
1903 (chip->phys_erase_shift - chip->page_shift);
1907 if (nand_has_exec_op(chip)) {
1908 const struct nand_interface_config *conf =
1909 nand_get_interface_config(chip);
1910 u8 addrs[3] = { page, page >> 8, page >> 16 };
1911 struct nand_op_instr instrs[] = {
1912 NAND_OP_CMD(NAND_CMD_ERASE1, 0),
1913 NAND_OP_ADDR(2, addrs, 0),
1914 NAND_OP_CMD(NAND_CMD_ERASE2,
1915 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1916 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tBERS_max),
1919 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1921 if (chip->options & NAND_ROW_ADDR_3)
1922 instrs[1].ctx.addr.naddrs++;
1924 ret = nand_exec_op(chip, &op);
1928 ret = nand_status_op(chip, &status);
1932 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE1, -1, page);
1933 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE2, -1, -1);
1935 ret = chip->legacy.waitfunc(chip);
1942 if (status & NAND_STATUS_FAIL)
1947 EXPORT_SYMBOL_GPL(nand_erase_op);
1950 * nand_set_features_op - Do a SET FEATURES operation
1951 * @chip: The NAND chip
1952 * @feature: feature id
1953 * @data: 4 bytes of data
1955 * This function sends a SET FEATURES command and waits for the NAND to be
1956 * ready before returning.
1957 * This function does not select/unselect the CS line.
1959 * Returns 0 on success, a negative error code otherwise.
1961 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1964 const u8 *params = data;
1967 if (nand_has_exec_op(chip)) {
1968 const struct nand_interface_config *conf =
1969 nand_get_interface_config(chip);
1970 struct nand_op_instr instrs[] = {
1971 NAND_OP_CMD(NAND_CMD_SET_FEATURES, 0),
1972 NAND_OP_ADDR(1, &feature, NAND_COMMON_TIMING_NS(conf,
1974 NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
1975 NAND_COMMON_TIMING_NS(conf,
1977 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tFEAT_max),
1980 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1982 return nand_exec_op(chip, &op);
1985 chip->legacy.cmdfunc(chip, NAND_CMD_SET_FEATURES, feature, -1);
1986 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1987 chip->legacy.write_byte(chip, params[i]);
1989 ret = chip->legacy.waitfunc(chip);
1993 if (ret & NAND_STATUS_FAIL)
2000 * nand_get_features_op - Do a GET FEATURES operation
2001 * @chip: The NAND chip
2002 * @feature: feature id
2003 * @data: 4 bytes of data
2005 * This function sends a GET FEATURES command and waits for the NAND to be
2006 * ready before returning.
2007 * This function does not select/unselect the CS line.
2009 * Returns 0 on success, a negative error code otherwise.
2011 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
2014 u8 *params = data, ddrbuf[ONFI_SUBFEATURE_PARAM_LEN * 2];
2017 if (nand_has_exec_op(chip)) {
2018 const struct nand_interface_config *conf =
2019 nand_get_interface_config(chip);
2020 struct nand_op_instr instrs[] = {
2021 NAND_OP_CMD(NAND_CMD_GET_FEATURES, 0),
2022 NAND_OP_ADDR(1, &feature,
2023 NAND_COMMON_TIMING_NS(conf, tWB_max)),
2024 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tFEAT_max),
2025 NAND_COMMON_TIMING_NS(conf, tRR_min)),
2026 NAND_OP_8BIT_DATA_IN(ONFI_SUBFEATURE_PARAM_LEN,
2029 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2032 /* GET_FEATURE data bytes are received twice in NV-DDR mode */
2033 if (nand_interface_is_nvddr(conf)) {
2034 instrs[3].ctx.data.len *= 2;
2035 instrs[3].ctx.data.buf.in = ddrbuf;
2038 ret = nand_exec_op(chip, &op);
2039 if (nand_interface_is_nvddr(conf)) {
2040 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; i++)
2041 params[i] = ddrbuf[i * 2];
2047 chip->legacy.cmdfunc(chip, NAND_CMD_GET_FEATURES, feature, -1);
2048 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
2049 params[i] = chip->legacy.read_byte(chip);
2054 static int nand_wait_rdy_op(struct nand_chip *chip, unsigned int timeout_ms,
2055 unsigned int delay_ns)
2057 if (nand_has_exec_op(chip)) {
2058 struct nand_op_instr instrs[] = {
2059 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(timeout_ms),
2060 PSEC_TO_NSEC(delay_ns)),
2062 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2064 return nand_exec_op(chip, &op);
2067 /* Apply delay or wait for ready/busy pin */
2068 if (!chip->legacy.dev_ready)
2069 udelay(chip->legacy.chip_delay);
2071 nand_wait_ready(chip);
2077 * nand_reset_op - Do a reset operation
2078 * @chip: The NAND chip
2080 * This function sends a RESET command and waits for the NAND to be ready
2082 * This function does not select/unselect the CS line.
2084 * Returns 0 on success, a negative error code otherwise.
2086 int nand_reset_op(struct nand_chip *chip)
2088 if (nand_has_exec_op(chip)) {
2089 const struct nand_interface_config *conf =
2090 nand_get_interface_config(chip);
2091 struct nand_op_instr instrs[] = {
2092 NAND_OP_CMD(NAND_CMD_RESET,
2093 NAND_COMMON_TIMING_NS(conf, tWB_max)),
2094 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tRST_max),
2097 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2099 return nand_exec_op(chip, &op);
2102 chip->legacy.cmdfunc(chip, NAND_CMD_RESET, -1, -1);
2106 EXPORT_SYMBOL_GPL(nand_reset_op);
2109 * nand_read_data_op - Read data from the NAND
2110 * @chip: The NAND chip
2111 * @buf: buffer used to store the data
2112 * @len: length of the buffer
2113 * @force_8bit: force 8-bit bus access
2114 * @check_only: do not actually run the command, only checks if the
2115 * controller driver supports it
2117 * This function does a raw data read on the bus. Usually used after launching
2118 * another NAND operation like nand_read_page_op().
2119 * This function does not select/unselect the CS line.
2121 * Returns 0 on success, a negative error code otherwise.
2123 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
2124 bool force_8bit, bool check_only)
2129 if (nand_has_exec_op(chip)) {
2130 const struct nand_interface_config *conf =
2131 nand_get_interface_config(chip);
2132 struct nand_op_instr instrs[] = {
2133 NAND_OP_DATA_IN(len, buf, 0),
2135 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2139 instrs[0].ctx.data.force_8bit = force_8bit;
2142 * Parameter payloads (ID, status, features, etc) do not go
2143 * through the same pipeline as regular data, hence the
2144 * force_8bit flag must be set and this also indicates that in
2145 * case NV-DDR timings are being used the data will be received
2148 if (force_8bit && nand_interface_is_nvddr(conf)) {
2149 ddrbuf = kzalloc(len * 2, GFP_KERNEL);
2153 instrs[0].ctx.data.len *= 2;
2154 instrs[0].ctx.data.buf.in = ddrbuf;
2158 ret = nand_check_op(chip, &op);
2163 ret = nand_exec_op(chip, &op);
2164 if (!ret && force_8bit && nand_interface_is_nvddr(conf)) {
2167 for (i = 0; i < len; i++)
2168 dst[i] = ddrbuf[i * 2];
2183 for (i = 0; i < len; i++)
2184 p[i] = chip->legacy.read_byte(chip);
2186 chip->legacy.read_buf(chip, buf, len);
2191 EXPORT_SYMBOL_GPL(nand_read_data_op);
2194 * nand_write_data_op - Write data from the NAND
2195 * @chip: The NAND chip
2196 * @buf: buffer containing the data to send on the bus
2197 * @len: length of the buffer
2198 * @force_8bit: force 8-bit bus access
2200 * This function does a raw data write on the bus. Usually used after launching
2201 * another NAND operation like nand_write_page_begin_op().
2202 * This function does not select/unselect the CS line.
2204 * Returns 0 on success, a negative error code otherwise.
2206 int nand_write_data_op(struct nand_chip *chip, const void *buf,
2207 unsigned int len, bool force_8bit)
2212 if (nand_has_exec_op(chip)) {
2213 struct nand_op_instr instrs[] = {
2214 NAND_OP_DATA_OUT(len, buf, 0),
2216 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2218 instrs[0].ctx.data.force_8bit = force_8bit;
2220 return nand_exec_op(chip, &op);
2227 for (i = 0; i < len; i++)
2228 chip->legacy.write_byte(chip, p[i]);
2230 chip->legacy.write_buf(chip, buf, len);
2235 EXPORT_SYMBOL_GPL(nand_write_data_op);
2238 * struct nand_op_parser_ctx - Context used by the parser
2239 * @instrs: array of all the instructions that must be addressed
2240 * @ninstrs: length of the @instrs array
2241 * @subop: Sub-operation to be passed to the NAND controller
2243 * This structure is used by the core to split NAND operations into
2244 * sub-operations that can be handled by the NAND controller.
2246 struct nand_op_parser_ctx {
2247 const struct nand_op_instr *instrs;
2248 unsigned int ninstrs;
2249 struct nand_subop subop;
2253 * nand_op_parser_must_split_instr - Checks if an instruction must be split
2254 * @pat: the parser pattern element that matches @instr
2255 * @instr: pointer to the instruction to check
2256 * @start_offset: this is an in/out parameter. If @instr has already been
2257 * split, then @start_offset is the offset from which to start
2258 * (either an address cycle or an offset in the data buffer).
2259 * Conversely, if the function returns true (ie. instr must be
2260 * split), this parameter is updated to point to the first
2261 * data/address cycle that has not been taken care of.
2263 * Some NAND controllers are limited and cannot send X address cycles with a
2264 * unique operation, or cannot read/write more than Y bytes at the same time.
2265 * In this case, split the instruction that does not fit in a single
2266 * controller-operation into two or more chunks.
2268 * Returns true if the instruction must be split, false otherwise.
2269 * The @start_offset parameter is also updated to the offset at which the next
2270 * bundle of instruction must start (if an address or a data instruction).
2273 nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat,
2274 const struct nand_op_instr *instr,
2275 unsigned int *start_offset)
2277 switch (pat->type) {
2278 case NAND_OP_ADDR_INSTR:
2279 if (!pat->ctx.addr.maxcycles)
2282 if (instr->ctx.addr.naddrs - *start_offset >
2283 pat->ctx.addr.maxcycles) {
2284 *start_offset += pat->ctx.addr.maxcycles;
2289 case NAND_OP_DATA_IN_INSTR:
2290 case NAND_OP_DATA_OUT_INSTR:
2291 if (!pat->ctx.data.maxlen)
2294 if (instr->ctx.data.len - *start_offset >
2295 pat->ctx.data.maxlen) {
2296 *start_offset += pat->ctx.data.maxlen;
2309 * nand_op_parser_match_pat - Checks if a pattern matches the instructions
2310 * remaining in the parser context
2311 * @pat: the pattern to test
2312 * @ctx: the parser context structure to match with the pattern @pat
2314 * Check if @pat matches the set or a sub-set of instructions remaining in @ctx.
2315 * Returns true if this is the case, false ortherwise. When true is returned,
2316 * @ctx->subop is updated with the set of instructions to be passed to the
2317 * controller driver.
2320 nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
2321 struct nand_op_parser_ctx *ctx)
2323 unsigned int instr_offset = ctx->subop.first_instr_start_off;
2324 const struct nand_op_instr *end = ctx->instrs + ctx->ninstrs;
2325 const struct nand_op_instr *instr = ctx->subop.instrs;
2326 unsigned int i, ninstrs;
2328 for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
2330 * The pattern instruction does not match the operation
2331 * instruction. If the instruction is marked optional in the
2332 * pattern definition, we skip the pattern element and continue
2333 * to the next one. If the element is mandatory, there's no
2334 * match and we can return false directly.
2336 if (instr->type != pat->elems[i].type) {
2337 if (!pat->elems[i].optional)
2344 * Now check the pattern element constraints. If the pattern is
2345 * not able to handle the whole instruction in a single step,
2346 * we have to split it.
2347 * The last_instr_end_off value comes back updated to point to
2348 * the position where we have to split the instruction (the
2349 * start of the next subop chunk).
2351 if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
2364 * This can happen if all instructions of a pattern are optional.
2365 * Still, if there's not at least one instruction handled by this
2366 * pattern, this is not a match, and we should try the next one (if
2373 * We had a match on the pattern head, but the pattern may be longer
2374 * than the instructions we're asked to execute. We need to make sure
2375 * there's no mandatory elements in the pattern tail.
2377 for (; i < pat->nelems; i++) {
2378 if (!pat->elems[i].optional)
2383 * We have a match: update the subop structure accordingly and return
2386 ctx->subop.ninstrs = ninstrs;
2387 ctx->subop.last_instr_end_off = instr_offset;
2392 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
2393 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2395 const struct nand_op_instr *instr;
2399 pr_debug("executing subop (CS%d):\n", ctx->subop.cs);
2401 for (i = 0; i < ctx->ninstrs; i++) {
2402 instr = &ctx->instrs[i];
2404 if (instr == &ctx->subop.instrs[0])
2407 nand_op_trace(prefix, instr);
2409 if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
2414 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2420 static int nand_op_parser_cmp_ctx(const struct nand_op_parser_ctx *a,
2421 const struct nand_op_parser_ctx *b)
2423 if (a->subop.ninstrs < b->subop.ninstrs)
2425 else if (a->subop.ninstrs > b->subop.ninstrs)
2428 if (a->subop.last_instr_end_off < b->subop.last_instr_end_off)
2430 else if (a->subop.last_instr_end_off > b->subop.last_instr_end_off)
2437 * nand_op_parser_exec_op - exec_op parser
2438 * @chip: the NAND chip
2439 * @parser: patterns description provided by the controller driver
2440 * @op: the NAND operation to address
2441 * @check_only: when true, the function only checks if @op can be handled but
2442 * does not execute the operation
2444 * Helper function designed to ease integration of NAND controller drivers that
2445 * only support a limited set of instruction sequences. The supported sequences
2446 * are described in @parser, and the framework takes care of splitting @op into
2447 * multiple sub-operations (if required) and pass them back to the ->exec()
2448 * callback of the matching pattern if @check_only is set to false.
2450 * NAND controller drivers should call this function from their own ->exec_op()
2453 * Returns 0 on success, a negative error code otherwise. A failure can be
2454 * caused by an unsupported operation (none of the supported patterns is able
2455 * to handle the requested operation), or an error returned by one of the
2456 * matching pattern->exec() hook.
2458 int nand_op_parser_exec_op(struct nand_chip *chip,
2459 const struct nand_op_parser *parser,
2460 const struct nand_operation *op, bool check_only)
2462 struct nand_op_parser_ctx ctx = {
2464 .subop.instrs = op->instrs,
2465 .instrs = op->instrs,
2466 .ninstrs = op->ninstrs,
2470 while (ctx.subop.instrs < op->instrs + op->ninstrs) {
2471 const struct nand_op_parser_pattern *pattern;
2472 struct nand_op_parser_ctx best_ctx;
2473 int ret, best_pattern = -1;
2475 for (i = 0; i < parser->npatterns; i++) {
2476 struct nand_op_parser_ctx test_ctx = ctx;
2478 pattern = &parser->patterns[i];
2479 if (!nand_op_parser_match_pat(pattern, &test_ctx))
2482 if (best_pattern >= 0 &&
2483 nand_op_parser_cmp_ctx(&test_ctx, &best_ctx) <= 0)
2487 best_ctx = test_ctx;
2490 if (best_pattern < 0) {
2491 pr_debug("->exec_op() parser: pattern not found!\n");
2496 nand_op_parser_trace(&ctx);
2499 pattern = &parser->patterns[best_pattern];
2500 ret = pattern->exec(chip, &ctx.subop);
2506 * Update the context structure by pointing to the start of the
2509 ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
2510 if (ctx.subop.last_instr_end_off)
2511 ctx.subop.instrs -= 1;
2513 ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
2518 EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
2520 static bool nand_instr_is_data(const struct nand_op_instr *instr)
2522 return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
2523 instr->type == NAND_OP_DATA_OUT_INSTR);
2526 static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
2527 unsigned int instr_idx)
2529 return subop && instr_idx < subop->ninstrs;
2532 static unsigned int nand_subop_get_start_off(const struct nand_subop *subop,
2533 unsigned int instr_idx)
2538 return subop->first_instr_start_off;
2542 * nand_subop_get_addr_start_off - Get the start offset in an address array
2543 * @subop: The entire sub-operation
2544 * @instr_idx: Index of the instruction inside the sub-operation
2546 * During driver development, one could be tempted to directly use the
2547 * ->addr.addrs field of address instructions. This is wrong as address
2548 * instructions might be split.
2550 * Given an address instruction, returns the offset of the first cycle to issue.
2552 unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
2553 unsigned int instr_idx)
2555 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2556 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2559 return nand_subop_get_start_off(subop, instr_idx);
2561 EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
2564 * nand_subop_get_num_addr_cyc - Get the remaining address cycles to assert
2565 * @subop: The entire sub-operation
2566 * @instr_idx: Index of the instruction inside the sub-operation
2568 * During driver development, one could be tempted to directly use the
2569 * ->addr->naddrs field of a data instruction. This is wrong as instructions
2572 * Given an address instruction, returns the number of address cycle to issue.
2574 unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
2575 unsigned int instr_idx)
2577 int start_off, end_off;
2579 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2580 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2583 start_off = nand_subop_get_addr_start_off(subop, instr_idx);
2585 if (instr_idx == subop->ninstrs - 1 &&
2586 subop->last_instr_end_off)
2587 end_off = subop->last_instr_end_off;
2589 end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
2591 return end_off - start_off;
2593 EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
2596 * nand_subop_get_data_start_off - Get the start offset in a data array
2597 * @subop: The entire sub-operation
2598 * @instr_idx: Index of the instruction inside the sub-operation
2600 * During driver development, one could be tempted to directly use the
2601 * ->data->buf.{in,out} field of data instructions. This is wrong as data
2602 * instructions might be split.
2604 * Given a data instruction, returns the offset to start from.
2606 unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
2607 unsigned int instr_idx)
2609 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2610 !nand_instr_is_data(&subop->instrs[instr_idx])))
2613 return nand_subop_get_start_off(subop, instr_idx);
2615 EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
2618 * nand_subop_get_data_len - Get the number of bytes to retrieve
2619 * @subop: The entire sub-operation
2620 * @instr_idx: Index of the instruction inside the sub-operation
2622 * During driver development, one could be tempted to directly use the
2623 * ->data->len field of a data instruction. This is wrong as data instructions
2626 * Returns the length of the chunk of data to send/receive.
2628 unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
2629 unsigned int instr_idx)
2631 int start_off = 0, end_off;
2633 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2634 !nand_instr_is_data(&subop->instrs[instr_idx])))
2637 start_off = nand_subop_get_data_start_off(subop, instr_idx);
2639 if (instr_idx == subop->ninstrs - 1 &&
2640 subop->last_instr_end_off)
2641 end_off = subop->last_instr_end_off;
2643 end_off = subop->instrs[instr_idx].ctx.data.len;
2645 return end_off - start_off;
2647 EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
2650 * nand_reset - Reset and initialize a NAND device
2651 * @chip: The NAND chip
2652 * @chipnr: Internal die id
2654 * Save the timings data structure, then apply SDR timings mode 0 (see
2655 * nand_reset_interface for details), do the reset operation, and apply
2656 * back the previous timings.
2658 * Returns 0 on success, a negative error code otherwise.
2660 int nand_reset(struct nand_chip *chip, int chipnr)
2664 ret = nand_reset_interface(chip, chipnr);
2669 * The CS line has to be released before we can apply the new NAND
2670 * interface settings, hence this weird nand_select_target()
2671 * nand_deselect_target() dance.
2673 nand_select_target(chip, chipnr);
2674 ret = nand_reset_op(chip);
2675 nand_deselect_target(chip);
2679 ret = nand_setup_interface(chip, chipnr);
2685 EXPORT_SYMBOL_GPL(nand_reset);
2688 * nand_get_features - wrapper to perform a GET_FEATURE
2689 * @chip: NAND chip info structure
2690 * @addr: feature address
2691 * @subfeature_param: the subfeature parameters, a four bytes array
2693 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2694 * operation cannot be handled.
2696 int nand_get_features(struct nand_chip *chip, int addr,
2697 u8 *subfeature_param)
2699 if (!nand_supports_get_features(chip, addr))
2702 if (chip->legacy.get_features)
2703 return chip->legacy.get_features(chip, addr, subfeature_param);
2705 return nand_get_features_op(chip, addr, subfeature_param);
2709 * nand_set_features - wrapper to perform a SET_FEATURE
2710 * @chip: NAND chip info structure
2711 * @addr: feature address
2712 * @subfeature_param: the subfeature parameters, a four bytes array
2714 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2715 * operation cannot be handled.
2717 int nand_set_features(struct nand_chip *chip, int addr,
2718 u8 *subfeature_param)
2720 if (!nand_supports_set_features(chip, addr))
2723 if (chip->legacy.set_features)
2724 return chip->legacy.set_features(chip, addr, subfeature_param);
2726 return nand_set_features_op(chip, addr, subfeature_param);
2730 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
2731 * @buf: buffer to test
2732 * @len: buffer length
2733 * @bitflips_threshold: maximum number of bitflips
2735 * Check if a buffer contains only 0xff, which means the underlying region
2736 * has been erased and is ready to be programmed.
2737 * The bitflips_threshold specify the maximum number of bitflips before
2738 * considering the region is not erased.
2739 * Note: The logic of this function has been extracted from the memweight
2740 * implementation, except that nand_check_erased_buf function exit before
2741 * testing the whole buffer if the number of bitflips exceed the
2742 * bitflips_threshold value.
2744 * Returns a positive number of bitflips less than or equal to
2745 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2748 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
2750 const unsigned char *bitmap = buf;
2754 for (; len && ((uintptr_t)bitmap) % sizeof(long);
2756 weight = hweight8(*bitmap);
2757 bitflips += BITS_PER_BYTE - weight;
2758 if (unlikely(bitflips > bitflips_threshold))
2762 for (; len >= sizeof(long);
2763 len -= sizeof(long), bitmap += sizeof(long)) {
2764 unsigned long d = *((unsigned long *)bitmap);
2767 weight = hweight_long(d);
2768 bitflips += BITS_PER_LONG - weight;
2769 if (unlikely(bitflips > bitflips_threshold))
2773 for (; len > 0; len--, bitmap++) {
2774 weight = hweight8(*bitmap);
2775 bitflips += BITS_PER_BYTE - weight;
2776 if (unlikely(bitflips > bitflips_threshold))
2784 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
2786 * @data: data buffer to test
2787 * @datalen: data length
2789 * @ecclen: ECC length
2790 * @extraoob: extra OOB buffer
2791 * @extraooblen: extra OOB length
2792 * @bitflips_threshold: maximum number of bitflips
2794 * Check if a data buffer and its associated ECC and OOB data contains only
2795 * 0xff pattern, which means the underlying region has been erased and is
2796 * ready to be programmed.
2797 * The bitflips_threshold specify the maximum number of bitflips before
2798 * considering the region as not erased.
2801 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
2802 * different from the NAND page size. When fixing bitflips, ECC engines will
2803 * report the number of errors per chunk, and the NAND core infrastructure
2804 * expect you to return the maximum number of bitflips for the whole page.
2805 * This is why you should always use this function on a single chunk and
2806 * not on the whole page. After checking each chunk you should update your
2807 * max_bitflips value accordingly.
2808 * 2/ When checking for bitflips in erased pages you should not only check
2809 * the payload data but also their associated ECC data, because a user might
2810 * have programmed almost all bits to 1 but a few. In this case, we
2811 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
2813 * 3/ The extraoob argument is optional, and should be used if some of your OOB
2814 * data are protected by the ECC engine.
2815 * It could also be used if you support subpages and want to attach some
2816 * extra OOB data to an ECC chunk.
2818 * Returns a positive number of bitflips less than or equal to
2819 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2820 * threshold. In case of success, the passed buffers are filled with 0xff.
2822 int nand_check_erased_ecc_chunk(void *data, int datalen,
2823 void *ecc, int ecclen,
2824 void *extraoob, int extraooblen,
2825 int bitflips_threshold)
2827 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
2829 data_bitflips = nand_check_erased_buf(data, datalen,
2830 bitflips_threshold);
2831 if (data_bitflips < 0)
2832 return data_bitflips;
2834 bitflips_threshold -= data_bitflips;
2836 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
2837 if (ecc_bitflips < 0)
2838 return ecc_bitflips;
2840 bitflips_threshold -= ecc_bitflips;
2842 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
2843 bitflips_threshold);
2844 if (extraoob_bitflips < 0)
2845 return extraoob_bitflips;
2848 memset(data, 0xff, datalen);
2851 memset(ecc, 0xff, ecclen);
2853 if (extraoob_bitflips)
2854 memset(extraoob, 0xff, extraooblen);
2856 return data_bitflips + ecc_bitflips + extraoob_bitflips;
2858 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
2861 * nand_read_page_raw_notsupp - dummy read raw page function
2862 * @chip: nand chip info structure
2863 * @buf: buffer to store read data
2864 * @oob_required: caller requires OOB data read to chip->oob_poi
2865 * @page: page number to read
2867 * Returns -ENOTSUPP unconditionally.
2869 int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf,
2870 int oob_required, int page)
2876 * nand_read_page_raw - [INTERN] read raw page data without ecc
2877 * @chip: nand chip info structure
2878 * @buf: buffer to store read data
2879 * @oob_required: caller requires OOB data read to chip->oob_poi
2880 * @page: page number to read
2882 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2884 int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
2887 struct mtd_info *mtd = nand_to_mtd(chip);
2890 ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
2895 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
2903 EXPORT_SYMBOL(nand_read_page_raw);
2906 * nand_monolithic_read_page_raw - Monolithic page read in raw mode
2907 * @chip: NAND chip info structure
2908 * @buf: buffer to store read data
2909 * @oob_required: caller requires OOB data read to chip->oob_poi
2910 * @page: page number to read
2912 * This is a raw page read, ie. without any error detection/correction.
2913 * Monolithic means we are requesting all the relevant data (main plus
2914 * eventually OOB) to be loaded in the NAND cache and sent over the
2915 * bus (from the NAND chip to the NAND controller) in a single
2916 * operation. This is an alternative to nand_read_page_raw(), which
2917 * first reads the main data, and if the OOB data is requested too,
2918 * then reads more data on the bus.
2920 int nand_monolithic_read_page_raw(struct nand_chip *chip, u8 *buf,
2921 int oob_required, int page)
2923 struct mtd_info *mtd = nand_to_mtd(chip);
2924 unsigned int size = mtd->writesize;
2929 size += mtd->oobsize;
2931 if (buf != chip->data_buf)
2932 read_buf = nand_get_data_buf(chip);
2935 ret = nand_read_page_op(chip, page, 0, read_buf, size);
2939 if (buf != chip->data_buf)
2940 memcpy(buf, read_buf, mtd->writesize);
2944 EXPORT_SYMBOL(nand_monolithic_read_page_raw);
2947 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
2948 * @chip: nand chip info structure
2949 * @buf: buffer to store read data
2950 * @oob_required: caller requires OOB data read to chip->oob_poi
2951 * @page: page number to read
2953 * We need a special oob layout and handling even when OOB isn't used.
2955 static int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf,
2956 int oob_required, int page)
2958 struct mtd_info *mtd = nand_to_mtd(chip);
2959 int eccsize = chip->ecc.size;
2960 int eccbytes = chip->ecc.bytes;
2961 uint8_t *oob = chip->oob_poi;
2962 int steps, size, ret;
2964 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2968 for (steps = chip->ecc.steps; steps > 0; steps--) {
2969 ret = nand_read_data_op(chip, buf, eccsize, false, false);
2975 if (chip->ecc.prepad) {
2976 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2981 oob += chip->ecc.prepad;
2984 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
2990 if (chip->ecc.postpad) {
2991 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2996 oob += chip->ecc.postpad;
3000 size = mtd->oobsize - (oob - chip->oob_poi);
3002 ret = nand_read_data_op(chip, oob, size, false, false);
3011 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
3012 * @chip: nand chip info structure
3013 * @buf: buffer to store read data
3014 * @oob_required: caller requires OOB data read to chip->oob_poi
3015 * @page: page number to read
3017 static int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf,
3018 int oob_required, int page)
3020 struct mtd_info *mtd = nand_to_mtd(chip);
3021 int i, eccsize = chip->ecc.size, ret;
3022 int eccbytes = chip->ecc.bytes;
3023 int eccsteps = chip->ecc.steps;
3025 uint8_t *ecc_calc = chip->ecc.calc_buf;
3026 uint8_t *ecc_code = chip->ecc.code_buf;
3027 unsigned int max_bitflips = 0;
3029 chip->ecc.read_page_raw(chip, buf, 1, page);
3031 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
3032 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3034 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3039 eccsteps = chip->ecc.steps;
3042 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3045 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
3047 mtd->ecc_stats.failed++;
3049 mtd->ecc_stats.corrected += stat;
3050 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3053 return max_bitflips;
3057 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
3058 * @chip: nand chip info structure
3059 * @data_offs: offset of requested data within the page
3060 * @readlen: data length
3061 * @bufpoi: buffer to store read data
3062 * @page: page number to read
3064 static int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs,
3065 uint32_t readlen, uint8_t *bufpoi, int page)
3067 struct mtd_info *mtd = nand_to_mtd(chip);
3068 int start_step, end_step, num_steps, ret;
3070 int data_col_addr, i, gaps = 0;
3071 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
3072 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
3073 int index, section = 0;
3074 unsigned int max_bitflips = 0;
3075 struct mtd_oob_region oobregion = { };
3077 /* Column address within the page aligned to ECC size (256bytes) */
3078 start_step = data_offs / chip->ecc.size;
3079 end_step = (data_offs + readlen - 1) / chip->ecc.size;
3080 num_steps = end_step - start_step + 1;
3081 index = start_step * chip->ecc.bytes;
3083 /* Data size aligned to ECC ecc.size */
3084 datafrag_len = num_steps * chip->ecc.size;
3085 eccfrag_len = num_steps * chip->ecc.bytes;
3087 data_col_addr = start_step * chip->ecc.size;
3088 /* If we read not a page aligned data */
3089 p = bufpoi + data_col_addr;
3090 ret = nand_read_page_op(chip, page, data_col_addr, p, datafrag_len);
3095 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
3096 chip->ecc.calculate(chip, p, &chip->ecc.calc_buf[i]);
3099 * The performance is faster if we position offsets according to
3100 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
3102 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
3106 if (oobregion.length < eccfrag_len)
3110 ret = nand_change_read_column_op(chip, mtd->writesize,
3111 chip->oob_poi, mtd->oobsize,
3117 * Send the command to read the particular ECC bytes take care
3118 * about buswidth alignment in read_buf.
3120 aligned_pos = oobregion.offset & ~(busw - 1);
3121 aligned_len = eccfrag_len;
3122 if (oobregion.offset & (busw - 1))
3124 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
3128 ret = nand_change_read_column_op(chip,
3129 mtd->writesize + aligned_pos,
3130 &chip->oob_poi[aligned_pos],
3131 aligned_len, false);
3136 ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
3137 chip->oob_poi, index, eccfrag_len);
3141 p = bufpoi + data_col_addr;
3142 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
3145 stat = chip->ecc.correct(chip, p, &chip->ecc.code_buf[i],
3146 &chip->ecc.calc_buf[i]);
3147 if (stat == -EBADMSG &&
3148 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3149 /* check for empty pages with bitflips */
3150 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3151 &chip->ecc.code_buf[i],
3154 chip->ecc.strength);
3158 mtd->ecc_stats.failed++;
3160 mtd->ecc_stats.corrected += stat;
3161 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3164 return max_bitflips;
3168 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
3169 * @chip: nand chip info structure
3170 * @buf: buffer to store read data
3171 * @oob_required: caller requires OOB data read to chip->oob_poi
3172 * @page: page number to read
3174 * Not for syndrome calculating ECC controllers which need a special oob layout.
3176 static int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf,
3177 int oob_required, int page)
3179 struct mtd_info *mtd = nand_to_mtd(chip);
3180 int i, eccsize = chip->ecc.size, ret;
3181 int eccbytes = chip->ecc.bytes;
3182 int eccsteps = chip->ecc.steps;
3184 uint8_t *ecc_calc = chip->ecc.calc_buf;
3185 uint8_t *ecc_code = chip->ecc.code_buf;
3186 unsigned int max_bitflips = 0;
3188 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3192 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3193 chip->ecc.hwctl(chip, NAND_ECC_READ);
3195 ret = nand_read_data_op(chip, p, eccsize, false, false);
3199 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3202 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false,
3207 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3212 eccsteps = chip->ecc.steps;
3215 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3218 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
3219 if (stat == -EBADMSG &&
3220 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3221 /* check for empty pages with bitflips */
3222 stat = nand_check_erased_ecc_chunk(p, eccsize,
3223 &ecc_code[i], eccbytes,
3225 chip->ecc.strength);
3229 mtd->ecc_stats.failed++;
3231 mtd->ecc_stats.corrected += stat;
3232 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3235 return max_bitflips;
3239 * nand_read_page_hwecc_oob_first - Hardware ECC page read with ECC
3240 * data read from OOB area
3241 * @chip: nand chip info structure
3242 * @buf: buffer to store read data
3243 * @oob_required: caller requires OOB data read to chip->oob_poi
3244 * @page: page number to read
3246 * Hardware ECC for large page chips, which requires the ECC data to be
3247 * extracted from the OOB before the actual data is read.
3249 int nand_read_page_hwecc_oob_first(struct nand_chip *chip, uint8_t *buf,
3250 int oob_required, int page)
3252 struct mtd_info *mtd = nand_to_mtd(chip);
3253 int i, eccsize = chip->ecc.size, ret;
3254 int eccbytes = chip->ecc.bytes;
3255 int eccsteps = chip->ecc.steps;
3257 uint8_t *ecc_code = chip->ecc.code_buf;
3258 unsigned int max_bitflips = 0;
3260 /* Read the OOB area first */
3261 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3265 /* Move read cursor to start of page */
3266 ret = nand_change_read_column_op(chip, 0, NULL, 0, false);
3270 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3275 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3278 chip->ecc.hwctl(chip, NAND_ECC_READ);
3280 ret = nand_read_data_op(chip, p, eccsize, false, false);
3284 stat = chip->ecc.correct(chip, p, &ecc_code[i], NULL);
3285 if (stat == -EBADMSG &&
3286 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3287 /* check for empty pages with bitflips */
3288 stat = nand_check_erased_ecc_chunk(p, eccsize,
3291 chip->ecc.strength);
3295 mtd->ecc_stats.failed++;
3297 mtd->ecc_stats.corrected += stat;
3298 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3301 return max_bitflips;
3303 EXPORT_SYMBOL_GPL(nand_read_page_hwecc_oob_first);
3306 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
3307 * @chip: nand chip info structure
3308 * @buf: buffer to store read data
3309 * @oob_required: caller requires OOB data read to chip->oob_poi
3310 * @page: page number to read
3312 * The hw generator calculates the error syndrome automatically. Therefore we
3313 * need a special oob layout and handling.
3315 static int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf,
3316 int oob_required, int page)
3318 struct mtd_info *mtd = nand_to_mtd(chip);
3319 int ret, i, eccsize = chip->ecc.size;
3320 int eccbytes = chip->ecc.bytes;
3321 int eccsteps = chip->ecc.steps;
3322 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
3324 uint8_t *oob = chip->oob_poi;
3325 unsigned int max_bitflips = 0;
3327 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3331 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3334 chip->ecc.hwctl(chip, NAND_ECC_READ);
3336 ret = nand_read_data_op(chip, p, eccsize, false, false);
3340 if (chip->ecc.prepad) {
3341 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3346 oob += chip->ecc.prepad;
3349 chip->ecc.hwctl(chip, NAND_ECC_READSYN);
3351 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
3355 stat = chip->ecc.correct(chip, p, oob, NULL);
3359 if (chip->ecc.postpad) {
3360 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3365 oob += chip->ecc.postpad;
3368 if (stat == -EBADMSG &&
3369 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3370 /* check for empty pages with bitflips */
3371 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3375 chip->ecc.strength);
3379 mtd->ecc_stats.failed++;
3381 mtd->ecc_stats.corrected += stat;
3382 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3386 /* Calculate remaining oob bytes */
3387 i = mtd->oobsize - (oob - chip->oob_poi);
3389 ret = nand_read_data_op(chip, oob, i, false, false);
3394 return max_bitflips;
3398 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
3399 * @chip: NAND chip object
3400 * @oob: oob destination address
3401 * @ops: oob ops structure
3402 * @len: size of oob to transfer
3404 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
3405 struct mtd_oob_ops *ops, size_t len)
3407 struct mtd_info *mtd = nand_to_mtd(chip);
3410 switch (ops->mode) {
3412 case MTD_OPS_PLACE_OOB:
3414 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
3417 case MTD_OPS_AUTO_OOB:
3418 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
3429 static void rawnand_enable_cont_reads(struct nand_chip *chip, unsigned int page,
3430 u32 readlen, int col)
3432 struct mtd_info *mtd = nand_to_mtd(chip);
3434 if (!chip->controller->supported_op.cont_read)
3437 if ((col && col + readlen < (3 * mtd->writesize)) ||
3438 (!col && readlen < (2 * mtd->writesize))) {
3439 chip->cont_read.ongoing = false;
3443 chip->cont_read.ongoing = true;
3444 chip->cont_read.first_page = page;
3446 chip->cont_read.first_page++;
3447 chip->cont_read.last_page = page + ((readlen >> chip->page_shift) & chip->pagemask);
3451 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
3452 * @chip: NAND chip object
3453 * @retry_mode: the retry mode to use
3455 * Some vendors supply a special command to shift the Vt threshold, to be used
3456 * when there are too many bitflips in a page (i.e., ECC error). After setting
3457 * a new threshold, the host should retry reading the page.
3459 static int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
3461 pr_debug("setting READ RETRY mode %d\n", retry_mode);
3463 if (retry_mode >= chip->read_retries)
3466 if (!chip->ops.setup_read_retry)
3469 return chip->ops.setup_read_retry(chip, retry_mode);
3472 static void nand_wait_readrdy(struct nand_chip *chip)
3474 const struct nand_interface_config *conf;
3476 if (!(chip->options & NAND_NEED_READRDY))
3479 conf = nand_get_interface_config(chip);
3480 WARN_ON(nand_wait_rdy_op(chip, NAND_COMMON_TIMING_MS(conf, tR_max), 0));
3484 * nand_do_read_ops - [INTERN] Read data with ECC
3485 * @chip: NAND chip object
3486 * @from: offset to read from
3487 * @ops: oob ops structure
3489 * Internal function. Called with chip held.
3491 static int nand_do_read_ops(struct nand_chip *chip, loff_t from,
3492 struct mtd_oob_ops *ops)
3494 int chipnr, page, realpage, col, bytes, aligned, oob_required;
3495 struct mtd_info *mtd = nand_to_mtd(chip);
3497 uint32_t readlen = ops->len;
3498 uint32_t oobreadlen = ops->ooblen;
3499 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
3501 uint8_t *bufpoi, *oob, *buf;
3503 unsigned int max_bitflips = 0;
3505 bool ecc_fail = false;
3507 /* Check if the region is secured */
3508 if (nand_region_is_secured(chip, from, readlen))
3511 chipnr = (int)(from >> chip->chip_shift);
3512 nand_select_target(chip, chipnr);
3514 realpage = (int)(from >> chip->page_shift);
3515 page = realpage & chip->pagemask;
3517 col = (int)(from & (mtd->writesize - 1));
3521 oob_required = oob ? 1 : 0;
3523 rawnand_enable_cont_reads(chip, page, readlen, col);
3526 struct mtd_ecc_stats ecc_stats = mtd->ecc_stats;
3528 bytes = min(mtd->writesize - col, readlen);
3529 aligned = (bytes == mtd->writesize);
3533 else if (chip->options & NAND_USES_DMA)
3534 use_bounce_buf = !virt_addr_valid(buf) ||
3535 !IS_ALIGNED((unsigned long)buf,
3540 /* Is the current page in the buffer? */
3541 if (realpage != chip->pagecache.page || oob) {
3542 bufpoi = use_bounce_buf ? chip->data_buf : buf;
3544 if (use_bounce_buf && aligned)
3545 pr_debug("%s: using read bounce buffer for buf@%p\n",
3550 * Now read the page into the buffer. Absent an error,
3551 * the read methods return max bitflips per ecc step.
3553 if (unlikely(ops->mode == MTD_OPS_RAW))
3554 ret = chip->ecc.read_page_raw(chip, bufpoi,
3557 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
3559 ret = chip->ecc.read_subpage(chip, col, bytes,
3562 ret = chip->ecc.read_page(chip, bufpoi,
3563 oob_required, page);
3566 /* Invalidate page cache */
3567 chip->pagecache.page = -1;
3572 * Copy back the data in the initial buffer when reading
3573 * partial pages or when a bounce buffer is required.
3575 if (use_bounce_buf) {
3576 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
3577 !(mtd->ecc_stats.failed - ecc_stats.failed) &&
3578 (ops->mode != MTD_OPS_RAW)) {
3579 chip->pagecache.page = realpage;
3580 chip->pagecache.bitflips = ret;
3582 /* Invalidate page cache */
3583 chip->pagecache.page = -1;
3585 memcpy(buf, bufpoi + col, bytes);
3588 if (unlikely(oob)) {
3589 int toread = min(oobreadlen, max_oobsize);
3592 oob = nand_transfer_oob(chip, oob, ops,
3594 oobreadlen -= toread;
3598 nand_wait_readrdy(chip);
3600 if (mtd->ecc_stats.failed - ecc_stats.failed) {
3601 if (retry_mode + 1 < chip->read_retries) {
3603 ret = nand_setup_read_retry(chip,
3608 /* Reset ecc_stats; retry */
3609 mtd->ecc_stats = ecc_stats;
3612 /* No more retry modes; real failure */
3618 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3620 memcpy(buf, chip->data_buf + col, bytes);
3622 max_bitflips = max_t(unsigned int, max_bitflips,
3623 chip->pagecache.bitflips);
3628 /* Reset to retry mode 0 */
3630 ret = nand_setup_read_retry(chip, 0);
3639 /* For subsequent reads align to page boundary */
3641 /* Increment page address */
3644 page = realpage & chip->pagemask;
3645 /* Check, if we cross a chip boundary */
3648 nand_deselect_target(chip);
3649 nand_select_target(chip, chipnr);
3652 nand_deselect_target(chip);
3654 ops->retlen = ops->len - (size_t) readlen;
3656 ops->oobretlen = ops->ooblen - oobreadlen;
3664 return max_bitflips;
3668 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
3669 * @chip: nand chip info structure
3670 * @page: page number to read
3672 int nand_read_oob_std(struct nand_chip *chip, int page)
3674 struct mtd_info *mtd = nand_to_mtd(chip);
3676 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3678 EXPORT_SYMBOL(nand_read_oob_std);
3681 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
3683 * @chip: nand chip info structure
3684 * @page: page number to read
3686 static int nand_read_oob_syndrome(struct nand_chip *chip, int page)
3688 struct mtd_info *mtd = nand_to_mtd(chip);
3689 int length = mtd->oobsize;
3690 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3691 int eccsize = chip->ecc.size;
3692 uint8_t *bufpoi = chip->oob_poi;
3693 int i, toread, sndrnd = 0, pos, ret;
3695 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
3699 for (i = 0; i < chip->ecc.steps; i++) {
3703 pos = eccsize + i * (eccsize + chunk);
3704 if (mtd->writesize > 512)
3705 ret = nand_change_read_column_op(chip, pos,
3709 ret = nand_read_page_op(chip, page, pos, NULL,
3716 toread = min_t(int, length, chunk);
3718 ret = nand_read_data_op(chip, bufpoi, toread, false, false);
3726 ret = nand_read_data_op(chip, bufpoi, length, false, false);
3735 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
3736 * @chip: nand chip info structure
3737 * @page: page number to write
3739 int nand_write_oob_std(struct nand_chip *chip, int page)
3741 struct mtd_info *mtd = nand_to_mtd(chip);
3743 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
3746 EXPORT_SYMBOL(nand_write_oob_std);
3749 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
3750 * with syndrome - only for large page flash
3751 * @chip: nand chip info structure
3752 * @page: page number to write
3754 static int nand_write_oob_syndrome(struct nand_chip *chip, int page)
3756 struct mtd_info *mtd = nand_to_mtd(chip);
3757 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3758 int eccsize = chip->ecc.size, length = mtd->oobsize;
3759 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
3760 const uint8_t *bufpoi = chip->oob_poi;
3763 * data-ecc-data-ecc ... ecc-oob
3765 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
3767 if (!chip->ecc.prepad && !chip->ecc.postpad) {
3768 pos = steps * (eccsize + chunk);
3773 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
3777 for (i = 0; i < steps; i++) {
3779 if (mtd->writesize <= 512) {
3780 uint32_t fill = 0xFFFFFFFF;
3784 int num = min_t(int, len, 4);
3786 ret = nand_write_data_op(chip, &fill,
3794 pos = eccsize + i * (eccsize + chunk);
3795 ret = nand_change_write_column_op(chip, pos,
3803 len = min_t(int, length, chunk);
3805 ret = nand_write_data_op(chip, bufpoi, len, false);
3813 ret = nand_write_data_op(chip, bufpoi, length, false);
3818 return nand_prog_page_end_op(chip);
3822 * nand_do_read_oob - [INTERN] NAND read out-of-band
3823 * @chip: NAND chip object
3824 * @from: offset to read from
3825 * @ops: oob operations description structure
3827 * NAND read out-of-band data from the spare area.
3829 static int nand_do_read_oob(struct nand_chip *chip, loff_t from,
3830 struct mtd_oob_ops *ops)
3832 struct mtd_info *mtd = nand_to_mtd(chip);
3833 unsigned int max_bitflips = 0;
3834 int page, realpage, chipnr;
3835 struct mtd_ecc_stats stats;
3836 int readlen = ops->ooblen;
3838 uint8_t *buf = ops->oobbuf;
3841 pr_debug("%s: from = 0x%08Lx, len = %i\n",
3842 __func__, (unsigned long long)from, readlen);
3844 /* Check if the region is secured */
3845 if (nand_region_is_secured(chip, from, readlen))
3848 stats = mtd->ecc_stats;
3850 len = mtd_oobavail(mtd, ops);
3852 chipnr = (int)(from >> chip->chip_shift);
3853 nand_select_target(chip, chipnr);
3855 /* Shift to get page */
3856 realpage = (int)(from >> chip->page_shift);
3857 page = realpage & chip->pagemask;
3860 if (ops->mode == MTD_OPS_RAW)
3861 ret = chip->ecc.read_oob_raw(chip, page);
3863 ret = chip->ecc.read_oob(chip, page);
3868 len = min(len, readlen);
3869 buf = nand_transfer_oob(chip, buf, ops, len);
3871 nand_wait_readrdy(chip);
3873 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3879 /* Increment page address */
3882 page = realpage & chip->pagemask;
3883 /* Check, if we cross a chip boundary */
3886 nand_deselect_target(chip);
3887 nand_select_target(chip, chipnr);
3890 nand_deselect_target(chip);
3892 ops->oobretlen = ops->ooblen - readlen;
3897 if (mtd->ecc_stats.failed - stats.failed)
3900 return max_bitflips;
3904 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
3905 * @mtd: MTD device structure
3906 * @from: offset to read from
3907 * @ops: oob operation description structure
3909 * NAND read data and/or out-of-band data.
3911 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
3912 struct mtd_oob_ops *ops)
3914 struct nand_chip *chip = mtd_to_nand(mtd);
3915 struct mtd_ecc_stats old_stats;
3920 if (ops->mode != MTD_OPS_PLACE_OOB &&
3921 ops->mode != MTD_OPS_AUTO_OOB &&
3922 ops->mode != MTD_OPS_RAW)
3925 nand_get_device(chip);
3927 old_stats = mtd->ecc_stats;
3930 ret = nand_do_read_oob(chip, from, ops);
3932 ret = nand_do_read_ops(chip, from, ops);
3935 ops->stats->uncorrectable_errors +=
3936 mtd->ecc_stats.failed - old_stats.failed;
3937 ops->stats->corrected_bitflips +=
3938 mtd->ecc_stats.corrected - old_stats.corrected;
3941 nand_release_device(chip);
3946 * nand_write_page_raw_notsupp - dummy raw page write function
3947 * @chip: nand chip info structure
3949 * @oob_required: must write chip->oob_poi to OOB
3950 * @page: page number to write
3952 * Returns -ENOTSUPP unconditionally.
3954 int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf,
3955 int oob_required, int page)
3961 * nand_write_page_raw - [INTERN] raw page write function
3962 * @chip: nand chip info structure
3964 * @oob_required: must write chip->oob_poi to OOB
3965 * @page: page number to write
3967 * Not for syndrome calculating ECC controllers, which use a special oob layout.
3969 int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
3970 int oob_required, int page)
3972 struct mtd_info *mtd = nand_to_mtd(chip);
3975 ret = nand_prog_page_begin_op(chip, page, 0, buf, mtd->writesize);
3980 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
3986 return nand_prog_page_end_op(chip);
3988 EXPORT_SYMBOL(nand_write_page_raw);
3991 * nand_monolithic_write_page_raw - Monolithic page write in raw mode
3992 * @chip: NAND chip info structure
3993 * @buf: data buffer to write
3994 * @oob_required: must write chip->oob_poi to OOB
3995 * @page: page number to write
3997 * This is a raw page write, ie. without any error detection/correction.
3998 * Monolithic means we are requesting all the relevant data (main plus
3999 * eventually OOB) to be sent over the bus and effectively programmed
4000 * into the NAND chip arrays in a single operation. This is an
4001 * alternative to nand_write_page_raw(), which first sends the main
4002 * data, then eventually send the OOB data by latching more data
4003 * cycles on the NAND bus, and finally sends the program command to
4004 * synchronyze the NAND chip cache.
4006 int nand_monolithic_write_page_raw(struct nand_chip *chip, const u8 *buf,
4007 int oob_required, int page)
4009 struct mtd_info *mtd = nand_to_mtd(chip);
4010 unsigned int size = mtd->writesize;
4011 u8 *write_buf = (u8 *)buf;
4014 size += mtd->oobsize;
4016 if (buf != chip->data_buf) {
4017 write_buf = nand_get_data_buf(chip);
4018 memcpy(write_buf, buf, mtd->writesize);
4022 return nand_prog_page_op(chip, page, 0, write_buf, size);
4024 EXPORT_SYMBOL(nand_monolithic_write_page_raw);
4027 * nand_write_page_raw_syndrome - [INTERN] raw page write function
4028 * @chip: nand chip info structure
4030 * @oob_required: must write chip->oob_poi to OOB
4031 * @page: page number to write
4033 * We need a special oob layout and handling even when ECC isn't checked.
4035 static int nand_write_page_raw_syndrome(struct nand_chip *chip,
4036 const uint8_t *buf, int oob_required,
4039 struct mtd_info *mtd = nand_to_mtd(chip);
4040 int eccsize = chip->ecc.size;
4041 int eccbytes = chip->ecc.bytes;
4042 uint8_t *oob = chip->oob_poi;
4043 int steps, size, ret;
4045 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4049 for (steps = chip->ecc.steps; steps > 0; steps--) {
4050 ret = nand_write_data_op(chip, buf, eccsize, false);
4056 if (chip->ecc.prepad) {
4057 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4062 oob += chip->ecc.prepad;
4065 ret = nand_write_data_op(chip, oob, eccbytes, false);
4071 if (chip->ecc.postpad) {
4072 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4077 oob += chip->ecc.postpad;
4081 size = mtd->oobsize - (oob - chip->oob_poi);
4083 ret = nand_write_data_op(chip, oob, size, false);
4088 return nand_prog_page_end_op(chip);
4091 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
4092 * @chip: nand chip info structure
4094 * @oob_required: must write chip->oob_poi to OOB
4095 * @page: page number to write
4097 static int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf,
4098 int oob_required, int page)
4100 struct mtd_info *mtd = nand_to_mtd(chip);
4101 int i, eccsize = chip->ecc.size, ret;
4102 int eccbytes = chip->ecc.bytes;
4103 int eccsteps = chip->ecc.steps;
4104 uint8_t *ecc_calc = chip->ecc.calc_buf;
4105 const uint8_t *p = buf;
4107 /* Software ECC calculation */
4108 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
4109 chip->ecc.calculate(chip, p, &ecc_calc[i]);
4111 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4116 return chip->ecc.write_page_raw(chip, buf, 1, page);
4120 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
4121 * @chip: nand chip info structure
4123 * @oob_required: must write chip->oob_poi to OOB
4124 * @page: page number to write
4126 static int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf,
4127 int oob_required, int page)
4129 struct mtd_info *mtd = nand_to_mtd(chip);
4130 int i, eccsize = chip->ecc.size, ret;
4131 int eccbytes = chip->ecc.bytes;
4132 int eccsteps = chip->ecc.steps;
4133 uint8_t *ecc_calc = chip->ecc.calc_buf;
4134 const uint8_t *p = buf;
4136 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4140 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4141 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4143 ret = nand_write_data_op(chip, p, eccsize, false);
4147 chip->ecc.calculate(chip, p, &ecc_calc[i]);
4150 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4155 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
4159 return nand_prog_page_end_op(chip);
4164 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
4165 * @chip: nand chip info structure
4166 * @offset: column address of subpage within the page
4167 * @data_len: data length
4169 * @oob_required: must write chip->oob_poi to OOB
4170 * @page: page number to write
4172 static int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset,
4173 uint32_t data_len, const uint8_t *buf,
4174 int oob_required, int page)
4176 struct mtd_info *mtd = nand_to_mtd(chip);
4177 uint8_t *oob_buf = chip->oob_poi;
4178 uint8_t *ecc_calc = chip->ecc.calc_buf;
4179 int ecc_size = chip->ecc.size;
4180 int ecc_bytes = chip->ecc.bytes;
4181 int ecc_steps = chip->ecc.steps;
4182 uint32_t start_step = offset / ecc_size;
4183 uint32_t end_step = (offset + data_len - 1) / ecc_size;
4184 int oob_bytes = mtd->oobsize / ecc_steps;
4187 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4191 for (step = 0; step < ecc_steps; step++) {
4192 /* configure controller for WRITE access */
4193 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4195 /* write data (untouched subpages already masked by 0xFF) */
4196 ret = nand_write_data_op(chip, buf, ecc_size, false);
4200 /* mask ECC of un-touched subpages by padding 0xFF */
4201 if ((step < start_step) || (step > end_step))
4202 memset(ecc_calc, 0xff, ecc_bytes);
4204 chip->ecc.calculate(chip, buf, ecc_calc);
4206 /* mask OOB of un-touched subpages by padding 0xFF */
4207 /* if oob_required, preserve OOB metadata of written subpage */
4208 if (!oob_required || (step < start_step) || (step > end_step))
4209 memset(oob_buf, 0xff, oob_bytes);
4212 ecc_calc += ecc_bytes;
4213 oob_buf += oob_bytes;
4216 /* copy calculated ECC for whole page to chip->buffer->oob */
4217 /* this include masked-value(0xFF) for unwritten subpages */
4218 ecc_calc = chip->ecc.calc_buf;
4219 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4224 /* write OOB buffer to NAND device */
4225 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
4229 return nand_prog_page_end_op(chip);
4234 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
4235 * @chip: nand chip info structure
4237 * @oob_required: must write chip->oob_poi to OOB
4238 * @page: page number to write
4240 * The hw generator calculates the error syndrome automatically. Therefore we
4241 * need a special oob layout and handling.
4243 static int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf,
4244 int oob_required, int page)
4246 struct mtd_info *mtd = nand_to_mtd(chip);
4247 int i, eccsize = chip->ecc.size;
4248 int eccbytes = chip->ecc.bytes;
4249 int eccsteps = chip->ecc.steps;
4250 const uint8_t *p = buf;
4251 uint8_t *oob = chip->oob_poi;
4254 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4258 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4259 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4261 ret = nand_write_data_op(chip, p, eccsize, false);
4265 if (chip->ecc.prepad) {
4266 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4271 oob += chip->ecc.prepad;
4274 chip->ecc.calculate(chip, p, oob);
4276 ret = nand_write_data_op(chip, oob, eccbytes, false);
4282 if (chip->ecc.postpad) {
4283 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4288 oob += chip->ecc.postpad;
4292 /* Calculate remaining oob bytes */
4293 i = mtd->oobsize - (oob - chip->oob_poi);
4295 ret = nand_write_data_op(chip, oob, i, false);
4300 return nand_prog_page_end_op(chip);
4304 * nand_write_page - write one page
4305 * @chip: NAND chip descriptor
4306 * @offset: address offset within the page
4307 * @data_len: length of actual data to be written
4308 * @buf: the data to write
4309 * @oob_required: must write chip->oob_poi to OOB
4310 * @page: page number to write
4311 * @raw: use _raw version of write_page
4313 static int nand_write_page(struct nand_chip *chip, uint32_t offset,
4314 int data_len, const uint8_t *buf, int oob_required,
4317 struct mtd_info *mtd = nand_to_mtd(chip);
4318 int status, subpage;
4320 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
4321 chip->ecc.write_subpage)
4322 subpage = offset || (data_len < mtd->writesize);
4327 status = chip->ecc.write_page_raw(chip, buf, oob_required,
4330 status = chip->ecc.write_subpage(chip, offset, data_len, buf,
4331 oob_required, page);
4333 status = chip->ecc.write_page(chip, buf, oob_required, page);
4341 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
4344 * nand_do_write_ops - [INTERN] NAND write with ECC
4345 * @chip: NAND chip object
4346 * @to: offset to write to
4347 * @ops: oob operations description structure
4349 * NAND write with ECC.
4351 static int nand_do_write_ops(struct nand_chip *chip, loff_t to,
4352 struct mtd_oob_ops *ops)
4354 struct mtd_info *mtd = nand_to_mtd(chip);
4355 int chipnr, realpage, page, column;
4356 uint32_t writelen = ops->len;
4358 uint32_t oobwritelen = ops->ooblen;
4359 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
4361 uint8_t *oob = ops->oobbuf;
4362 uint8_t *buf = ops->datbuf;
4364 int oob_required = oob ? 1 : 0;
4370 /* Reject writes, which are not page aligned */
4371 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
4372 pr_notice("%s: attempt to write non page aligned data\n",
4377 /* Check if the region is secured */
4378 if (nand_region_is_secured(chip, to, writelen))
4381 column = to & (mtd->writesize - 1);
4383 chipnr = (int)(to >> chip->chip_shift);
4384 nand_select_target(chip, chipnr);
4386 /* Check, if it is write protected */
4387 if (nand_check_wp(chip)) {
4392 realpage = (int)(to >> chip->page_shift);
4393 page = realpage & chip->pagemask;
4395 /* Invalidate the page cache, when we write to the cached page */
4396 if (to <= ((loff_t)chip->pagecache.page << chip->page_shift) &&
4397 ((loff_t)chip->pagecache.page << chip->page_shift) < (to + ops->len))
4398 chip->pagecache.page = -1;
4400 /* Don't allow multipage oob writes with offset */
4401 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
4407 int bytes = mtd->writesize;
4408 uint8_t *wbuf = buf;
4410 int part_pagewr = (column || writelen < mtd->writesize);
4414 else if (chip->options & NAND_USES_DMA)
4415 use_bounce_buf = !virt_addr_valid(buf) ||
4416 !IS_ALIGNED((unsigned long)buf,
4422 * Copy the data from the initial buffer when doing partial page
4423 * writes or when a bounce buffer is required.
4425 if (use_bounce_buf) {
4426 pr_debug("%s: using write bounce buffer for buf@%p\n",
4429 bytes = min_t(int, bytes - column, writelen);
4430 wbuf = nand_get_data_buf(chip);
4431 memset(wbuf, 0xff, mtd->writesize);
4432 memcpy(&wbuf[column], buf, bytes);
4435 if (unlikely(oob)) {
4436 size_t len = min(oobwritelen, oobmaxlen);
4437 oob = nand_fill_oob(chip, oob, len, ops);
4440 /* We still need to erase leftover OOB data */
4441 memset(chip->oob_poi, 0xff, mtd->oobsize);
4444 ret = nand_write_page(chip, column, bytes, wbuf,
4446 (ops->mode == MTD_OPS_RAW));
4458 page = realpage & chip->pagemask;
4459 /* Check, if we cross a chip boundary */
4462 nand_deselect_target(chip);
4463 nand_select_target(chip, chipnr);
4467 ops->retlen = ops->len - writelen;
4469 ops->oobretlen = ops->ooblen;
4472 nand_deselect_target(chip);
4477 * panic_nand_write - [MTD Interface] NAND write with ECC
4478 * @mtd: MTD device structure
4479 * @to: offset to write to
4480 * @len: number of bytes to write
4481 * @retlen: pointer to variable to store the number of written bytes
4482 * @buf: the data to write
4484 * NAND write with ECC. Used when performing writes in interrupt context, this
4485 * may for example be called by mtdoops when writing an oops while in panic.
4487 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
4488 size_t *retlen, const uint8_t *buf)
4490 struct nand_chip *chip = mtd_to_nand(mtd);
4491 int chipnr = (int)(to >> chip->chip_shift);
4492 struct mtd_oob_ops ops;
4495 nand_select_target(chip, chipnr);
4497 /* Wait for the device to get ready */
4498 panic_nand_wait(chip, 400);
4500 memset(&ops, 0, sizeof(ops));
4502 ops.datbuf = (uint8_t *)buf;
4503 ops.mode = MTD_OPS_PLACE_OOB;
4505 ret = nand_do_write_ops(chip, to, &ops);
4507 *retlen = ops.retlen;
4512 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
4513 * @mtd: MTD device structure
4514 * @to: offset to write to
4515 * @ops: oob operation description structure
4517 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
4518 struct mtd_oob_ops *ops)
4520 struct nand_chip *chip = mtd_to_nand(mtd);
4525 nand_get_device(chip);
4527 switch (ops->mode) {
4528 case MTD_OPS_PLACE_OOB:
4529 case MTD_OPS_AUTO_OOB:
4538 ret = nand_do_write_oob(chip, to, ops);
4540 ret = nand_do_write_ops(chip, to, ops);
4543 nand_release_device(chip);
4548 * nand_erase - [MTD Interface] erase block(s)
4549 * @mtd: MTD device structure
4550 * @instr: erase instruction
4552 * Erase one ore more blocks.
4554 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
4556 return nand_erase_nand(mtd_to_nand(mtd), instr, 0);
4560 * nand_erase_nand - [INTERN] erase block(s)
4561 * @chip: NAND chip object
4562 * @instr: erase instruction
4563 * @allowbbt: allow erasing the bbt area
4565 * Erase one ore more blocks.
4567 int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr,
4570 int page, pages_per_block, ret, chipnr;
4573 pr_debug("%s: start = 0x%012llx, len = %llu\n",
4574 __func__, (unsigned long long)instr->addr,
4575 (unsigned long long)instr->len);
4577 if (check_offs_len(chip, instr->addr, instr->len))
4580 /* Check if the region is secured */
4581 if (nand_region_is_secured(chip, instr->addr, instr->len))
4584 /* Grab the lock and see if the device is available */
4585 nand_get_device(chip);
4587 /* Shift to get first page */
4588 page = (int)(instr->addr >> chip->page_shift);
4589 chipnr = (int)(instr->addr >> chip->chip_shift);
4591 /* Calculate pages in each block */
4592 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
4594 /* Select the NAND device */
4595 nand_select_target(chip, chipnr);
4597 /* Check, if it is write protected */
4598 if (nand_check_wp(chip)) {
4599 pr_debug("%s: device is write protected!\n",
4605 /* Loop through the pages */
4609 loff_t ofs = (loff_t)page << chip->page_shift;
4611 /* Check if we have a bad block, we do not erase bad blocks! */
4612 if (nand_block_checkbad(chip, ((loff_t) page) <<
4613 chip->page_shift, allowbbt)) {
4614 pr_warn("%s: attempt to erase a bad block at 0x%08llx\n",
4615 __func__, (unsigned long long)ofs);
4621 * Invalidate the page cache, if we erase the block which
4622 * contains the current cached page.
4624 if (page <= chip->pagecache.page && chip->pagecache.page <
4625 (page + pages_per_block))
4626 chip->pagecache.page = -1;
4628 ret = nand_erase_op(chip, (page & chip->pagemask) >>
4629 (chip->phys_erase_shift - chip->page_shift));
4631 pr_debug("%s: failed erase, page 0x%08x\n",
4633 instr->fail_addr = ofs;
4637 /* Increment page address and decrement length */
4638 len -= (1ULL << chip->phys_erase_shift);
4639 page += pages_per_block;
4641 /* Check, if we cross a chip boundary */
4642 if (len && !(page & chip->pagemask)) {
4644 nand_deselect_target(chip);
4645 nand_select_target(chip, chipnr);
4652 /* Deselect and wake up anyone waiting on the device */
4653 nand_deselect_target(chip);
4654 nand_release_device(chip);
4656 /* Return more or less happy */
4661 * nand_sync - [MTD Interface] sync
4662 * @mtd: MTD device structure
4664 * Sync is actually a wait for chip ready function.
4666 static void nand_sync(struct mtd_info *mtd)
4668 struct nand_chip *chip = mtd_to_nand(mtd);
4670 pr_debug("%s: called\n", __func__);
4672 /* Grab the lock and see if the device is available */
4673 nand_get_device(chip);
4674 /* Release it and go back */
4675 nand_release_device(chip);
4679 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
4680 * @mtd: MTD device structure
4681 * @offs: offset relative to mtd start
4683 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
4685 struct nand_chip *chip = mtd_to_nand(mtd);
4686 int chipnr = (int)(offs >> chip->chip_shift);
4689 /* Select the NAND device */
4690 nand_get_device(chip);
4692 nand_select_target(chip, chipnr);
4694 ret = nand_block_checkbad(chip, offs, 0);
4696 nand_deselect_target(chip);
4697 nand_release_device(chip);
4703 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
4704 * @mtd: MTD device structure
4705 * @ofs: offset relative to mtd start
4707 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
4711 ret = nand_block_isbad(mtd, ofs);
4713 /* If it was bad already, return success and do nothing */
4719 return nand_block_markbad_lowlevel(mtd_to_nand(mtd), ofs);
4723 * nand_suspend - [MTD Interface] Suspend the NAND flash
4724 * @mtd: MTD device structure
4726 * Returns 0 for success or negative error code otherwise.
4728 static int nand_suspend(struct mtd_info *mtd)
4730 struct nand_chip *chip = mtd_to_nand(mtd);
4733 mutex_lock(&chip->lock);
4734 if (chip->ops.suspend)
4735 ret = chip->ops.suspend(chip);
4737 chip->suspended = 1;
4738 mutex_unlock(&chip->lock);
4744 * nand_resume - [MTD Interface] Resume the NAND flash
4745 * @mtd: MTD device structure
4747 static void nand_resume(struct mtd_info *mtd)
4749 struct nand_chip *chip = mtd_to_nand(mtd);
4751 mutex_lock(&chip->lock);
4752 if (chip->suspended) {
4753 if (chip->ops.resume)
4754 chip->ops.resume(chip);
4755 chip->suspended = 0;
4757 pr_err("%s called for a chip which is not in suspended state\n",
4760 mutex_unlock(&chip->lock);
4762 wake_up_all(&chip->resume_wq);
4766 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
4767 * prevent further operations
4768 * @mtd: MTD device structure
4770 static void nand_shutdown(struct mtd_info *mtd)
4776 * nand_lock - [MTD Interface] Lock the NAND flash
4777 * @mtd: MTD device structure
4778 * @ofs: offset byte address
4779 * @len: number of bytes to lock (must be a multiple of block/page size)
4781 static int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4783 struct nand_chip *chip = mtd_to_nand(mtd);
4785 if (!chip->ops.lock_area)
4788 return chip->ops.lock_area(chip, ofs, len);
4792 * nand_unlock - [MTD Interface] Unlock the NAND flash
4793 * @mtd: MTD device structure
4794 * @ofs: offset byte address
4795 * @len: number of bytes to unlock (must be a multiple of block/page size)
4797 static int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4799 struct nand_chip *chip = mtd_to_nand(mtd);
4801 if (!chip->ops.unlock_area)
4804 return chip->ops.unlock_area(chip, ofs, len);
4807 /* Set default functions */
4808 static void nand_set_defaults(struct nand_chip *chip)
4810 /* If no controller is provided, use the dummy, legacy one. */
4811 if (!chip->controller) {
4812 chip->controller = &chip->legacy.dummy_controller;
4813 nand_controller_init(chip->controller);
4816 nand_legacy_set_defaults(chip);
4818 if (!chip->buf_align)
4819 chip->buf_align = 1;
4822 /* Sanitize ONFI strings so we can safely print them */
4823 void sanitize_string(uint8_t *s, size_t len)
4827 /* Null terminate */
4830 /* Remove non printable chars */
4831 for (i = 0; i < len - 1; i++) {
4832 if (s[i] < ' ' || s[i] > 127)
4836 /* Remove trailing spaces */
4841 * nand_id_has_period - Check if an ID string has a given wraparound period
4842 * @id_data: the ID string
4843 * @arrlen: the length of the @id_data array
4844 * @period: the period of repitition
4846 * Check if an ID string is repeated within a given sequence of bytes at
4847 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4848 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4849 * if the repetition has a period of @period; otherwise, returns zero.
4851 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4854 for (i = 0; i < period; i++)
4855 for (j = i + period; j < arrlen; j += period)
4856 if (id_data[i] != id_data[j])
4862 * nand_id_len - Get the length of an ID string returned by CMD_READID
4863 * @id_data: the ID string
4864 * @arrlen: the length of the @id_data array
4866 * Returns the length of the ID string, according to known wraparound/trailing
4867 * zero patterns. If no pattern exists, returns the length of the array.
4869 static int nand_id_len(u8 *id_data, int arrlen)
4871 int last_nonzero, period;
4873 /* Find last non-zero byte */
4874 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4875 if (id_data[last_nonzero])
4879 if (last_nonzero < 0)
4882 /* Calculate wraparound period */
4883 for (period = 1; period < arrlen; period++)
4884 if (nand_id_has_period(id_data, arrlen, period))
4887 /* There's a repeated pattern */
4888 if (period < arrlen)
4891 /* There are trailing zeros */
4892 if (last_nonzero < arrlen - 1)
4893 return last_nonzero + 1;
4895 /* No pattern detected */
4899 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4900 static int nand_get_bits_per_cell(u8 cellinfo)
4904 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4905 bits >>= NAND_CI_CELLTYPE_SHIFT;
4910 * Many new NAND share similar device ID codes, which represent the size of the
4911 * chip. The rest of the parameters must be decoded according to generic or
4912 * manufacturer-specific "extended ID" decoding patterns.
4914 void nand_decode_ext_id(struct nand_chip *chip)
4916 struct nand_memory_organization *memorg;
4917 struct mtd_info *mtd = nand_to_mtd(chip);
4919 u8 *id_data = chip->id.data;
4921 memorg = nanddev_get_memorg(&chip->base);
4923 /* The 3rd id byte holds MLC / multichip data */
4924 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4925 /* The 4th id byte is the important one */
4929 memorg->pagesize = 1024 << (extid & 0x03);
4930 mtd->writesize = memorg->pagesize;
4933 memorg->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
4934 mtd->oobsize = memorg->oobsize;
4936 /* Calc blocksize. Blocksize is multiples of 64KiB */
4937 memorg->pages_per_eraseblock = ((64 * 1024) << (extid & 0x03)) /
4939 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4941 /* Get buswidth information */
4943 chip->options |= NAND_BUSWIDTH_16;
4945 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
4948 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4949 * decodes a matching ID table entry and assigns the MTD size parameters for
4952 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
4954 struct mtd_info *mtd = nand_to_mtd(chip);
4955 struct nand_memory_organization *memorg;
4957 memorg = nanddev_get_memorg(&chip->base);
4959 memorg->pages_per_eraseblock = type->erasesize / type->pagesize;
4960 mtd->erasesize = type->erasesize;
4961 memorg->pagesize = type->pagesize;
4962 mtd->writesize = memorg->pagesize;
4963 memorg->oobsize = memorg->pagesize / 32;
4964 mtd->oobsize = memorg->oobsize;
4966 /* All legacy ID NAND are small-page, SLC */
4967 memorg->bits_per_cell = 1;
4971 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4972 * heuristic patterns using various detected parameters (e.g., manufacturer,
4973 * page size, cell-type information).
4975 static void nand_decode_bbm_options(struct nand_chip *chip)
4977 struct mtd_info *mtd = nand_to_mtd(chip);
4979 /* Set the bad block position */
4980 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4981 chip->badblockpos = NAND_BBM_POS_LARGE;
4983 chip->badblockpos = NAND_BBM_POS_SMALL;
4986 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4988 return type->id_len;
4991 static bool find_full_id_nand(struct nand_chip *chip,
4992 struct nand_flash_dev *type)
4994 struct nand_device *base = &chip->base;
4995 struct nand_ecc_props requirements;
4996 struct mtd_info *mtd = nand_to_mtd(chip);
4997 struct nand_memory_organization *memorg;
4998 u8 *id_data = chip->id.data;
5000 memorg = nanddev_get_memorg(&chip->base);
5002 if (!strncmp(type->id, id_data, type->id_len)) {
5003 memorg->pagesize = type->pagesize;
5004 mtd->writesize = memorg->pagesize;
5005 memorg->pages_per_eraseblock = type->erasesize /
5007 mtd->erasesize = type->erasesize;
5008 memorg->oobsize = type->oobsize;
5009 mtd->oobsize = memorg->oobsize;
5011 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
5012 memorg->eraseblocks_per_lun =
5013 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
5015 memorg->pages_per_eraseblock);
5016 chip->options |= type->options;
5017 requirements.strength = NAND_ECC_STRENGTH(type);
5018 requirements.step_size = NAND_ECC_STEP(type);
5019 nanddev_set_ecc_requirements(base, &requirements);
5021 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
5022 if (!chip->parameters.model)
5031 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
5032 * compliant and does not have a full-id or legacy-id entry in the nand_ids
5035 static void nand_manufacturer_detect(struct nand_chip *chip)
5038 * Try manufacturer detection if available and use
5039 * nand_decode_ext_id() otherwise.
5041 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
5042 chip->manufacturer.desc->ops->detect) {
5043 struct nand_memory_organization *memorg;
5045 memorg = nanddev_get_memorg(&chip->base);
5047 /* The 3rd id byte holds MLC / multichip data */
5048 memorg->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
5049 chip->manufacturer.desc->ops->detect(chip);
5051 nand_decode_ext_id(chip);
5056 * Manufacturer initialization. This function is called for all NANDs including
5057 * ONFI and JEDEC compliant ones.
5058 * Manufacturer drivers should put all their specific initialization code in
5059 * their ->init() hook.
5061 static int nand_manufacturer_init(struct nand_chip *chip)
5063 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
5064 !chip->manufacturer.desc->ops->init)
5067 return chip->manufacturer.desc->ops->init(chip);
5071 * Manufacturer cleanup. This function is called for all NANDs including
5072 * ONFI and JEDEC compliant ones.
5073 * Manufacturer drivers should put all their specific cleanup code in their
5076 static void nand_manufacturer_cleanup(struct nand_chip *chip)
5078 /* Release manufacturer private data */
5079 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
5080 chip->manufacturer.desc->ops->cleanup)
5081 chip->manufacturer.desc->ops->cleanup(chip);
5085 nand_manufacturer_name(const struct nand_manufacturer_desc *manufacturer_desc)
5087 return manufacturer_desc ? manufacturer_desc->name : "Unknown";
5090 static void rawnand_check_data_only_read_support(struct nand_chip *chip)
5092 /* Use an arbitrary size for the check */
5093 if (!nand_read_data_op(chip, NULL, SZ_512, true, true))
5094 chip->controller->supported_op.data_only_read = 1;
5097 static void rawnand_early_check_supported_ops(struct nand_chip *chip)
5099 /* The supported_op fields should not be set by individual drivers */
5100 WARN_ON_ONCE(chip->controller->supported_op.data_only_read);
5102 if (!nand_has_exec_op(chip))
5105 rawnand_check_data_only_read_support(chip);
5108 static void rawnand_check_cont_read_support(struct nand_chip *chip)
5110 struct mtd_info *mtd = nand_to_mtd(chip);
5112 if (!chip->parameters.supports_read_cache)
5115 if (chip->read_retries)
5118 if (!nand_lp_exec_cont_read_page_op(chip, 0, 0, NULL,
5119 mtd->writesize, true))
5120 chip->controller->supported_op.cont_read = 1;
5123 static void rawnand_late_check_supported_ops(struct nand_chip *chip)
5125 /* The supported_op fields should not be set by individual drivers */
5126 WARN_ON_ONCE(chip->controller->supported_op.cont_read);
5128 if (!nand_has_exec_op(chip))
5131 rawnand_check_cont_read_support(chip);
5135 * Get the flash and manufacturer id and lookup if the type is supported.
5137 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
5139 const struct nand_manufacturer_desc *manufacturer_desc;
5140 struct mtd_info *mtd = nand_to_mtd(chip);
5141 struct nand_memory_organization *memorg;
5143 u8 *id_data = chip->id.data;
5148 * Let's start by initializing memorg fields that might be left
5149 * unassigned by the ID-based detection logic.
5151 memorg = nanddev_get_memorg(&chip->base);
5152 memorg->planes_per_lun = 1;
5153 memorg->luns_per_target = 1;
5156 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
5159 ret = nand_reset(chip, 0);
5163 /* Select the device */
5164 nand_select_target(chip, 0);
5166 rawnand_early_check_supported_ops(chip);
5168 /* Send the command for reading device ID */
5169 ret = nand_readid_op(chip, 0, id_data, 2);
5173 /* Read manufacturer and device IDs */
5174 maf_id = id_data[0];
5175 dev_id = id_data[1];
5178 * Try again to make sure, as some systems the bus-hold or other
5179 * interface concerns can cause random data which looks like a
5180 * possibly credible NAND flash to appear. If the two results do
5181 * not match, ignore the device completely.
5184 /* Read entire ID string */
5185 ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
5189 if (id_data[0] != maf_id || id_data[1] != dev_id) {
5190 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
5191 maf_id, dev_id, id_data[0], id_data[1]);
5195 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
5197 /* Try to identify manufacturer */
5198 manufacturer_desc = nand_get_manufacturer_desc(maf_id);
5199 chip->manufacturer.desc = manufacturer_desc;
5202 type = nand_flash_ids;
5205 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
5207 * This is required to make sure initial NAND bus width set by the
5208 * NAND controller driver is coherent with the real NAND bus width
5209 * (extracted by auto-detection code).
5211 busw = chip->options & NAND_BUSWIDTH_16;
5214 * The flag is only set (never cleared), reset it to its default value
5215 * before starting auto-detection.
5217 chip->options &= ~NAND_BUSWIDTH_16;
5219 for (; type->name != NULL; type++) {
5220 if (is_full_id_nand(type)) {
5221 if (find_full_id_nand(chip, type))
5223 } else if (dev_id == type->dev_id) {
5228 if (!type->name || !type->pagesize) {
5229 /* Check if the chip is ONFI compliant */
5230 ret = nand_onfi_detect(chip);
5236 /* Check if the chip is JEDEC compliant */
5237 ret = nand_jedec_detect(chip);
5247 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
5248 if (!chip->parameters.model)
5251 if (!type->pagesize)
5252 nand_manufacturer_detect(chip);
5254 nand_decode_id(chip, type);
5256 /* Get chip options */
5257 chip->options |= type->options;
5259 memorg->eraseblocks_per_lun =
5260 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
5262 memorg->pages_per_eraseblock);
5266 mtd->name = chip->parameters.model;
5268 if (chip->options & NAND_BUSWIDTH_AUTO) {
5269 WARN_ON(busw & NAND_BUSWIDTH_16);
5270 nand_set_defaults(chip);
5271 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
5273 * Check, if buswidth is correct. Hardware drivers should set
5276 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5278 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
5280 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
5281 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
5284 goto free_detect_allocation;
5287 nand_decode_bbm_options(chip);
5289 /* Calculate the address shift from the page size */
5290 chip->page_shift = ffs(mtd->writesize) - 1;
5291 /* Convert chipsize to number of pages per chip -1 */
5292 targetsize = nanddev_target_size(&chip->base);
5293 chip->pagemask = (targetsize >> chip->page_shift) - 1;
5295 chip->bbt_erase_shift = chip->phys_erase_shift =
5296 ffs(mtd->erasesize) - 1;
5297 if (targetsize & 0xffffffff)
5298 chip->chip_shift = ffs((unsigned)targetsize) - 1;
5300 chip->chip_shift = ffs((unsigned)(targetsize >> 32));
5301 chip->chip_shift += 32 - 1;
5304 if (chip->chip_shift - chip->page_shift > 16)
5305 chip->options |= NAND_ROW_ADDR_3;
5307 chip->badblockbits = 8;
5309 nand_legacy_adjust_cmdfunc(chip);
5311 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5313 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
5314 chip->parameters.model);
5315 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
5316 (int)(targetsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
5317 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
5320 free_detect_allocation:
5321 kfree(chip->parameters.model);
5326 static enum nand_ecc_engine_type
5327 of_get_rawnand_ecc_engine_type_legacy(struct device_node *np)
5329 enum nand_ecc_legacy_mode {
5335 NAND_ECC_HW_SYNDROME,
5338 const char * const nand_ecc_legacy_modes[] = {
5339 [NAND_ECC_NONE] = "none",
5340 [NAND_ECC_SOFT] = "soft",
5341 [NAND_ECC_SOFT_BCH] = "soft_bch",
5342 [NAND_ECC_HW] = "hw",
5343 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
5344 [NAND_ECC_ON_DIE] = "on-die",
5346 enum nand_ecc_legacy_mode eng_type;
5350 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5352 return NAND_ECC_ENGINE_TYPE_INVALID;
5354 for (eng_type = NAND_ECC_NONE;
5355 eng_type < ARRAY_SIZE(nand_ecc_legacy_modes); eng_type++) {
5356 if (!strcasecmp(pm, nand_ecc_legacy_modes[eng_type])) {
5359 return NAND_ECC_ENGINE_TYPE_NONE;
5361 case NAND_ECC_SOFT_BCH:
5362 return NAND_ECC_ENGINE_TYPE_SOFT;
5364 case NAND_ECC_HW_SYNDROME:
5365 return NAND_ECC_ENGINE_TYPE_ON_HOST;
5366 case NAND_ECC_ON_DIE:
5367 return NAND_ECC_ENGINE_TYPE_ON_DIE;
5374 return NAND_ECC_ENGINE_TYPE_INVALID;
5377 static enum nand_ecc_placement
5378 of_get_rawnand_ecc_placement_legacy(struct device_node *np)
5383 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5385 if (!strcasecmp(pm, "hw_syndrome"))
5386 return NAND_ECC_PLACEMENT_INTERLEAVED;
5389 return NAND_ECC_PLACEMENT_UNKNOWN;
5392 static enum nand_ecc_algo of_get_rawnand_ecc_algo_legacy(struct device_node *np)
5397 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5399 if (!strcasecmp(pm, "soft"))
5400 return NAND_ECC_ALGO_HAMMING;
5401 else if (!strcasecmp(pm, "soft_bch"))
5402 return NAND_ECC_ALGO_BCH;
5405 return NAND_ECC_ALGO_UNKNOWN;
5408 static void of_get_nand_ecc_legacy_user_config(struct nand_chip *chip)
5410 struct device_node *dn = nand_get_flash_node(chip);
5411 struct nand_ecc_props *user_conf = &chip->base.ecc.user_conf;
5413 if (user_conf->engine_type == NAND_ECC_ENGINE_TYPE_INVALID)
5414 user_conf->engine_type = of_get_rawnand_ecc_engine_type_legacy(dn);
5416 if (user_conf->algo == NAND_ECC_ALGO_UNKNOWN)
5417 user_conf->algo = of_get_rawnand_ecc_algo_legacy(dn);
5419 if (user_conf->placement == NAND_ECC_PLACEMENT_UNKNOWN)
5420 user_conf->placement = of_get_rawnand_ecc_placement_legacy(dn);
5423 static int of_get_nand_bus_width(struct nand_chip *chip)
5425 struct device_node *dn = nand_get_flash_node(chip);
5429 ret = of_property_read_u32(dn, "nand-bus-width", &val);
5431 /* Buswidth defaults to 8 if the property does not exist .*/
5437 chip->options |= NAND_BUSWIDTH_16;
5443 static int of_get_nand_secure_regions(struct nand_chip *chip)
5445 struct device_node *dn = nand_get_flash_node(chip);
5446 struct property *prop;
5449 /* Only proceed if the "secure-regions" property is present in DT */
5450 prop = of_find_property(dn, "secure-regions", NULL);
5454 nr_elem = of_property_count_elems_of_size(dn, "secure-regions", sizeof(u64));
5458 chip->nr_secure_regions = nr_elem / 2;
5459 chip->secure_regions = kcalloc(chip->nr_secure_regions, sizeof(*chip->secure_regions),
5461 if (!chip->secure_regions)
5464 for (i = 0, j = 0; i < chip->nr_secure_regions; i++, j += 2) {
5465 of_property_read_u64_index(dn, "secure-regions", j,
5466 &chip->secure_regions[i].offset);
5467 of_property_read_u64_index(dn, "secure-regions", j + 1,
5468 &chip->secure_regions[i].size);
5475 * rawnand_dt_parse_gpio_cs - Parse the gpio-cs property of a controller
5476 * @dev: Device that will be parsed. Also used for managed allocations.
5477 * @cs_array: Array of GPIO desc pointers allocated on success
5478 * @ncs_array: Number of entries in @cs_array updated on success.
5479 * @return 0 on success, an error otherwise.
5481 int rawnand_dt_parse_gpio_cs(struct device *dev, struct gpio_desc ***cs_array,
5482 unsigned int *ncs_array)
5484 struct gpio_desc **descs;
5487 ndescs = gpiod_count(dev, "cs");
5489 dev_dbg(dev, "No valid cs-gpios property\n");
5493 descs = devm_kcalloc(dev, ndescs, sizeof(*descs), GFP_KERNEL);
5497 for (i = 0; i < ndescs; i++) {
5498 descs[i] = gpiod_get_index_optional(dev, "cs", i,
5500 if (IS_ERR(descs[i]))
5501 return PTR_ERR(descs[i]);
5504 *ncs_array = ndescs;
5509 EXPORT_SYMBOL(rawnand_dt_parse_gpio_cs);
5511 static int rawnand_dt_init(struct nand_chip *chip)
5513 struct nand_device *nand = mtd_to_nanddev(nand_to_mtd(chip));
5514 struct device_node *dn = nand_get_flash_node(chip);
5520 ret = of_get_nand_bus_width(chip);
5524 if (of_property_read_bool(dn, "nand-is-boot-medium"))
5525 chip->options |= NAND_IS_BOOT_MEDIUM;
5527 if (of_property_read_bool(dn, "nand-on-flash-bbt"))
5528 chip->bbt_options |= NAND_BBT_USE_FLASH;
5530 of_get_nand_ecc_user_config(nand);
5531 of_get_nand_ecc_legacy_user_config(chip);
5534 * If neither the user nor the NAND controller have requested a specific
5535 * ECC engine type, we will default to NAND_ECC_ENGINE_TYPE_ON_HOST.
5537 nand->ecc.defaults.engine_type = NAND_ECC_ENGINE_TYPE_ON_HOST;
5540 * Use the user requested engine type, unless there is none, in this
5541 * case default to the NAND controller choice, otherwise fallback to
5542 * the raw NAND default one.
5544 if (nand->ecc.user_conf.engine_type != NAND_ECC_ENGINE_TYPE_INVALID)
5545 chip->ecc.engine_type = nand->ecc.user_conf.engine_type;
5546 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_INVALID)
5547 chip->ecc.engine_type = nand->ecc.defaults.engine_type;
5549 chip->ecc.placement = nand->ecc.user_conf.placement;
5550 chip->ecc.algo = nand->ecc.user_conf.algo;
5551 chip->ecc.strength = nand->ecc.user_conf.strength;
5552 chip->ecc.size = nand->ecc.user_conf.step_size;
5558 * nand_scan_ident - Scan for the NAND device
5559 * @chip: NAND chip object
5560 * @maxchips: number of chips to scan for
5561 * @table: alternative NAND ID table
5563 * This is the first phase of the normal nand_scan() function. It reads the
5564 * flash ID and sets up MTD fields accordingly.
5566 * This helper used to be called directly from controller drivers that needed
5567 * to tweak some ECC-related parameters before nand_scan_tail(). This separation
5568 * prevented dynamic allocations during this phase which was unconvenient and
5569 * as been banned for the benefit of the ->init_ecc()/cleanup_ecc() hooks.
5571 static int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips,
5572 struct nand_flash_dev *table)
5574 struct mtd_info *mtd = nand_to_mtd(chip);
5575 struct nand_memory_organization *memorg;
5576 int nand_maf_id, nand_dev_id;
5580 memorg = nanddev_get_memorg(&chip->base);
5582 /* Assume all dies are deselected when we enter nand_scan_ident(). */
5585 mutex_init(&chip->lock);
5586 init_waitqueue_head(&chip->resume_wq);
5588 /* Enforce the right timings for reset/detection */
5589 chip->current_interface_config = nand_get_reset_interface_config();
5591 ret = rawnand_dt_init(chip);
5595 if (!mtd->name && mtd->dev.parent)
5596 mtd->name = dev_name(mtd->dev.parent);
5598 /* Set the default functions */
5599 nand_set_defaults(chip);
5601 ret = nand_legacy_check_hooks(chip);
5605 memorg->ntargets = maxchips;
5607 /* Read the flash type */
5608 ret = nand_detect(chip, table);
5610 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
5611 pr_warn("No NAND device found\n");
5612 nand_deselect_target(chip);
5616 nand_maf_id = chip->id.data[0];
5617 nand_dev_id = chip->id.data[1];
5619 nand_deselect_target(chip);
5621 /* Check for a chip array */
5622 for (i = 1; i < maxchips; i++) {
5625 /* See comment in nand_get_flash_type for reset */
5626 ret = nand_reset(chip, i);
5630 nand_select_target(chip, i);
5631 /* Send the command for reading device ID */
5632 ret = nand_readid_op(chip, 0, id, sizeof(id));
5635 /* Read manufacturer and device IDs */
5636 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
5637 nand_deselect_target(chip);
5640 nand_deselect_target(chip);
5643 pr_info("%d chips detected\n", i);
5645 /* Store the number of chips and calc total size for mtd */
5646 memorg->ntargets = i;
5647 mtd->size = i * nanddev_target_size(&chip->base);
5652 static void nand_scan_ident_cleanup(struct nand_chip *chip)
5654 kfree(chip->parameters.model);
5655 kfree(chip->parameters.onfi);
5658 int rawnand_sw_hamming_init(struct nand_chip *chip)
5660 struct nand_ecc_sw_hamming_conf *engine_conf;
5661 struct nand_device *base = &chip->base;
5664 base->ecc.user_conf.engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5665 base->ecc.user_conf.algo = NAND_ECC_ALGO_HAMMING;
5666 base->ecc.user_conf.strength = chip->ecc.strength;
5667 base->ecc.user_conf.step_size = chip->ecc.size;
5669 ret = nand_ecc_sw_hamming_init_ctx(base);
5673 engine_conf = base->ecc.ctx.priv;
5675 if (chip->ecc.options & NAND_ECC_SOFT_HAMMING_SM_ORDER)
5676 engine_conf->sm_order = true;
5678 chip->ecc.size = base->ecc.ctx.conf.step_size;
5679 chip->ecc.strength = base->ecc.ctx.conf.strength;
5680 chip->ecc.total = base->ecc.ctx.total;
5681 chip->ecc.steps = nanddev_get_ecc_nsteps(base);
5682 chip->ecc.bytes = base->ecc.ctx.total / nanddev_get_ecc_nsteps(base);
5686 EXPORT_SYMBOL(rawnand_sw_hamming_init);
5688 int rawnand_sw_hamming_calculate(struct nand_chip *chip,
5689 const unsigned char *buf,
5690 unsigned char *code)
5692 struct nand_device *base = &chip->base;
5694 return nand_ecc_sw_hamming_calculate(base, buf, code);
5696 EXPORT_SYMBOL(rawnand_sw_hamming_calculate);
5698 int rawnand_sw_hamming_correct(struct nand_chip *chip,
5700 unsigned char *read_ecc,
5701 unsigned char *calc_ecc)
5703 struct nand_device *base = &chip->base;
5705 return nand_ecc_sw_hamming_correct(base, buf, read_ecc, calc_ecc);
5707 EXPORT_SYMBOL(rawnand_sw_hamming_correct);
5709 void rawnand_sw_hamming_cleanup(struct nand_chip *chip)
5711 struct nand_device *base = &chip->base;
5713 nand_ecc_sw_hamming_cleanup_ctx(base);
5715 EXPORT_SYMBOL(rawnand_sw_hamming_cleanup);
5717 int rawnand_sw_bch_init(struct nand_chip *chip)
5719 struct nand_device *base = &chip->base;
5720 const struct nand_ecc_props *ecc_conf = nanddev_get_ecc_conf(base);
5723 base->ecc.user_conf.engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5724 base->ecc.user_conf.algo = NAND_ECC_ALGO_BCH;
5725 base->ecc.user_conf.step_size = chip->ecc.size;
5726 base->ecc.user_conf.strength = chip->ecc.strength;
5728 ret = nand_ecc_sw_bch_init_ctx(base);
5732 chip->ecc.size = ecc_conf->step_size;
5733 chip->ecc.strength = ecc_conf->strength;
5734 chip->ecc.total = base->ecc.ctx.total;
5735 chip->ecc.steps = nanddev_get_ecc_nsteps(base);
5736 chip->ecc.bytes = base->ecc.ctx.total / nanddev_get_ecc_nsteps(base);
5740 EXPORT_SYMBOL(rawnand_sw_bch_init);
5742 static int rawnand_sw_bch_calculate(struct nand_chip *chip,
5743 const unsigned char *buf,
5744 unsigned char *code)
5746 struct nand_device *base = &chip->base;
5748 return nand_ecc_sw_bch_calculate(base, buf, code);
5751 int rawnand_sw_bch_correct(struct nand_chip *chip, unsigned char *buf,
5752 unsigned char *read_ecc, unsigned char *calc_ecc)
5754 struct nand_device *base = &chip->base;
5756 return nand_ecc_sw_bch_correct(base, buf, read_ecc, calc_ecc);
5758 EXPORT_SYMBOL(rawnand_sw_bch_correct);
5760 void rawnand_sw_bch_cleanup(struct nand_chip *chip)
5762 struct nand_device *base = &chip->base;
5764 nand_ecc_sw_bch_cleanup_ctx(base);
5766 EXPORT_SYMBOL(rawnand_sw_bch_cleanup);
5768 static int nand_set_ecc_on_host_ops(struct nand_chip *chip)
5770 struct nand_ecc_ctrl *ecc = &chip->ecc;
5772 switch (ecc->placement) {
5773 case NAND_ECC_PLACEMENT_UNKNOWN:
5774 case NAND_ECC_PLACEMENT_OOB:
5775 /* Use standard hwecc read page function? */
5776 if (!ecc->read_page)
5777 ecc->read_page = nand_read_page_hwecc;
5778 if (!ecc->write_page)
5779 ecc->write_page = nand_write_page_hwecc;
5780 if (!ecc->read_page_raw)
5781 ecc->read_page_raw = nand_read_page_raw;
5782 if (!ecc->write_page_raw)
5783 ecc->write_page_raw = nand_write_page_raw;
5785 ecc->read_oob = nand_read_oob_std;
5786 if (!ecc->write_oob)
5787 ecc->write_oob = nand_write_oob_std;
5788 if (!ecc->read_subpage)
5789 ecc->read_subpage = nand_read_subpage;
5790 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5791 ecc->write_subpage = nand_write_subpage_hwecc;
5794 case NAND_ECC_PLACEMENT_INTERLEAVED:
5795 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5797 ecc->read_page == nand_read_page_hwecc ||
5799 ecc->write_page == nand_write_page_hwecc)) {
5800 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5803 /* Use standard syndrome read/write page function? */
5804 if (!ecc->read_page)
5805 ecc->read_page = nand_read_page_syndrome;
5806 if (!ecc->write_page)
5807 ecc->write_page = nand_write_page_syndrome;
5808 if (!ecc->read_page_raw)
5809 ecc->read_page_raw = nand_read_page_raw_syndrome;
5810 if (!ecc->write_page_raw)
5811 ecc->write_page_raw = nand_write_page_raw_syndrome;
5813 ecc->read_oob = nand_read_oob_syndrome;
5814 if (!ecc->write_oob)
5815 ecc->write_oob = nand_write_oob_syndrome;
5819 pr_warn("Invalid NAND_ECC_PLACEMENT %d\n",
5827 static int nand_set_ecc_soft_ops(struct nand_chip *chip)
5829 struct mtd_info *mtd = nand_to_mtd(chip);
5830 struct nand_device *nanddev = mtd_to_nanddev(mtd);
5831 struct nand_ecc_ctrl *ecc = &chip->ecc;
5834 if (WARN_ON(ecc->engine_type != NAND_ECC_ENGINE_TYPE_SOFT))
5837 switch (ecc->algo) {
5838 case NAND_ECC_ALGO_HAMMING:
5839 ecc->calculate = rawnand_sw_hamming_calculate;
5840 ecc->correct = rawnand_sw_hamming_correct;
5841 ecc->read_page = nand_read_page_swecc;
5842 ecc->read_subpage = nand_read_subpage;
5843 ecc->write_page = nand_write_page_swecc;
5844 if (!ecc->read_page_raw)
5845 ecc->read_page_raw = nand_read_page_raw;
5846 if (!ecc->write_page_raw)
5847 ecc->write_page_raw = nand_write_page_raw;
5848 ecc->read_oob = nand_read_oob_std;
5849 ecc->write_oob = nand_write_oob_std;
5855 if (IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_HAMMING_SMC))
5856 ecc->options |= NAND_ECC_SOFT_HAMMING_SM_ORDER;
5858 ret = rawnand_sw_hamming_init(chip);
5860 WARN(1, "Hamming ECC initialization failed!\n");
5865 case NAND_ECC_ALGO_BCH:
5866 if (!IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_BCH)) {
5867 WARN(1, "CONFIG_MTD_NAND_ECC_SW_BCH not enabled\n");
5870 ecc->calculate = rawnand_sw_bch_calculate;
5871 ecc->correct = rawnand_sw_bch_correct;
5872 ecc->read_page = nand_read_page_swecc;
5873 ecc->read_subpage = nand_read_subpage;
5874 ecc->write_page = nand_write_page_swecc;
5875 if (!ecc->read_page_raw)
5876 ecc->read_page_raw = nand_read_page_raw;
5877 if (!ecc->write_page_raw)
5878 ecc->write_page_raw = nand_write_page_raw;
5879 ecc->read_oob = nand_read_oob_std;
5880 ecc->write_oob = nand_write_oob_std;
5883 * We can only maximize ECC config when the default layout is
5884 * used, otherwise we don't know how many bytes can really be
5887 if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH &&
5888 mtd->ooblayout != nand_get_large_page_ooblayout())
5889 nanddev->ecc.user_conf.flags &= ~NAND_ECC_MAXIMIZE_STRENGTH;
5891 ret = rawnand_sw_bch_init(chip);
5893 WARN(1, "BCH ECC initialization failed!\n");
5899 WARN(1, "Unsupported ECC algorithm!\n");
5905 * nand_check_ecc_caps - check the sanity of preset ECC settings
5906 * @chip: nand chip info structure
5907 * @caps: ECC caps info structure
5908 * @oobavail: OOB size that the ECC engine can use
5910 * When ECC step size and strength are already set, check if they are supported
5911 * by the controller and the calculated ECC bytes fit within the chip's OOB.
5912 * On success, the calculated ECC bytes is set.
5915 nand_check_ecc_caps(struct nand_chip *chip,
5916 const struct nand_ecc_caps *caps, int oobavail)
5918 struct mtd_info *mtd = nand_to_mtd(chip);
5919 const struct nand_ecc_step_info *stepinfo;
5920 int preset_step = chip->ecc.size;
5921 int preset_strength = chip->ecc.strength;
5922 int ecc_bytes, nsteps = mtd->writesize / preset_step;
5925 for (i = 0; i < caps->nstepinfos; i++) {
5926 stepinfo = &caps->stepinfos[i];
5928 if (stepinfo->stepsize != preset_step)
5931 for (j = 0; j < stepinfo->nstrengths; j++) {
5932 if (stepinfo->strengths[j] != preset_strength)
5935 ecc_bytes = caps->calc_ecc_bytes(preset_step,
5937 if (WARN_ON_ONCE(ecc_bytes < 0))
5940 if (ecc_bytes * nsteps > oobavail) {
5941 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
5942 preset_step, preset_strength);
5946 chip->ecc.bytes = ecc_bytes;
5952 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
5953 preset_step, preset_strength);
5959 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
5960 * @chip: nand chip info structure
5961 * @caps: ECC engine caps info structure
5962 * @oobavail: OOB size that the ECC engine can use
5964 * If a chip's ECC requirement is provided, try to meet it with the least
5965 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
5966 * On success, the chosen ECC settings are set.
5969 nand_match_ecc_req(struct nand_chip *chip,
5970 const struct nand_ecc_caps *caps, int oobavail)
5972 const struct nand_ecc_props *requirements =
5973 nanddev_get_ecc_requirements(&chip->base);
5974 struct mtd_info *mtd = nand_to_mtd(chip);
5975 const struct nand_ecc_step_info *stepinfo;
5976 int req_step = requirements->step_size;
5977 int req_strength = requirements->strength;
5978 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
5979 int best_step = 0, best_strength = 0, best_ecc_bytes = 0;
5980 int best_ecc_bytes_total = INT_MAX;
5983 /* No information provided by the NAND chip */
5984 if (!req_step || !req_strength)
5987 /* number of correctable bits the chip requires in a page */
5988 req_corr = mtd->writesize / req_step * req_strength;
5990 for (i = 0; i < caps->nstepinfos; i++) {
5991 stepinfo = &caps->stepinfos[i];
5992 step_size = stepinfo->stepsize;
5994 for (j = 0; j < stepinfo->nstrengths; j++) {
5995 strength = stepinfo->strengths[j];
5998 * If both step size and strength are smaller than the
5999 * chip's requirement, it is not easy to compare the
6000 * resulted reliability.
6002 if (step_size < req_step && strength < req_strength)
6005 if (mtd->writesize % step_size)
6008 nsteps = mtd->writesize / step_size;
6010 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
6011 if (WARN_ON_ONCE(ecc_bytes < 0))
6013 ecc_bytes_total = ecc_bytes * nsteps;
6015 if (ecc_bytes_total > oobavail ||
6016 strength * nsteps < req_corr)
6020 * We assume the best is to meet the chip's requrement
6021 * with the least number of ECC bytes.
6023 if (ecc_bytes_total < best_ecc_bytes_total) {
6024 best_ecc_bytes_total = ecc_bytes_total;
6025 best_step = step_size;
6026 best_strength = strength;
6027 best_ecc_bytes = ecc_bytes;
6032 if (best_ecc_bytes_total == INT_MAX)
6035 chip->ecc.size = best_step;
6036 chip->ecc.strength = best_strength;
6037 chip->ecc.bytes = best_ecc_bytes;
6043 * nand_maximize_ecc - choose the max ECC strength available
6044 * @chip: nand chip info structure
6045 * @caps: ECC engine caps info structure
6046 * @oobavail: OOB size that the ECC engine can use
6048 * Choose the max ECC strength that is supported on the controller, and can fit
6049 * within the chip's OOB. On success, the chosen ECC settings are set.
6052 nand_maximize_ecc(struct nand_chip *chip,
6053 const struct nand_ecc_caps *caps, int oobavail)
6055 struct mtd_info *mtd = nand_to_mtd(chip);
6056 const struct nand_ecc_step_info *stepinfo;
6057 int step_size, strength, nsteps, ecc_bytes, corr;
6060 int best_strength = 0, best_ecc_bytes = 0;
6063 for (i = 0; i < caps->nstepinfos; i++) {
6064 stepinfo = &caps->stepinfos[i];
6065 step_size = stepinfo->stepsize;
6067 /* If chip->ecc.size is already set, respect it */
6068 if (chip->ecc.size && step_size != chip->ecc.size)
6071 for (j = 0; j < stepinfo->nstrengths; j++) {
6072 strength = stepinfo->strengths[j];
6074 if (mtd->writesize % step_size)
6077 nsteps = mtd->writesize / step_size;
6079 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
6080 if (WARN_ON_ONCE(ecc_bytes < 0))
6083 if (ecc_bytes * nsteps > oobavail)
6086 corr = strength * nsteps;
6089 * If the number of correctable bits is the same,
6090 * bigger step_size has more reliability.
6092 if (corr > best_corr ||
6093 (corr == best_corr && step_size > best_step)) {
6095 best_step = step_size;
6096 best_strength = strength;
6097 best_ecc_bytes = ecc_bytes;
6105 chip->ecc.size = best_step;
6106 chip->ecc.strength = best_strength;
6107 chip->ecc.bytes = best_ecc_bytes;
6113 * nand_ecc_choose_conf - Set the ECC strength and ECC step size
6114 * @chip: nand chip info structure
6115 * @caps: ECC engine caps info structure
6116 * @oobavail: OOB size that the ECC engine can use
6118 * Choose the ECC configuration according to following logic.
6120 * 1. If both ECC step size and ECC strength are already set (usually by DT)
6121 * then check if it is supported by this controller.
6122 * 2. If the user provided the nand-ecc-maximize property, then select maximum
6124 * 3. Otherwise, try to match the ECC step size and ECC strength closest
6125 * to the chip's requirement. If available OOB size can't fit the chip
6126 * requirement then fallback to the maximum ECC step size and ECC strength.
6128 * On success, the chosen ECC settings are set.
6130 int nand_ecc_choose_conf(struct nand_chip *chip,
6131 const struct nand_ecc_caps *caps, int oobavail)
6133 struct mtd_info *mtd = nand_to_mtd(chip);
6134 struct nand_device *nanddev = mtd_to_nanddev(mtd);
6136 if (WARN_ON(oobavail < 0 || oobavail > mtd->oobsize))
6139 if (chip->ecc.size && chip->ecc.strength)
6140 return nand_check_ecc_caps(chip, caps, oobavail);
6142 if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH)
6143 return nand_maximize_ecc(chip, caps, oobavail);
6145 if (!nand_match_ecc_req(chip, caps, oobavail))
6148 return nand_maximize_ecc(chip, caps, oobavail);
6150 EXPORT_SYMBOL_GPL(nand_ecc_choose_conf);
6152 static int rawnand_erase(struct nand_device *nand, const struct nand_pos *pos)
6154 struct nand_chip *chip = container_of(nand, struct nand_chip,
6156 unsigned int eb = nanddev_pos_to_row(nand, pos);
6159 eb >>= nand->rowconv.eraseblock_addr_shift;
6161 nand_select_target(chip, pos->target);
6162 ret = nand_erase_op(chip, eb);
6163 nand_deselect_target(chip);
6168 static int rawnand_markbad(struct nand_device *nand,
6169 const struct nand_pos *pos)
6171 struct nand_chip *chip = container_of(nand, struct nand_chip,
6174 return nand_markbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
6177 static bool rawnand_isbad(struct nand_device *nand, const struct nand_pos *pos)
6179 struct nand_chip *chip = container_of(nand, struct nand_chip,
6183 nand_select_target(chip, pos->target);
6184 ret = nand_isbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
6185 nand_deselect_target(chip);
6190 static const struct nand_ops rawnand_ops = {
6191 .erase = rawnand_erase,
6192 .markbad = rawnand_markbad,
6193 .isbad = rawnand_isbad,
6197 * nand_scan_tail - Scan for the NAND device
6198 * @chip: NAND chip object
6200 * This is the second phase of the normal nand_scan() function. It fills out
6201 * all the uninitialized function pointers with the defaults and scans for a
6202 * bad block table if appropriate.
6204 static int nand_scan_tail(struct nand_chip *chip)
6206 struct mtd_info *mtd = nand_to_mtd(chip);
6207 struct nand_ecc_ctrl *ecc = &chip->ecc;
6210 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
6211 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
6212 !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
6216 chip->data_buf = kmalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
6217 if (!chip->data_buf)
6221 * FIXME: some NAND manufacturer drivers expect the first die to be
6222 * selected when manufacturer->init() is called. They should be fixed
6223 * to explictly select the relevant die when interacting with the NAND
6226 nand_select_target(chip, 0);
6227 ret = nand_manufacturer_init(chip);
6228 nand_deselect_target(chip);
6232 /* Set the internal oob buffer location, just after the page data */
6233 chip->oob_poi = chip->data_buf + mtd->writesize;
6236 * If no default placement scheme is given, select an appropriate one.
6238 if (!mtd->ooblayout &&
6239 !(ecc->engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
6240 ecc->algo == NAND_ECC_ALGO_BCH) &&
6241 !(ecc->engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
6242 ecc->algo == NAND_ECC_ALGO_HAMMING)) {
6243 switch (mtd->oobsize) {
6246 mtd_set_ooblayout(mtd, nand_get_small_page_ooblayout());
6250 mtd_set_ooblayout(mtd,
6251 nand_get_large_page_hamming_ooblayout());
6255 * Expose the whole OOB area to users if ECC_NONE
6256 * is passed. We could do that for all kind of
6257 * ->oobsize, but we must keep the old large/small
6258 * page with ECC layout when ->oobsize <= 128 for
6259 * compatibility reasons.
6261 if (ecc->engine_type == NAND_ECC_ENGINE_TYPE_NONE) {
6262 mtd_set_ooblayout(mtd,
6263 nand_get_large_page_ooblayout());
6267 WARN(1, "No oob scheme defined for oobsize %d\n",
6270 goto err_nand_manuf_cleanup;
6275 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
6276 * selected and we have 256 byte pagesize fallback to software ECC
6279 switch (ecc->engine_type) {
6280 case NAND_ECC_ENGINE_TYPE_ON_HOST:
6281 ret = nand_set_ecc_on_host_ops(chip);
6283 goto err_nand_manuf_cleanup;
6285 if (mtd->writesize >= ecc->size) {
6286 if (!ecc->strength) {
6287 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
6289 goto err_nand_manuf_cleanup;
6293 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
6294 ecc->size, mtd->writesize);
6295 ecc->engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
6296 ecc->algo = NAND_ECC_ALGO_HAMMING;
6299 case NAND_ECC_ENGINE_TYPE_SOFT:
6300 ret = nand_set_ecc_soft_ops(chip);
6302 goto err_nand_manuf_cleanup;
6305 case NAND_ECC_ENGINE_TYPE_ON_DIE:
6306 if (!ecc->read_page || !ecc->write_page) {
6307 WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
6309 goto err_nand_manuf_cleanup;
6312 ecc->read_oob = nand_read_oob_std;
6313 if (!ecc->write_oob)
6314 ecc->write_oob = nand_write_oob_std;
6317 case NAND_ECC_ENGINE_TYPE_NONE:
6318 pr_warn("NAND_ECC_ENGINE_TYPE_NONE selected by board driver. This is not recommended!\n");
6319 ecc->read_page = nand_read_page_raw;
6320 ecc->write_page = nand_write_page_raw;
6321 ecc->read_oob = nand_read_oob_std;
6322 ecc->read_page_raw = nand_read_page_raw;
6323 ecc->write_page_raw = nand_write_page_raw;
6324 ecc->write_oob = nand_write_oob_std;
6325 ecc->size = mtd->writesize;
6331 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->engine_type);
6333 goto err_nand_manuf_cleanup;
6336 if (ecc->correct || ecc->calculate) {
6337 ecc->calc_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
6338 ecc->code_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
6339 if (!ecc->calc_buf || !ecc->code_buf) {
6341 goto err_nand_manuf_cleanup;
6345 /* For many systems, the standard OOB write also works for raw */
6346 if (!ecc->read_oob_raw)
6347 ecc->read_oob_raw = ecc->read_oob;
6348 if (!ecc->write_oob_raw)
6349 ecc->write_oob_raw = ecc->write_oob;
6351 /* propagate ecc info to mtd_info */
6352 mtd->ecc_strength = ecc->strength;
6353 mtd->ecc_step_size = ecc->size;
6356 * Set the number of read / write steps for one page depending on ECC
6360 ecc->steps = mtd->writesize / ecc->size;
6361 if (ecc->steps * ecc->size != mtd->writesize) {
6362 WARN(1, "Invalid ECC parameters\n");
6364 goto err_nand_manuf_cleanup;
6368 ecc->total = ecc->steps * ecc->bytes;
6369 chip->base.ecc.ctx.total = ecc->total;
6372 if (ecc->total > mtd->oobsize) {
6373 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
6375 goto err_nand_manuf_cleanup;
6379 * The number of bytes available for a client to place data into
6380 * the out of band area.
6382 ret = mtd_ooblayout_count_freebytes(mtd);
6386 mtd->oobavail = ret;
6388 /* ECC sanity check: warn if it's too weak */
6389 if (!nand_ecc_is_strong_enough(&chip->base))
6390 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",
6391 mtd->name, chip->ecc.strength, chip->ecc.size,
6392 nanddev_get_ecc_requirements(&chip->base)->strength,
6393 nanddev_get_ecc_requirements(&chip->base)->step_size);
6395 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
6396 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
6397 switch (ecc->steps) {
6399 mtd->subpage_sft = 1;
6404 mtd->subpage_sft = 2;
6408 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
6410 /* Invalidate the pagebuffer reference */
6411 chip->pagecache.page = -1;
6413 /* Large page NAND with SOFT_ECC should support subpage reads */
6414 switch (ecc->engine_type) {
6415 case NAND_ECC_ENGINE_TYPE_SOFT:
6416 if (chip->page_shift > 9)
6417 chip->options |= NAND_SUBPAGE_READ;
6424 ret = nanddev_init(&chip->base, &rawnand_ops, mtd->owner);
6426 goto err_nand_manuf_cleanup;
6428 /* Adjust the MTD_CAP_ flags when NAND_ROM is set. */
6429 if (chip->options & NAND_ROM)
6430 mtd->flags = MTD_CAP_ROM;
6432 /* Fill in remaining MTD driver data */
6433 mtd->_erase = nand_erase;
6435 mtd->_unpoint = NULL;
6436 mtd->_panic_write = panic_nand_write;
6437 mtd->_read_oob = nand_read_oob;
6438 mtd->_write_oob = nand_write_oob;
6439 mtd->_sync = nand_sync;
6440 mtd->_lock = nand_lock;
6441 mtd->_unlock = nand_unlock;
6442 mtd->_suspend = nand_suspend;
6443 mtd->_resume = nand_resume;
6444 mtd->_reboot = nand_shutdown;
6445 mtd->_block_isreserved = nand_block_isreserved;
6446 mtd->_block_isbad = nand_block_isbad;
6447 mtd->_block_markbad = nand_block_markbad;
6448 mtd->_max_bad_blocks = nanddev_mtd_max_bad_blocks;
6451 * Initialize bitflip_threshold to its default prior scan_bbt() call.
6452 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
6455 if (!mtd->bitflip_threshold)
6456 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
6458 /* Find the fastest data interface for this chip */
6459 ret = nand_choose_interface_config(chip);
6461 goto err_nanddev_cleanup;
6463 /* Enter fastest possible mode on all dies. */
6464 for (i = 0; i < nanddev_ntargets(&chip->base); i++) {
6465 ret = nand_setup_interface(chip, i);
6467 goto err_free_interface_config;
6470 rawnand_late_check_supported_ops(chip);
6473 * Look for secure regions in the NAND chip. These regions are supposed
6474 * to be protected by a secure element like Trustzone. So the read/write
6475 * accesses to these regions will be blocked in the runtime by this
6478 ret = of_get_nand_secure_regions(chip);
6480 goto err_free_interface_config;
6482 /* Check, if we should skip the bad block table scan */
6483 if (chip->options & NAND_SKIP_BBTSCAN)
6486 /* Build bad block table */
6487 ret = nand_create_bbt(chip);
6489 goto err_free_secure_regions;
6493 err_free_secure_regions:
6494 kfree(chip->secure_regions);
6496 err_free_interface_config:
6497 kfree(chip->best_interface_config);
6499 err_nanddev_cleanup:
6500 nanddev_cleanup(&chip->base);
6502 err_nand_manuf_cleanup:
6503 nand_manufacturer_cleanup(chip);
6506 kfree(chip->data_buf);
6507 kfree(ecc->code_buf);
6508 kfree(ecc->calc_buf);
6513 static int nand_attach(struct nand_chip *chip)
6515 if (chip->controller->ops && chip->controller->ops->attach_chip)
6516 return chip->controller->ops->attach_chip(chip);
6521 static void nand_detach(struct nand_chip *chip)
6523 if (chip->controller->ops && chip->controller->ops->detach_chip)
6524 chip->controller->ops->detach_chip(chip);
6528 * nand_scan_with_ids - [NAND Interface] Scan for the NAND device
6529 * @chip: NAND chip object
6530 * @maxchips: number of chips to scan for.
6531 * @ids: optional flash IDs table
6533 * This fills out all the uninitialized function pointers with the defaults.
6534 * The flash ID is read and the mtd/chip structures are filled with the
6535 * appropriate values.
6537 int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips,
6538 struct nand_flash_dev *ids)
6545 ret = nand_scan_ident(chip, maxchips, ids);
6549 ret = nand_attach(chip);
6553 ret = nand_scan_tail(chip);
6562 nand_scan_ident_cleanup(chip);
6566 EXPORT_SYMBOL(nand_scan_with_ids);
6569 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
6570 * @chip: NAND chip object
6572 void nand_cleanup(struct nand_chip *chip)
6574 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_SOFT) {
6575 if (chip->ecc.algo == NAND_ECC_ALGO_HAMMING)
6576 rawnand_sw_hamming_cleanup(chip);
6577 else if (chip->ecc.algo == NAND_ECC_ALGO_BCH)
6578 rawnand_sw_bch_cleanup(chip);
6581 nanddev_cleanup(&chip->base);
6583 /* Free secure regions data */
6584 kfree(chip->secure_regions);
6586 /* Free bad block table memory */
6588 kfree(chip->data_buf);
6589 kfree(chip->ecc.code_buf);
6590 kfree(chip->ecc.calc_buf);
6592 /* Free bad block descriptor memory */
6593 if (chip->badblock_pattern && chip->badblock_pattern->options
6594 & NAND_BBT_DYNAMICSTRUCT)
6595 kfree(chip->badblock_pattern);
6597 /* Free the data interface */
6598 kfree(chip->best_interface_config);
6600 /* Free manufacturer priv data. */
6601 nand_manufacturer_cleanup(chip);
6603 /* Free controller specific allocations after chip identification */
6606 /* Free identification phase allocations */
6607 nand_scan_ident_cleanup(chip);
6610 EXPORT_SYMBOL_GPL(nand_cleanup);
6612 MODULE_LICENSE("GPL");
6615 MODULE_DESCRIPTION("Generic NAND flash driver code");