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 /* controller responsible for NAND write protect */
370 if (chip->controller->controller_wp)
373 /* Check the WP bit */
374 ret = nand_status_op(chip, &status);
378 return status & NAND_STATUS_WP ? 0 : 1;
382 * nand_fill_oob - [INTERN] Transfer client buffer to oob
383 * @chip: NAND chip object
384 * @oob: oob data buffer
385 * @len: oob data write length
386 * @ops: oob ops structure
388 static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len,
389 struct mtd_oob_ops *ops)
391 struct mtd_info *mtd = nand_to_mtd(chip);
395 * Initialise to all 0xFF, to avoid the possibility of left over OOB
396 * data from a previous OOB read.
398 memset(chip->oob_poi, 0xff, mtd->oobsize);
402 case MTD_OPS_PLACE_OOB:
404 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
407 case MTD_OPS_AUTO_OOB:
408 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
420 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
421 * @chip: NAND chip object
422 * @to: offset to write to
423 * @ops: oob operation description structure
425 * NAND write out-of-band.
427 static int nand_do_write_oob(struct nand_chip *chip, loff_t to,
428 struct mtd_oob_ops *ops)
430 struct mtd_info *mtd = nand_to_mtd(chip);
431 int chipnr, page, status, len, ret;
433 pr_debug("%s: to = 0x%08x, len = %i\n",
434 __func__, (unsigned int)to, (int)ops->ooblen);
436 len = mtd_oobavail(mtd, ops);
438 /* Do not allow write past end of page */
439 if ((ops->ooboffs + ops->ooblen) > len) {
440 pr_debug("%s: attempt to write past end of page\n",
445 /* Check if the region is secured */
446 if (nand_region_is_secured(chip, to, ops->ooblen))
449 chipnr = (int)(to >> chip->chip_shift);
452 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
453 * of my DiskOnChip 2000 test units) will clear the whole data page too
454 * if we don't do this. I have no clue why, but I seem to have 'fixed'
455 * it in the doc2000 driver in August 1999. dwmw2.
457 ret = nand_reset(chip, chipnr);
461 nand_select_target(chip, chipnr);
463 /* Shift to get page */
464 page = (int)(to >> chip->page_shift);
466 /* Check, if it is write protected */
467 if (nand_check_wp(chip)) {
468 nand_deselect_target(chip);
472 /* Invalidate the page cache, if we write to the cached page */
473 if (page == chip->pagecache.page)
474 chip->pagecache.page = -1;
476 nand_fill_oob(chip, ops->oobbuf, ops->ooblen, ops);
478 if (ops->mode == MTD_OPS_RAW)
479 status = chip->ecc.write_oob_raw(chip, page & chip->pagemask);
481 status = chip->ecc.write_oob(chip, page & chip->pagemask);
483 nand_deselect_target(chip);
488 ops->oobretlen = ops->ooblen;
494 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
495 * @chip: NAND chip object
496 * @ofs: offset from device start
498 * This is the default implementation, which can be overridden by a hardware
499 * specific driver. It provides the details for writing a bad block marker to a
502 static int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
504 struct mtd_info *mtd = nand_to_mtd(chip);
505 struct mtd_oob_ops ops;
506 uint8_t buf[2] = { 0, 0 };
507 int ret = 0, res, page_offset;
509 memset(&ops, 0, sizeof(ops));
511 ops.ooboffs = chip->badblockpos;
512 if (chip->options & NAND_BUSWIDTH_16) {
513 ops.ooboffs &= ~0x01;
514 ops.len = ops.ooblen = 2;
516 ops.len = ops.ooblen = 1;
518 ops.mode = MTD_OPS_PLACE_OOB;
520 page_offset = nand_bbm_get_next_page(chip, 0);
522 while (page_offset >= 0) {
523 res = nand_do_write_oob(chip,
524 ofs + (page_offset * mtd->writesize),
530 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
537 * nand_markbad_bbm - mark a block by updating the BBM
538 * @chip: NAND chip object
539 * @ofs: offset of the block to mark bad
541 int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
543 if (chip->legacy.block_markbad)
544 return chip->legacy.block_markbad(chip, ofs);
546 return nand_default_block_markbad(chip, ofs);
550 * nand_block_markbad_lowlevel - mark a block bad
551 * @chip: NAND chip object
552 * @ofs: offset from device start
554 * This function performs the generic NAND bad block marking steps (i.e., bad
555 * block table(s) and/or marker(s)). We only allow the hardware driver to
556 * specify how to write bad block markers to OOB (chip->legacy.block_markbad).
558 * We try operations in the following order:
560 * (1) erase the affected block, to allow OOB marker to be written cleanly
561 * (2) write bad block marker to OOB area of affected block (unless flag
562 * NAND_BBT_NO_OOB_BBM is present)
565 * Note that we retain the first error encountered in (2) or (3), finish the
566 * procedures, and dump the error in the end.
568 static int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
570 struct mtd_info *mtd = nand_to_mtd(chip);
573 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
574 struct erase_info einfo;
576 /* Attempt erase before marking OOB */
577 memset(&einfo, 0, sizeof(einfo));
579 einfo.len = 1ULL << chip->phys_erase_shift;
580 nand_erase_nand(chip, &einfo, 0);
582 /* Write bad block marker to OOB */
583 nand_get_device(chip);
585 ret = nand_markbad_bbm(chip, ofs);
586 nand_release_device(chip);
589 /* Mark block bad in BBT */
591 res = nand_markbad_bbt(chip, ofs);
597 mtd->ecc_stats.badblocks++;
603 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
604 * @mtd: MTD device structure
605 * @ofs: offset from device start
607 * Check if the block is marked as reserved.
609 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
611 struct nand_chip *chip = mtd_to_nand(mtd);
615 /* Return info from the table */
616 return nand_isreserved_bbt(chip, ofs);
620 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
621 * @chip: NAND chip object
622 * @ofs: offset from device start
623 * @allowbbt: 1, if its allowed to access the bbt area
625 * Check, if the block is bad. Either by reading the bad block table or
626 * calling of the scan function.
628 static int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
630 /* Return info from the table */
632 return nand_isbad_bbt(chip, ofs, allowbbt);
634 return nand_isbad_bbm(chip, ofs);
638 * nand_soft_waitrdy - Poll STATUS reg until RDY bit is set to 1
639 * @chip: NAND chip structure
640 * @timeout_ms: Timeout in ms
642 * Poll the STATUS register using ->exec_op() until the RDY bit becomes 1.
643 * If that does not happen whitin the specified timeout, -ETIMEDOUT is
646 * This helper is intended to be used when the controller does not have access
647 * to the NAND R/B pin.
649 * Be aware that calling this helper from an ->exec_op() implementation means
650 * ->exec_op() must be re-entrant.
652 * Return 0 if the NAND chip is ready, a negative error otherwise.
654 int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
656 const struct nand_interface_config *conf;
660 if (!nand_has_exec_op(chip))
663 /* Wait tWB before polling the STATUS reg. */
664 conf = nand_get_interface_config(chip);
665 ndelay(NAND_COMMON_TIMING_NS(conf, tWB_max));
667 ret = nand_status_op(chip, NULL);
672 * +1 below is necessary because if we are now in the last fraction
673 * of jiffy and msecs_to_jiffies is 1 then we will wait only that
674 * small jiffy fraction - possibly leading to false timeout
676 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
678 ret = nand_read_data_op(chip, &status, sizeof(status), true,
683 if (status & NAND_STATUS_READY)
687 * Typical lowest execution time for a tR on most NANDs is 10us,
688 * use this as polling delay before doing something smarter (ie.
689 * deriving a delay from the timeout value, timeout_ms/ratio).
692 } while (time_before(jiffies, timeout_ms));
695 * We have to exit READ_STATUS mode in order to read real data on the
696 * bus in case the WAITRDY instruction is preceding a DATA_IN
699 nand_exit_status_op(chip);
704 return status & NAND_STATUS_READY ? 0 : -ETIMEDOUT;
706 EXPORT_SYMBOL_GPL(nand_soft_waitrdy);
709 * nand_gpio_waitrdy - Poll R/B GPIO pin until ready
710 * @chip: NAND chip structure
711 * @gpiod: GPIO descriptor of R/B pin
712 * @timeout_ms: Timeout in ms
714 * Poll the R/B GPIO pin until it becomes ready. If that does not happen
715 * whitin the specified timeout, -ETIMEDOUT is returned.
717 * This helper is intended to be used when the controller has access to the
718 * NAND R/B pin over GPIO.
720 * Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.
722 int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
723 unsigned long timeout_ms)
727 * Wait until R/B pin indicates chip is ready or timeout occurs.
728 * +1 below is necessary because if we are now in the last fraction
729 * of jiffy and msecs_to_jiffies is 1 then we will wait only that
730 * small jiffy fraction - possibly leading to false timeout.
732 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
734 if (gpiod_get_value_cansleep(gpiod))
738 } while (time_before(jiffies, timeout_ms));
740 return gpiod_get_value_cansleep(gpiod) ? 0 : -ETIMEDOUT;
742 EXPORT_SYMBOL_GPL(nand_gpio_waitrdy);
745 * panic_nand_wait - [GENERIC] wait until the command is done
746 * @chip: NAND chip structure
749 * Wait for command done. This is a helper function for nand_wait used when
750 * we are in interrupt context. May happen when in panic and trying to write
751 * an oops through mtdoops.
753 void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
756 for (i = 0; i < timeo; i++) {
757 if (chip->legacy.dev_ready) {
758 if (chip->legacy.dev_ready(chip))
764 ret = nand_read_data_op(chip, &status, sizeof(status),
769 if (status & NAND_STATUS_READY)
776 static bool nand_supports_get_features(struct nand_chip *chip, int addr)
778 return (chip->parameters.supports_set_get_features &&
779 test_bit(addr, chip->parameters.get_feature_list));
782 static bool nand_supports_set_features(struct nand_chip *chip, int addr)
784 return (chip->parameters.supports_set_get_features &&
785 test_bit(addr, chip->parameters.set_feature_list));
789 * nand_reset_interface - Reset data interface and timings
790 * @chip: The NAND chip
791 * @chipnr: Internal die id
793 * Reset the Data interface and timings to ONFI mode 0.
795 * Returns 0 for success or negative error code otherwise.
797 static int nand_reset_interface(struct nand_chip *chip, int chipnr)
799 const struct nand_controller_ops *ops = chip->controller->ops;
802 if (!nand_controller_can_setup_interface(chip))
806 * The ONFI specification says:
808 * To transition from NV-DDR or NV-DDR2 to the SDR data
809 * interface, the host shall use the Reset (FFh) command
810 * using SDR timing mode 0. A device in any timing mode is
811 * required to recognize Reset (FFh) command issued in SDR
815 * Configure the data interface in SDR mode and set the
816 * timings to timing mode 0.
819 chip->current_interface_config = nand_get_reset_interface_config();
820 ret = ops->setup_interface(chip, chipnr,
821 chip->current_interface_config);
823 pr_err("Failed to configure data interface to SDR timing mode 0\n");
829 * nand_setup_interface - Setup the best data interface and timings
830 * @chip: The NAND chip
831 * @chipnr: Internal die id
833 * Configure what has been reported to be the best data interface and NAND
834 * timings supported by the chip and the driver.
836 * Returns 0 for success or negative error code otherwise.
838 static int nand_setup_interface(struct nand_chip *chip, int chipnr)
840 const struct nand_controller_ops *ops = chip->controller->ops;
841 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = { }, request;
844 if (!nand_controller_can_setup_interface(chip))
848 * A nand_reset_interface() put both the NAND chip and the NAND
849 * controller in timings mode 0. If the default mode for this chip is
850 * also 0, no need to proceed to the change again. Plus, at probe time,
851 * nand_setup_interface() uses ->set/get_features() which would
852 * fail anyway as the parameter page is not available yet.
854 if (!chip->best_interface_config)
857 request = chip->best_interface_config->timings.mode;
858 if (nand_interface_is_sdr(chip->best_interface_config))
859 request |= ONFI_DATA_INTERFACE_SDR;
861 request |= ONFI_DATA_INTERFACE_NVDDR;
862 tmode_param[0] = request;
864 /* Change the mode on the chip side (if supported by the NAND chip) */
865 if (nand_supports_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE)) {
866 nand_select_target(chip, chipnr);
867 ret = nand_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
869 nand_deselect_target(chip);
874 /* Change the mode on the controller side */
875 ret = ops->setup_interface(chip, chipnr, chip->best_interface_config);
879 /* Check the mode has been accepted by the chip, if supported */
880 if (!nand_supports_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE))
881 goto update_interface_config;
883 memset(tmode_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
884 nand_select_target(chip, chipnr);
885 ret = nand_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
887 nand_deselect_target(chip);
891 if (request != tmode_param[0]) {
892 pr_warn("%s timing mode %d not acknowledged by the NAND chip\n",
893 nand_interface_is_nvddr(chip->best_interface_config) ? "NV-DDR" : "SDR",
894 chip->best_interface_config->timings.mode);
895 pr_debug("NAND chip would work in %s timing mode %d\n",
896 tmode_param[0] & ONFI_DATA_INTERFACE_NVDDR ? "NV-DDR" : "SDR",
897 (unsigned int)ONFI_TIMING_MODE_PARAM(tmode_param[0]));
901 update_interface_config:
902 chip->current_interface_config = chip->best_interface_config;
908 * Fallback to mode 0 if the chip explicitly did not ack the chosen
911 nand_reset_interface(chip, chipnr);
912 nand_select_target(chip, chipnr);
914 nand_deselect_target(chip);
920 * nand_choose_best_sdr_timings - Pick up the best SDR timings that both the
921 * NAND controller and the NAND chip support
922 * @chip: the NAND chip
923 * @iface: the interface configuration (can eventually be updated)
924 * @spec_timings: specific timings, when not fitting the ONFI specification
926 * If specific timings are provided, use them. Otherwise, retrieve supported
927 * timing modes from ONFI information.
929 int nand_choose_best_sdr_timings(struct nand_chip *chip,
930 struct nand_interface_config *iface,
931 struct nand_sdr_timings *spec_timings)
933 const struct nand_controller_ops *ops = chip->controller->ops;
934 int best_mode = 0, mode, ret = -EOPNOTSUPP;
936 iface->type = NAND_SDR_IFACE;
939 iface->timings.sdr = *spec_timings;
940 iface->timings.mode = onfi_find_closest_sdr_mode(spec_timings);
942 /* Verify the controller supports the requested interface */
943 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
946 chip->best_interface_config = iface;
950 /* Fallback to slower modes */
951 best_mode = iface->timings.mode;
952 } else if (chip->parameters.onfi) {
953 best_mode = fls(chip->parameters.onfi->sdr_timing_modes) - 1;
956 for (mode = best_mode; mode >= 0; mode--) {
957 onfi_fill_interface_config(chip, iface, NAND_SDR_IFACE, mode);
959 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
962 chip->best_interface_config = iface;
971 * nand_choose_best_nvddr_timings - Pick up the best NVDDR timings that both the
972 * NAND controller and the NAND chip support
973 * @chip: the NAND chip
974 * @iface: the interface configuration (can eventually be updated)
975 * @spec_timings: specific timings, when not fitting the ONFI specification
977 * If specific timings are provided, use them. Otherwise, retrieve supported
978 * timing modes from ONFI information.
980 int nand_choose_best_nvddr_timings(struct nand_chip *chip,
981 struct nand_interface_config *iface,
982 struct nand_nvddr_timings *spec_timings)
984 const struct nand_controller_ops *ops = chip->controller->ops;
985 int best_mode = 0, mode, ret = -EOPNOTSUPP;
987 iface->type = NAND_NVDDR_IFACE;
990 iface->timings.nvddr = *spec_timings;
991 iface->timings.mode = onfi_find_closest_nvddr_mode(spec_timings);
993 /* Verify the controller supports the requested interface */
994 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
997 chip->best_interface_config = iface;
1001 /* Fallback to slower modes */
1002 best_mode = iface->timings.mode;
1003 } else if (chip->parameters.onfi) {
1004 best_mode = fls(chip->parameters.onfi->nvddr_timing_modes) - 1;
1007 for (mode = best_mode; mode >= 0; mode--) {
1008 onfi_fill_interface_config(chip, iface, NAND_NVDDR_IFACE, mode);
1010 ret = ops->setup_interface(chip, NAND_DATA_IFACE_CHECK_ONLY,
1013 chip->best_interface_config = iface;
1022 * nand_choose_best_timings - Pick up the best NVDDR or SDR timings that both
1023 * NAND controller and the NAND chip support
1024 * @chip: the NAND chip
1025 * @iface: the interface configuration (can eventually be updated)
1027 * If specific timings are provided, use them. Otherwise, retrieve supported
1028 * timing modes from ONFI information.
1030 static int nand_choose_best_timings(struct nand_chip *chip,
1031 struct nand_interface_config *iface)
1035 /* Try the fastest timings: NV-DDR */
1036 ret = nand_choose_best_nvddr_timings(chip, iface, NULL);
1040 /* Fallback to SDR timings otherwise */
1041 return nand_choose_best_sdr_timings(chip, iface, NULL);
1045 * nand_choose_interface_config - find the best data interface and timings
1046 * @chip: The NAND chip
1048 * Find the best data interface and NAND timings supported by the chip
1049 * and the driver. Eventually let the NAND manufacturer driver propose his own
1052 * After this function nand_chip->interface_config is initialized with the best
1053 * timing mode available.
1055 * Returns 0 for success or negative error code otherwise.
1057 static int nand_choose_interface_config(struct nand_chip *chip)
1059 struct nand_interface_config *iface;
1062 if (!nand_controller_can_setup_interface(chip))
1065 iface = kzalloc(sizeof(*iface), GFP_KERNEL);
1069 if (chip->ops.choose_interface_config)
1070 ret = chip->ops.choose_interface_config(chip, iface);
1072 ret = nand_choose_best_timings(chip, iface);
1081 * nand_fill_column_cycles - fill the column cycles of an address
1082 * @chip: The NAND chip
1083 * @addrs: Array of address cycles to fill
1084 * @offset_in_page: The offset in the page
1086 * Fills the first or the first two bytes of the @addrs field depending
1087 * on the NAND bus width and the page size.
1089 * Returns the number of cycles needed to encode the column, or a negative
1090 * error code in case one of the arguments is invalid.
1092 static int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs,
1093 unsigned int offset_in_page)
1095 struct mtd_info *mtd = nand_to_mtd(chip);
1096 bool ident_stage = !mtd->writesize;
1098 /* Bypass all checks during NAND identification */
1099 if (likely(!ident_stage)) {
1100 /* Make sure the offset is less than the actual page size. */
1101 if (offset_in_page > mtd->writesize + mtd->oobsize)
1105 * On small page NANDs, there's a dedicated command to access the OOB
1106 * area, and the column address is relative to the start of the OOB
1107 * area, not the start of the page. Asjust the address accordingly.
1109 if (mtd->writesize <= 512 && offset_in_page >= mtd->writesize)
1110 offset_in_page -= mtd->writesize;
1113 * The offset in page is expressed in bytes, if the NAND bus is 16-bit
1114 * wide, then it must be divided by 2.
1116 if (chip->options & NAND_BUSWIDTH_16) {
1117 if (WARN_ON(offset_in_page % 2))
1120 offset_in_page /= 2;
1124 addrs[0] = offset_in_page;
1127 * Small page NANDs use 1 cycle for the columns, while large page NANDs
1130 if (!ident_stage && mtd->writesize <= 512)
1133 addrs[1] = offset_in_page >> 8;
1138 static int nand_sp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1139 unsigned int offset_in_page, void *buf,
1142 const struct nand_interface_config *conf =
1143 nand_get_interface_config(chip);
1144 struct mtd_info *mtd = nand_to_mtd(chip);
1146 struct nand_op_instr instrs[] = {
1147 NAND_OP_CMD(NAND_CMD_READ0, 0),
1148 NAND_OP_ADDR(3, addrs, NAND_COMMON_TIMING_NS(conf, tWB_max)),
1149 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1150 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1151 NAND_OP_DATA_IN(len, buf, 0),
1153 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1156 /* Drop the DATA_IN instruction if len is set to 0. */
1160 if (offset_in_page >= mtd->writesize)
1161 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1162 else if (offset_in_page >= 256 &&
1163 !(chip->options & NAND_BUSWIDTH_16))
1164 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1166 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1171 addrs[2] = page >> 8;
1173 if (chip->options & NAND_ROW_ADDR_3) {
1174 addrs[3] = page >> 16;
1175 instrs[1].ctx.addr.naddrs++;
1178 return nand_exec_op(chip, &op);
1181 static int nand_lp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1182 unsigned int offset_in_page, void *buf,
1185 const struct nand_interface_config *conf =
1186 nand_get_interface_config(chip);
1188 struct nand_op_instr instrs[] = {
1189 NAND_OP_CMD(NAND_CMD_READ0, 0),
1190 NAND_OP_ADDR(4, addrs, 0),
1191 NAND_OP_CMD(NAND_CMD_READSTART, NAND_COMMON_TIMING_NS(conf, tWB_max)),
1192 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1193 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1194 NAND_OP_DATA_IN(len, buf, 0),
1196 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1199 /* Drop the DATA_IN instruction if len is set to 0. */
1203 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1208 addrs[3] = page >> 8;
1210 if (chip->options & NAND_ROW_ADDR_3) {
1211 addrs[4] = page >> 16;
1212 instrs[1].ctx.addr.naddrs++;
1215 return nand_exec_op(chip, &op);
1218 static unsigned int rawnand_last_page_of_lun(unsigned int pages_per_lun, unsigned int lun)
1220 /* lun is expected to be very small */
1221 return (lun * pages_per_lun) + pages_per_lun - 1;
1224 static void rawnand_cap_cont_reads(struct nand_chip *chip)
1226 struct nand_memory_organization *memorg;
1227 unsigned int ppl, first_lun, last_lun;
1229 memorg = nanddev_get_memorg(&chip->base);
1230 ppl = memorg->pages_per_eraseblock * memorg->eraseblocks_per_lun;
1231 first_lun = chip->cont_read.first_page / ppl;
1232 last_lun = chip->cont_read.last_page / ppl;
1234 /* Prevent sequential cache reads across LUN boundaries */
1235 if (first_lun != last_lun)
1236 chip->cont_read.pause_page = rawnand_last_page_of_lun(ppl, first_lun);
1238 chip->cont_read.pause_page = chip->cont_read.last_page;
1240 if (chip->cont_read.first_page == chip->cont_read.pause_page) {
1241 chip->cont_read.first_page++;
1242 chip->cont_read.pause_page = min(chip->cont_read.last_page,
1243 rawnand_last_page_of_lun(ppl, first_lun + 1));
1246 if (chip->cont_read.first_page >= chip->cont_read.last_page)
1247 chip->cont_read.ongoing = false;
1250 static int nand_lp_exec_cont_read_page_op(struct nand_chip *chip, unsigned int page,
1251 unsigned int offset_in_page, void *buf,
1252 unsigned int len, bool check_only)
1254 const struct nand_interface_config *conf =
1255 nand_get_interface_config(chip);
1257 struct nand_op_instr start_instrs[] = {
1258 NAND_OP_CMD(NAND_CMD_READ0, 0),
1259 NAND_OP_ADDR(4, addrs, 0),
1260 NAND_OP_CMD(NAND_CMD_READSTART, NAND_COMMON_TIMING_NS(conf, tWB_max)),
1261 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max), 0),
1262 NAND_OP_CMD(NAND_CMD_READCACHESEQ, NAND_COMMON_TIMING_NS(conf, tWB_max)),
1263 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1264 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1265 NAND_OP_DATA_IN(len, buf, 0),
1267 struct nand_op_instr cont_instrs[] = {
1268 NAND_OP_CMD(page == chip->cont_read.pause_page ?
1269 NAND_CMD_READCACHEEND : NAND_CMD_READCACHESEQ,
1270 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1271 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1272 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1273 NAND_OP_DATA_IN(len, buf, 0),
1275 struct nand_operation start_op = NAND_OPERATION(chip->cur_cs, start_instrs);
1276 struct nand_operation cont_op = NAND_OPERATION(chip->cur_cs, cont_instrs);
1284 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1289 addrs[3] = page >> 8;
1291 if (chip->options & NAND_ROW_ADDR_3) {
1292 addrs[4] = page >> 16;
1293 start_instrs[1].ctx.addr.naddrs++;
1296 /* Check if cache reads are supported */
1298 if (nand_check_op(chip, &start_op) || nand_check_op(chip, &cont_op))
1304 if (page == chip->cont_read.first_page)
1305 ret = nand_exec_op(chip, &start_op);
1307 ret = nand_exec_op(chip, &cont_op);
1311 if (!chip->cont_read.ongoing)
1314 if (page == chip->cont_read.last_page) {
1315 chip->cont_read.ongoing = false;
1316 } else if (page == chip->cont_read.pause_page) {
1317 chip->cont_read.first_page++;
1318 rawnand_cap_cont_reads(chip);
1324 static bool rawnand_cont_read_ongoing(struct nand_chip *chip, unsigned int page)
1326 return chip->cont_read.ongoing && page >= chip->cont_read.first_page;
1330 * nand_read_page_op - Do a READ PAGE operation
1331 * @chip: The NAND chip
1332 * @page: page to read
1333 * @offset_in_page: offset within the page
1334 * @buf: buffer used to store the data
1335 * @len: length of the buffer
1337 * This function issues a READ PAGE operation.
1338 * This function does not select/unselect the CS line.
1340 * Returns 0 on success, a negative error code otherwise.
1342 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1343 unsigned int offset_in_page, void *buf, unsigned int len)
1345 struct mtd_info *mtd = nand_to_mtd(chip);
1350 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1353 if (nand_has_exec_op(chip)) {
1354 if (mtd->writesize > 512) {
1355 if (rawnand_cont_read_ongoing(chip, page))
1356 return nand_lp_exec_cont_read_page_op(chip, page,
1360 return nand_lp_exec_read_page_op(chip, page,
1361 offset_in_page, buf,
1365 return nand_sp_exec_read_page_op(chip, page, offset_in_page,
1369 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, offset_in_page, page);
1371 chip->legacy.read_buf(chip, buf, len);
1375 EXPORT_SYMBOL_GPL(nand_read_page_op);
1378 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1379 * @chip: The NAND chip
1380 * @page: parameter page to read
1381 * @buf: buffer used to store the data
1382 * @len: length of the buffer
1384 * This function issues a READ PARAMETER PAGE operation.
1385 * This function does not select/unselect the CS line.
1387 * Returns 0 on success, a negative error code otherwise.
1389 int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1398 if (nand_has_exec_op(chip)) {
1399 const struct nand_interface_config *conf =
1400 nand_get_interface_config(chip);
1401 struct nand_op_instr instrs[] = {
1402 NAND_OP_CMD(NAND_CMD_PARAM, 0),
1403 NAND_OP_ADDR(1, &page,
1404 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1405 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tR_max),
1406 NAND_COMMON_TIMING_NS(conf, tRR_min)),
1407 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1409 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1411 /* Drop the DATA_IN instruction if len is set to 0. */
1415 return nand_exec_op(chip, &op);
1418 chip->legacy.cmdfunc(chip, NAND_CMD_PARAM, page, -1);
1419 for (i = 0; i < len; i++)
1420 p[i] = chip->legacy.read_byte(chip);
1426 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1427 * @chip: The NAND chip
1428 * @offset_in_page: offset within the page
1429 * @buf: buffer used to store the data
1430 * @len: length of the buffer
1431 * @force_8bit: force 8-bit bus access
1433 * This function issues a CHANGE READ COLUMN operation.
1434 * This function does not select/unselect the CS line.
1436 * Returns 0 on success, a negative error code otherwise.
1438 int nand_change_read_column_op(struct nand_chip *chip,
1439 unsigned int offset_in_page, void *buf,
1440 unsigned int len, bool force_8bit)
1442 struct mtd_info *mtd = nand_to_mtd(chip);
1443 bool ident_stage = !mtd->writesize;
1449 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1452 /* Small page NANDs do not support column change. */
1453 if (mtd->writesize <= 512)
1457 if (nand_has_exec_op(chip)) {
1458 const struct nand_interface_config *conf =
1459 nand_get_interface_config(chip);
1461 struct nand_op_instr instrs[] = {
1462 NAND_OP_CMD(NAND_CMD_RNDOUT, 0),
1463 NAND_OP_ADDR(2, addrs, 0),
1464 NAND_OP_CMD(NAND_CMD_RNDOUTSTART,
1465 NAND_COMMON_TIMING_NS(conf, tCCS_min)),
1466 NAND_OP_DATA_IN(len, buf, 0),
1468 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1471 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1475 /* Drop the DATA_IN instruction if len is set to 0. */
1479 instrs[3].ctx.data.force_8bit = force_8bit;
1481 return nand_exec_op(chip, &op);
1484 chip->legacy.cmdfunc(chip, NAND_CMD_RNDOUT, offset_in_page, -1);
1486 chip->legacy.read_buf(chip, buf, len);
1490 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1493 * nand_read_oob_op - Do a READ OOB operation
1494 * @chip: The NAND chip
1495 * @page: page to read
1496 * @offset_in_oob: offset within the OOB area
1497 * @buf: buffer used to store the data
1498 * @len: length of the buffer
1500 * This function issues a READ OOB operation.
1501 * This function does not select/unselect the CS line.
1503 * Returns 0 on success, a negative error code otherwise.
1505 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1506 unsigned int offset_in_oob, void *buf, unsigned int len)
1508 struct mtd_info *mtd = nand_to_mtd(chip);
1513 if (offset_in_oob + len > mtd->oobsize)
1516 if (nand_has_exec_op(chip))
1517 return nand_read_page_op(chip, page,
1518 mtd->writesize + offset_in_oob,
1521 chip->legacy.cmdfunc(chip, NAND_CMD_READOOB, offset_in_oob, page);
1523 chip->legacy.read_buf(chip, buf, len);
1527 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1529 static int nand_exec_prog_page_op(struct nand_chip *chip, unsigned int page,
1530 unsigned int offset_in_page, const void *buf,
1531 unsigned int len, bool prog)
1533 const struct nand_interface_config *conf =
1534 nand_get_interface_config(chip);
1535 struct mtd_info *mtd = nand_to_mtd(chip);
1537 struct nand_op_instr instrs[] = {
1539 * The first instruction will be dropped if we're dealing
1540 * with a large page NAND and adjusted if we're dealing
1541 * with a small page NAND and the page offset is > 255.
1543 NAND_OP_CMD(NAND_CMD_READ0, 0),
1544 NAND_OP_CMD(NAND_CMD_SEQIN, 0),
1545 NAND_OP_ADDR(0, addrs, NAND_COMMON_TIMING_NS(conf, tADL_min)),
1546 NAND_OP_DATA_OUT(len, buf, 0),
1547 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1548 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1549 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tPROG_max), 0),
1551 struct nand_operation op = NAND_DESTRUCTIVE_OPERATION(chip->cur_cs,
1553 int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
1558 addrs[naddrs++] = page;
1559 addrs[naddrs++] = page >> 8;
1560 if (chip->options & NAND_ROW_ADDR_3)
1561 addrs[naddrs++] = page >> 16;
1563 instrs[2].ctx.addr.naddrs = naddrs;
1565 /* Drop the last two instructions if we're not programming the page. */
1568 /* Also drop the DATA_OUT instruction if empty. */
1573 if (mtd->writesize <= 512) {
1575 * Small pages need some more tweaking: we have to adjust the
1576 * first instruction depending on the page offset we're trying
1579 if (offset_in_page >= mtd->writesize)
1580 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1581 else if (offset_in_page >= 256 &&
1582 !(chip->options & NAND_BUSWIDTH_16))
1583 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1586 * Drop the first command if we're dealing with a large page
1593 return nand_exec_op(chip, &op);
1597 * nand_prog_page_begin_op - starts a PROG PAGE operation
1598 * @chip: The NAND chip
1599 * @page: page to write
1600 * @offset_in_page: offset within the page
1601 * @buf: buffer containing the data to write to the page
1602 * @len: length of the buffer
1604 * This function issues the first half of a PROG PAGE operation.
1605 * This function does not select/unselect the CS line.
1607 * Returns 0 on success, a negative error code otherwise.
1609 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1610 unsigned int offset_in_page, const void *buf,
1613 struct mtd_info *mtd = nand_to_mtd(chip);
1618 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1621 if (nand_has_exec_op(chip))
1622 return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1625 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page, page);
1628 chip->legacy.write_buf(chip, buf, len);
1632 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1635 * nand_prog_page_end_op - ends a PROG PAGE operation
1636 * @chip: The NAND chip
1638 * This function issues the second half of a PROG PAGE operation.
1639 * This function does not select/unselect the CS line.
1641 * Returns 0 on success, a negative error code otherwise.
1643 int nand_prog_page_end_op(struct nand_chip *chip)
1648 if (nand_has_exec_op(chip)) {
1649 const struct nand_interface_config *conf =
1650 nand_get_interface_config(chip);
1651 struct nand_op_instr instrs[] = {
1652 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1653 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1654 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tPROG_max),
1657 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1659 ret = nand_exec_op(chip, &op);
1663 ret = nand_status_op(chip, &status);
1667 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1668 ret = chip->legacy.waitfunc(chip);
1675 if (status & NAND_STATUS_FAIL)
1680 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1683 * nand_prog_page_op - Do a full PROG PAGE operation
1684 * @chip: The NAND chip
1685 * @page: page to write
1686 * @offset_in_page: offset within the page
1687 * @buf: buffer containing the data to write to the page
1688 * @len: length of the buffer
1690 * This function issues a full PROG PAGE operation.
1691 * This function does not select/unselect the CS line.
1693 * Returns 0 on success, a negative error code otherwise.
1695 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1696 unsigned int offset_in_page, const void *buf,
1699 struct mtd_info *mtd = nand_to_mtd(chip);
1706 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1709 if (nand_has_exec_op(chip)) {
1710 ret = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1715 ret = nand_status_op(chip, &status);
1719 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page,
1721 chip->legacy.write_buf(chip, buf, len);
1722 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1723 ret = chip->legacy.waitfunc(chip);
1730 if (status & NAND_STATUS_FAIL)
1735 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1738 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1739 * @chip: The NAND chip
1740 * @offset_in_page: offset within the page
1741 * @buf: buffer containing the data to send to the NAND
1742 * @len: length of the buffer
1743 * @force_8bit: force 8-bit bus access
1745 * This function issues a CHANGE WRITE COLUMN operation.
1746 * This function does not select/unselect the CS line.
1748 * Returns 0 on success, a negative error code otherwise.
1750 int nand_change_write_column_op(struct nand_chip *chip,
1751 unsigned int offset_in_page,
1752 const void *buf, unsigned int len,
1755 struct mtd_info *mtd = nand_to_mtd(chip);
1760 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1763 /* Small page NANDs do not support column change. */
1764 if (mtd->writesize <= 512)
1767 if (nand_has_exec_op(chip)) {
1768 const struct nand_interface_config *conf =
1769 nand_get_interface_config(chip);
1771 struct nand_op_instr instrs[] = {
1772 NAND_OP_CMD(NAND_CMD_RNDIN, 0),
1773 NAND_OP_ADDR(2, addrs, NAND_COMMON_TIMING_NS(conf, tCCS_min)),
1774 NAND_OP_DATA_OUT(len, buf, 0),
1776 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1779 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1783 instrs[2].ctx.data.force_8bit = force_8bit;
1785 /* Drop the DATA_OUT instruction if len is set to 0. */
1789 return nand_exec_op(chip, &op);
1792 chip->legacy.cmdfunc(chip, NAND_CMD_RNDIN, offset_in_page, -1);
1794 chip->legacy.write_buf(chip, buf, len);
1798 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1801 * nand_readid_op - Do a READID operation
1802 * @chip: The NAND chip
1803 * @addr: address cycle to pass after the READID command
1804 * @buf: buffer used to store the ID
1805 * @len: length of the buffer
1807 * This function sends a READID command and reads back the ID returned by the
1809 * This function does not select/unselect the CS line.
1811 * Returns 0 on success, a negative error code otherwise.
1813 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1817 u8 *id = buf, *ddrbuf = NULL;
1822 if (nand_has_exec_op(chip)) {
1823 const struct nand_interface_config *conf =
1824 nand_get_interface_config(chip);
1825 struct nand_op_instr instrs[] = {
1826 NAND_OP_CMD(NAND_CMD_READID, 0),
1827 NAND_OP_ADDR(1, &addr,
1828 NAND_COMMON_TIMING_NS(conf, tADL_min)),
1829 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1831 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1834 /* READ_ID data bytes are received twice in NV-DDR mode */
1835 if (len && nand_interface_is_nvddr(conf)) {
1836 ddrbuf = kzalloc(len * 2, GFP_KERNEL);
1840 instrs[2].ctx.data.len *= 2;
1841 instrs[2].ctx.data.buf.in = ddrbuf;
1844 /* Drop the DATA_IN instruction if len is set to 0. */
1848 ret = nand_exec_op(chip, &op);
1849 if (!ret && len && nand_interface_is_nvddr(conf)) {
1850 for (i = 0; i < len; i++)
1851 id[i] = ddrbuf[i * 2];
1859 chip->legacy.cmdfunc(chip, NAND_CMD_READID, addr, -1);
1861 for (i = 0; i < len; i++)
1862 id[i] = chip->legacy.read_byte(chip);
1866 EXPORT_SYMBOL_GPL(nand_readid_op);
1869 * nand_status_op - Do a STATUS operation
1870 * @chip: The NAND chip
1871 * @status: out variable to store the NAND status
1873 * This function sends a STATUS command and reads back the status returned by
1875 * This function does not select/unselect the CS line.
1877 * Returns 0 on success, a negative error code otherwise.
1879 int nand_status_op(struct nand_chip *chip, u8 *status)
1881 if (nand_has_exec_op(chip)) {
1882 const struct nand_interface_config *conf =
1883 nand_get_interface_config(chip);
1885 struct nand_op_instr instrs[] = {
1886 NAND_OP_CMD(NAND_CMD_STATUS,
1887 NAND_COMMON_TIMING_NS(conf, tADL_min)),
1888 NAND_OP_8BIT_DATA_IN(1, status, 0),
1890 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1893 /* The status data byte will be received twice in NV-DDR mode */
1894 if (status && nand_interface_is_nvddr(conf)) {
1895 instrs[1].ctx.data.len *= 2;
1896 instrs[1].ctx.data.buf.in = ddrstatus;
1902 ret = nand_exec_op(chip, &op);
1903 if (!ret && status && nand_interface_is_nvddr(conf))
1904 *status = ddrstatus[0];
1909 chip->legacy.cmdfunc(chip, NAND_CMD_STATUS, -1, -1);
1911 *status = chip->legacy.read_byte(chip);
1915 EXPORT_SYMBOL_GPL(nand_status_op);
1918 * nand_exit_status_op - Exit a STATUS operation
1919 * @chip: The NAND chip
1921 * This function sends a READ0 command to cancel the effect of the STATUS
1922 * command to avoid reading only the status until a new read command is sent.
1924 * This function does not select/unselect the CS line.
1926 * Returns 0 on success, a negative error code otherwise.
1928 int nand_exit_status_op(struct nand_chip *chip)
1930 if (nand_has_exec_op(chip)) {
1931 struct nand_op_instr instrs[] = {
1932 NAND_OP_CMD(NAND_CMD_READ0, 0),
1934 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1936 return nand_exec_op(chip, &op);
1939 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, -1, -1);
1943 EXPORT_SYMBOL_GPL(nand_exit_status_op);
1946 * nand_erase_op - Do an erase operation
1947 * @chip: The NAND chip
1948 * @eraseblock: block to erase
1950 * This function sends an ERASE command and waits for the NAND to be ready
1952 * This function does not select/unselect the CS line.
1954 * Returns 0 on success, a negative error code otherwise.
1956 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1958 unsigned int page = eraseblock <<
1959 (chip->phys_erase_shift - chip->page_shift);
1963 if (nand_has_exec_op(chip)) {
1964 const struct nand_interface_config *conf =
1965 nand_get_interface_config(chip);
1966 u8 addrs[3] = { page, page >> 8, page >> 16 };
1967 struct nand_op_instr instrs[] = {
1968 NAND_OP_CMD(NAND_CMD_ERASE1, 0),
1969 NAND_OP_ADDR(2, addrs, 0),
1970 NAND_OP_CMD(NAND_CMD_ERASE2,
1971 NAND_COMMON_TIMING_NS(conf, tWB_max)),
1972 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tBERS_max),
1975 struct nand_operation op = NAND_DESTRUCTIVE_OPERATION(chip->cur_cs,
1978 if (chip->options & NAND_ROW_ADDR_3)
1979 instrs[1].ctx.addr.naddrs++;
1981 ret = nand_exec_op(chip, &op);
1985 ret = nand_status_op(chip, &status);
1989 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE1, -1, page);
1990 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE2, -1, -1);
1992 ret = chip->legacy.waitfunc(chip);
1999 if (status & NAND_STATUS_FAIL)
2004 EXPORT_SYMBOL_GPL(nand_erase_op);
2007 * nand_set_features_op - Do a SET FEATURES operation
2008 * @chip: The NAND chip
2009 * @feature: feature id
2010 * @data: 4 bytes of data
2012 * This function sends a SET FEATURES command and waits for the NAND to be
2013 * ready before returning.
2014 * This function does not select/unselect the CS line.
2016 * Returns 0 on success, a negative error code otherwise.
2018 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
2021 const u8 *params = data;
2024 if (nand_has_exec_op(chip)) {
2025 const struct nand_interface_config *conf =
2026 nand_get_interface_config(chip);
2027 struct nand_op_instr instrs[] = {
2028 NAND_OP_CMD(NAND_CMD_SET_FEATURES, 0),
2029 NAND_OP_ADDR(1, &feature, NAND_COMMON_TIMING_NS(conf,
2031 NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
2032 NAND_COMMON_TIMING_NS(conf,
2034 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tFEAT_max),
2037 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2039 return nand_exec_op(chip, &op);
2042 chip->legacy.cmdfunc(chip, NAND_CMD_SET_FEATURES, feature, -1);
2043 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
2044 chip->legacy.write_byte(chip, params[i]);
2046 ret = chip->legacy.waitfunc(chip);
2050 if (ret & NAND_STATUS_FAIL)
2057 * nand_get_features_op - Do a GET FEATURES operation
2058 * @chip: The NAND chip
2059 * @feature: feature id
2060 * @data: 4 bytes of data
2062 * This function sends a GET FEATURES command and waits for the NAND to be
2063 * ready before returning.
2064 * This function does not select/unselect the CS line.
2066 * Returns 0 on success, a negative error code otherwise.
2068 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
2071 u8 *params = data, ddrbuf[ONFI_SUBFEATURE_PARAM_LEN * 2];
2074 if (nand_has_exec_op(chip)) {
2075 const struct nand_interface_config *conf =
2076 nand_get_interface_config(chip);
2077 struct nand_op_instr instrs[] = {
2078 NAND_OP_CMD(NAND_CMD_GET_FEATURES, 0),
2079 NAND_OP_ADDR(1, &feature,
2080 NAND_COMMON_TIMING_NS(conf, tWB_max)),
2081 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tFEAT_max),
2082 NAND_COMMON_TIMING_NS(conf, tRR_min)),
2083 NAND_OP_8BIT_DATA_IN(ONFI_SUBFEATURE_PARAM_LEN,
2086 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2089 /* GET_FEATURE data bytes are received twice in NV-DDR mode */
2090 if (nand_interface_is_nvddr(conf)) {
2091 instrs[3].ctx.data.len *= 2;
2092 instrs[3].ctx.data.buf.in = ddrbuf;
2095 ret = nand_exec_op(chip, &op);
2096 if (nand_interface_is_nvddr(conf)) {
2097 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; i++)
2098 params[i] = ddrbuf[i * 2];
2104 chip->legacy.cmdfunc(chip, NAND_CMD_GET_FEATURES, feature, -1);
2105 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
2106 params[i] = chip->legacy.read_byte(chip);
2111 static int nand_wait_rdy_op(struct nand_chip *chip, unsigned int timeout_ms,
2112 unsigned int delay_ns)
2114 if (nand_has_exec_op(chip)) {
2115 struct nand_op_instr instrs[] = {
2116 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(timeout_ms),
2117 PSEC_TO_NSEC(delay_ns)),
2119 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2121 return nand_exec_op(chip, &op);
2124 /* Apply delay or wait for ready/busy pin */
2125 if (!chip->legacy.dev_ready)
2126 udelay(chip->legacy.chip_delay);
2128 nand_wait_ready(chip);
2134 * nand_reset_op - Do a reset operation
2135 * @chip: The NAND chip
2137 * This function sends a RESET command and waits for the NAND to be ready
2139 * This function does not select/unselect the CS line.
2141 * Returns 0 on success, a negative error code otherwise.
2143 int nand_reset_op(struct nand_chip *chip)
2145 if (nand_has_exec_op(chip)) {
2146 const struct nand_interface_config *conf =
2147 nand_get_interface_config(chip);
2148 struct nand_op_instr instrs[] = {
2149 NAND_OP_CMD(NAND_CMD_RESET,
2150 NAND_COMMON_TIMING_NS(conf, tWB_max)),
2151 NAND_OP_WAIT_RDY(NAND_COMMON_TIMING_MS(conf, tRST_max),
2154 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2156 return nand_exec_op(chip, &op);
2159 chip->legacy.cmdfunc(chip, NAND_CMD_RESET, -1, -1);
2163 EXPORT_SYMBOL_GPL(nand_reset_op);
2166 * nand_read_data_op - Read data from the NAND
2167 * @chip: The NAND chip
2168 * @buf: buffer used to store the data
2169 * @len: length of the buffer
2170 * @force_8bit: force 8-bit bus access
2171 * @check_only: do not actually run the command, only checks if the
2172 * controller driver supports it
2174 * This function does a raw data read on the bus. Usually used after launching
2175 * another NAND operation like nand_read_page_op().
2176 * This function does not select/unselect the CS line.
2178 * Returns 0 on success, a negative error code otherwise.
2180 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
2181 bool force_8bit, bool check_only)
2183 if (!len || (!check_only && !buf))
2186 if (nand_has_exec_op(chip)) {
2187 const struct nand_interface_config *conf =
2188 nand_get_interface_config(chip);
2189 struct nand_op_instr instrs[] = {
2190 NAND_OP_DATA_IN(len, buf, 0),
2192 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2196 instrs[0].ctx.data.force_8bit = force_8bit;
2199 * Parameter payloads (ID, status, features, etc) do not go
2200 * through the same pipeline as regular data, hence the
2201 * force_8bit flag must be set and this also indicates that in
2202 * case NV-DDR timings are being used the data will be received
2205 if (force_8bit && nand_interface_is_nvddr(conf)) {
2206 ddrbuf = kzalloc(len * 2, GFP_KERNEL);
2210 instrs[0].ctx.data.len *= 2;
2211 instrs[0].ctx.data.buf.in = ddrbuf;
2215 ret = nand_check_op(chip, &op);
2220 ret = nand_exec_op(chip, &op);
2221 if (!ret && force_8bit && nand_interface_is_nvddr(conf)) {
2224 for (i = 0; i < len; i++)
2225 dst[i] = ddrbuf[i * 2];
2240 for (i = 0; i < len; i++)
2241 p[i] = chip->legacy.read_byte(chip);
2243 chip->legacy.read_buf(chip, buf, len);
2248 EXPORT_SYMBOL_GPL(nand_read_data_op);
2251 * nand_write_data_op - Write data from the NAND
2252 * @chip: The NAND chip
2253 * @buf: buffer containing the data to send on the bus
2254 * @len: length of the buffer
2255 * @force_8bit: force 8-bit bus access
2257 * This function does a raw data write on the bus. Usually used after launching
2258 * another NAND operation like nand_write_page_begin_op().
2259 * This function does not select/unselect the CS line.
2261 * Returns 0 on success, a negative error code otherwise.
2263 int nand_write_data_op(struct nand_chip *chip, const void *buf,
2264 unsigned int len, bool force_8bit)
2269 if (nand_has_exec_op(chip)) {
2270 struct nand_op_instr instrs[] = {
2271 NAND_OP_DATA_OUT(len, buf, 0),
2273 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
2275 instrs[0].ctx.data.force_8bit = force_8bit;
2277 return nand_exec_op(chip, &op);
2284 for (i = 0; i < len; i++)
2285 chip->legacy.write_byte(chip, p[i]);
2287 chip->legacy.write_buf(chip, buf, len);
2292 EXPORT_SYMBOL_GPL(nand_write_data_op);
2295 * struct nand_op_parser_ctx - Context used by the parser
2296 * @instrs: array of all the instructions that must be addressed
2297 * @ninstrs: length of the @instrs array
2298 * @subop: Sub-operation to be passed to the NAND controller
2300 * This structure is used by the core to split NAND operations into
2301 * sub-operations that can be handled by the NAND controller.
2303 struct nand_op_parser_ctx {
2304 const struct nand_op_instr *instrs;
2305 unsigned int ninstrs;
2306 struct nand_subop subop;
2310 * nand_op_parser_must_split_instr - Checks if an instruction must be split
2311 * @pat: the parser pattern element that matches @instr
2312 * @instr: pointer to the instruction to check
2313 * @start_offset: this is an in/out parameter. If @instr has already been
2314 * split, then @start_offset is the offset from which to start
2315 * (either an address cycle or an offset in the data buffer).
2316 * Conversely, if the function returns true (ie. instr must be
2317 * split), this parameter is updated to point to the first
2318 * data/address cycle that has not been taken care of.
2320 * Some NAND controllers are limited and cannot send X address cycles with a
2321 * unique operation, or cannot read/write more than Y bytes at the same time.
2322 * In this case, split the instruction that does not fit in a single
2323 * controller-operation into two or more chunks.
2325 * Returns true if the instruction must be split, false otherwise.
2326 * The @start_offset parameter is also updated to the offset at which the next
2327 * bundle of instruction must start (if an address or a data instruction).
2330 nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat,
2331 const struct nand_op_instr *instr,
2332 unsigned int *start_offset)
2334 switch (pat->type) {
2335 case NAND_OP_ADDR_INSTR:
2336 if (!pat->ctx.addr.maxcycles)
2339 if (instr->ctx.addr.naddrs - *start_offset >
2340 pat->ctx.addr.maxcycles) {
2341 *start_offset += pat->ctx.addr.maxcycles;
2346 case NAND_OP_DATA_IN_INSTR:
2347 case NAND_OP_DATA_OUT_INSTR:
2348 if (!pat->ctx.data.maxlen)
2351 if (instr->ctx.data.len - *start_offset >
2352 pat->ctx.data.maxlen) {
2353 *start_offset += pat->ctx.data.maxlen;
2366 * nand_op_parser_match_pat - Checks if a pattern matches the instructions
2367 * remaining in the parser context
2368 * @pat: the pattern to test
2369 * @ctx: the parser context structure to match with the pattern @pat
2371 * Check if @pat matches the set or a sub-set of instructions remaining in @ctx.
2372 * Returns true if this is the case, false ortherwise. When true is returned,
2373 * @ctx->subop is updated with the set of instructions to be passed to the
2374 * controller driver.
2377 nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
2378 struct nand_op_parser_ctx *ctx)
2380 unsigned int instr_offset = ctx->subop.first_instr_start_off;
2381 const struct nand_op_instr *end = ctx->instrs + ctx->ninstrs;
2382 const struct nand_op_instr *instr = ctx->subop.instrs;
2383 unsigned int i, ninstrs;
2385 for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
2387 * The pattern instruction does not match the operation
2388 * instruction. If the instruction is marked optional in the
2389 * pattern definition, we skip the pattern element and continue
2390 * to the next one. If the element is mandatory, there's no
2391 * match and we can return false directly.
2393 if (instr->type != pat->elems[i].type) {
2394 if (!pat->elems[i].optional)
2401 * Now check the pattern element constraints. If the pattern is
2402 * not able to handle the whole instruction in a single step,
2403 * we have to split it.
2404 * The last_instr_end_off value comes back updated to point to
2405 * the position where we have to split the instruction (the
2406 * start of the next subop chunk).
2408 if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
2421 * This can happen if all instructions of a pattern are optional.
2422 * Still, if there's not at least one instruction handled by this
2423 * pattern, this is not a match, and we should try the next one (if
2430 * We had a match on the pattern head, but the pattern may be longer
2431 * than the instructions we're asked to execute. We need to make sure
2432 * there's no mandatory elements in the pattern tail.
2434 for (; i < pat->nelems; i++) {
2435 if (!pat->elems[i].optional)
2440 * We have a match: update the subop structure accordingly and return
2443 ctx->subop.ninstrs = ninstrs;
2444 ctx->subop.last_instr_end_off = instr_offset;
2449 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
2450 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2452 const struct nand_op_instr *instr;
2456 pr_debug("executing subop (CS%d):\n", ctx->subop.cs);
2458 for (i = 0; i < ctx->ninstrs; i++) {
2459 instr = &ctx->instrs[i];
2461 if (instr == &ctx->subop.instrs[0])
2464 nand_op_trace(prefix, instr);
2466 if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
2471 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2477 static int nand_op_parser_cmp_ctx(const struct nand_op_parser_ctx *a,
2478 const struct nand_op_parser_ctx *b)
2480 if (a->subop.ninstrs < b->subop.ninstrs)
2482 else if (a->subop.ninstrs > b->subop.ninstrs)
2485 if (a->subop.last_instr_end_off < b->subop.last_instr_end_off)
2487 else if (a->subop.last_instr_end_off > b->subop.last_instr_end_off)
2494 * nand_op_parser_exec_op - exec_op parser
2495 * @chip: the NAND chip
2496 * @parser: patterns description provided by the controller driver
2497 * @op: the NAND operation to address
2498 * @check_only: when true, the function only checks if @op can be handled but
2499 * does not execute the operation
2501 * Helper function designed to ease integration of NAND controller drivers that
2502 * only support a limited set of instruction sequences. The supported sequences
2503 * are described in @parser, and the framework takes care of splitting @op into
2504 * multiple sub-operations (if required) and pass them back to the ->exec()
2505 * callback of the matching pattern if @check_only is set to false.
2507 * NAND controller drivers should call this function from their own ->exec_op()
2510 * Returns 0 on success, a negative error code otherwise. A failure can be
2511 * caused by an unsupported operation (none of the supported patterns is able
2512 * to handle the requested operation), or an error returned by one of the
2513 * matching pattern->exec() hook.
2515 int nand_op_parser_exec_op(struct nand_chip *chip,
2516 const struct nand_op_parser *parser,
2517 const struct nand_operation *op, bool check_only)
2519 struct nand_op_parser_ctx ctx = {
2521 .subop.instrs = op->instrs,
2522 .instrs = op->instrs,
2523 .ninstrs = op->ninstrs,
2527 while (ctx.subop.instrs < op->instrs + op->ninstrs) {
2528 const struct nand_op_parser_pattern *pattern;
2529 struct nand_op_parser_ctx best_ctx;
2530 int ret, best_pattern = -1;
2532 for (i = 0; i < parser->npatterns; i++) {
2533 struct nand_op_parser_ctx test_ctx = ctx;
2535 pattern = &parser->patterns[i];
2536 if (!nand_op_parser_match_pat(pattern, &test_ctx))
2539 if (best_pattern >= 0 &&
2540 nand_op_parser_cmp_ctx(&test_ctx, &best_ctx) <= 0)
2544 best_ctx = test_ctx;
2547 if (best_pattern < 0) {
2548 pr_debug("->exec_op() parser: pattern not found!\n");
2553 nand_op_parser_trace(&ctx);
2556 pattern = &parser->patterns[best_pattern];
2557 ret = pattern->exec(chip, &ctx.subop);
2563 * Update the context structure by pointing to the start of the
2566 ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
2567 if (ctx.subop.last_instr_end_off)
2568 ctx.subop.instrs -= 1;
2570 ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
2575 EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
2577 static bool nand_instr_is_data(const struct nand_op_instr *instr)
2579 return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
2580 instr->type == NAND_OP_DATA_OUT_INSTR);
2583 static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
2584 unsigned int instr_idx)
2586 return subop && instr_idx < subop->ninstrs;
2589 static unsigned int nand_subop_get_start_off(const struct nand_subop *subop,
2590 unsigned int instr_idx)
2595 return subop->first_instr_start_off;
2599 * nand_subop_get_addr_start_off - Get the start offset in an address array
2600 * @subop: The entire sub-operation
2601 * @instr_idx: Index of the instruction inside the sub-operation
2603 * During driver development, one could be tempted to directly use the
2604 * ->addr.addrs field of address instructions. This is wrong as address
2605 * instructions might be split.
2607 * Given an address instruction, returns the offset of the first cycle to issue.
2609 unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
2610 unsigned int instr_idx)
2612 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2613 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2616 return nand_subop_get_start_off(subop, instr_idx);
2618 EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
2621 * nand_subop_get_num_addr_cyc - Get the remaining address cycles to assert
2622 * @subop: The entire sub-operation
2623 * @instr_idx: Index of the instruction inside the sub-operation
2625 * During driver development, one could be tempted to directly use the
2626 * ->addr->naddrs field of a data instruction. This is wrong as instructions
2629 * Given an address instruction, returns the number of address cycle to issue.
2631 unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
2632 unsigned int instr_idx)
2634 int start_off, end_off;
2636 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2637 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2640 start_off = nand_subop_get_addr_start_off(subop, instr_idx);
2642 if (instr_idx == subop->ninstrs - 1 &&
2643 subop->last_instr_end_off)
2644 end_off = subop->last_instr_end_off;
2646 end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
2648 return end_off - start_off;
2650 EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
2653 * nand_subop_get_data_start_off - Get the start offset in a data array
2654 * @subop: The entire sub-operation
2655 * @instr_idx: Index of the instruction inside the sub-operation
2657 * During driver development, one could be tempted to directly use the
2658 * ->data->buf.{in,out} field of data instructions. This is wrong as data
2659 * instructions might be split.
2661 * Given a data instruction, returns the offset to start from.
2663 unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
2664 unsigned int instr_idx)
2666 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2667 !nand_instr_is_data(&subop->instrs[instr_idx])))
2670 return nand_subop_get_start_off(subop, instr_idx);
2672 EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
2675 * nand_subop_get_data_len - Get the number of bytes to retrieve
2676 * @subop: The entire sub-operation
2677 * @instr_idx: Index of the instruction inside the sub-operation
2679 * During driver development, one could be tempted to directly use the
2680 * ->data->len field of a data instruction. This is wrong as data instructions
2683 * Returns the length of the chunk of data to send/receive.
2685 unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
2686 unsigned int instr_idx)
2688 int start_off = 0, end_off;
2690 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2691 !nand_instr_is_data(&subop->instrs[instr_idx])))
2694 start_off = nand_subop_get_data_start_off(subop, instr_idx);
2696 if (instr_idx == subop->ninstrs - 1 &&
2697 subop->last_instr_end_off)
2698 end_off = subop->last_instr_end_off;
2700 end_off = subop->instrs[instr_idx].ctx.data.len;
2702 return end_off - start_off;
2704 EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
2707 * nand_reset - Reset and initialize a NAND device
2708 * @chip: The NAND chip
2709 * @chipnr: Internal die id
2711 * Save the timings data structure, then apply SDR timings mode 0 (see
2712 * nand_reset_interface for details), do the reset operation, and apply
2713 * back the previous timings.
2715 * Returns 0 on success, a negative error code otherwise.
2717 int nand_reset(struct nand_chip *chip, int chipnr)
2721 ret = nand_reset_interface(chip, chipnr);
2726 * The CS line has to be released before we can apply the new NAND
2727 * interface settings, hence this weird nand_select_target()
2728 * nand_deselect_target() dance.
2730 nand_select_target(chip, chipnr);
2731 ret = nand_reset_op(chip);
2732 nand_deselect_target(chip);
2736 ret = nand_setup_interface(chip, chipnr);
2742 EXPORT_SYMBOL_GPL(nand_reset);
2745 * nand_get_features - wrapper to perform a GET_FEATURE
2746 * @chip: NAND chip info structure
2747 * @addr: feature address
2748 * @subfeature_param: the subfeature parameters, a four bytes array
2750 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2751 * operation cannot be handled.
2753 int nand_get_features(struct nand_chip *chip, int addr,
2754 u8 *subfeature_param)
2756 if (!nand_supports_get_features(chip, addr))
2759 if (chip->legacy.get_features)
2760 return chip->legacy.get_features(chip, addr, subfeature_param);
2762 return nand_get_features_op(chip, addr, subfeature_param);
2766 * nand_set_features - wrapper to perform a SET_FEATURE
2767 * @chip: NAND chip info structure
2768 * @addr: feature address
2769 * @subfeature_param: the subfeature parameters, a four bytes array
2771 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2772 * operation cannot be handled.
2774 int nand_set_features(struct nand_chip *chip, int addr,
2775 u8 *subfeature_param)
2777 if (!nand_supports_set_features(chip, addr))
2780 if (chip->legacy.set_features)
2781 return chip->legacy.set_features(chip, addr, subfeature_param);
2783 return nand_set_features_op(chip, addr, subfeature_param);
2787 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
2788 * @buf: buffer to test
2789 * @len: buffer length
2790 * @bitflips_threshold: maximum number of bitflips
2792 * Check if a buffer contains only 0xff, which means the underlying region
2793 * has been erased and is ready to be programmed.
2794 * The bitflips_threshold specify the maximum number of bitflips before
2795 * considering the region is not erased.
2796 * Note: The logic of this function has been extracted from the memweight
2797 * implementation, except that nand_check_erased_buf function exit before
2798 * testing the whole buffer if the number of bitflips exceed the
2799 * bitflips_threshold value.
2801 * Returns a positive number of bitflips less than or equal to
2802 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2805 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
2807 const unsigned char *bitmap = buf;
2811 for (; len && ((uintptr_t)bitmap) % sizeof(long);
2813 weight = hweight8(*bitmap);
2814 bitflips += BITS_PER_BYTE - weight;
2815 if (unlikely(bitflips > bitflips_threshold))
2819 for (; len >= sizeof(long);
2820 len -= sizeof(long), bitmap += sizeof(long)) {
2821 unsigned long d = *((unsigned long *)bitmap);
2824 weight = hweight_long(d);
2825 bitflips += BITS_PER_LONG - weight;
2826 if (unlikely(bitflips > bitflips_threshold))
2830 for (; len > 0; len--, bitmap++) {
2831 weight = hweight8(*bitmap);
2832 bitflips += BITS_PER_BYTE - weight;
2833 if (unlikely(bitflips > bitflips_threshold))
2841 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
2843 * @data: data buffer to test
2844 * @datalen: data length
2846 * @ecclen: ECC length
2847 * @extraoob: extra OOB buffer
2848 * @extraooblen: extra OOB length
2849 * @bitflips_threshold: maximum number of bitflips
2851 * Check if a data buffer and its associated ECC and OOB data contains only
2852 * 0xff pattern, which means the underlying region has been erased and is
2853 * ready to be programmed.
2854 * The bitflips_threshold specify the maximum number of bitflips before
2855 * considering the region as not erased.
2858 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
2859 * different from the NAND page size. When fixing bitflips, ECC engines will
2860 * report the number of errors per chunk, and the NAND core infrastructure
2861 * expect you to return the maximum number of bitflips for the whole page.
2862 * This is why you should always use this function on a single chunk and
2863 * not on the whole page. After checking each chunk you should update your
2864 * max_bitflips value accordingly.
2865 * 2/ When checking for bitflips in erased pages you should not only check
2866 * the payload data but also their associated ECC data, because a user might
2867 * have programmed almost all bits to 1 but a few. In this case, we
2868 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
2870 * 3/ The extraoob argument is optional, and should be used if some of your OOB
2871 * data are protected by the ECC engine.
2872 * It could also be used if you support subpages and want to attach some
2873 * extra OOB data to an ECC chunk.
2875 * Returns a positive number of bitflips less than or equal to
2876 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2877 * threshold. In case of success, the passed buffers are filled with 0xff.
2879 int nand_check_erased_ecc_chunk(void *data, int datalen,
2880 void *ecc, int ecclen,
2881 void *extraoob, int extraooblen,
2882 int bitflips_threshold)
2884 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
2886 data_bitflips = nand_check_erased_buf(data, datalen,
2887 bitflips_threshold);
2888 if (data_bitflips < 0)
2889 return data_bitflips;
2891 bitflips_threshold -= data_bitflips;
2893 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
2894 if (ecc_bitflips < 0)
2895 return ecc_bitflips;
2897 bitflips_threshold -= ecc_bitflips;
2899 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
2900 bitflips_threshold);
2901 if (extraoob_bitflips < 0)
2902 return extraoob_bitflips;
2905 memset(data, 0xff, datalen);
2908 memset(ecc, 0xff, ecclen);
2910 if (extraoob_bitflips)
2911 memset(extraoob, 0xff, extraooblen);
2913 return data_bitflips + ecc_bitflips + extraoob_bitflips;
2915 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
2918 * nand_read_page_raw_notsupp - dummy read raw page function
2919 * @chip: nand chip info structure
2920 * @buf: buffer to store read data
2921 * @oob_required: caller requires OOB data read to chip->oob_poi
2922 * @page: page number to read
2924 * Returns -ENOTSUPP unconditionally.
2926 int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf,
2927 int oob_required, int page)
2933 * nand_read_page_raw - [INTERN] read raw page data without ecc
2934 * @chip: nand chip info structure
2935 * @buf: buffer to store read data
2936 * @oob_required: caller requires OOB data read to chip->oob_poi
2937 * @page: page number to read
2939 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2941 int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
2944 struct mtd_info *mtd = nand_to_mtd(chip);
2947 ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
2952 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
2960 EXPORT_SYMBOL(nand_read_page_raw);
2963 * nand_monolithic_read_page_raw - Monolithic page read in raw mode
2964 * @chip: NAND chip info structure
2965 * @buf: buffer to store read data
2966 * @oob_required: caller requires OOB data read to chip->oob_poi
2967 * @page: page number to read
2969 * This is a raw page read, ie. without any error detection/correction.
2970 * Monolithic means we are requesting all the relevant data (main plus
2971 * eventually OOB) to be loaded in the NAND cache and sent over the
2972 * bus (from the NAND chip to the NAND controller) in a single
2973 * operation. This is an alternative to nand_read_page_raw(), which
2974 * first reads the main data, and if the OOB data is requested too,
2975 * then reads more data on the bus.
2977 int nand_monolithic_read_page_raw(struct nand_chip *chip, u8 *buf,
2978 int oob_required, int page)
2980 struct mtd_info *mtd = nand_to_mtd(chip);
2981 unsigned int size = mtd->writesize;
2986 size += mtd->oobsize;
2988 if (buf != chip->data_buf)
2989 read_buf = nand_get_data_buf(chip);
2992 ret = nand_read_page_op(chip, page, 0, read_buf, size);
2996 if (buf != chip->data_buf)
2997 memcpy(buf, read_buf, mtd->writesize);
3001 EXPORT_SYMBOL(nand_monolithic_read_page_raw);
3004 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
3005 * @chip: nand chip info structure
3006 * @buf: buffer to store read data
3007 * @oob_required: caller requires OOB data read to chip->oob_poi
3008 * @page: page number to read
3010 * We need a special oob layout and handling even when OOB isn't used.
3012 static int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf,
3013 int oob_required, int page)
3015 struct mtd_info *mtd = nand_to_mtd(chip);
3016 int eccsize = chip->ecc.size;
3017 int eccbytes = chip->ecc.bytes;
3018 uint8_t *oob = chip->oob_poi;
3019 int steps, size, ret;
3021 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3025 for (steps = chip->ecc.steps; steps > 0; steps--) {
3026 ret = nand_read_data_op(chip, buf, eccsize, false, false);
3032 if (chip->ecc.prepad) {
3033 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3038 oob += chip->ecc.prepad;
3041 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
3047 if (chip->ecc.postpad) {
3048 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3053 oob += chip->ecc.postpad;
3057 size = mtd->oobsize - (oob - chip->oob_poi);
3059 ret = nand_read_data_op(chip, oob, size, false, false);
3068 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
3069 * @chip: nand chip info structure
3070 * @buf: buffer to store read data
3071 * @oob_required: caller requires OOB data read to chip->oob_poi
3072 * @page: page number to read
3074 static int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf,
3075 int oob_required, int page)
3077 struct mtd_info *mtd = nand_to_mtd(chip);
3078 int i, eccsize = chip->ecc.size, ret;
3079 int eccbytes = chip->ecc.bytes;
3080 int eccsteps = chip->ecc.steps;
3082 uint8_t *ecc_calc = chip->ecc.calc_buf;
3083 uint8_t *ecc_code = chip->ecc.code_buf;
3084 unsigned int max_bitflips = 0;
3086 chip->ecc.read_page_raw(chip, buf, 1, page);
3088 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
3089 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3091 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3096 eccsteps = chip->ecc.steps;
3099 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3102 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
3104 mtd->ecc_stats.failed++;
3106 mtd->ecc_stats.corrected += stat;
3107 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3110 return max_bitflips;
3114 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
3115 * @chip: nand chip info structure
3116 * @data_offs: offset of requested data within the page
3117 * @readlen: data length
3118 * @bufpoi: buffer to store read data
3119 * @page: page number to read
3121 static int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs,
3122 uint32_t readlen, uint8_t *bufpoi, int page)
3124 struct mtd_info *mtd = nand_to_mtd(chip);
3125 int start_step, end_step, num_steps, ret;
3127 int data_col_addr, i, gaps = 0;
3128 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
3129 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
3130 int index, section = 0;
3131 unsigned int max_bitflips = 0;
3132 struct mtd_oob_region oobregion = { };
3134 /* Column address within the page aligned to ECC size (256bytes) */
3135 start_step = data_offs / chip->ecc.size;
3136 end_step = (data_offs + readlen - 1) / chip->ecc.size;
3137 num_steps = end_step - start_step + 1;
3138 index = start_step * chip->ecc.bytes;
3140 /* Data size aligned to ECC ecc.size */
3141 datafrag_len = num_steps * chip->ecc.size;
3142 eccfrag_len = num_steps * chip->ecc.bytes;
3144 data_col_addr = start_step * chip->ecc.size;
3145 /* If we read not a page aligned data */
3146 p = bufpoi + data_col_addr;
3147 ret = nand_read_page_op(chip, page, data_col_addr, p, datafrag_len);
3152 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
3153 chip->ecc.calculate(chip, p, &chip->ecc.calc_buf[i]);
3156 * The performance is faster if we position offsets according to
3157 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
3159 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
3163 if (oobregion.length < eccfrag_len)
3167 ret = nand_change_read_column_op(chip, mtd->writesize,
3168 chip->oob_poi, mtd->oobsize,
3174 * Send the command to read the particular ECC bytes take care
3175 * about buswidth alignment in read_buf.
3177 aligned_pos = oobregion.offset & ~(busw - 1);
3178 aligned_len = eccfrag_len;
3179 if (oobregion.offset & (busw - 1))
3181 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
3185 ret = nand_change_read_column_op(chip,
3186 mtd->writesize + aligned_pos,
3187 &chip->oob_poi[aligned_pos],
3188 aligned_len, false);
3193 ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
3194 chip->oob_poi, index, eccfrag_len);
3198 p = bufpoi + data_col_addr;
3199 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
3202 stat = chip->ecc.correct(chip, p, &chip->ecc.code_buf[i],
3203 &chip->ecc.calc_buf[i]);
3204 if (stat == -EBADMSG &&
3205 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3206 /* check for empty pages with bitflips */
3207 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3208 &chip->ecc.code_buf[i],
3211 chip->ecc.strength);
3215 mtd->ecc_stats.failed++;
3217 mtd->ecc_stats.corrected += stat;
3218 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3221 return max_bitflips;
3225 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
3226 * @chip: nand chip info structure
3227 * @buf: buffer to store read data
3228 * @oob_required: caller requires OOB data read to chip->oob_poi
3229 * @page: page number to read
3231 * Not for syndrome calculating ECC controllers which need a special oob layout.
3233 static int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf,
3234 int oob_required, int page)
3236 struct mtd_info *mtd = nand_to_mtd(chip);
3237 int i, eccsize = chip->ecc.size, ret;
3238 int eccbytes = chip->ecc.bytes;
3239 int eccsteps = chip->ecc.steps;
3241 uint8_t *ecc_calc = chip->ecc.calc_buf;
3242 uint8_t *ecc_code = chip->ecc.code_buf;
3243 unsigned int max_bitflips = 0;
3245 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3249 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3250 chip->ecc.hwctl(chip, NAND_ECC_READ);
3252 ret = nand_read_data_op(chip, p, eccsize, false, false);
3256 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3259 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false,
3264 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3269 eccsteps = chip->ecc.steps;
3272 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3275 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
3276 if (stat == -EBADMSG &&
3277 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3278 /* check for empty pages with bitflips */
3279 stat = nand_check_erased_ecc_chunk(p, eccsize,
3280 &ecc_code[i], eccbytes,
3282 chip->ecc.strength);
3286 mtd->ecc_stats.failed++;
3288 mtd->ecc_stats.corrected += stat;
3289 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3292 return max_bitflips;
3296 * nand_read_page_hwecc_oob_first - Hardware ECC page read with ECC
3297 * data read from OOB area
3298 * @chip: nand chip info structure
3299 * @buf: buffer to store read data
3300 * @oob_required: caller requires OOB data read to chip->oob_poi
3301 * @page: page number to read
3303 * Hardware ECC for large page chips, which requires the ECC data to be
3304 * extracted from the OOB before the actual data is read.
3306 int nand_read_page_hwecc_oob_first(struct nand_chip *chip, uint8_t *buf,
3307 int oob_required, int page)
3309 struct mtd_info *mtd = nand_to_mtd(chip);
3310 int i, eccsize = chip->ecc.size, ret;
3311 int eccbytes = chip->ecc.bytes;
3312 int eccsteps = chip->ecc.steps;
3314 uint8_t *ecc_code = chip->ecc.code_buf;
3315 unsigned int max_bitflips = 0;
3317 /* Read the OOB area first */
3318 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3322 /* Move read cursor to start of page */
3323 ret = nand_change_read_column_op(chip, 0, NULL, 0, false);
3327 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3332 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3335 chip->ecc.hwctl(chip, NAND_ECC_READ);
3337 ret = nand_read_data_op(chip, p, eccsize, false, false);
3341 stat = chip->ecc.correct(chip, p, &ecc_code[i], NULL);
3342 if (stat == -EBADMSG &&
3343 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3344 /* check for empty pages with bitflips */
3345 stat = nand_check_erased_ecc_chunk(p, eccsize,
3348 chip->ecc.strength);
3352 mtd->ecc_stats.failed++;
3354 mtd->ecc_stats.corrected += stat;
3355 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3358 return max_bitflips;
3360 EXPORT_SYMBOL_GPL(nand_read_page_hwecc_oob_first);
3363 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
3364 * @chip: nand chip info structure
3365 * @buf: buffer to store read data
3366 * @oob_required: caller requires OOB data read to chip->oob_poi
3367 * @page: page number to read
3369 * The hw generator calculates the error syndrome automatically. Therefore we
3370 * need a special oob layout and handling.
3372 static int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf,
3373 int oob_required, int page)
3375 struct mtd_info *mtd = nand_to_mtd(chip);
3376 int ret, i, eccsize = chip->ecc.size;
3377 int eccbytes = chip->ecc.bytes;
3378 int eccsteps = chip->ecc.steps;
3379 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
3381 uint8_t *oob = chip->oob_poi;
3382 unsigned int max_bitflips = 0;
3384 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3388 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3391 chip->ecc.hwctl(chip, NAND_ECC_READ);
3393 ret = nand_read_data_op(chip, p, eccsize, false, false);
3397 if (chip->ecc.prepad) {
3398 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3403 oob += chip->ecc.prepad;
3406 chip->ecc.hwctl(chip, NAND_ECC_READSYN);
3408 ret = nand_read_data_op(chip, oob, eccbytes, false, false);
3412 stat = chip->ecc.correct(chip, p, oob, NULL);
3416 if (chip->ecc.postpad) {
3417 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3422 oob += chip->ecc.postpad;
3425 if (stat == -EBADMSG &&
3426 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3427 /* check for empty pages with bitflips */
3428 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3432 chip->ecc.strength);
3436 mtd->ecc_stats.failed++;
3438 mtd->ecc_stats.corrected += stat;
3439 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3443 /* Calculate remaining oob bytes */
3444 i = mtd->oobsize - (oob - chip->oob_poi);
3446 ret = nand_read_data_op(chip, oob, i, false, false);
3451 return max_bitflips;
3455 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
3456 * @chip: NAND chip object
3457 * @oob: oob destination address
3458 * @ops: oob ops structure
3459 * @len: size of oob to transfer
3461 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
3462 struct mtd_oob_ops *ops, size_t len)
3464 struct mtd_info *mtd = nand_to_mtd(chip);
3467 switch (ops->mode) {
3469 case MTD_OPS_PLACE_OOB:
3471 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
3474 case MTD_OPS_AUTO_OOB:
3475 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
3486 static void rawnand_enable_cont_reads(struct nand_chip *chip, unsigned int page,
3487 u32 readlen, int col)
3489 struct mtd_info *mtd = nand_to_mtd(chip);
3490 unsigned int first_page, last_page;
3492 chip->cont_read.ongoing = false;
3494 if (!chip->controller->supported_op.cont_read)
3498 * Don't bother making any calculations if the length is too small.
3499 * Side effect: avoids possible integer underflows below.
3501 if (readlen < (2 * mtd->writesize))
3504 /* Derive the page where continuous read should start (the first full page read) */
3509 /* Derive the page where continuous read should stop (the last full page read) */
3510 last_page = page + ((col + readlen) / mtd->writesize) - 1;
3512 /* Configure and enable continuous read when suitable */
3513 if (first_page < last_page) {
3514 chip->cont_read.first_page = first_page;
3515 chip->cont_read.last_page = last_page;
3516 chip->cont_read.ongoing = true;
3517 /* May reset the ongoing flag */
3518 rawnand_cap_cont_reads(chip);
3522 static void rawnand_cont_read_skip_first_page(struct nand_chip *chip, unsigned int page)
3524 if (!chip->cont_read.ongoing || page != chip->cont_read.first_page)
3527 chip->cont_read.first_page++;
3528 rawnand_cap_cont_reads(chip);
3532 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
3533 * @chip: NAND chip object
3534 * @retry_mode: the retry mode to use
3536 * Some vendors supply a special command to shift the Vt threshold, to be used
3537 * when there are too many bitflips in a page (i.e., ECC error). After setting
3538 * a new threshold, the host should retry reading the page.
3540 static int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
3542 pr_debug("setting READ RETRY mode %d\n", retry_mode);
3544 if (retry_mode >= chip->read_retries)
3547 if (!chip->ops.setup_read_retry)
3550 return chip->ops.setup_read_retry(chip, retry_mode);
3553 static void nand_wait_readrdy(struct nand_chip *chip)
3555 const struct nand_interface_config *conf;
3557 if (!(chip->options & NAND_NEED_READRDY))
3560 conf = nand_get_interface_config(chip);
3561 WARN_ON(nand_wait_rdy_op(chip, NAND_COMMON_TIMING_MS(conf, tR_max), 0));
3565 * nand_do_read_ops - [INTERN] Read data with ECC
3566 * @chip: NAND chip object
3567 * @from: offset to read from
3568 * @ops: oob ops structure
3570 * Internal function. Called with chip held.
3572 static int nand_do_read_ops(struct nand_chip *chip, loff_t from,
3573 struct mtd_oob_ops *ops)
3575 int chipnr, page, realpage, col, bytes, aligned, oob_required;
3576 struct mtd_info *mtd = nand_to_mtd(chip);
3578 uint32_t readlen = ops->len;
3579 uint32_t oobreadlen = ops->ooblen;
3580 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
3582 uint8_t *bufpoi, *oob, *buf;
3584 unsigned int max_bitflips = 0;
3586 bool ecc_fail = false;
3588 /* Check if the region is secured */
3589 if (nand_region_is_secured(chip, from, readlen))
3592 chipnr = (int)(from >> chip->chip_shift);
3593 nand_select_target(chip, chipnr);
3595 realpage = (int)(from >> chip->page_shift);
3596 page = realpage & chip->pagemask;
3598 col = (int)(from & (mtd->writesize - 1));
3602 oob_required = oob ? 1 : 0;
3604 if (likely(ops->mode != MTD_OPS_RAW))
3605 rawnand_enable_cont_reads(chip, page, readlen, col);
3608 struct mtd_ecc_stats ecc_stats = mtd->ecc_stats;
3610 bytes = min(mtd->writesize - col, readlen);
3611 aligned = (bytes == mtd->writesize);
3615 else if (chip->options & NAND_USES_DMA)
3616 use_bounce_buf = !virt_addr_valid(buf) ||
3617 !IS_ALIGNED((unsigned long)buf,
3622 /* Is the current page in the buffer? */
3623 if (realpage != chip->pagecache.page || oob) {
3624 bufpoi = use_bounce_buf ? chip->data_buf : buf;
3626 if (use_bounce_buf && aligned)
3627 pr_debug("%s: using read bounce buffer for buf@%p\n",
3632 * Now read the page into the buffer. Absent an error,
3633 * the read methods return max bitflips per ecc step.
3635 if (unlikely(ops->mode == MTD_OPS_RAW))
3636 ret = chip->ecc.read_page_raw(chip, bufpoi,
3639 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
3641 ret = chip->ecc.read_subpage(chip, col, bytes,
3644 ret = chip->ecc.read_page(chip, bufpoi,
3645 oob_required, page);
3648 /* Invalidate page cache */
3649 chip->pagecache.page = -1;
3654 * Copy back the data in the initial buffer when reading
3655 * partial pages or when a bounce buffer is required.
3657 if (use_bounce_buf) {
3658 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
3659 !(mtd->ecc_stats.failed - ecc_stats.failed) &&
3660 (ops->mode != MTD_OPS_RAW)) {
3661 chip->pagecache.page = realpage;
3662 chip->pagecache.bitflips = ret;
3664 /* Invalidate page cache */
3665 chip->pagecache.page = -1;
3667 memcpy(buf, bufpoi + col, bytes);
3670 if (unlikely(oob)) {
3671 int toread = min(oobreadlen, max_oobsize);
3674 oob = nand_transfer_oob(chip, oob, ops,
3676 oobreadlen -= toread;
3680 nand_wait_readrdy(chip);
3682 if (mtd->ecc_stats.failed - ecc_stats.failed) {
3683 if (retry_mode + 1 < chip->read_retries) {
3685 ret = nand_setup_read_retry(chip,
3690 /* Reset ecc_stats; retry */
3691 mtd->ecc_stats = ecc_stats;
3694 /* No more retry modes; real failure */
3700 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3702 memcpy(buf, chip->data_buf + col, bytes);
3704 max_bitflips = max_t(unsigned int, max_bitflips,
3705 chip->pagecache.bitflips);
3707 rawnand_cont_read_skip_first_page(chip, page);
3712 /* Reset to retry mode 0 */
3714 ret = nand_setup_read_retry(chip, 0);
3723 /* For subsequent reads align to page boundary */
3725 /* Increment page address */
3728 page = realpage & chip->pagemask;
3729 /* Check, if we cross a chip boundary */
3732 nand_deselect_target(chip);
3733 nand_select_target(chip, chipnr);
3736 nand_deselect_target(chip);
3738 if (WARN_ON_ONCE(chip->cont_read.ongoing))
3739 chip->cont_read.ongoing = false;
3741 ops->retlen = ops->len - (size_t) readlen;
3743 ops->oobretlen = ops->ooblen - oobreadlen;
3751 return max_bitflips;
3755 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
3756 * @chip: nand chip info structure
3757 * @page: page number to read
3759 int nand_read_oob_std(struct nand_chip *chip, int page)
3761 struct mtd_info *mtd = nand_to_mtd(chip);
3763 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3765 EXPORT_SYMBOL(nand_read_oob_std);
3768 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
3770 * @chip: nand chip info structure
3771 * @page: page number to read
3773 static int nand_read_oob_syndrome(struct nand_chip *chip, int page)
3775 struct mtd_info *mtd = nand_to_mtd(chip);
3776 int length = mtd->oobsize;
3777 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3778 int eccsize = chip->ecc.size;
3779 uint8_t *bufpoi = chip->oob_poi;
3780 int i, toread, sndrnd = 0, pos, ret;
3782 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
3786 for (i = 0; i < chip->ecc.steps; i++) {
3790 pos = eccsize + i * (eccsize + chunk);
3791 if (mtd->writesize > 512)
3792 ret = nand_change_read_column_op(chip, pos,
3796 ret = nand_read_page_op(chip, page, pos, NULL,
3803 toread = min_t(int, length, chunk);
3805 ret = nand_read_data_op(chip, bufpoi, toread, false, false);
3813 ret = nand_read_data_op(chip, bufpoi, length, false, false);
3822 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
3823 * @chip: nand chip info structure
3824 * @page: page number to write
3826 int nand_write_oob_std(struct nand_chip *chip, int page)
3828 struct mtd_info *mtd = nand_to_mtd(chip);
3830 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
3833 EXPORT_SYMBOL(nand_write_oob_std);
3836 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
3837 * with syndrome - only for large page flash
3838 * @chip: nand chip info structure
3839 * @page: page number to write
3841 static int nand_write_oob_syndrome(struct nand_chip *chip, int page)
3843 struct mtd_info *mtd = nand_to_mtd(chip);
3844 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3845 int eccsize = chip->ecc.size, length = mtd->oobsize;
3846 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
3847 const uint8_t *bufpoi = chip->oob_poi;
3850 * data-ecc-data-ecc ... ecc-oob
3852 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
3854 if (!chip->ecc.prepad && !chip->ecc.postpad) {
3855 pos = steps * (eccsize + chunk);
3860 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
3864 for (i = 0; i < steps; i++) {
3866 if (mtd->writesize <= 512) {
3867 uint32_t fill = 0xFFFFFFFF;
3871 int num = min_t(int, len, 4);
3873 ret = nand_write_data_op(chip, &fill,
3881 pos = eccsize + i * (eccsize + chunk);
3882 ret = nand_change_write_column_op(chip, pos,
3890 len = min_t(int, length, chunk);
3892 ret = nand_write_data_op(chip, bufpoi, len, false);
3900 ret = nand_write_data_op(chip, bufpoi, length, false);
3905 return nand_prog_page_end_op(chip);
3909 * nand_do_read_oob - [INTERN] NAND read out-of-band
3910 * @chip: NAND chip object
3911 * @from: offset to read from
3912 * @ops: oob operations description structure
3914 * NAND read out-of-band data from the spare area.
3916 static int nand_do_read_oob(struct nand_chip *chip, loff_t from,
3917 struct mtd_oob_ops *ops)
3919 struct mtd_info *mtd = nand_to_mtd(chip);
3920 unsigned int max_bitflips = 0;
3921 int page, realpage, chipnr;
3922 struct mtd_ecc_stats stats;
3923 int readlen = ops->ooblen;
3925 uint8_t *buf = ops->oobbuf;
3928 pr_debug("%s: from = 0x%08Lx, len = %i\n",
3929 __func__, (unsigned long long)from, readlen);
3931 /* Check if the region is secured */
3932 if (nand_region_is_secured(chip, from, readlen))
3935 stats = mtd->ecc_stats;
3937 len = mtd_oobavail(mtd, ops);
3939 chipnr = (int)(from >> chip->chip_shift);
3940 nand_select_target(chip, chipnr);
3942 /* Shift to get page */
3943 realpage = (int)(from >> chip->page_shift);
3944 page = realpage & chip->pagemask;
3947 if (ops->mode == MTD_OPS_RAW)
3948 ret = chip->ecc.read_oob_raw(chip, page);
3950 ret = chip->ecc.read_oob(chip, page);
3955 len = min(len, readlen);
3956 buf = nand_transfer_oob(chip, buf, ops, len);
3958 nand_wait_readrdy(chip);
3960 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3966 /* Increment page address */
3969 page = realpage & chip->pagemask;
3970 /* Check, if we cross a chip boundary */
3973 nand_deselect_target(chip);
3974 nand_select_target(chip, chipnr);
3977 nand_deselect_target(chip);
3979 ops->oobretlen = ops->ooblen - readlen;
3984 if (mtd->ecc_stats.failed - stats.failed)
3987 return max_bitflips;
3991 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
3992 * @mtd: MTD device structure
3993 * @from: offset to read from
3994 * @ops: oob operation description structure
3996 * NAND read data and/or out-of-band data.
3998 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
3999 struct mtd_oob_ops *ops)
4001 struct nand_chip *chip = mtd_to_nand(mtd);
4002 struct mtd_ecc_stats old_stats;
4007 if (ops->mode != MTD_OPS_PLACE_OOB &&
4008 ops->mode != MTD_OPS_AUTO_OOB &&
4009 ops->mode != MTD_OPS_RAW)
4012 nand_get_device(chip);
4014 old_stats = mtd->ecc_stats;
4017 ret = nand_do_read_oob(chip, from, ops);
4019 ret = nand_do_read_ops(chip, from, ops);
4022 ops->stats->uncorrectable_errors +=
4023 mtd->ecc_stats.failed - old_stats.failed;
4024 ops->stats->corrected_bitflips +=
4025 mtd->ecc_stats.corrected - old_stats.corrected;
4028 nand_release_device(chip);
4033 * nand_write_page_raw_notsupp - dummy raw page write function
4034 * @chip: nand chip info structure
4036 * @oob_required: must write chip->oob_poi to OOB
4037 * @page: page number to write
4039 * Returns -ENOTSUPP unconditionally.
4041 int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf,
4042 int oob_required, int page)
4048 * nand_write_page_raw - [INTERN] raw page write function
4049 * @chip: nand chip info structure
4051 * @oob_required: must write chip->oob_poi to OOB
4052 * @page: page number to write
4054 * Not for syndrome calculating ECC controllers, which use a special oob layout.
4056 int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
4057 int oob_required, int page)
4059 struct mtd_info *mtd = nand_to_mtd(chip);
4062 ret = nand_prog_page_begin_op(chip, page, 0, buf, mtd->writesize);
4067 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
4073 return nand_prog_page_end_op(chip);
4075 EXPORT_SYMBOL(nand_write_page_raw);
4078 * nand_monolithic_write_page_raw - Monolithic page write in raw mode
4079 * @chip: NAND chip info structure
4080 * @buf: data buffer to write
4081 * @oob_required: must write chip->oob_poi to OOB
4082 * @page: page number to write
4084 * This is a raw page write, ie. without any error detection/correction.
4085 * Monolithic means we are requesting all the relevant data (main plus
4086 * eventually OOB) to be sent over the bus and effectively programmed
4087 * into the NAND chip arrays in a single operation. This is an
4088 * alternative to nand_write_page_raw(), which first sends the main
4089 * data, then eventually send the OOB data by latching more data
4090 * cycles on the NAND bus, and finally sends the program command to
4091 * synchronyze the NAND chip cache.
4093 int nand_monolithic_write_page_raw(struct nand_chip *chip, const u8 *buf,
4094 int oob_required, int page)
4096 struct mtd_info *mtd = nand_to_mtd(chip);
4097 unsigned int size = mtd->writesize;
4098 u8 *write_buf = (u8 *)buf;
4101 size += mtd->oobsize;
4103 if (buf != chip->data_buf) {
4104 write_buf = nand_get_data_buf(chip);
4105 memcpy(write_buf, buf, mtd->writesize);
4109 return nand_prog_page_op(chip, page, 0, write_buf, size);
4111 EXPORT_SYMBOL(nand_monolithic_write_page_raw);
4114 * nand_write_page_raw_syndrome - [INTERN] raw page write function
4115 * @chip: nand chip info structure
4117 * @oob_required: must write chip->oob_poi to OOB
4118 * @page: page number to write
4120 * We need a special oob layout and handling even when ECC isn't checked.
4122 static int nand_write_page_raw_syndrome(struct nand_chip *chip,
4123 const uint8_t *buf, int oob_required,
4126 struct mtd_info *mtd = nand_to_mtd(chip);
4127 int eccsize = chip->ecc.size;
4128 int eccbytes = chip->ecc.bytes;
4129 uint8_t *oob = chip->oob_poi;
4130 int steps, size, ret;
4132 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4136 for (steps = chip->ecc.steps; steps > 0; steps--) {
4137 ret = nand_write_data_op(chip, buf, eccsize, false);
4143 if (chip->ecc.prepad) {
4144 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4149 oob += chip->ecc.prepad;
4152 ret = nand_write_data_op(chip, oob, eccbytes, false);
4158 if (chip->ecc.postpad) {
4159 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4164 oob += chip->ecc.postpad;
4168 size = mtd->oobsize - (oob - chip->oob_poi);
4170 ret = nand_write_data_op(chip, oob, size, false);
4175 return nand_prog_page_end_op(chip);
4178 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
4179 * @chip: nand chip info structure
4181 * @oob_required: must write chip->oob_poi to OOB
4182 * @page: page number to write
4184 static int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf,
4185 int oob_required, int page)
4187 struct mtd_info *mtd = nand_to_mtd(chip);
4188 int i, eccsize = chip->ecc.size, ret;
4189 int eccbytes = chip->ecc.bytes;
4190 int eccsteps = chip->ecc.steps;
4191 uint8_t *ecc_calc = chip->ecc.calc_buf;
4192 const uint8_t *p = buf;
4194 /* Software ECC calculation */
4195 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
4196 chip->ecc.calculate(chip, p, &ecc_calc[i]);
4198 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4203 return chip->ecc.write_page_raw(chip, buf, 1, page);
4207 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
4208 * @chip: nand chip info structure
4210 * @oob_required: must write chip->oob_poi to OOB
4211 * @page: page number to write
4213 static int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf,
4214 int oob_required, int page)
4216 struct mtd_info *mtd = nand_to_mtd(chip);
4217 int i, eccsize = chip->ecc.size, ret;
4218 int eccbytes = chip->ecc.bytes;
4219 int eccsteps = chip->ecc.steps;
4220 uint8_t *ecc_calc = chip->ecc.calc_buf;
4221 const uint8_t *p = buf;
4223 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4227 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4228 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4230 ret = nand_write_data_op(chip, p, eccsize, false);
4234 chip->ecc.calculate(chip, p, &ecc_calc[i]);
4237 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4242 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
4246 return nand_prog_page_end_op(chip);
4251 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
4252 * @chip: nand chip info structure
4253 * @offset: column address of subpage within the page
4254 * @data_len: data length
4256 * @oob_required: must write chip->oob_poi to OOB
4257 * @page: page number to write
4259 static int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset,
4260 uint32_t data_len, const uint8_t *buf,
4261 int oob_required, int page)
4263 struct mtd_info *mtd = nand_to_mtd(chip);
4264 uint8_t *oob_buf = chip->oob_poi;
4265 uint8_t *ecc_calc = chip->ecc.calc_buf;
4266 int ecc_size = chip->ecc.size;
4267 int ecc_bytes = chip->ecc.bytes;
4268 int ecc_steps = chip->ecc.steps;
4269 uint32_t start_step = offset / ecc_size;
4270 uint32_t end_step = (offset + data_len - 1) / ecc_size;
4271 int oob_bytes = mtd->oobsize / ecc_steps;
4274 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4278 for (step = 0; step < ecc_steps; step++) {
4279 /* configure controller for WRITE access */
4280 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4282 /* write data (untouched subpages already masked by 0xFF) */
4283 ret = nand_write_data_op(chip, buf, ecc_size, false);
4287 /* mask ECC of un-touched subpages by padding 0xFF */
4288 if ((step < start_step) || (step > end_step))
4289 memset(ecc_calc, 0xff, ecc_bytes);
4291 chip->ecc.calculate(chip, buf, ecc_calc);
4293 /* mask OOB of un-touched subpages by padding 0xFF */
4294 /* if oob_required, preserve OOB metadata of written subpage */
4295 if (!oob_required || (step < start_step) || (step > end_step))
4296 memset(oob_buf, 0xff, oob_bytes);
4299 ecc_calc += ecc_bytes;
4300 oob_buf += oob_bytes;
4303 /* copy calculated ECC for whole page to chip->buffer->oob */
4304 /* this include masked-value(0xFF) for unwritten subpages */
4305 ecc_calc = chip->ecc.calc_buf;
4306 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4311 /* write OOB buffer to NAND device */
4312 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
4316 return nand_prog_page_end_op(chip);
4321 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
4322 * @chip: nand chip info structure
4324 * @oob_required: must write chip->oob_poi to OOB
4325 * @page: page number to write
4327 * The hw generator calculates the error syndrome automatically. Therefore we
4328 * need a special oob layout and handling.
4330 static int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf,
4331 int oob_required, int page)
4333 struct mtd_info *mtd = nand_to_mtd(chip);
4334 int i, eccsize = chip->ecc.size;
4335 int eccbytes = chip->ecc.bytes;
4336 int eccsteps = chip->ecc.steps;
4337 const uint8_t *p = buf;
4338 uint8_t *oob = chip->oob_poi;
4341 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4345 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4346 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
4348 ret = nand_write_data_op(chip, p, eccsize, false);
4352 if (chip->ecc.prepad) {
4353 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4358 oob += chip->ecc.prepad;
4361 chip->ecc.calculate(chip, p, oob);
4363 ret = nand_write_data_op(chip, oob, eccbytes, false);
4369 if (chip->ecc.postpad) {
4370 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4375 oob += chip->ecc.postpad;
4379 /* Calculate remaining oob bytes */
4380 i = mtd->oobsize - (oob - chip->oob_poi);
4382 ret = nand_write_data_op(chip, oob, i, false);
4387 return nand_prog_page_end_op(chip);
4391 * nand_write_page - write one page
4392 * @chip: NAND chip descriptor
4393 * @offset: address offset within the page
4394 * @data_len: length of actual data to be written
4395 * @buf: the data to write
4396 * @oob_required: must write chip->oob_poi to OOB
4397 * @page: page number to write
4398 * @raw: use _raw version of write_page
4400 static int nand_write_page(struct nand_chip *chip, uint32_t offset,
4401 int data_len, const uint8_t *buf, int oob_required,
4404 struct mtd_info *mtd = nand_to_mtd(chip);
4405 int status, subpage;
4407 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
4408 chip->ecc.write_subpage)
4409 subpage = offset || (data_len < mtd->writesize);
4414 status = chip->ecc.write_page_raw(chip, buf, oob_required,
4417 status = chip->ecc.write_subpage(chip, offset, data_len, buf,
4418 oob_required, page);
4420 status = chip->ecc.write_page(chip, buf, oob_required, page);
4428 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
4431 * nand_do_write_ops - [INTERN] NAND write with ECC
4432 * @chip: NAND chip object
4433 * @to: offset to write to
4434 * @ops: oob operations description structure
4436 * NAND write with ECC.
4438 static int nand_do_write_ops(struct nand_chip *chip, loff_t to,
4439 struct mtd_oob_ops *ops)
4441 struct mtd_info *mtd = nand_to_mtd(chip);
4442 int chipnr, realpage, page, column;
4443 uint32_t writelen = ops->len;
4445 uint32_t oobwritelen = ops->ooblen;
4446 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
4448 uint8_t *oob = ops->oobbuf;
4449 uint8_t *buf = ops->datbuf;
4451 int oob_required = oob ? 1 : 0;
4457 /* Reject writes, which are not page aligned */
4458 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
4459 pr_notice("%s: attempt to write non page aligned data\n",
4464 /* Check if the region is secured */
4465 if (nand_region_is_secured(chip, to, writelen))
4468 column = to & (mtd->writesize - 1);
4470 chipnr = (int)(to >> chip->chip_shift);
4471 nand_select_target(chip, chipnr);
4473 /* Check, if it is write protected */
4474 if (nand_check_wp(chip)) {
4479 realpage = (int)(to >> chip->page_shift);
4480 page = realpage & chip->pagemask;
4482 /* Invalidate the page cache, when we write to the cached page */
4483 if (to <= ((loff_t)chip->pagecache.page << chip->page_shift) &&
4484 ((loff_t)chip->pagecache.page << chip->page_shift) < (to + ops->len))
4485 chip->pagecache.page = -1;
4487 /* Don't allow multipage oob writes with offset */
4488 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
4494 int bytes = mtd->writesize;
4495 uint8_t *wbuf = buf;
4497 int part_pagewr = (column || writelen < mtd->writesize);
4501 else if (chip->options & NAND_USES_DMA)
4502 use_bounce_buf = !virt_addr_valid(buf) ||
4503 !IS_ALIGNED((unsigned long)buf,
4509 * Copy the data from the initial buffer when doing partial page
4510 * writes or when a bounce buffer is required.
4512 if (use_bounce_buf) {
4513 pr_debug("%s: using write bounce buffer for buf@%p\n",
4516 bytes = min_t(int, bytes - column, writelen);
4517 wbuf = nand_get_data_buf(chip);
4518 memset(wbuf, 0xff, mtd->writesize);
4519 memcpy(&wbuf[column], buf, bytes);
4522 if (unlikely(oob)) {
4523 size_t len = min(oobwritelen, oobmaxlen);
4524 oob = nand_fill_oob(chip, oob, len, ops);
4527 /* We still need to erase leftover OOB data */
4528 memset(chip->oob_poi, 0xff, mtd->oobsize);
4531 ret = nand_write_page(chip, column, bytes, wbuf,
4533 (ops->mode == MTD_OPS_RAW));
4545 page = realpage & chip->pagemask;
4546 /* Check, if we cross a chip boundary */
4549 nand_deselect_target(chip);
4550 nand_select_target(chip, chipnr);
4554 ops->retlen = ops->len - writelen;
4556 ops->oobretlen = ops->ooblen;
4559 nand_deselect_target(chip);
4564 * panic_nand_write - [MTD Interface] NAND write with ECC
4565 * @mtd: MTD device structure
4566 * @to: offset to write to
4567 * @len: number of bytes to write
4568 * @retlen: pointer to variable to store the number of written bytes
4569 * @buf: the data to write
4571 * NAND write with ECC. Used when performing writes in interrupt context, this
4572 * may for example be called by mtdoops when writing an oops while in panic.
4574 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
4575 size_t *retlen, const uint8_t *buf)
4577 struct nand_chip *chip = mtd_to_nand(mtd);
4578 int chipnr = (int)(to >> chip->chip_shift);
4579 struct mtd_oob_ops ops;
4582 nand_select_target(chip, chipnr);
4584 /* Wait for the device to get ready */
4585 panic_nand_wait(chip, 400);
4587 memset(&ops, 0, sizeof(ops));
4589 ops.datbuf = (uint8_t *)buf;
4590 ops.mode = MTD_OPS_PLACE_OOB;
4592 ret = nand_do_write_ops(chip, to, &ops);
4594 *retlen = ops.retlen;
4599 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
4600 * @mtd: MTD device structure
4601 * @to: offset to write to
4602 * @ops: oob operation description structure
4604 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
4605 struct mtd_oob_ops *ops)
4607 struct nand_chip *chip = mtd_to_nand(mtd);
4612 nand_get_device(chip);
4614 switch (ops->mode) {
4615 case MTD_OPS_PLACE_OOB:
4616 case MTD_OPS_AUTO_OOB:
4625 ret = nand_do_write_oob(chip, to, ops);
4627 ret = nand_do_write_ops(chip, to, ops);
4630 nand_release_device(chip);
4635 * nand_erase - [MTD Interface] erase block(s)
4636 * @mtd: MTD device structure
4637 * @instr: erase instruction
4639 * Erase one ore more blocks.
4641 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
4643 return nand_erase_nand(mtd_to_nand(mtd), instr, 0);
4647 * nand_erase_nand - [INTERN] erase block(s)
4648 * @chip: NAND chip object
4649 * @instr: erase instruction
4650 * @allowbbt: allow erasing the bbt area
4652 * Erase one ore more blocks.
4654 int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr,
4657 int page, pages_per_block, ret, chipnr;
4660 pr_debug("%s: start = 0x%012llx, len = %llu\n",
4661 __func__, (unsigned long long)instr->addr,
4662 (unsigned long long)instr->len);
4664 if (check_offs_len(chip, instr->addr, instr->len))
4667 /* Check if the region is secured */
4668 if (nand_region_is_secured(chip, instr->addr, instr->len))
4671 /* Grab the lock and see if the device is available */
4672 nand_get_device(chip);
4674 /* Shift to get first page */
4675 page = (int)(instr->addr >> chip->page_shift);
4676 chipnr = (int)(instr->addr >> chip->chip_shift);
4678 /* Calculate pages in each block */
4679 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
4681 /* Select the NAND device */
4682 nand_select_target(chip, chipnr);
4684 /* Check, if it is write protected */
4685 if (nand_check_wp(chip)) {
4686 pr_debug("%s: device is write protected!\n",
4692 /* Loop through the pages */
4696 loff_t ofs = (loff_t)page << chip->page_shift;
4698 /* Check if we have a bad block, we do not erase bad blocks! */
4699 if (nand_block_checkbad(chip, ((loff_t) page) <<
4700 chip->page_shift, allowbbt)) {
4701 pr_warn("%s: attempt to erase a bad block at 0x%08llx\n",
4702 __func__, (unsigned long long)ofs);
4708 * Invalidate the page cache, if we erase the block which
4709 * contains the current cached page.
4711 if (page <= chip->pagecache.page && chip->pagecache.page <
4712 (page + pages_per_block))
4713 chip->pagecache.page = -1;
4715 ret = nand_erase_op(chip, (page & chip->pagemask) >>
4716 (chip->phys_erase_shift - chip->page_shift));
4718 pr_debug("%s: failed erase, page 0x%08x\n",
4720 instr->fail_addr = ofs;
4724 /* Increment page address and decrement length */
4725 len -= (1ULL << chip->phys_erase_shift);
4726 page += pages_per_block;
4728 /* Check, if we cross a chip boundary */
4729 if (len && !(page & chip->pagemask)) {
4731 nand_deselect_target(chip);
4732 nand_select_target(chip, chipnr);
4739 /* Deselect and wake up anyone waiting on the device */
4740 nand_deselect_target(chip);
4741 nand_release_device(chip);
4743 /* Return more or less happy */
4748 * nand_sync - [MTD Interface] sync
4749 * @mtd: MTD device structure
4751 * Sync is actually a wait for chip ready function.
4753 static void nand_sync(struct mtd_info *mtd)
4755 struct nand_chip *chip = mtd_to_nand(mtd);
4757 pr_debug("%s: called\n", __func__);
4759 /* Grab the lock and see if the device is available */
4760 nand_get_device(chip);
4761 /* Release it and go back */
4762 nand_release_device(chip);
4766 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
4767 * @mtd: MTD device structure
4768 * @offs: offset relative to mtd start
4770 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
4772 struct nand_chip *chip = mtd_to_nand(mtd);
4773 int chipnr = (int)(offs >> chip->chip_shift);
4776 /* Select the NAND device */
4777 nand_get_device(chip);
4779 nand_select_target(chip, chipnr);
4781 ret = nand_block_checkbad(chip, offs, 0);
4783 nand_deselect_target(chip);
4784 nand_release_device(chip);
4790 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
4791 * @mtd: MTD device structure
4792 * @ofs: offset relative to mtd start
4794 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
4798 ret = nand_block_isbad(mtd, ofs);
4800 /* If it was bad already, return success and do nothing */
4806 return nand_block_markbad_lowlevel(mtd_to_nand(mtd), ofs);
4810 * nand_suspend - [MTD Interface] Suspend the NAND flash
4811 * @mtd: MTD device structure
4813 * Returns 0 for success or negative error code otherwise.
4815 static int nand_suspend(struct mtd_info *mtd)
4817 struct nand_chip *chip = mtd_to_nand(mtd);
4820 mutex_lock(&chip->lock);
4821 if (chip->ops.suspend)
4822 ret = chip->ops.suspend(chip);
4824 chip->suspended = 1;
4825 mutex_unlock(&chip->lock);
4831 * nand_resume - [MTD Interface] Resume the NAND flash
4832 * @mtd: MTD device structure
4834 static void nand_resume(struct mtd_info *mtd)
4836 struct nand_chip *chip = mtd_to_nand(mtd);
4838 mutex_lock(&chip->lock);
4839 if (chip->suspended) {
4840 if (chip->ops.resume)
4841 chip->ops.resume(chip);
4842 chip->suspended = 0;
4844 pr_err("%s called for a chip which is not in suspended state\n",
4847 mutex_unlock(&chip->lock);
4849 wake_up_all(&chip->resume_wq);
4853 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
4854 * prevent further operations
4855 * @mtd: MTD device structure
4857 static void nand_shutdown(struct mtd_info *mtd)
4863 * nand_lock - [MTD Interface] Lock the NAND flash
4864 * @mtd: MTD device structure
4865 * @ofs: offset byte address
4866 * @len: number of bytes to lock (must be a multiple of block/page size)
4868 static int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4870 struct nand_chip *chip = mtd_to_nand(mtd);
4872 if (!chip->ops.lock_area)
4875 return chip->ops.lock_area(chip, ofs, len);
4879 * nand_unlock - [MTD Interface] Unlock the NAND flash
4880 * @mtd: MTD device structure
4881 * @ofs: offset byte address
4882 * @len: number of bytes to unlock (must be a multiple of block/page size)
4884 static int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
4886 struct nand_chip *chip = mtd_to_nand(mtd);
4888 if (!chip->ops.unlock_area)
4891 return chip->ops.unlock_area(chip, ofs, len);
4894 /* Set default functions */
4895 static void nand_set_defaults(struct nand_chip *chip)
4897 /* If no controller is provided, use the dummy, legacy one. */
4898 if (!chip->controller) {
4899 chip->controller = &chip->legacy.dummy_controller;
4900 nand_controller_init(chip->controller);
4903 nand_legacy_set_defaults(chip);
4905 if (!chip->buf_align)
4906 chip->buf_align = 1;
4909 /* Sanitize ONFI strings so we can safely print them */
4910 void sanitize_string(uint8_t *s, size_t len)
4914 /* Null terminate */
4917 /* Remove non printable chars */
4918 for (i = 0; i < len - 1; i++) {
4919 if (s[i] < ' ' || s[i] > 127)
4923 /* Remove trailing spaces */
4928 * nand_id_has_period - Check if an ID string has a given wraparound period
4929 * @id_data: the ID string
4930 * @arrlen: the length of the @id_data array
4931 * @period: the period of repitition
4933 * Check if an ID string is repeated within a given sequence of bytes at
4934 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4935 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4936 * if the repetition has a period of @period; otherwise, returns zero.
4938 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4941 for (i = 0; i < period; i++)
4942 for (j = i + period; j < arrlen; j += period)
4943 if (id_data[i] != id_data[j])
4949 * nand_id_len - Get the length of an ID string returned by CMD_READID
4950 * @id_data: the ID string
4951 * @arrlen: the length of the @id_data array
4953 * Returns the length of the ID string, according to known wraparound/trailing
4954 * zero patterns. If no pattern exists, returns the length of the array.
4956 static int nand_id_len(u8 *id_data, int arrlen)
4958 int last_nonzero, period;
4960 /* Find last non-zero byte */
4961 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4962 if (id_data[last_nonzero])
4966 if (last_nonzero < 0)
4969 /* Calculate wraparound period */
4970 for (period = 1; period < arrlen; period++)
4971 if (nand_id_has_period(id_data, arrlen, period))
4974 /* There's a repeated pattern */
4975 if (period < arrlen)
4978 /* There are trailing zeros */
4979 if (last_nonzero < arrlen - 1)
4980 return last_nonzero + 1;
4982 /* No pattern detected */
4986 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4987 static int nand_get_bits_per_cell(u8 cellinfo)
4991 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4992 bits >>= NAND_CI_CELLTYPE_SHIFT;
4997 * Many new NAND share similar device ID codes, which represent the size of the
4998 * chip. The rest of the parameters must be decoded according to generic or
4999 * manufacturer-specific "extended ID" decoding patterns.
5001 void nand_decode_ext_id(struct nand_chip *chip)
5003 struct nand_memory_organization *memorg;
5004 struct mtd_info *mtd = nand_to_mtd(chip);
5006 u8 *id_data = chip->id.data;
5008 memorg = nanddev_get_memorg(&chip->base);
5010 /* The 3rd id byte holds MLC / multichip data */
5011 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
5012 /* The 4th id byte is the important one */
5016 memorg->pagesize = 1024 << (extid & 0x03);
5017 mtd->writesize = memorg->pagesize;
5020 memorg->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
5021 mtd->oobsize = memorg->oobsize;
5023 /* Calc blocksize. Blocksize is multiples of 64KiB */
5024 memorg->pages_per_eraseblock = ((64 * 1024) << (extid & 0x03)) /
5026 mtd->erasesize = (64 * 1024) << (extid & 0x03);
5028 /* Get buswidth information */
5030 chip->options |= NAND_BUSWIDTH_16;
5032 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
5035 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
5036 * decodes a matching ID table entry and assigns the MTD size parameters for
5039 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
5041 struct mtd_info *mtd = nand_to_mtd(chip);
5042 struct nand_memory_organization *memorg;
5044 memorg = nanddev_get_memorg(&chip->base);
5046 memorg->pages_per_eraseblock = type->erasesize / type->pagesize;
5047 mtd->erasesize = type->erasesize;
5048 memorg->pagesize = type->pagesize;
5049 mtd->writesize = memorg->pagesize;
5050 memorg->oobsize = memorg->pagesize / 32;
5051 mtd->oobsize = memorg->oobsize;
5053 /* All legacy ID NAND are small-page, SLC */
5054 memorg->bits_per_cell = 1;
5058 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
5059 * heuristic patterns using various detected parameters (e.g., manufacturer,
5060 * page size, cell-type information).
5062 static void nand_decode_bbm_options(struct nand_chip *chip)
5064 struct mtd_info *mtd = nand_to_mtd(chip);
5066 /* Set the bad block position */
5067 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
5068 chip->badblockpos = NAND_BBM_POS_LARGE;
5070 chip->badblockpos = NAND_BBM_POS_SMALL;
5073 static inline bool is_full_id_nand(struct nand_flash_dev *type)
5075 return type->id_len;
5078 static bool find_full_id_nand(struct nand_chip *chip,
5079 struct nand_flash_dev *type)
5081 struct nand_device *base = &chip->base;
5082 struct nand_ecc_props requirements;
5083 struct mtd_info *mtd = nand_to_mtd(chip);
5084 struct nand_memory_organization *memorg;
5085 u8 *id_data = chip->id.data;
5087 memorg = nanddev_get_memorg(&chip->base);
5089 if (!strncmp(type->id, id_data, type->id_len)) {
5090 memorg->pagesize = type->pagesize;
5091 mtd->writesize = memorg->pagesize;
5092 memorg->pages_per_eraseblock = type->erasesize /
5094 mtd->erasesize = type->erasesize;
5095 memorg->oobsize = type->oobsize;
5096 mtd->oobsize = memorg->oobsize;
5098 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
5099 memorg->eraseblocks_per_lun =
5100 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
5102 memorg->pages_per_eraseblock);
5103 chip->options |= type->options;
5104 requirements.strength = NAND_ECC_STRENGTH(type);
5105 requirements.step_size = NAND_ECC_STEP(type);
5106 nanddev_set_ecc_requirements(base, &requirements);
5108 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
5109 if (!chip->parameters.model)
5118 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
5119 * compliant and does not have a full-id or legacy-id entry in the nand_ids
5122 static void nand_manufacturer_detect(struct nand_chip *chip)
5125 * Try manufacturer detection if available and use
5126 * nand_decode_ext_id() otherwise.
5128 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
5129 chip->manufacturer.desc->ops->detect) {
5130 struct nand_memory_organization *memorg;
5132 memorg = nanddev_get_memorg(&chip->base);
5134 /* The 3rd id byte holds MLC / multichip data */
5135 memorg->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
5136 chip->manufacturer.desc->ops->detect(chip);
5138 nand_decode_ext_id(chip);
5143 * Manufacturer initialization. This function is called for all NANDs including
5144 * ONFI and JEDEC compliant ones.
5145 * Manufacturer drivers should put all their specific initialization code in
5146 * their ->init() hook.
5148 static int nand_manufacturer_init(struct nand_chip *chip)
5150 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
5151 !chip->manufacturer.desc->ops->init)
5154 return chip->manufacturer.desc->ops->init(chip);
5158 * Manufacturer cleanup. This function is called for all NANDs including
5159 * ONFI and JEDEC compliant ones.
5160 * Manufacturer drivers should put all their specific cleanup code in their
5163 static void nand_manufacturer_cleanup(struct nand_chip *chip)
5165 /* Release manufacturer private data */
5166 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
5167 chip->manufacturer.desc->ops->cleanup)
5168 chip->manufacturer.desc->ops->cleanup(chip);
5172 nand_manufacturer_name(const struct nand_manufacturer_desc *manufacturer_desc)
5174 return manufacturer_desc ? manufacturer_desc->name : "Unknown";
5177 static void rawnand_check_data_only_read_support(struct nand_chip *chip)
5179 /* Use an arbitrary size for the check */
5180 if (!nand_read_data_op(chip, NULL, SZ_512, true, true))
5181 chip->controller->supported_op.data_only_read = 1;
5184 static void rawnand_early_check_supported_ops(struct nand_chip *chip)
5186 /* The supported_op fields should not be set by individual drivers */
5187 WARN_ON_ONCE(chip->controller->supported_op.data_only_read);
5189 if (!nand_has_exec_op(chip))
5192 rawnand_check_data_only_read_support(chip);
5195 static void rawnand_check_cont_read_support(struct nand_chip *chip)
5197 struct mtd_info *mtd = nand_to_mtd(chip);
5199 if (!chip->parameters.supports_read_cache)
5202 if (chip->read_retries)
5205 if (!nand_lp_exec_cont_read_page_op(chip, 0, 0, NULL,
5206 mtd->writesize, true))
5207 chip->controller->supported_op.cont_read = 1;
5210 static void rawnand_late_check_supported_ops(struct nand_chip *chip)
5212 /* The supported_op fields should not be set by individual drivers */
5213 WARN_ON_ONCE(chip->controller->supported_op.cont_read);
5216 * Too many devices do not support sequential cached reads with on-die
5217 * ECC correction enabled, so in this case refuse to perform the
5220 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_ON_DIE)
5223 if (!nand_has_exec_op(chip))
5227 * For now, continuous reads can only be used with the core page helpers.
5228 * This can be extended later.
5230 if (!(chip->ecc.read_page == nand_read_page_hwecc ||
5231 chip->ecc.read_page == nand_read_page_syndrome ||
5232 chip->ecc.read_page == nand_read_page_swecc))
5235 rawnand_check_cont_read_support(chip);
5239 * Get the flash and manufacturer id and lookup if the type is supported.
5241 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
5243 const struct nand_manufacturer_desc *manufacturer_desc;
5244 struct mtd_info *mtd = nand_to_mtd(chip);
5245 struct nand_memory_organization *memorg;
5247 u8 *id_data = chip->id.data;
5252 * Let's start by initializing memorg fields that might be left
5253 * unassigned by the ID-based detection logic.
5255 memorg = nanddev_get_memorg(&chip->base);
5256 memorg->planes_per_lun = 1;
5257 memorg->luns_per_target = 1;
5260 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
5263 ret = nand_reset(chip, 0);
5267 /* Select the device */
5268 nand_select_target(chip, 0);
5270 rawnand_early_check_supported_ops(chip);
5272 /* Send the command for reading device ID */
5273 ret = nand_readid_op(chip, 0, id_data, 2);
5277 /* Read manufacturer and device IDs */
5278 maf_id = id_data[0];
5279 dev_id = id_data[1];
5282 * Try again to make sure, as some systems the bus-hold or other
5283 * interface concerns can cause random data which looks like a
5284 * possibly credible NAND flash to appear. If the two results do
5285 * not match, ignore the device completely.
5288 /* Read entire ID string */
5289 ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
5293 if (id_data[0] != maf_id || id_data[1] != dev_id) {
5294 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
5295 maf_id, dev_id, id_data[0], id_data[1]);
5299 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
5301 /* Try to identify manufacturer */
5302 manufacturer_desc = nand_get_manufacturer_desc(maf_id);
5303 chip->manufacturer.desc = manufacturer_desc;
5306 type = nand_flash_ids;
5309 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
5311 * This is required to make sure initial NAND bus width set by the
5312 * NAND controller driver is coherent with the real NAND bus width
5313 * (extracted by auto-detection code).
5315 busw = chip->options & NAND_BUSWIDTH_16;
5318 * The flag is only set (never cleared), reset it to its default value
5319 * before starting auto-detection.
5321 chip->options &= ~NAND_BUSWIDTH_16;
5323 for (; type->name != NULL; type++) {
5324 if (is_full_id_nand(type)) {
5325 if (find_full_id_nand(chip, type))
5327 } else if (dev_id == type->dev_id) {
5332 if (!type->name || !type->pagesize) {
5333 /* Check if the chip is ONFI compliant */
5334 ret = nand_onfi_detect(chip);
5340 /* Check if the chip is JEDEC compliant */
5341 ret = nand_jedec_detect(chip);
5351 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
5352 if (!chip->parameters.model)
5355 if (!type->pagesize)
5356 nand_manufacturer_detect(chip);
5358 nand_decode_id(chip, type);
5360 /* Get chip options */
5361 chip->options |= type->options;
5363 memorg->eraseblocks_per_lun =
5364 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
5366 memorg->pages_per_eraseblock);
5370 mtd->name = chip->parameters.model;
5372 if (chip->options & NAND_BUSWIDTH_AUTO) {
5373 WARN_ON(busw & NAND_BUSWIDTH_16);
5374 nand_set_defaults(chip);
5375 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
5377 * Check, if buswidth is correct. Hardware drivers should set
5380 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5382 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
5384 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
5385 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
5388 goto free_detect_allocation;
5391 nand_decode_bbm_options(chip);
5393 /* Calculate the address shift from the page size */
5394 chip->page_shift = ffs(mtd->writesize) - 1;
5395 /* Convert chipsize to number of pages per chip -1 */
5396 targetsize = nanddev_target_size(&chip->base);
5397 chip->pagemask = (targetsize >> chip->page_shift) - 1;
5399 chip->bbt_erase_shift = chip->phys_erase_shift =
5400 ffs(mtd->erasesize) - 1;
5401 if (targetsize & 0xffffffff)
5402 chip->chip_shift = ffs((unsigned)targetsize) - 1;
5404 chip->chip_shift = ffs((unsigned)(targetsize >> 32));
5405 chip->chip_shift += 32 - 1;
5408 if (chip->chip_shift - chip->page_shift > 16)
5409 chip->options |= NAND_ROW_ADDR_3;
5411 chip->badblockbits = 8;
5413 nand_legacy_adjust_cmdfunc(chip);
5415 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5417 pr_info("%s %s\n", nand_manufacturer_name(manufacturer_desc),
5418 chip->parameters.model);
5419 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
5420 (int)(targetsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
5421 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
5424 free_detect_allocation:
5425 kfree(chip->parameters.model);
5430 static enum nand_ecc_engine_type
5431 of_get_rawnand_ecc_engine_type_legacy(struct device_node *np)
5433 enum nand_ecc_legacy_mode {
5439 NAND_ECC_HW_SYNDROME,
5442 const char * const nand_ecc_legacy_modes[] = {
5443 [NAND_ECC_NONE] = "none",
5444 [NAND_ECC_SOFT] = "soft",
5445 [NAND_ECC_SOFT_BCH] = "soft_bch",
5446 [NAND_ECC_HW] = "hw",
5447 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
5448 [NAND_ECC_ON_DIE] = "on-die",
5450 enum nand_ecc_legacy_mode eng_type;
5454 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5456 return NAND_ECC_ENGINE_TYPE_INVALID;
5458 for (eng_type = NAND_ECC_NONE;
5459 eng_type < ARRAY_SIZE(nand_ecc_legacy_modes); eng_type++) {
5460 if (!strcasecmp(pm, nand_ecc_legacy_modes[eng_type])) {
5463 return NAND_ECC_ENGINE_TYPE_NONE;
5465 case NAND_ECC_SOFT_BCH:
5466 return NAND_ECC_ENGINE_TYPE_SOFT;
5468 case NAND_ECC_HW_SYNDROME:
5469 return NAND_ECC_ENGINE_TYPE_ON_HOST;
5470 case NAND_ECC_ON_DIE:
5471 return NAND_ECC_ENGINE_TYPE_ON_DIE;
5478 return NAND_ECC_ENGINE_TYPE_INVALID;
5481 static enum nand_ecc_placement
5482 of_get_rawnand_ecc_placement_legacy(struct device_node *np)
5487 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5489 if (!strcasecmp(pm, "hw_syndrome"))
5490 return NAND_ECC_PLACEMENT_INTERLEAVED;
5493 return NAND_ECC_PLACEMENT_UNKNOWN;
5496 static enum nand_ecc_algo of_get_rawnand_ecc_algo_legacy(struct device_node *np)
5501 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5503 if (!strcasecmp(pm, "soft"))
5504 return NAND_ECC_ALGO_HAMMING;
5505 else if (!strcasecmp(pm, "soft_bch"))
5506 return NAND_ECC_ALGO_BCH;
5509 return NAND_ECC_ALGO_UNKNOWN;
5512 static void of_get_nand_ecc_legacy_user_config(struct nand_chip *chip)
5514 struct device_node *dn = nand_get_flash_node(chip);
5515 struct nand_ecc_props *user_conf = &chip->base.ecc.user_conf;
5517 if (user_conf->engine_type == NAND_ECC_ENGINE_TYPE_INVALID)
5518 user_conf->engine_type = of_get_rawnand_ecc_engine_type_legacy(dn);
5520 if (user_conf->algo == NAND_ECC_ALGO_UNKNOWN)
5521 user_conf->algo = of_get_rawnand_ecc_algo_legacy(dn);
5523 if (user_conf->placement == NAND_ECC_PLACEMENT_UNKNOWN)
5524 user_conf->placement = of_get_rawnand_ecc_placement_legacy(dn);
5527 static int of_get_nand_bus_width(struct nand_chip *chip)
5529 struct device_node *dn = nand_get_flash_node(chip);
5533 ret = of_property_read_u32(dn, "nand-bus-width", &val);
5535 /* Buswidth defaults to 8 if the property does not exist .*/
5541 chip->options |= NAND_BUSWIDTH_16;
5547 static int of_get_nand_secure_regions(struct nand_chip *chip)
5549 struct device_node *dn = nand_get_flash_node(chip);
5550 struct property *prop;
5553 /* Only proceed if the "secure-regions" property is present in DT */
5554 prop = of_find_property(dn, "secure-regions", NULL);
5558 nr_elem = of_property_count_elems_of_size(dn, "secure-regions", sizeof(u64));
5562 chip->nr_secure_regions = nr_elem / 2;
5563 chip->secure_regions = kcalloc(chip->nr_secure_regions, sizeof(*chip->secure_regions),
5565 if (!chip->secure_regions)
5568 for (i = 0, j = 0; i < chip->nr_secure_regions; i++, j += 2) {
5569 of_property_read_u64_index(dn, "secure-regions", j,
5570 &chip->secure_regions[i].offset);
5571 of_property_read_u64_index(dn, "secure-regions", j + 1,
5572 &chip->secure_regions[i].size);
5579 * rawnand_dt_parse_gpio_cs - Parse the gpio-cs property of a controller
5580 * @dev: Device that will be parsed. Also used for managed allocations.
5581 * @cs_array: Array of GPIO desc pointers allocated on success
5582 * @ncs_array: Number of entries in @cs_array updated on success.
5583 * @return 0 on success, an error otherwise.
5585 int rawnand_dt_parse_gpio_cs(struct device *dev, struct gpio_desc ***cs_array,
5586 unsigned int *ncs_array)
5588 struct gpio_desc **descs;
5591 ndescs = gpiod_count(dev, "cs");
5593 dev_dbg(dev, "No valid cs-gpios property\n");
5597 descs = devm_kcalloc(dev, ndescs, sizeof(*descs), GFP_KERNEL);
5601 for (i = 0; i < ndescs; i++) {
5602 descs[i] = gpiod_get_index_optional(dev, "cs", i,
5604 if (IS_ERR(descs[i]))
5605 return PTR_ERR(descs[i]);
5608 *ncs_array = ndescs;
5613 EXPORT_SYMBOL(rawnand_dt_parse_gpio_cs);
5615 static int rawnand_dt_init(struct nand_chip *chip)
5617 struct nand_device *nand = mtd_to_nanddev(nand_to_mtd(chip));
5618 struct device_node *dn = nand_get_flash_node(chip);
5624 ret = of_get_nand_bus_width(chip);
5628 if (of_property_read_bool(dn, "nand-is-boot-medium"))
5629 chip->options |= NAND_IS_BOOT_MEDIUM;
5631 if (of_property_read_bool(dn, "nand-on-flash-bbt"))
5632 chip->bbt_options |= NAND_BBT_USE_FLASH;
5634 of_get_nand_ecc_user_config(nand);
5635 of_get_nand_ecc_legacy_user_config(chip);
5638 * If neither the user nor the NAND controller have requested a specific
5639 * ECC engine type, we will default to NAND_ECC_ENGINE_TYPE_ON_HOST.
5641 nand->ecc.defaults.engine_type = NAND_ECC_ENGINE_TYPE_ON_HOST;
5644 * Use the user requested engine type, unless there is none, in this
5645 * case default to the NAND controller choice, otherwise fallback to
5646 * the raw NAND default one.
5648 if (nand->ecc.user_conf.engine_type != NAND_ECC_ENGINE_TYPE_INVALID)
5649 chip->ecc.engine_type = nand->ecc.user_conf.engine_type;
5650 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_INVALID)
5651 chip->ecc.engine_type = nand->ecc.defaults.engine_type;
5653 chip->ecc.placement = nand->ecc.user_conf.placement;
5654 chip->ecc.algo = nand->ecc.user_conf.algo;
5655 chip->ecc.strength = nand->ecc.user_conf.strength;
5656 chip->ecc.size = nand->ecc.user_conf.step_size;
5662 * nand_scan_ident - Scan for the NAND device
5663 * @chip: NAND chip object
5664 * @maxchips: number of chips to scan for
5665 * @table: alternative NAND ID table
5667 * This is the first phase of the normal nand_scan() function. It reads the
5668 * flash ID and sets up MTD fields accordingly.
5670 * This helper used to be called directly from controller drivers that needed
5671 * to tweak some ECC-related parameters before nand_scan_tail(). This separation
5672 * prevented dynamic allocations during this phase which was unconvenient and
5673 * as been banned for the benefit of the ->init_ecc()/cleanup_ecc() hooks.
5675 static int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips,
5676 struct nand_flash_dev *table)
5678 struct mtd_info *mtd = nand_to_mtd(chip);
5679 struct nand_memory_organization *memorg;
5680 int nand_maf_id, nand_dev_id;
5684 memorg = nanddev_get_memorg(&chip->base);
5686 /* Assume all dies are deselected when we enter nand_scan_ident(). */
5689 mutex_init(&chip->lock);
5690 init_waitqueue_head(&chip->resume_wq);
5692 /* Enforce the right timings for reset/detection */
5693 chip->current_interface_config = nand_get_reset_interface_config();
5695 ret = rawnand_dt_init(chip);
5699 if (!mtd->name && mtd->dev.parent)
5700 mtd->name = dev_name(mtd->dev.parent);
5702 /* Set the default functions */
5703 nand_set_defaults(chip);
5705 ret = nand_legacy_check_hooks(chip);
5709 memorg->ntargets = maxchips;
5711 /* Read the flash type */
5712 ret = nand_detect(chip, table);
5714 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
5715 pr_warn("No NAND device found\n");
5716 nand_deselect_target(chip);
5720 nand_maf_id = chip->id.data[0];
5721 nand_dev_id = chip->id.data[1];
5723 nand_deselect_target(chip);
5725 /* Check for a chip array */
5726 for (i = 1; i < maxchips; i++) {
5729 /* See comment in nand_get_flash_type for reset */
5730 ret = nand_reset(chip, i);
5734 nand_select_target(chip, i);
5735 /* Send the command for reading device ID */
5736 ret = nand_readid_op(chip, 0, id, sizeof(id));
5739 /* Read manufacturer and device IDs */
5740 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
5741 nand_deselect_target(chip);
5744 nand_deselect_target(chip);
5747 pr_info("%d chips detected\n", i);
5749 /* Store the number of chips and calc total size for mtd */
5750 memorg->ntargets = i;
5751 mtd->size = i * nanddev_target_size(&chip->base);
5756 static void nand_scan_ident_cleanup(struct nand_chip *chip)
5758 kfree(chip->parameters.model);
5759 kfree(chip->parameters.onfi);
5762 int rawnand_sw_hamming_init(struct nand_chip *chip)
5764 struct nand_ecc_sw_hamming_conf *engine_conf;
5765 struct nand_device *base = &chip->base;
5768 base->ecc.user_conf.engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5769 base->ecc.user_conf.algo = NAND_ECC_ALGO_HAMMING;
5770 base->ecc.user_conf.strength = chip->ecc.strength;
5771 base->ecc.user_conf.step_size = chip->ecc.size;
5773 ret = nand_ecc_sw_hamming_init_ctx(base);
5777 engine_conf = base->ecc.ctx.priv;
5779 if (chip->ecc.options & NAND_ECC_SOFT_HAMMING_SM_ORDER)
5780 engine_conf->sm_order = true;
5782 chip->ecc.size = base->ecc.ctx.conf.step_size;
5783 chip->ecc.strength = base->ecc.ctx.conf.strength;
5784 chip->ecc.total = base->ecc.ctx.total;
5785 chip->ecc.steps = nanddev_get_ecc_nsteps(base);
5786 chip->ecc.bytes = base->ecc.ctx.total / nanddev_get_ecc_nsteps(base);
5790 EXPORT_SYMBOL(rawnand_sw_hamming_init);
5792 int rawnand_sw_hamming_calculate(struct nand_chip *chip,
5793 const unsigned char *buf,
5794 unsigned char *code)
5796 struct nand_device *base = &chip->base;
5798 return nand_ecc_sw_hamming_calculate(base, buf, code);
5800 EXPORT_SYMBOL(rawnand_sw_hamming_calculate);
5802 int rawnand_sw_hamming_correct(struct nand_chip *chip,
5804 unsigned char *read_ecc,
5805 unsigned char *calc_ecc)
5807 struct nand_device *base = &chip->base;
5809 return nand_ecc_sw_hamming_correct(base, buf, read_ecc, calc_ecc);
5811 EXPORT_SYMBOL(rawnand_sw_hamming_correct);
5813 void rawnand_sw_hamming_cleanup(struct nand_chip *chip)
5815 struct nand_device *base = &chip->base;
5817 nand_ecc_sw_hamming_cleanup_ctx(base);
5819 EXPORT_SYMBOL(rawnand_sw_hamming_cleanup);
5821 int rawnand_sw_bch_init(struct nand_chip *chip)
5823 struct nand_device *base = &chip->base;
5824 const struct nand_ecc_props *ecc_conf = nanddev_get_ecc_conf(base);
5827 base->ecc.user_conf.engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
5828 base->ecc.user_conf.algo = NAND_ECC_ALGO_BCH;
5829 base->ecc.user_conf.step_size = chip->ecc.size;
5830 base->ecc.user_conf.strength = chip->ecc.strength;
5832 ret = nand_ecc_sw_bch_init_ctx(base);
5836 chip->ecc.size = ecc_conf->step_size;
5837 chip->ecc.strength = ecc_conf->strength;
5838 chip->ecc.total = base->ecc.ctx.total;
5839 chip->ecc.steps = nanddev_get_ecc_nsteps(base);
5840 chip->ecc.bytes = base->ecc.ctx.total / nanddev_get_ecc_nsteps(base);
5844 EXPORT_SYMBOL(rawnand_sw_bch_init);
5846 static int rawnand_sw_bch_calculate(struct nand_chip *chip,
5847 const unsigned char *buf,
5848 unsigned char *code)
5850 struct nand_device *base = &chip->base;
5852 return nand_ecc_sw_bch_calculate(base, buf, code);
5855 int rawnand_sw_bch_correct(struct nand_chip *chip, unsigned char *buf,
5856 unsigned char *read_ecc, unsigned char *calc_ecc)
5858 struct nand_device *base = &chip->base;
5860 return nand_ecc_sw_bch_correct(base, buf, read_ecc, calc_ecc);
5862 EXPORT_SYMBOL(rawnand_sw_bch_correct);
5864 void rawnand_sw_bch_cleanup(struct nand_chip *chip)
5866 struct nand_device *base = &chip->base;
5868 nand_ecc_sw_bch_cleanup_ctx(base);
5870 EXPORT_SYMBOL(rawnand_sw_bch_cleanup);
5872 static int nand_set_ecc_on_host_ops(struct nand_chip *chip)
5874 struct nand_ecc_ctrl *ecc = &chip->ecc;
5876 switch (ecc->placement) {
5877 case NAND_ECC_PLACEMENT_UNKNOWN:
5878 case NAND_ECC_PLACEMENT_OOB:
5879 /* Use standard hwecc read page function? */
5880 if (!ecc->read_page)
5881 ecc->read_page = nand_read_page_hwecc;
5882 if (!ecc->write_page)
5883 ecc->write_page = nand_write_page_hwecc;
5884 if (!ecc->read_page_raw)
5885 ecc->read_page_raw = nand_read_page_raw;
5886 if (!ecc->write_page_raw)
5887 ecc->write_page_raw = nand_write_page_raw;
5889 ecc->read_oob = nand_read_oob_std;
5890 if (!ecc->write_oob)
5891 ecc->write_oob = nand_write_oob_std;
5892 if (!ecc->read_subpage)
5893 ecc->read_subpage = nand_read_subpage;
5894 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5895 ecc->write_subpage = nand_write_subpage_hwecc;
5898 case NAND_ECC_PLACEMENT_INTERLEAVED:
5899 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5901 ecc->read_page == nand_read_page_hwecc ||
5903 ecc->write_page == nand_write_page_hwecc)) {
5904 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5907 /* Use standard syndrome read/write page function? */
5908 if (!ecc->read_page)
5909 ecc->read_page = nand_read_page_syndrome;
5910 if (!ecc->write_page)
5911 ecc->write_page = nand_write_page_syndrome;
5912 if (!ecc->read_page_raw)
5913 ecc->read_page_raw = nand_read_page_raw_syndrome;
5914 if (!ecc->write_page_raw)
5915 ecc->write_page_raw = nand_write_page_raw_syndrome;
5917 ecc->read_oob = nand_read_oob_syndrome;
5918 if (!ecc->write_oob)
5919 ecc->write_oob = nand_write_oob_syndrome;
5923 pr_warn("Invalid NAND_ECC_PLACEMENT %d\n",
5931 static int nand_set_ecc_soft_ops(struct nand_chip *chip)
5933 struct mtd_info *mtd = nand_to_mtd(chip);
5934 struct nand_device *nanddev = mtd_to_nanddev(mtd);
5935 struct nand_ecc_ctrl *ecc = &chip->ecc;
5938 if (WARN_ON(ecc->engine_type != NAND_ECC_ENGINE_TYPE_SOFT))
5941 switch (ecc->algo) {
5942 case NAND_ECC_ALGO_HAMMING:
5943 ecc->calculate = rawnand_sw_hamming_calculate;
5944 ecc->correct = rawnand_sw_hamming_correct;
5945 ecc->read_page = nand_read_page_swecc;
5946 ecc->read_subpage = nand_read_subpage;
5947 ecc->write_page = nand_write_page_swecc;
5948 if (!ecc->read_page_raw)
5949 ecc->read_page_raw = nand_read_page_raw;
5950 if (!ecc->write_page_raw)
5951 ecc->write_page_raw = nand_write_page_raw;
5952 ecc->read_oob = nand_read_oob_std;
5953 ecc->write_oob = nand_write_oob_std;
5959 if (IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_HAMMING_SMC))
5960 ecc->options |= NAND_ECC_SOFT_HAMMING_SM_ORDER;
5962 ret = rawnand_sw_hamming_init(chip);
5964 WARN(1, "Hamming ECC initialization failed!\n");
5969 case NAND_ECC_ALGO_BCH:
5970 if (!IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_BCH)) {
5971 WARN(1, "CONFIG_MTD_NAND_ECC_SW_BCH not enabled\n");
5974 ecc->calculate = rawnand_sw_bch_calculate;
5975 ecc->correct = rawnand_sw_bch_correct;
5976 ecc->read_page = nand_read_page_swecc;
5977 ecc->read_subpage = nand_read_subpage;
5978 ecc->write_page = nand_write_page_swecc;
5979 if (!ecc->read_page_raw)
5980 ecc->read_page_raw = nand_read_page_raw;
5981 if (!ecc->write_page_raw)
5982 ecc->write_page_raw = nand_write_page_raw;
5983 ecc->read_oob = nand_read_oob_std;
5984 ecc->write_oob = nand_write_oob_std;
5987 * We can only maximize ECC config when the default layout is
5988 * used, otherwise we don't know how many bytes can really be
5991 if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH &&
5992 mtd->ooblayout != nand_get_large_page_ooblayout())
5993 nanddev->ecc.user_conf.flags &= ~NAND_ECC_MAXIMIZE_STRENGTH;
5995 ret = rawnand_sw_bch_init(chip);
5997 WARN(1, "BCH ECC initialization failed!\n");
6003 WARN(1, "Unsupported ECC algorithm!\n");
6009 * nand_check_ecc_caps - check the sanity of preset ECC settings
6010 * @chip: nand chip info structure
6011 * @caps: ECC caps info structure
6012 * @oobavail: OOB size that the ECC engine can use
6014 * When ECC step size and strength are already set, check if they are supported
6015 * by the controller and the calculated ECC bytes fit within the chip's OOB.
6016 * On success, the calculated ECC bytes is set.
6019 nand_check_ecc_caps(struct nand_chip *chip,
6020 const struct nand_ecc_caps *caps, int oobavail)
6022 struct mtd_info *mtd = nand_to_mtd(chip);
6023 const struct nand_ecc_step_info *stepinfo;
6024 int preset_step = chip->ecc.size;
6025 int preset_strength = chip->ecc.strength;
6026 int ecc_bytes, nsteps = mtd->writesize / preset_step;
6029 for (i = 0; i < caps->nstepinfos; i++) {
6030 stepinfo = &caps->stepinfos[i];
6032 if (stepinfo->stepsize != preset_step)
6035 for (j = 0; j < stepinfo->nstrengths; j++) {
6036 if (stepinfo->strengths[j] != preset_strength)
6039 ecc_bytes = caps->calc_ecc_bytes(preset_step,
6041 if (WARN_ON_ONCE(ecc_bytes < 0))
6044 if (ecc_bytes * nsteps > oobavail) {
6045 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
6046 preset_step, preset_strength);
6050 chip->ecc.bytes = ecc_bytes;
6056 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
6057 preset_step, preset_strength);
6063 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
6064 * @chip: nand chip info structure
6065 * @caps: ECC engine caps info structure
6066 * @oobavail: OOB size that the ECC engine can use
6068 * If a chip's ECC requirement is provided, try to meet it with the least
6069 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
6070 * On success, the chosen ECC settings are set.
6073 nand_match_ecc_req(struct nand_chip *chip,
6074 const struct nand_ecc_caps *caps, int oobavail)
6076 const struct nand_ecc_props *requirements =
6077 nanddev_get_ecc_requirements(&chip->base);
6078 struct mtd_info *mtd = nand_to_mtd(chip);
6079 const struct nand_ecc_step_info *stepinfo;
6080 int req_step = requirements->step_size;
6081 int req_strength = requirements->strength;
6082 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
6083 int best_step = 0, best_strength = 0, best_ecc_bytes = 0;
6084 int best_ecc_bytes_total = INT_MAX;
6087 /* No information provided by the NAND chip */
6088 if (!req_step || !req_strength)
6091 /* number of correctable bits the chip requires in a page */
6092 req_corr = mtd->writesize / req_step * req_strength;
6094 for (i = 0; i < caps->nstepinfos; i++) {
6095 stepinfo = &caps->stepinfos[i];
6096 step_size = stepinfo->stepsize;
6098 for (j = 0; j < stepinfo->nstrengths; j++) {
6099 strength = stepinfo->strengths[j];
6102 * If both step size and strength are smaller than the
6103 * chip's requirement, it is not easy to compare the
6104 * resulted reliability.
6106 if (step_size < req_step && strength < req_strength)
6109 if (mtd->writesize % step_size)
6112 nsteps = mtd->writesize / step_size;
6114 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
6115 if (WARN_ON_ONCE(ecc_bytes < 0))
6117 ecc_bytes_total = ecc_bytes * nsteps;
6119 if (ecc_bytes_total > oobavail ||
6120 strength * nsteps < req_corr)
6124 * We assume the best is to meet the chip's requrement
6125 * with the least number of ECC bytes.
6127 if (ecc_bytes_total < best_ecc_bytes_total) {
6128 best_ecc_bytes_total = ecc_bytes_total;
6129 best_step = step_size;
6130 best_strength = strength;
6131 best_ecc_bytes = ecc_bytes;
6136 if (best_ecc_bytes_total == INT_MAX)
6139 chip->ecc.size = best_step;
6140 chip->ecc.strength = best_strength;
6141 chip->ecc.bytes = best_ecc_bytes;
6147 * nand_maximize_ecc - choose the max ECC strength available
6148 * @chip: nand chip info structure
6149 * @caps: ECC engine caps info structure
6150 * @oobavail: OOB size that the ECC engine can use
6152 * Choose the max ECC strength that is supported on the controller, and can fit
6153 * within the chip's OOB. On success, the chosen ECC settings are set.
6156 nand_maximize_ecc(struct nand_chip *chip,
6157 const struct nand_ecc_caps *caps, int oobavail)
6159 struct mtd_info *mtd = nand_to_mtd(chip);
6160 const struct nand_ecc_step_info *stepinfo;
6161 int step_size, strength, nsteps, ecc_bytes, corr;
6164 int best_strength = 0, best_ecc_bytes = 0;
6167 for (i = 0; i < caps->nstepinfos; i++) {
6168 stepinfo = &caps->stepinfos[i];
6169 step_size = stepinfo->stepsize;
6171 /* If chip->ecc.size is already set, respect it */
6172 if (chip->ecc.size && step_size != chip->ecc.size)
6175 for (j = 0; j < stepinfo->nstrengths; j++) {
6176 strength = stepinfo->strengths[j];
6178 if (mtd->writesize % step_size)
6181 nsteps = mtd->writesize / step_size;
6183 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
6184 if (WARN_ON_ONCE(ecc_bytes < 0))
6187 if (ecc_bytes * nsteps > oobavail)
6190 corr = strength * nsteps;
6193 * If the number of correctable bits is the same,
6194 * bigger step_size has more reliability.
6196 if (corr > best_corr ||
6197 (corr == best_corr && step_size > best_step)) {
6199 best_step = step_size;
6200 best_strength = strength;
6201 best_ecc_bytes = ecc_bytes;
6209 chip->ecc.size = best_step;
6210 chip->ecc.strength = best_strength;
6211 chip->ecc.bytes = best_ecc_bytes;
6217 * nand_ecc_choose_conf - Set the ECC strength and ECC step size
6218 * @chip: nand chip info structure
6219 * @caps: ECC engine caps info structure
6220 * @oobavail: OOB size that the ECC engine can use
6222 * Choose the ECC configuration according to following logic.
6224 * 1. If both ECC step size and ECC strength are already set (usually by DT)
6225 * then check if it is supported by this controller.
6226 * 2. If the user provided the nand-ecc-maximize property, then select maximum
6228 * 3. Otherwise, try to match the ECC step size and ECC strength closest
6229 * to the chip's requirement. If available OOB size can't fit the chip
6230 * requirement then fallback to the maximum ECC step size and ECC strength.
6232 * On success, the chosen ECC settings are set.
6234 int nand_ecc_choose_conf(struct nand_chip *chip,
6235 const struct nand_ecc_caps *caps, int oobavail)
6237 struct mtd_info *mtd = nand_to_mtd(chip);
6238 struct nand_device *nanddev = mtd_to_nanddev(mtd);
6240 if (WARN_ON(oobavail < 0 || oobavail > mtd->oobsize))
6243 if (chip->ecc.size && chip->ecc.strength)
6244 return nand_check_ecc_caps(chip, caps, oobavail);
6246 if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH)
6247 return nand_maximize_ecc(chip, caps, oobavail);
6249 if (!nand_match_ecc_req(chip, caps, oobavail))
6252 return nand_maximize_ecc(chip, caps, oobavail);
6254 EXPORT_SYMBOL_GPL(nand_ecc_choose_conf);
6256 static int rawnand_erase(struct nand_device *nand, const struct nand_pos *pos)
6258 struct nand_chip *chip = container_of(nand, struct nand_chip,
6260 unsigned int eb = nanddev_pos_to_row(nand, pos);
6263 eb >>= nand->rowconv.eraseblock_addr_shift;
6265 nand_select_target(chip, pos->target);
6266 ret = nand_erase_op(chip, eb);
6267 nand_deselect_target(chip);
6272 static int rawnand_markbad(struct nand_device *nand,
6273 const struct nand_pos *pos)
6275 struct nand_chip *chip = container_of(nand, struct nand_chip,
6278 return nand_markbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
6281 static bool rawnand_isbad(struct nand_device *nand, const struct nand_pos *pos)
6283 struct nand_chip *chip = container_of(nand, struct nand_chip,
6287 nand_select_target(chip, pos->target);
6288 ret = nand_isbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
6289 nand_deselect_target(chip);
6294 static const struct nand_ops rawnand_ops = {
6295 .erase = rawnand_erase,
6296 .markbad = rawnand_markbad,
6297 .isbad = rawnand_isbad,
6301 * nand_scan_tail - Scan for the NAND device
6302 * @chip: NAND chip object
6304 * This is the second phase of the normal nand_scan() function. It fills out
6305 * all the uninitialized function pointers with the defaults and scans for a
6306 * bad block table if appropriate.
6308 static int nand_scan_tail(struct nand_chip *chip)
6310 struct mtd_info *mtd = nand_to_mtd(chip);
6311 struct nand_device *base = &chip->base;
6312 struct nand_ecc_ctrl *ecc = &chip->ecc;
6315 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
6316 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
6317 !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
6321 chip->data_buf = kmalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
6322 if (!chip->data_buf)
6326 * FIXME: some NAND manufacturer drivers expect the first die to be
6327 * selected when manufacturer->init() is called. They should be fixed
6328 * to explictly select the relevant die when interacting with the NAND
6331 nand_select_target(chip, 0);
6332 ret = nand_manufacturer_init(chip);
6333 nand_deselect_target(chip);
6337 /* Set the internal oob buffer location, just after the page data */
6338 chip->oob_poi = chip->data_buf + mtd->writesize;
6341 * If no default placement scheme is given, select an appropriate one.
6343 if (!mtd->ooblayout &&
6344 !(ecc->engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
6345 ecc->algo == NAND_ECC_ALGO_BCH) &&
6346 !(ecc->engine_type == NAND_ECC_ENGINE_TYPE_SOFT &&
6347 ecc->algo == NAND_ECC_ALGO_HAMMING)) {
6348 switch (mtd->oobsize) {
6351 mtd_set_ooblayout(mtd, nand_get_small_page_ooblayout());
6355 mtd_set_ooblayout(mtd,
6356 nand_get_large_page_hamming_ooblayout());
6360 * Expose the whole OOB area to users if ECC_NONE
6361 * is passed. We could do that for all kind of
6362 * ->oobsize, but we must keep the old large/small
6363 * page with ECC layout when ->oobsize <= 128 for
6364 * compatibility reasons.
6366 if (ecc->engine_type == NAND_ECC_ENGINE_TYPE_NONE) {
6367 mtd_set_ooblayout(mtd,
6368 nand_get_large_page_ooblayout());
6372 WARN(1, "No oob scheme defined for oobsize %d\n",
6375 goto err_nand_manuf_cleanup;
6380 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
6381 * selected and we have 256 byte pagesize fallback to software ECC
6384 switch (ecc->engine_type) {
6385 case NAND_ECC_ENGINE_TYPE_ON_HOST:
6386 ret = nand_set_ecc_on_host_ops(chip);
6388 goto err_nand_manuf_cleanup;
6390 if (mtd->writesize >= ecc->size) {
6391 if (!ecc->strength) {
6392 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
6394 goto err_nand_manuf_cleanup;
6398 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
6399 ecc->size, mtd->writesize);
6400 ecc->engine_type = NAND_ECC_ENGINE_TYPE_SOFT;
6401 ecc->algo = NAND_ECC_ALGO_HAMMING;
6404 case NAND_ECC_ENGINE_TYPE_SOFT:
6405 ret = nand_set_ecc_soft_ops(chip);
6407 goto err_nand_manuf_cleanup;
6410 case NAND_ECC_ENGINE_TYPE_ON_DIE:
6411 if (!ecc->read_page || !ecc->write_page) {
6412 WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
6414 goto err_nand_manuf_cleanup;
6417 ecc->read_oob = nand_read_oob_std;
6418 if (!ecc->write_oob)
6419 ecc->write_oob = nand_write_oob_std;
6422 case NAND_ECC_ENGINE_TYPE_NONE:
6423 pr_warn("NAND_ECC_ENGINE_TYPE_NONE selected by board driver. This is not recommended!\n");
6424 ecc->read_page = nand_read_page_raw;
6425 ecc->write_page = nand_write_page_raw;
6426 ecc->read_oob = nand_read_oob_std;
6427 ecc->read_page_raw = nand_read_page_raw;
6428 ecc->write_page_raw = nand_write_page_raw;
6429 ecc->write_oob = nand_write_oob_std;
6430 ecc->size = mtd->writesize;
6436 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->engine_type);
6438 goto err_nand_manuf_cleanup;
6441 if (ecc->correct || ecc->calculate) {
6442 ecc->calc_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
6443 ecc->code_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
6444 if (!ecc->calc_buf || !ecc->code_buf) {
6446 goto err_nand_manuf_cleanup;
6450 /* For many systems, the standard OOB write also works for raw */
6451 if (!ecc->read_oob_raw)
6452 ecc->read_oob_raw = ecc->read_oob;
6453 if (!ecc->write_oob_raw)
6454 ecc->write_oob_raw = ecc->write_oob;
6456 /* Propagate ECC info to the generic NAND and MTD layers */
6457 mtd->ecc_strength = ecc->strength;
6458 if (!base->ecc.ctx.conf.strength)
6459 base->ecc.ctx.conf.strength = ecc->strength;
6460 mtd->ecc_step_size = ecc->size;
6461 if (!base->ecc.ctx.conf.step_size)
6462 base->ecc.ctx.conf.step_size = ecc->size;
6465 * Set the number of read / write steps for one page depending on ECC
6469 ecc->steps = mtd->writesize / ecc->size;
6470 if (!base->ecc.ctx.nsteps)
6471 base->ecc.ctx.nsteps = ecc->steps;
6472 if (ecc->steps * ecc->size != mtd->writesize) {
6473 WARN(1, "Invalid ECC parameters\n");
6475 goto err_nand_manuf_cleanup;
6479 ecc->total = ecc->steps * ecc->bytes;
6480 chip->base.ecc.ctx.total = ecc->total;
6483 if (ecc->total > mtd->oobsize) {
6484 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
6486 goto err_nand_manuf_cleanup;
6490 * The number of bytes available for a client to place data into
6491 * the out of band area.
6493 ret = mtd_ooblayout_count_freebytes(mtd);
6497 mtd->oobavail = ret;
6499 /* ECC sanity check: warn if it's too weak */
6500 if (!nand_ecc_is_strong_enough(&chip->base))
6501 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",
6502 mtd->name, chip->ecc.strength, chip->ecc.size,
6503 nanddev_get_ecc_requirements(&chip->base)->strength,
6504 nanddev_get_ecc_requirements(&chip->base)->step_size);
6506 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
6507 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
6508 switch (ecc->steps) {
6510 mtd->subpage_sft = 1;
6515 mtd->subpage_sft = 2;
6519 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
6521 /* Invalidate the pagebuffer reference */
6522 chip->pagecache.page = -1;
6524 /* Large page NAND with SOFT_ECC should support subpage reads */
6525 switch (ecc->engine_type) {
6526 case NAND_ECC_ENGINE_TYPE_SOFT:
6527 if (chip->page_shift > 9)
6528 chip->options |= NAND_SUBPAGE_READ;
6535 ret = nanddev_init(&chip->base, &rawnand_ops, mtd->owner);
6537 goto err_nand_manuf_cleanup;
6539 /* Adjust the MTD_CAP_ flags when NAND_ROM is set. */
6540 if (chip->options & NAND_ROM)
6541 mtd->flags = MTD_CAP_ROM;
6543 /* Fill in remaining MTD driver data */
6544 mtd->_erase = nand_erase;
6546 mtd->_unpoint = NULL;
6547 mtd->_panic_write = panic_nand_write;
6548 mtd->_read_oob = nand_read_oob;
6549 mtd->_write_oob = nand_write_oob;
6550 mtd->_sync = nand_sync;
6551 mtd->_lock = nand_lock;
6552 mtd->_unlock = nand_unlock;
6553 mtd->_suspend = nand_suspend;
6554 mtd->_resume = nand_resume;
6555 mtd->_reboot = nand_shutdown;
6556 mtd->_block_isreserved = nand_block_isreserved;
6557 mtd->_block_isbad = nand_block_isbad;
6558 mtd->_block_markbad = nand_block_markbad;
6559 mtd->_max_bad_blocks = nanddev_mtd_max_bad_blocks;
6562 * Initialize bitflip_threshold to its default prior scan_bbt() call.
6563 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
6566 if (!mtd->bitflip_threshold)
6567 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
6569 /* Find the fastest data interface for this chip */
6570 ret = nand_choose_interface_config(chip);
6572 goto err_nanddev_cleanup;
6574 /* Enter fastest possible mode on all dies. */
6575 for (i = 0; i < nanddev_ntargets(&chip->base); i++) {
6576 ret = nand_setup_interface(chip, i);
6578 goto err_free_interface_config;
6581 rawnand_late_check_supported_ops(chip);
6584 * Look for secure regions in the NAND chip. These regions are supposed
6585 * to be protected by a secure element like Trustzone. So the read/write
6586 * accesses to these regions will be blocked in the runtime by this
6589 ret = of_get_nand_secure_regions(chip);
6591 goto err_free_interface_config;
6593 /* Check, if we should skip the bad block table scan */
6594 if (chip->options & NAND_SKIP_BBTSCAN)
6597 /* Build bad block table */
6598 ret = nand_create_bbt(chip);
6600 goto err_free_secure_regions;
6604 err_free_secure_regions:
6605 kfree(chip->secure_regions);
6607 err_free_interface_config:
6608 kfree(chip->best_interface_config);
6610 err_nanddev_cleanup:
6611 nanddev_cleanup(&chip->base);
6613 err_nand_manuf_cleanup:
6614 nand_manufacturer_cleanup(chip);
6617 kfree(chip->data_buf);
6618 kfree(ecc->code_buf);
6619 kfree(ecc->calc_buf);
6624 static int nand_attach(struct nand_chip *chip)
6626 if (chip->controller->ops && chip->controller->ops->attach_chip)
6627 return chip->controller->ops->attach_chip(chip);
6632 static void nand_detach(struct nand_chip *chip)
6634 if (chip->controller->ops && chip->controller->ops->detach_chip)
6635 chip->controller->ops->detach_chip(chip);
6639 * nand_scan_with_ids - [NAND Interface] Scan for the NAND device
6640 * @chip: NAND chip object
6641 * @maxchips: number of chips to scan for.
6642 * @ids: optional flash IDs table
6644 * This fills out all the uninitialized function pointers with the defaults.
6645 * The flash ID is read and the mtd/chip structures are filled with the
6646 * appropriate values.
6648 int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips,
6649 struct nand_flash_dev *ids)
6656 ret = nand_scan_ident(chip, maxchips, ids);
6660 ret = nand_attach(chip);
6664 ret = nand_scan_tail(chip);
6673 nand_scan_ident_cleanup(chip);
6677 EXPORT_SYMBOL(nand_scan_with_ids);
6680 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
6681 * @chip: NAND chip object
6683 void nand_cleanup(struct nand_chip *chip)
6685 if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_SOFT) {
6686 if (chip->ecc.algo == NAND_ECC_ALGO_HAMMING)
6687 rawnand_sw_hamming_cleanup(chip);
6688 else if (chip->ecc.algo == NAND_ECC_ALGO_BCH)
6689 rawnand_sw_bch_cleanup(chip);
6692 nanddev_cleanup(&chip->base);
6694 /* Free secure regions data */
6695 kfree(chip->secure_regions);
6697 /* Free bad block table memory */
6699 kfree(chip->data_buf);
6700 kfree(chip->ecc.code_buf);
6701 kfree(chip->ecc.calc_buf);
6703 /* Free bad block descriptor memory */
6704 if (chip->badblock_pattern && chip->badblock_pattern->options
6705 & NAND_BBT_DYNAMICSTRUCT)
6706 kfree(chip->badblock_pattern);
6708 /* Free the data interface */
6709 kfree(chip->best_interface_config);
6711 /* Free manufacturer priv data. */
6712 nand_manufacturer_cleanup(chip);
6714 /* Free controller specific allocations after chip identification */
6717 /* Free identification phase allocations */
6718 nand_scan_ident_cleanup(chip);
6721 EXPORT_SYMBOL_GPL(nand_cleanup);
6723 MODULE_LICENSE("GPL");
6726 MODULE_DESCRIPTION("Generic NAND flash driver code");