blob: 3a14b79ddfaef1af3b3b69c691f35b2640958cca [file] [log] [blame]
/*
* Overview:
* This is the generic MTD driver for NAND flash devices. It should be
* capable of working with almost all NAND chips currently available.
*
* Additional technical information is available on
* http://www.linux-mtd.infradead.org/doc/nand.html
*
* Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
* 2002-2006 Thomas Gleixner (tglx@linutronix.de)
*
* Credits:
* David Woodhouse for adding multichip support
*
* Aleph One Ltd. and Toby Churchill Ltd. for supporting the
* rework for 2K page size chips
*
* TODO:
* Enable cached programming for 2k page size chips
* Check, if mtd->ecctype should be set to MTD_ECC_HW
* if we have HW ECC support.
* BBT table is not serialized, has to be fixed
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/types.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/nand_bch.h>
#include <linux/interrupt.h>
#include <linux/bitops.h>
#include <linux/io.h>
#include <linux/mtd/partitions.h>
#include <linux/of.h>
#include <linux/gpio/consumer.h>
#include "internals.h"
/* Define default oob placement schemes for large and small page devices */
static int nand_ooblayout_ecc_sp(struct mtd_info *mtd, int section,
struct mtd_oob_region *oobregion)
{
struct nand_chip *chip = mtd_to_nand(mtd);
struct nand_ecc_ctrl *ecc = &chip->ecc;
if (section > 1)
return -ERANGE;
if (!section) {
oobregion->offset = 0;
if (mtd->oobsize == 16)
oobregion->length = 4;
else
oobregion->length = 3;
} else {
if (mtd->oobsize == 8)
return -ERANGE;
oobregion->offset = 6;
oobregion->length = ecc->total - 4;
}
return 0;
}
static int nand_ooblayout_free_sp(struct mtd_info *mtd, int section,
struct mtd_oob_region *oobregion)
{
if (section > 1)
return -ERANGE;
if (mtd->oobsize == 16) {
if (section)
return -ERANGE;
oobregion->length = 8;
oobregion->offset = 8;
} else {
oobregion->length = 2;
if (!section)
oobregion->offset = 3;
else
oobregion->offset = 6;
}
return 0;
}
const struct mtd_ooblayout_ops nand_ooblayout_sp_ops = {
.ecc = nand_ooblayout_ecc_sp,
.free = nand_ooblayout_free_sp,
};
EXPORT_SYMBOL_GPL(nand_ooblayout_sp_ops);
static int nand_ooblayout_ecc_lp(struct mtd_info *mtd, int section,
struct mtd_oob_region *oobregion)
{
struct nand_chip *chip = mtd_to_nand(mtd);
struct nand_ecc_ctrl *ecc = &chip->ecc;
if (section || !ecc->total)
return -ERANGE;
oobregion->length = ecc->total;
oobregion->offset = mtd->oobsize - oobregion->length;
return 0;
}
static int nand_ooblayout_free_lp(struct mtd_info *mtd, int section,
struct mtd_oob_region *oobregion)
{
struct nand_chip *chip = mtd_to_nand(mtd);
struct nand_ecc_ctrl *ecc = &chip->ecc;
if (section)
return -ERANGE;
oobregion->length = mtd->oobsize - ecc->total - 2;
oobregion->offset = 2;
return 0;
}
const struct mtd_ooblayout_ops nand_ooblayout_lp_ops = {
.ecc = nand_ooblayout_ecc_lp,
.free = nand_ooblayout_free_lp,
};
EXPORT_SYMBOL_GPL(nand_ooblayout_lp_ops);
/*
* Support the old "large page" layout used for 1-bit Hamming ECC where ECC
* are placed at a fixed offset.
*/
static int nand_ooblayout_ecc_lp_hamming(struct mtd_info *mtd, int section,
struct mtd_oob_region *oobregion)
{
struct nand_chip *chip = mtd_to_nand(mtd);
struct nand_ecc_ctrl *ecc = &chip->ecc;
if (section)
return -ERANGE;
switch (mtd->oobsize) {
case 64:
oobregion->offset = 40;
break;
case 128:
oobregion->offset = 80;
break;
default:
return -EINVAL;
}
oobregion->length = ecc->total;
if (oobregion->offset + oobregion->length > mtd->oobsize)
return -ERANGE;
return 0;
}
static int nand_ooblayout_free_lp_hamming(struct mtd_info *mtd, int section,
struct mtd_oob_region *oobregion)
{
struct nand_chip *chip = mtd_to_nand(mtd);
struct nand_ecc_ctrl *ecc = &chip->ecc;
int ecc_offset = 0;
if (section < 0 || section > 1)
return -ERANGE;
switch (mtd->oobsize) {
case 64:
ecc_offset = 40;
break;
case 128:
ecc_offset = 80;
break;
default:
return -EINVAL;
}
if (section == 0) {
oobregion->offset = 2;
oobregion->length = ecc_offset - 2;
} else {
oobregion->offset = ecc_offset + ecc->total;
oobregion->length = mtd->oobsize - oobregion->offset;
}
return 0;
}
static const struct mtd_ooblayout_ops nand_ooblayout_lp_hamming_ops = {
.ecc = nand_ooblayout_ecc_lp_hamming,
.free = nand_ooblayout_free_lp_hamming,
};
static int check_offs_len(struct nand_chip *chip, loff_t ofs, uint64_t len)
{
int ret = 0;
/* Start address must align on block boundary */
if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
pr_debug("%s: unaligned address\n", __func__);
ret = -EINVAL;
}
/* Length must align on block boundary */
if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
pr_debug("%s: length not block aligned\n", __func__);
ret = -EINVAL;
}
return ret;
}
/**
* nand_select_target() - Select a NAND target (A.K.A. die)
* @chip: NAND chip object
* @cs: the CS line to select. Note that this CS id is always from the chip
* PoV, not the controller one
*
* Select a NAND target so that further operations executed on @chip go to the
* selected NAND target.
*/
void nand_select_target(struct nand_chip *chip, unsigned int cs)
{
/*
* cs should always lie between 0 and nanddev_ntargets(), when that's
* not the case it's a bug and the caller should be fixed.
*/
if (WARN_ON(cs > nanddev_ntargets(&chip->base)))
return;
chip->cur_cs = cs;
if (chip->legacy.select_chip)
chip->legacy.select_chip(chip, cs);
}
EXPORT_SYMBOL_GPL(nand_select_target);
/**
* nand_deselect_target() - Deselect the currently selected target
* @chip: NAND chip object
*
* Deselect the currently selected NAND target. The result of operations
* executed on @chip after the target has been deselected is undefined.
*/
void nand_deselect_target(struct nand_chip *chip)
{
if (chip->legacy.select_chip)
chip->legacy.select_chip(chip, -1);
chip->cur_cs = -1;
}
EXPORT_SYMBOL_GPL(nand_deselect_target);
/**
* nand_release_device - [GENERIC] release chip
* @chip: NAND chip object
*
* Release chip lock and wake up anyone waiting on the device.
*/
static void nand_release_device(struct nand_chip *chip)
{
/* Release the controller and the chip */
mutex_unlock(&chip->controller->lock);
mutex_unlock(&chip->lock);
}
/**
* nand_bbm_get_next_page - Get the next page for bad block markers
* @chip: NAND chip object
* @page: First page to start checking for bad block marker usage
*
* Returns an integer that corresponds to the page offset within a block, for
* a page that is used to store bad block markers. If no more pages are
* available, -EINVAL is returned.
*/
int nand_bbm_get_next_page(struct nand_chip *chip, int page)
{
struct mtd_info *mtd = nand_to_mtd(chip);
int last_page = ((mtd->erasesize - mtd->writesize) >>
chip->page_shift) & chip->pagemask;
if (page == 0 && chip->options & NAND_BBM_FIRSTPAGE)
return 0;
else if (page <= 1 && chip->options & NAND_BBM_SECONDPAGE)
return 1;
else if (page <= last_page && chip->options & NAND_BBM_LASTPAGE)
return last_page;
return -EINVAL;
}
/**
* nand_block_bad - [DEFAULT] Read bad block marker from the chip
* @chip: NAND chip object
* @ofs: offset from device start
*
* Check, if the block is bad.
*/
static int nand_block_bad(struct nand_chip *chip, loff_t ofs)
{
int first_page, page_offset;
int res;
u8 bad;
first_page = (int)(ofs >> chip->page_shift) & chip->pagemask;
page_offset = nand_bbm_get_next_page(chip, 0);
while (page_offset >= 0) {
res = chip->ecc.read_oob(chip, first_page + page_offset);
if (res < 0)
return res;
bad = chip->oob_poi[chip->badblockpos];
if (likely(chip->badblockbits == 8))
res = bad != 0xFF;
else
res = hweight8(bad) < chip->badblockbits;
if (res)
return res;
page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
}
return 0;
}
static int nand_isbad_bbm(struct nand_chip *chip, loff_t ofs)
{
if (chip->legacy.block_bad)
return chip->legacy.block_bad(chip, ofs);
return nand_block_bad(chip, ofs);
}
/**
* nand_get_device - [GENERIC] Get chip for selected access
* @chip: NAND chip structure
*
* Lock the device and its controller for exclusive access
*
* Return: -EBUSY if the chip has been suspended, 0 otherwise
*/
static int nand_get_device(struct nand_chip *chip)
{
mutex_lock(&chip->lock);
if (chip->suspended) {
mutex_unlock(&chip->lock);
return -EBUSY;
}
mutex_lock(&chip->controller->lock);
return 0;
}
/**
* nand_check_wp - [GENERIC] check if the chip is write protected
* @chip: NAND chip object
*
* Check, if the device is write protected. The function expects, that the
* device is already selected.
*/
static int nand_check_wp(struct nand_chip *chip)
{
u8 status;
int ret;
/* Broken xD cards report WP despite being writable */
if (chip->options & NAND_BROKEN_XD)
return 0;
/* Check the WP bit */
ret = nand_status_op(chip, &status);
if (ret)
return ret;
return status & NAND_STATUS_WP ? 0 : 1;
}
/**
* nand_fill_oob - [INTERN] Transfer client buffer to oob
* @chip: NAND chip object
* @oob: oob data buffer
* @len: oob data write length
* @ops: oob ops structure
*/
static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len,
struct mtd_oob_ops *ops)
{
struct mtd_info *mtd = nand_to_mtd(chip);
int ret;
/*
* Initialise to all 0xFF, to avoid the possibility of left over OOB
* data from a previous OOB read.
*/
memset(chip->oob_poi, 0xff, mtd->oobsize);
switch (ops->mode) {
case MTD_OPS_PLACE_OOB:
case MTD_OPS_RAW:
memcpy(chip->oob_poi + ops->ooboffs, oob, len);
return oob + len;
case MTD_OPS_AUTO_OOB:
ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
ops->ooboffs, len);
BUG_ON(ret);
return oob + len;
default:
BUG();
}
return NULL;
}
/**
* nand_do_write_oob - [MTD Interface] NAND write out-of-band
* @chip: NAND chip object
* @to: offset to write to
* @ops: oob operation description structure
*
* NAND write out-of-band.
*/
static int nand_do_write_oob(struct nand_chip *chip, loff_t to,
struct mtd_oob_ops *ops)
{
struct mtd_info *mtd = nand_to_mtd(chip);
int chipnr, page, status, len, ret;
pr_debug("%s: to = 0x%08x, len = %i\n",
__func__, (unsigned int)to, (int)ops->ooblen);
len = mtd_oobavail(mtd, ops);
/* Do not allow write past end of page */
if ((ops->ooboffs + ops->ooblen) > len) {
pr_debug("%s: attempt to write past end of page\n",
__func__);
return -EINVAL;
}
chipnr = (int)(to >> chip->chip_shift);
/*
* Reset the chip. Some chips (like the Toshiba TC5832DC found in one
* of my DiskOnChip 2000 test units) will clear the whole data page too
* if we don't do this. I have no clue why, but I seem to have 'fixed'
* it in the doc2000 driver in August 1999. dwmw2.
*/
ret = nand_reset(chip, chipnr);
if (ret)
return ret;
nand_select_target(chip, chipnr);
/* Shift to get page */
page = (int)(to >> chip->page_shift);
/* Check, if it is write protected */
if (nand_check_wp(chip)) {
nand_deselect_target(chip);
return -EROFS;
}
/* Invalidate the page cache, if we write to the cached page */
if (page == chip->pagecache.page)
chip->pagecache.page = -1;
nand_fill_oob(chip, ops->oobbuf, ops->ooblen, ops);
if (ops->mode == MTD_OPS_RAW)
status = chip->ecc.write_oob_raw(chip, page & chip->pagemask);
else
status = chip->ecc.write_oob(chip, page & chip->pagemask);
nand_deselect_target(chip);
if (status)
return status;
ops->oobretlen = ops->ooblen;
return 0;
}
/**
* nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
* @chip: NAND chip object
* @ofs: offset from device start
*
* This is the default implementation, which can be overridden by a hardware
* specific driver. It provides the details for writing a bad block marker to a
* block.
*/
static int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
{
struct mtd_info *mtd = nand_to_mtd(chip);
struct mtd_oob_ops ops;
uint8_t buf[2] = { 0, 0 };
int ret = 0, res, page_offset;
memset(&ops, 0, sizeof(ops));
ops.oobbuf = buf;
ops.ooboffs = chip->badblockpos;
if (chip->options & NAND_BUSWIDTH_16) {
ops.ooboffs &= ~0x01;
ops.len = ops.ooblen = 2;
} else {
ops.len = ops.ooblen = 1;
}
ops.mode = MTD_OPS_PLACE_OOB;
page_offset = nand_bbm_get_next_page(chip, 0);
while (page_offset >= 0) {
res = nand_do_write_oob(chip,
ofs + (page_offset * mtd->writesize),
&ops);
if (!ret)
ret = res;
page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
}
return ret;
}
/**
* nand_markbad_bbm - mark a block by updating the BBM
* @chip: NAND chip object
* @ofs: offset of the block to mark bad
*/
int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
{
if (chip->legacy.block_markbad)
return chip->legacy.block_markbad(chip, ofs);
return nand_default_block_markbad(chip, ofs);
}
/**
* nand_block_markbad_lowlevel - mark a block bad
* @chip: NAND chip object
* @ofs: offset from device start
*
* This function performs the generic NAND bad block marking steps (i.e., bad
* block table(s) and/or marker(s)). We only allow the hardware driver to
* specify how to write bad block markers to OOB (chip->legacy.block_markbad).
*
* We try operations in the following order:
*
* (1) erase the affected block, to allow OOB marker to be written cleanly
* (2) write bad block marker to OOB area of affected block (unless flag
* NAND_BBT_NO_OOB_BBM is present)
* (3) update the BBT
*
* Note that we retain the first error encountered in (2) or (3), finish the
* procedures, and dump the error in the end.
*/
static int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
{
struct mtd_info *mtd = nand_to_mtd(chip);
int res, ret = 0;
if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
struct erase_info einfo;
/* Attempt erase before marking OOB */
memset(&einfo, 0, sizeof(einfo));
einfo.addr = ofs;
einfo.len = 1ULL << chip->phys_erase_shift;
nand_erase_nand(chip, &einfo, 0);
/* Write bad block marker to OOB */
ret = nand_get_device(chip);
if (ret)
return ret;
ret = nand_markbad_bbm(chip, ofs);
nand_release_device(chip);
}
/* Mark block bad in BBT */
if (chip->bbt) {
res = nand_markbad_bbt(chip, ofs);
if (!ret)
ret = res;
}
if (!ret)
mtd->ecc_stats.badblocks++;
return ret;
}
/**
* nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
* @mtd: MTD device structure
* @ofs: offset from device start
*
* Check if the block is marked as reserved.
*/
static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
{
struct nand_chip *chip = mtd_to_nand(mtd);
if (!chip->bbt)
return 0;
/* Return info from the table */
return nand_isreserved_bbt(chip, ofs);
}
/**
* nand_block_checkbad - [GENERIC] Check if a block is marked bad
* @chip: NAND chip object
* @ofs: offset from device start
* @allowbbt: 1, if its allowed to access the bbt area
*
* Check, if the block is bad. Either by reading the bad block table or
* calling of the scan function.
*/
static int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
{
/* Return info from the table */
if (chip->bbt)
return nand_isbad_bbt(chip, ofs, allowbbt);
return nand_isbad_bbm(chip, ofs);
}
/**
* nand_soft_waitrdy - Poll STATUS reg until RDY bit is set to 1
* @chip: NAND chip structure
* @timeout_ms: Timeout in ms
*
* Poll the STATUS register using ->exec_op() until the RDY bit becomes 1.
* If that does not happen whitin the specified timeout, -ETIMEDOUT is
* returned.
*
* This helper is intended to be used when the controller does not have access
* to the NAND R/B pin.
*
* Be aware that calling this helper from an ->exec_op() implementation means
* ->exec_op() must be re-entrant.
*
* Return 0 if the NAND chip is ready, a negative error otherwise.
*/
int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
{
const struct nand_sdr_timings *timings;
u8 status = 0;
int ret;
if (!nand_has_exec_op(chip))
return -ENOTSUPP;
/* Wait tWB before polling the STATUS reg. */
timings = nand_get_sdr_timings(&chip->data_interface);
ndelay(PSEC_TO_NSEC(timings->tWB_max));
ret = nand_status_op(chip, NULL);
if (ret)
return ret;
timeout_ms = jiffies + msecs_to_jiffies(timeout_ms);
do {
ret = nand_read_data_op(chip, &status, sizeof(status), true);
if (ret)
break;
if (status & NAND_STATUS_READY)
break;
/*
* Typical lowest execution time for a tR on most NANDs is 10us,
* use this as polling delay before doing something smarter (ie.
* deriving a delay from the timeout value, timeout_ms/ratio).
*/
udelay(10);
} while (time_before(jiffies, timeout_ms));
/*
* We have to exit READ_STATUS mode in order to read real data on the
* bus in case the WAITRDY instruction is preceding a DATA_IN
* instruction.
*/
nand_exit_status_op(chip);
if (ret)
return ret;
return status & NAND_STATUS_READY ? 0 : -ETIMEDOUT;
};
EXPORT_SYMBOL_GPL(nand_soft_waitrdy);
/**
* nand_gpio_waitrdy - Poll R/B GPIO pin until ready
* @chip: NAND chip structure
* @gpiod: GPIO descriptor of R/B pin
* @timeout_ms: Timeout in ms
*
* Poll the R/B GPIO pin until it becomes ready. If that does not happen
* whitin the specified timeout, -ETIMEDOUT is returned.
*
* This helper is intended to be used when the controller has access to the
* NAND R/B pin over GPIO.
*
* Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.
*/
int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
unsigned long timeout_ms)
{
/* Wait until R/B pin indicates chip is ready or timeout occurs */
timeout_ms = jiffies + msecs_to_jiffies(timeout_ms);
do {
if (gpiod_get_value_cansleep(gpiod))
return 0;
cond_resched();
} while (time_before(jiffies, timeout_ms));
return gpiod_get_value_cansleep(gpiod) ? 0 : -ETIMEDOUT;
};
EXPORT_SYMBOL_GPL(nand_gpio_waitrdy);
/**
* panic_nand_wait - [GENERIC] wait until the command is done
* @chip: NAND chip structure
* @timeo: timeout
*
* Wait for command done. This is a helper function for nand_wait used when
* we are in interrupt context. May happen when in panic and trying to write
* an oops through mtdoops.
*/
void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
{
int i;
for (i = 0; i < timeo; i++) {
if (chip->legacy.dev_ready) {
if (chip->legacy.dev_ready(chip))
break;
} else {
int ret;
u8 status;
ret = nand_read_data_op(chip, &status, sizeof(status),
true);
if (ret)
return;
if (status & NAND_STATUS_READY)
break;
}
mdelay(1);
}
}
static bool nand_supports_get_features(struct nand_chip *chip, int addr)
{
return (chip->parameters.supports_set_get_features &&
test_bit(addr, chip->parameters.get_feature_list));
}
static bool nand_supports_set_features(struct nand_chip *chip, int addr)
{
return (chip->parameters.supports_set_get_features &&
test_bit(addr, chip->parameters.set_feature_list));
}
/**
* nand_reset_data_interface - Reset data interface and timings
* @chip: The NAND chip
* @chipnr: Internal die id
*
* Reset the Data interface and timings to ONFI mode 0.
*
* Returns 0 for success or negative error code otherwise.
*/
static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
{
int ret;
if (!nand_has_setup_data_iface(chip))
return 0;
/*
* The ONFI specification says:
* "
* To transition from NV-DDR or NV-DDR2 to the SDR data
* interface, the host shall use the Reset (FFh) command
* using SDR timing mode 0. A device in any timing mode is
* required to recognize Reset (FFh) command issued in SDR
* timing mode 0.
* "
*
* Configure the data interface in SDR mode and set the
* timings to timing mode 0.
*/
onfi_fill_data_interface(chip, NAND_SDR_IFACE, 0);
ret = chip->controller->ops->setup_data_interface(chip, chipnr,
&chip->data_interface);
if (ret)
pr_err("Failed to configure data interface to SDR timing mode 0\n");
return ret;
}
/**
* nand_setup_data_interface - Setup the best data interface and timings
* @chip: The NAND chip
* @chipnr: Internal die id
*
* Find and configure the best data interface and NAND timings supported by
* the chip and the driver.
* First tries to retrieve supported timing modes from ONFI information,
* and if the NAND chip does not support ONFI, relies on the
* ->onfi_timing_mode_default specified in the nand_ids table.
*
* Returns 0 for success or negative error code otherwise.
*/
static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
{
u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
chip->onfi_timing_mode_default,
};
int ret;
if (!nand_has_setup_data_iface(chip))
return 0;
/* Change the mode on the chip side (if supported by the NAND chip) */
if (nand_supports_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE)) {
nand_select_target(chip, chipnr);
ret = nand_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
tmode_param);
nand_deselect_target(chip);
if (ret)
return ret;
}
/* Change the mode on the controller side */
ret = chip->controller->ops->setup_data_interface(chip, chipnr,
&chip->data_interface);
if (ret)
return ret;
/* Check the mode has been accepted by the chip, if supported */
if (!nand_supports_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE))
return 0;
memset(tmode_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
nand_select_target(chip, chipnr);
ret = nand_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
tmode_param);
nand_deselect_target(chip);
if (ret)
goto err_reset_chip;
if (tmode_param[0] != chip->onfi_timing_mode_default) {
pr_warn("timing mode %d not acknowledged by the NAND chip\n",
chip->onfi_timing_mode_default);
goto err_reset_chip;
}
return 0;
err_reset_chip:
/*
* Fallback to mode 0 if the chip explicitly did not ack the chosen
* timing mode.
*/
nand_reset_data_interface(chip, chipnr);
nand_select_target(chip, chipnr);
nand_reset_op(chip);
nand_deselect_target(chip);
return ret;
}
/**
* nand_init_data_interface - find the best data interface and timings
* @chip: The NAND chip
*
* Find the best data interface and NAND timings supported by the chip
* and the driver.
* First tries to retrieve supported timing modes from ONFI information,
* and if the NAND chip does not support ONFI, relies on the
* ->onfi_timing_mode_default specified in the nand_ids table. After this
* function nand_chip->data_interface is initialized with the best timing mode
* available.
*
* Returns 0 for success or negative error code otherwise.
*/
static int nand_init_data_interface(struct nand_chip *chip)
{
int modes, mode, ret;
if (!nand_has_setup_data_iface(chip))
return 0;
/*
* First try to identify the best timings from ONFI parameters and
* if the NAND does not support ONFI, fallback to the default ONFI
* timing mode.
*/
if (chip->parameters.onfi) {
modes = chip->parameters.onfi->async_timing_mode;
} else {
if (!chip->onfi_timing_mode_default)
return 0;
modes = GENMASK(chip->onfi_timing_mode_default, 0);
}
for (mode = fls(modes) - 1; mode >= 0; mode--) {
ret = onfi_fill_data_interface(chip, NAND_SDR_IFACE, mode);
if (ret)
continue;
/*
* Pass NAND_DATA_IFACE_CHECK_ONLY to only check if the
* controller supports the requested timings.
*/
ret = chip->controller->ops->setup_data_interface(chip,
NAND_DATA_IFACE_CHECK_ONLY,
&chip->data_interface);
if (!ret) {
chip->onfi_timing_mode_default = mode;
break;
}
}
return 0;
}
/**
* nand_fill_column_cycles - fill the column cycles of an address
* @chip: The NAND chip
* @addrs: Array of address cycles to fill
* @offset_in_page: The offset in the page
*
* Fills the first or the first two bytes of the @addrs field depending
* on the NAND bus width and the page size.
*
* Returns the number of cycles needed to encode the column, or a negative
* error code in case one of the arguments is invalid.
*/
static int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs,
unsigned int offset_in_page)
{
struct mtd_info *mtd = nand_to_mtd(chip);
/* Make sure the offset is less than the actual page size. */
if (offset_in_page > mtd->writesize + mtd->oobsize)
return -EINVAL;
/*
* On small page NANDs, there's a dedicated command to access the OOB
* area, and the column address is relative to the start of the OOB
* area, not the start of the page. Asjust the address accordingly.
*/
if (mtd->writesize <= 512 && offset_in_page >= mtd->writesize)
offset_in_page -= mtd->writesize;
/*
* The offset in page is expressed in bytes, if the NAND bus is 16-bit
* wide, then it must be divided by 2.
*/
if (chip->options & NAND_BUSWIDTH_16) {
if (WARN_ON(offset_in_page % 2))
return -EINVAL;
offset_in_page /= 2;
}
addrs[0] = offset_in_page;
/*
* Small page NANDs use 1 cycle for the columns, while large page NANDs
* need 2
*/
if (mtd->writesize <= 512)
return 1;
addrs[1] = offset_in_page >> 8;
return 2;
}
static int nand_sp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
unsigned int offset_in_page, void *buf,
unsigned int len)
{
struct mtd_info *mtd = nand_to_mtd(chip);
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
u8 addrs[4];
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_READ0, 0),
NAND_OP_ADDR(3, addrs, PSEC_TO_NSEC(sdr->tWB_max)),
NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
PSEC_TO_NSEC(sdr->tRR_min)),
NAND_OP_DATA_IN(len, buf, 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
int ret;
/* Drop the DATA_IN instruction if len is set to 0. */
if (!len)
op.ninstrs--;
if (offset_in_page >= mtd->writesize)
instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
else if (offset_in_page >= 256 &&
!(chip->options & NAND_BUSWIDTH_16))
instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
if (ret < 0)
return ret;
addrs[1] = page;
addrs[2] = page >> 8;
if (chip->options & NAND_ROW_ADDR_3) {
addrs[3] = page >> 16;
instrs[1].ctx.addr.naddrs++;
}
return nand_exec_op(chip, &op);
}
static int nand_lp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
unsigned int offset_in_page, void *buf,
unsigned int len)
{
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
u8 addrs[5];
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_READ0, 0),
NAND_OP_ADDR(4, addrs, 0),
NAND_OP_CMD(NAND_CMD_READSTART, PSEC_TO_NSEC(sdr->tWB_max)),
NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
PSEC_TO_NSEC(sdr->tRR_min)),
NAND_OP_DATA_IN(len, buf, 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
int ret;
/* Drop the DATA_IN instruction if len is set to 0. */
if (!len)
op.ninstrs--;
ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
if (ret < 0)
return ret;
addrs[2] = page;
addrs[3] = page >> 8;
if (chip->options & NAND_ROW_ADDR_3) {
addrs[4] = page >> 16;
instrs[1].ctx.addr.naddrs++;
}
return nand_exec_op(chip, &op);
}
/**
* nand_read_page_op - Do a READ PAGE operation
* @chip: The NAND chip
* @page: page to read
* @offset_in_page: offset within the page
* @buf: buffer used to store the data
* @len: length of the buffer
*
* This function issues a READ PAGE operation.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_read_page_op(struct nand_chip *chip, unsigned int page,
unsigned int offset_in_page, void *buf, unsigned int len)
{
struct mtd_info *mtd = nand_to_mtd(chip);
if (len && !buf)
return -EINVAL;
if (offset_in_page + len > mtd->writesize + mtd->oobsize)
return -EINVAL;
if (nand_has_exec_op(chip)) {
if (mtd->writesize > 512)
return nand_lp_exec_read_page_op(chip, page,
offset_in_page, buf,
len);
return nand_sp_exec_read_page_op(chip, page, offset_in_page,
buf, len);
}
chip->legacy.cmdfunc(chip, NAND_CMD_READ0, offset_in_page, page);
if (len)
chip->legacy.read_buf(chip, buf, len);
return 0;
}
EXPORT_SYMBOL_GPL(nand_read_page_op);
/**
* nand_read_param_page_op - Do a READ PARAMETER PAGE operation
* @chip: The NAND chip
* @page: parameter page to read
* @buf: buffer used to store the data
* @len: length of the buffer
*
* This function issues a READ PARAMETER PAGE operation.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
unsigned int len)
{
unsigned int i;
u8 *p = buf;
if (len && !buf)
return -EINVAL;
if (nand_has_exec_op(chip)) {
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_PARAM, 0),
NAND_OP_ADDR(1, &page, PSEC_TO_NSEC(sdr->tWB_max)),
NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
PSEC_TO_NSEC(sdr->tRR_min)),
NAND_OP_8BIT_DATA_IN(len, buf, 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
/* Drop the DATA_IN instruction if len is set to 0. */
if (!len)
op.ninstrs--;
return nand_exec_op(chip, &op);
}
chip->legacy.cmdfunc(chip, NAND_CMD_PARAM, page, -1);
for (i = 0; i < len; i++)
p[i] = chip->legacy.read_byte(chip);
return 0;
}
/**
* nand_change_read_column_op - Do a CHANGE READ COLUMN operation
* @chip: The NAND chip
* @offset_in_page: offset within the page
* @buf: buffer used to store the data
* @len: length of the buffer
* @force_8bit: force 8-bit bus access
*
* This function issues a CHANGE READ COLUMN operation.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_change_read_column_op(struct nand_chip *chip,
unsigned int offset_in_page, void *buf,
unsigned int len, bool force_8bit)
{
struct mtd_info *mtd = nand_to_mtd(chip);
if (len && !buf)
return -EINVAL;
if (offset_in_page + len > mtd->writesize + mtd->oobsize)
return -EINVAL;
/* Small page NANDs do not support column change. */
if (mtd->writesize <= 512)
return -ENOTSUPP;
if (nand_has_exec_op(chip)) {
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
u8 addrs[2] = {};
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_RNDOUT, 0),
NAND_OP_ADDR(2, addrs, 0),
NAND_OP_CMD(NAND_CMD_RNDOUTSTART,
PSEC_TO_NSEC(sdr->tCCS_min)),
NAND_OP_DATA_IN(len, buf, 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
int ret;
ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
if (ret < 0)
return ret;
/* Drop the DATA_IN instruction if len is set to 0. */
if (!len)
op.ninstrs--;
instrs[3].ctx.data.force_8bit = force_8bit;
return nand_exec_op(chip, &op);
}
chip->legacy.cmdfunc(chip, NAND_CMD_RNDOUT, offset_in_page, -1);
if (len)
chip->legacy.read_buf(chip, buf, len);
return 0;
}
EXPORT_SYMBOL_GPL(nand_change_read_column_op);
/**
* nand_read_oob_op - Do a READ OOB operation
* @chip: The NAND chip
* @page: page to read
* @offset_in_oob: offset within the OOB area
* @buf: buffer used to store the data
* @len: length of the buffer
*
* This function issues a READ OOB operation.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
unsigned int offset_in_oob, void *buf, unsigned int len)
{
struct mtd_info *mtd = nand_to_mtd(chip);
if (len && !buf)
return -EINVAL;
if (offset_in_oob + len > mtd->oobsize)
return -EINVAL;
if (nand_has_exec_op(chip))
return nand_read_page_op(chip, page,
mtd->writesize + offset_in_oob,
buf, len);
chip->legacy.cmdfunc(chip, NAND_CMD_READOOB, offset_in_oob, page);
if (len)
chip->legacy.read_buf(chip, buf, len);
return 0;
}
EXPORT_SYMBOL_GPL(nand_read_oob_op);
static int nand_exec_prog_page_op(struct nand_chip *chip, unsigned int page,
unsigned int offset_in_page, const void *buf,
unsigned int len, bool prog)
{
struct mtd_info *mtd = nand_to_mtd(chip);
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
u8 addrs[5] = {};
struct nand_op_instr instrs[] = {
/*
* The first instruction will be dropped if we're dealing
* with a large page NAND and adjusted if we're dealing
* with a small page NAND and the page offset is > 255.
*/
NAND_OP_CMD(NAND_CMD_READ0, 0),
NAND_OP_CMD(NAND_CMD_SEQIN, 0),
NAND_OP_ADDR(0, addrs, PSEC_TO_NSEC(sdr->tADL_min)),
NAND_OP_DATA_OUT(len, buf, 0),
NAND_OP_CMD(NAND_CMD_PAGEPROG, PSEC_TO_NSEC(sdr->tWB_max)),
NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
int ret;
u8 status;
if (naddrs < 0)
return naddrs;
addrs[naddrs++] = page;
addrs[naddrs++] = page >> 8;
if (chip->options & NAND_ROW_ADDR_3)
addrs[naddrs++] = page >> 16;
instrs[2].ctx.addr.naddrs = naddrs;
/* Drop the last two instructions if we're not programming the page. */
if (!prog) {
op.ninstrs -= 2;
/* Also drop the DATA_OUT instruction if empty. */
if (!len)
op.ninstrs--;
}
if (mtd->writesize <= 512) {
/*
* Small pages need some more tweaking: we have to adjust the
* first instruction depending on the page offset we're trying
* to access.
*/
if (offset_in_page >= mtd->writesize)
instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
else if (offset_in_page >= 256 &&
!(chip->options & NAND_BUSWIDTH_16))
instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
} else {
/*
* Drop the first command if we're dealing with a large page
* NAND.
*/
op.instrs++;
op.ninstrs--;
}
ret = nand_exec_op(chip, &op);
if (!prog || ret)
return ret;
ret = nand_status_op(chip, &status);
if (ret)
return ret;
return status;
}
/**
* nand_prog_page_begin_op - starts a PROG PAGE operation
* @chip: The NAND chip
* @page: page to write
* @offset_in_page: offset within the page
* @buf: buffer containing the data to write to the page
* @len: length of the buffer
*
* This function issues the first half of a PROG PAGE operation.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
unsigned int offset_in_page, const void *buf,
unsigned int len)
{
struct mtd_info *mtd = nand_to_mtd(chip);
if (len && !buf)
return -EINVAL;
if (offset_in_page + len > mtd->writesize + mtd->oobsize)
return -EINVAL;
if (nand_has_exec_op(chip))
return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
len, false);
chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page, page);
if (buf)
chip->legacy.write_buf(chip, buf, len);
return 0;
}
EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
/**
* nand_prog_page_end_op - ends a PROG PAGE operation
* @chip: The NAND chip
*
* This function issues the second half of a PROG PAGE operation.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_prog_page_end_op(struct nand_chip *chip)
{
int ret;
u8 status;
if (nand_has_exec_op(chip)) {
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_PAGEPROG,
PSEC_TO_NSEC(sdr->tWB_max)),
NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
ret = nand_exec_op(chip, &op);
if (ret)
return ret;
ret = nand_status_op(chip, &status);
if (ret)
return ret;
} else {
chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
ret = chip->legacy.waitfunc(chip);
if (ret < 0)
return ret;
status = ret;
}
if (status & NAND_STATUS_FAIL)
return -EIO;
return 0;
}
EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
/**
* nand_prog_page_op - Do a full PROG PAGE operation
* @chip: The NAND chip
* @page: page to write
* @offset_in_page: offset within the page
* @buf: buffer containing the data to write to the page
* @len: length of the buffer
*
* This function issues a full PROG PAGE operation.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
unsigned int offset_in_page, const void *buf,
unsigned int len)
{
struct mtd_info *mtd = nand_to_mtd(chip);
int status;
if (!len || !buf)
return -EINVAL;
if (offset_in_page + len > mtd->writesize + mtd->oobsize)
return -EINVAL;
if (nand_has_exec_op(chip)) {
status = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
len, true);
} else {
chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page,
page);
chip->legacy.write_buf(chip, buf, len);
chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
status = chip->legacy.waitfunc(chip);
}
if (status & NAND_STATUS_FAIL)
return -EIO;
return 0;
}
EXPORT_SYMBOL_GPL(nand_prog_page_op);
/**
* nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
* @chip: The NAND chip
* @offset_in_page: offset within the page
* @buf: buffer containing the data to send to the NAND
* @len: length of the buffer
* @force_8bit: force 8-bit bus access
*
* This function issues a CHANGE WRITE COLUMN operation.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_change_write_column_op(struct nand_chip *chip,
unsigned int offset_in_page,
const void *buf, unsigned int len,
bool force_8bit)
{
struct mtd_info *mtd = nand_to_mtd(chip);
if (len && !buf)
return -EINVAL;
if (offset_in_page + len > mtd->writesize + mtd->oobsize)
return -EINVAL;
/* Small page NANDs do not support column change. */
if (mtd->writesize <= 512)
return -ENOTSUPP;
if (nand_has_exec_op(chip)) {
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
u8 addrs[2];
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_RNDIN, 0),
NAND_OP_ADDR(2, addrs, PSEC_TO_NSEC(sdr->tCCS_min)),
NAND_OP_DATA_OUT(len, buf, 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
int ret;
ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
if (ret < 0)
return ret;
instrs[2].ctx.data.force_8bit = force_8bit;
/* Drop the DATA_OUT instruction if len is set to 0. */
if (!len)
op.ninstrs--;
return nand_exec_op(chip, &op);
}
chip->legacy.cmdfunc(chip, NAND_CMD_RNDIN, offset_in_page, -1);
if (len)
chip->legacy.write_buf(chip, buf, len);
return 0;
}
EXPORT_SYMBOL_GPL(nand_change_write_column_op);
/**
* nand_readid_op - Do a READID operation
* @chip: The NAND chip
* @addr: address cycle to pass after the READID command
* @buf: buffer used to store the ID
* @len: length of the buffer
*
* This function sends a READID command and reads back the ID returned by the
* NAND.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
unsigned int len)
{
unsigned int i;
u8 *id = buf;
if (len && !buf)
return -EINVAL;
if (nand_has_exec_op(chip)) {
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_READID, 0),
NAND_OP_ADDR(1, &addr, PSEC_TO_NSEC(sdr->tADL_min)),
NAND_OP_8BIT_DATA_IN(len, buf, 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
/* Drop the DATA_IN instruction if len is set to 0. */
if (!len)
op.ninstrs--;
return nand_exec_op(chip, &op);
}
chip->legacy.cmdfunc(chip, NAND_CMD_READID, addr, -1);
for (i = 0; i < len; i++)
id[i] = chip->legacy.read_byte(chip);
return 0;
}
EXPORT_SYMBOL_GPL(nand_readid_op);
/**
* nand_status_op - Do a STATUS operation
* @chip: The NAND chip
* @status: out variable to store the NAND status
*
* This function sends a STATUS command and reads back the status returned by
* the NAND.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_status_op(struct nand_chip *chip, u8 *status)
{
if (nand_has_exec_op(chip)) {
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_STATUS,
PSEC_TO_NSEC(sdr->tADL_min)),
NAND_OP_8BIT_DATA_IN(1, status, 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
if (!status)
op.ninstrs--;
return nand_exec_op(chip, &op);
}
chip->legacy.cmdfunc(chip, NAND_CMD_STATUS, -1, -1);
if (status)
*status = chip->legacy.read_byte(chip);
return 0;
}
EXPORT_SYMBOL_GPL(nand_status_op);
/**
* nand_exit_status_op - Exit a STATUS operation
* @chip: The NAND chip
*
* This function sends a READ0 command to cancel the effect of the STATUS
* command to avoid reading only the status until a new read command is sent.
*
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_exit_status_op(struct nand_chip *chip)
{
if (nand_has_exec_op(chip)) {
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_READ0, 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
return nand_exec_op(chip, &op);
}
chip->legacy.cmdfunc(chip, NAND_CMD_READ0, -1, -1);
return 0;
}
/**
* nand_erase_op - Do an erase operation
* @chip: The NAND chip
* @eraseblock: block to erase
*
* This function sends an ERASE command and waits for the NAND to be ready
* before returning.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
{
unsigned int page = eraseblock <<
(chip->phys_erase_shift - chip->page_shift);
int ret;
u8 status;
if (nand_has_exec_op(chip)) {
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
u8 addrs[3] = { page, page >> 8, page >> 16 };
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_ERASE1, 0),
NAND_OP_ADDR(2, addrs, 0),
NAND_OP_CMD(NAND_CMD_ERASE2,
PSEC_TO_MSEC(sdr->tWB_max)),
NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tBERS_max), 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
if (chip->options & NAND_ROW_ADDR_3)
instrs[1].ctx.addr.naddrs++;
ret = nand_exec_op(chip, &op);
if (ret)
return ret;
ret = nand_status_op(chip, &status);
if (ret)
return ret;
} else {
chip->legacy.cmdfunc(chip, NAND_CMD_ERASE1, -1, page);
chip->legacy.cmdfunc(chip, NAND_CMD_ERASE2, -1, -1);
ret = chip->legacy.waitfunc(chip);
if (ret < 0)
return ret;
status = ret;
}
if (status & NAND_STATUS_FAIL)
return -EIO;
return 0;
}
EXPORT_SYMBOL_GPL(nand_erase_op);
/**
* nand_set_features_op - Do a SET FEATURES operation
* @chip: The NAND chip
* @feature: feature id
* @data: 4 bytes of data
*
* This function sends a SET FEATURES command and waits for the NAND to be
* ready before returning.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
static int nand_set_features_op(struct nand_chip *chip, u8 feature,
const void *data)
{
const u8 *params = data;
int i, ret;
if (nand_has_exec_op(chip)) {
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_SET_FEATURES, 0),
NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tADL_min)),
NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
PSEC_TO_NSEC(sdr->tWB_max)),
NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max), 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
return nand_exec_op(chip, &op);
}
chip->legacy.cmdfunc(chip, NAND_CMD_SET_FEATURES, feature, -1);
for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
chip->legacy.write_byte(chip, params[i]);
ret = chip->legacy.waitfunc(chip);
if (ret < 0)
return ret;
if (ret & NAND_STATUS_FAIL)
return -EIO;
return 0;
}
/**
* nand_get_features_op - Do a GET FEATURES operation
* @chip: The NAND chip
* @feature: feature id
* @data: 4 bytes of data
*
* This function sends a GET FEATURES command and waits for the NAND to be
* ready before returning.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
static int nand_get_features_op(struct nand_chip *chip, u8 feature,
void *data)
{
u8 *params = data;
int i;
if (nand_has_exec_op(chip)) {
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_GET_FEATURES, 0),
NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tWB_max)),
NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max),
PSEC_TO_NSEC(sdr->tRR_min)),
NAND_OP_8BIT_DATA_IN(ONFI_SUBFEATURE_PARAM_LEN,
data, 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
return nand_exec_op(chip, &op);
}
chip->legacy.cmdfunc(chip, NAND_CMD_GET_FEATURES, feature, -1);
for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
params[i] = chip->legacy.read_byte(chip);
return 0;
}
static int nand_wait_rdy_op(struct nand_chip *chip, unsigned int timeout_ms,
unsigned int delay_ns)
{
if (nand_has_exec_op(chip)) {
struct nand_op_instr instrs[] = {
NAND_OP_WAIT_RDY(PSEC_TO_MSEC(timeout_ms),
PSEC_TO_NSEC(delay_ns)),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
return nand_exec_op(chip, &op);
}
/* Apply delay or wait for ready/busy pin */
if (!chip->legacy.dev_ready)
udelay(chip->legacy.chip_delay);
else
nand_wait_ready(chip);
return 0;
}
/**
* nand_reset_op - Do a reset operation
* @chip: The NAND chip
*
* This function sends a RESET command and waits for the NAND to be ready
* before returning.
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_reset_op(struct nand_chip *chip)
{
if (nand_has_exec_op(chip)) {
const struct nand_sdr_timings *sdr =
nand_get_sdr_timings(&chip->data_interface);
struct nand_op_instr instrs[] = {
NAND_OP_CMD(NAND_CMD_RESET, PSEC_TO_NSEC(sdr->tWB_max)),
NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tRST_max), 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
return nand_exec_op(chip, &op);
}
chip->legacy.cmdfunc(chip, NAND_CMD_RESET, -1, -1);
return 0;
}
EXPORT_SYMBOL_GPL(nand_reset_op);
/**
* nand_read_data_op - Read data from the NAND
* @chip: The NAND chip
* @buf: buffer used to store the data
* @len: length of the buffer
* @force_8bit: force 8-bit bus access
*
* This function does a raw data read on the bus. Usually used after launching
* another NAND operation like nand_read_page_op().
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
bool force_8bit)
{
if (!len || !buf)
return -EINVAL;
if (nand_has_exec_op(chip)) {
struct nand_op_instr instrs[] = {
NAND_OP_DATA_IN(len, buf, 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
instrs[0].ctx.data.force_8bit = force_8bit;
return nand_exec_op(chip, &op);
}
if (force_8bit) {
u8 *p = buf;
unsigned int i;
for (i = 0; i < len; i++)
p[i] = chip->legacy.read_byte(chip);
} else {
chip->legacy.read_buf(chip, buf, len);
}
return 0;
}
EXPORT_SYMBOL_GPL(nand_read_data_op);
/**
* nand_write_data_op - Write data from the NAND
* @chip: The NAND chip
* @buf: buffer containing the data to send on the bus
* @len: length of the buffer
* @force_8bit: force 8-bit bus access
*
* This function does a raw data write on the bus. Usually used after launching
* another NAND operation like nand_write_page_begin_op().
* This function does not select/unselect the CS line.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_write_data_op(struct nand_chip *chip, const void *buf,
unsigned int len, bool force_8bit)
{
if (!len || !buf)
return -EINVAL;
if (nand_has_exec_op(chip)) {
struct nand_op_instr instrs[] = {
NAND_OP_DATA_OUT(len, buf, 0),
};
struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
instrs[0].ctx.data.force_8bit = force_8bit;
return nand_exec_op(chip, &op);
}
if (force_8bit) {
const u8 *p = buf;
unsigned int i;
for (i = 0; i < len; i++)
chip->legacy.write_byte(chip, p[i]);
} else {
chip->legacy.write_buf(chip, buf, len);
}
return 0;
}
EXPORT_SYMBOL_GPL(nand_write_data_op);
/**
* struct nand_op_parser_ctx - Context used by the parser
* @instrs: array of all the instructions that must be addressed
* @ninstrs: length of the @instrs array
* @subop: Sub-operation to be passed to the NAND controller
*
* This structure is used by the core to split NAND operations into
* sub-operations that can be handled by the NAND controller.
*/
struct nand_op_parser_ctx {
const struct nand_op_instr *instrs;
unsigned int ninstrs;
struct nand_subop subop;
};
/**
* nand_op_parser_must_split_instr - Checks if an instruction must be split
* @pat: the parser pattern element that matches @instr
* @instr: pointer to the instruction to check
* @start_offset: this is an in/out parameter. If @instr has already been
* split, then @start_offset is the offset from which to start
* (either an address cycle or an offset in the data buffer).
* Conversely, if the function returns true (ie. instr must be
* split), this parameter is updated to point to the first
* data/address cycle that has not been taken care of.
*
* Some NAND controllers are limited and cannot send X address cycles with a
* unique operation, or cannot read/write more than Y bytes at the same time.
* In this case, split the instruction that does not fit in a single
* controller-operation into two or more chunks.
*
* Returns true if the instruction must be split, false otherwise.
* The @start_offset parameter is also updated to the offset at which the next
* bundle of instruction must start (if an address or a data instruction).
*/
static bool
nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat,
const struct nand_op_instr *instr,
unsigned int *start_offset)
{
switch (pat->type) {
case NAND_OP_ADDR_INSTR:
if (!pat->ctx.addr.maxcycles)
break;
if (instr->ctx.addr.naddrs - *start_offset >
pat->ctx.addr.maxcycles) {
*start_offset += pat->ctx.addr.maxcycles;
return true;
}
break;
case NAND_OP_DATA_IN_INSTR:
case NAND_OP_DATA_OUT_INSTR:
if (!pat->ctx.data.maxlen)
break;
if (instr->ctx.data.len - *start_offset >
pat->ctx.data.maxlen) {
*start_offset += pat->ctx.data.maxlen;
return true;
}
break;
default:
break;
}
return false;
}
/**
* nand_op_parser_match_pat - Checks if a pattern matches the instructions
* remaining in the parser context
* @pat: the pattern to test
* @ctx: the parser context structure to match with the pattern @pat
*
* Check if @pat matches the set or a sub-set of instructions remaining in @ctx.
* Returns true if this is the case, false ortherwise. When true is returned,
* @ctx->subop is updated with the set of instructions to be passed to the
* controller driver.
*/
static bool
nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
struct nand_op_parser_ctx *ctx)
{
unsigned int instr_offset = ctx->subop.first_instr_start_off;
const struct nand_op_instr *end = ctx->instrs + ctx->ninstrs;
const struct nand_op_instr *instr = ctx->subop.instrs;
unsigned int i, ninstrs;
for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
/*
* The pattern instruction does not match the operation
* instruction. If the instruction is marked optional in the
* pattern definition, we skip the pattern element and continue
* to the next one. If the element is mandatory, there's no
* match and we can return false directly.
*/
if (instr->type != pat->elems[i].type) {
if (!pat->elems[i].optional)
return false;
continue;
}
/*
* Now check the pattern element constraints. If the pattern is
* not able to handle the whole instruction in a single step,
* we have to split it.
* The last_instr_end_off value comes back updated to point to
* the position where we have to split the instruction (the
* start of the next subop chunk).
*/
if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
&instr_offset)) {
ninstrs++;
i++;
break;
}
instr++;
ninstrs++;
instr_offset = 0;
}
/*
* This can happen if all instructions of a pattern are optional.
* Still, if there's not at least one instruction handled by this
* pattern, this is not a match, and we should try the next one (if
* any).
*/
if (!ninstrs)
return false;
/*
* We had a match on the pattern head, but the pattern may be longer
* than the instructions we're asked to execute. We need to make sure
* there's no mandatory elements in the pattern tail.
*/
for (; i < pat->nelems; i++) {
if (!pat->elems[i].optional)
return false;
}
/*
* We have a match: update the subop structure accordingly and return
* true.
*/
ctx->subop.ninstrs = ninstrs;
ctx->subop.last_instr_end_off = instr_offset;
return true;
}
#if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
{
const struct nand_op_instr *instr;
char *prefix = " ";
unsigned int i;
pr_debug("executing subop:\n");
for (i = 0; i < ctx->ninstrs; i++) {
instr = &ctx->instrs[i];
if (instr == &ctx->subop.instrs[0])
prefix = " ->";
switch (instr->type) {
case NAND_OP_CMD_INSTR:
pr_debug("%sCMD [0x%02x]\n", prefix,
instr->ctx.cmd.opcode);
break;
case NAND_OP_ADDR_INSTR:
pr_debug("%sADDR [%d cyc: %*ph]\n", prefix,
instr->ctx.addr.naddrs,
instr->ctx.addr.naddrs < 64 ?
instr->ctx.addr.naddrs : 64,
instr->ctx.addr.addrs);
break;
case NAND_OP_DATA_IN_INSTR:
pr_debug("%sDATA_IN [%d B%s]\n", prefix,
instr->ctx.data.len,
instr->ctx.data.force_8bit ?
", force 8-bit" : "");
break;
case NAND_OP_DATA_OUT_INSTR:
pr_debug("%sDATA_OUT [%d B%s]\n", prefix,
instr->ctx.data.len,
instr->ctx.data.force_8bit ?
", force 8-bit" : "");
break;
case NAND_OP_WAITRDY_INSTR:
pr_debug("%sWAITRDY [max %d ms]\n", prefix,
instr->ctx.waitrdy.timeout_ms);
break;
}
if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
prefix = " ";
}
}
#else
static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
{
/* NOP */
}
#endif
/**
* nand_op_parser_exec_op - exec_op parser
* @chip: the NAND chip
* @parser: patterns description provided by the controller driver
* @op: the NAND operation to address
* @check_only: when true, the function only checks if @op can be handled but
* does not execute the operation
*
* Helper function designed to ease integration of NAND controller drivers that
* only support a limited set of instruction sequences. The supported sequences
* are described in @parser, and the framework takes care of splitting @op into
* multiple sub-operations (if required) and pass them back to the ->exec()
* callback of the matching pattern if @check_only is set to false.
*
* NAND controller drivers should call this function from their own ->exec_op()
* implementation.
*
* Returns 0 on success, a negative error code otherwise. A failure can be
* caused by an unsupported operation (none of the supported patterns is able
* to handle the requested operation), or an error returned by one of the
* matching pattern->exec() hook.
*/
int nand_op_parser_exec_op(struct nand_chip *chip,
const struct nand_op_parser *parser,
const struct nand_operation *op, bool check_only)
{
struct nand_op_parser_ctx ctx = {
.subop.instrs = op->instrs,
.instrs = op->instrs,
.ninstrs = op->ninstrs,
};
unsigned int i;
while (ctx.subop.instrs < op->instrs + op->ninstrs) {
int ret;
for (i = 0; i < parser->npatterns; i++) {
const struct nand_op_parser_pattern *pattern;
pattern = &parser->patterns[i];
if (!nand_op_parser_match_pat(pattern, &ctx))
continue;
nand_op_parser_trace(&ctx);
if (check_only)
break;
ret = pattern->exec(chip, &ctx.subop);
if (ret)
return ret;
break;
}
if (i == parser->npatterns) {
pr_debug("->exec_op() parser: pattern not found!\n");
return -ENOTSUPP;
}
/*
* Update the context structure by pointing to the start of the
* next subop.
*/
ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
if (ctx.subop.last_instr_end_off)
ctx.subop.instrs -= 1;
ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
}
return 0;
}
EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
static bool nand_instr_is_data(const struct nand_op_instr *instr)
{
return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
instr->type == NAND_OP_DATA_OUT_INSTR);
}
static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
unsigned int instr_idx)
{
return subop && instr_idx < subop->ninstrs;
}
static unsigned int nand_subop_get_start_off(const struct nand_subop *subop,
unsigned int instr_idx)
{
if (instr_idx)
return 0;
return subop->first_instr_start_off;
}
/**
* nand_subop_get_addr_start_off - Get the start offset in an address array
* @subop: The entire sub-operation
* @instr_idx: Index of the instruction inside the sub-operation
*
* During driver development, one could be tempted to directly use the
* ->addr.addrs field of address instructions. This is wrong as address
* instructions might be split.
*
* Given an address instruction, returns the offset of the first cycle to issue.
*/
unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
unsigned int instr_idx)
{
if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
return 0;
return nand_subop_get_start_off(subop, instr_idx);
}
EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
/**
* nand_subop_get_num_addr_cyc - Get the remaining address cycles to assert
* @subop: The entire sub-operation
* @instr_idx: Index of the instruction inside the sub-operation
*
* During driver development, one could be tempted to directly use the
* ->addr->naddrs field of a data instruction. This is wrong as instructions
* might be split.
*
* Given an address instruction, returns the number of address cycle to issue.
*/
unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
unsigned int instr_idx)
{
int start_off, end_off;
if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
return 0;
start_off = nand_subop_get_addr_start_off(subop, instr_idx);
if (instr_idx == subop->ninstrs - 1 &&
subop->last_instr_end_off)
end_off = subop->last_instr_end_off;
else
end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
return end_off - start_off;
}
EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
/**
* nand_subop_get_data_start_off - Get the start offset in a data array
* @subop: The entire sub-operation
* @instr_idx: Index of the instruction inside the sub-operation
*
* During driver development, one could be tempted to directly use the
* ->data->buf.{in,out} field of data instructions. This is wrong as data
* instructions might be split.
*
* Given a data instruction, returns the offset to start from.
*/
unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
unsigned int instr_idx)
{
if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
!nand_instr_is_data(&subop->instrs[instr_idx])))
return 0;
return nand_subop_get_start_off(subop, instr_idx);
}
EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
/**
* nand_subop_get_data_len - Get the number of bytes to retrieve
* @subop: The entire sub-operation
* @instr_idx: Index of the instruction inside the sub-operation
*
* During driver development, one could be tempted to directly use the
* ->data->len field of a data instruction. This is wrong as data instructions
* might be split.
*
* Returns the length of the chunk of data to send/receive.
*/
unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
unsigned int instr_idx)
{
int start_off = 0, end_off;
if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
!nand_instr_is_data(&subop->instrs[instr_idx])))
return 0;
start_off = nand_subop_get_data_start_off(subop, instr_idx);
if (instr_idx == subop->ninstrs - 1 &&
subop->last_instr_end_off)
end_off = subop->last_instr_end_off;
else
end_off = subop->instrs[instr_idx].ctx.data.len;
return end_off - start_off;
}
EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
/**
* nand_reset - Reset and initialize a NAND device
* @chip: The NAND chip
* @chipnr: Internal die id
*
* Save the timings data structure, then apply SDR timings mode 0 (see
* nand_reset_data_interface for details), do the reset operation, and
* apply back the previous timings.
*
* Returns 0 on success, a negative error code otherwise.
*/
int nand_reset(struct nand_chip *chip, int chipnr)
{
struct nand_data_interface saved_data_intf = chip->data_interface;
int ret;
ret = nand_reset_data_interface(chip, chipnr);
if (ret)
return ret;
/*
* The CS line has to be released before we can apply the new NAND
* interface settings, hence this weird nand_select_target()
* nand_deselect_target() dance.
*/
nand_select_target(chip, chipnr);
ret = nand_reset_op(chip);
nand_deselect_target(chip);
if (ret)
return ret;
/*
* A nand_reset_data_interface() put both the NAND chip and the NAND
* controller in timings mode 0. If the default mode for this chip is
* also 0, no need to proceed to the change again. Plus, at probe time,
* nand_setup_data_interface() uses ->set/get_features() which would
* fail anyway as the parameter page is not available yet.
*/
if (!chip->onfi_timing_mode_default)
return 0;
chip->data_interface = saved_data_intf;
ret = nand_setup_data_interface(chip, chipnr);
if (ret)
return ret;
return 0;
}
EXPORT_SYMBOL_GPL(nand_reset);
/**
* nand_get_features - wrapper to perform a GET_FEATURE
* @chip: NAND chip info structure
* @addr: feature address
* @subfeature_param: the subfeature parameters, a four bytes array
*
* Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
* operation cannot be handled.
*/
int nand_get_features(struct nand_chip *chip, int addr,
u8 *subfeature_param)
{
if (!nand_supports_get_features(chip, addr))
return -ENOTSUPP;
if (chip->legacy.get_features)
return chip->legacy.get_features(chip, addr, subfeature_param);
return nand_get_features_op(chip, addr, subfeature_param);
}
/**
* nand_set_features - wrapper to perform a SET_FEATURE
* @chip: NAND chip info structure
* @addr: feature address
* @subfeature_param: the subfeature parameters, a four bytes array
*
* Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
* operation cannot be handled.
*/
int nand_set_features(struct nand_chip *chip, int addr,
u8 *subfeature_param)
{
if (!nand_supports_set_features(chip, addr))
return -ENOTSUPP;
if (chip->legacy.set_features)
return chip->legacy.set_features(chip, addr, subfeature_param);
return nand_set_features_op(chip, addr, subfeature_param);
}
/**
* nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
* @buf: buffer to test
* @len: buffer length
* @bitflips_threshold: maximum number of bitflips
*
* Check if a buffer contains only 0xff, which means the underlying region
* has been erased and is ready to be programmed.
* The bitflips_threshold specify the maximum number of bitflips before
* considering the region is not erased.
* Note: The logic of this function has been extracted from the memweight
* implementation, except that nand_check_erased_buf function exit before
* testing the whole buffer if the number of bitflips exceed the
* bitflips_threshold value.
*
* Returns a positive number of bitflips less than or equal to
* bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
* threshold.
*/
static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
{
const unsigned char *bitmap = buf;
int bitflips = 0;
int weight;
for (; len && ((uintptr_t)bitmap) % sizeof(long);
len--, bitmap++) {
weight = hweight8(*bitmap);
bitflips += BITS_PER_BYTE - weight;
if (unlikely(bitflips > bitflips_threshold))
return -EBADMSG;
}
for (; len >= sizeof(long);
len -= sizeof(long), bitmap += sizeof(long)) {
unsigned long d = *((unsigned long *)bitmap);
if (d == ~0UL)
continue;
weight = hweight_long(d);
bitflips += BITS_PER_LONG - weight;
if (unlikely(bitflips > bitflips_threshold))
return -EBADMSG;
}
for (; len > 0; len--, bitmap++) {
weight = hweight8(*bitmap);
bitflips += BITS_PER_BYTE - weight;
if (unlikely(bitflips > bitflips_threshold))
return -EBADMSG;
}
return bitflips;
}
/**
* nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
* 0xff data
* @data: data buffer to test
* @datalen: data length
* @ecc: ECC buffer
* @ecclen: ECC length
* @extraoob: extra OOB buffer
* @extraooblen: extra OOB length
* @bitflips_threshold: maximum number of bitflips
*
* Check if a data buffer and its associated ECC and OOB data contains only
* 0xff pattern, which means the underlying region has been erased and is
* ready to be programmed.
* The bitflips_threshold specify the maximum number of bitflips before
* considering the region as not erased.
*
* Note:
* 1/ ECC algorithms are working on pre-defined block sizes which are usually
* different from the NAND page size. When fixing bitflips, ECC engines will
* report the number of errors per chunk, and the NAND core infrastructure
* expect you to return the maximum number of bitflips for the whole page.
* This is why you should always use this function on a single chunk and
* not on the whole page. After checking each chunk you should update your
* max_bitflips value accordingly.
* 2/ When checking for bitflips in erased pages you should not only check
* the payload data but also their associated ECC data, because a user might
* have programmed almost all bits to 1 but a few. In this case, we
* shouldn't consider the chunk as erased, and checking ECC bytes prevent
* this case.
* 3/ The extraoob argument is optional, and should be used if some of your OOB
* data are protected by the ECC engine.
* It could also be used if you support subpages and want to attach some
* extra OOB data to an ECC chunk.
*
* Returns a positive number of bitflips less than or equal to
* bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
* threshold. In case of success, the passed buffers are filled with 0xff.
*/
int nand_check_erased_ecc_chunk(void *data, int datalen,
void *ecc, int ecclen,
void *extraoob, int extraooblen,
int bitflips_threshold)
{
int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
data_bitflips = nand_check_erased_buf(data, datalen,
bitflips_threshold);
if (data_bitflips < 0)
return data_bitflips;
bitflips_threshold -= data_bitflips;
ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
if (ecc_bitflips < 0)
return ecc_bitflips;
bitflips_threshold -= ecc_bitflips;
extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
bitflips_threshold);
if (extraoob_bitflips < 0)
return extraoob_bitflips;
if (data_bitflips)
memset(data, 0xff, datalen);
if (ecc_bitflips)
memset(ecc, 0xff, ecclen);
if (extraoob_bitflips)
memset(extraoob, 0xff, extraooblen);
return data_bitflips + ecc_bitflips + extraoob_bitflips;
}
EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
/**
* nand_read_page_raw_notsupp - dummy read raw page function
* @chip: nand chip info structure
* @buf: buffer to store read data
* @oob_required: caller requires OOB data read to chip->oob_poi
* @page: page number to read
*
* Returns -ENOTSUPP unconditionally.
*/
int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf,
int oob_required, int page)
{
return -ENOTSUPP;
}
/**
* nand_read_page_raw - [INTERN] read raw page data without ecc
* @chip: nand chip info structure
* @buf: buffer to store read data
* @oob_required: caller requires OOB data read to chip->oob_poi
* @page: page number to read
*
* Not for syndrome calculating ECC controllers, which use a special oob layout.
*/
int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
int page)
{
struct mtd_info *mtd = nand_to_mtd(chip);
int ret;
ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
if (ret)
return ret;
if (oob_required) {
ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
false);
if (ret)
return ret;
}
return 0;
}
EXPORT_SYMBOL(nand_read_page_raw);
/**
* nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
* @chip: nand chip info structure
* @buf: buffer to store read data
* @oob_required: caller requires OOB data read to chip->oob_poi
* @page: page number to read
*
* We need a special oob layout and handling even when OOB isn't used.
*/
static int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf,
int oob_required, int page)
{
struct mtd_info *mtd = nand_to_mtd(chip);
int eccsize = chip->ecc.size;
int eccbytes = chip->ecc.bytes;
uint8_t *oob = chip->oob_poi;
int steps, size, ret;
ret = nand_read_page_op(chip, page, 0, NULL, 0);
if (ret)
return ret;
for (steps = chip->ecc.steps; steps > 0; steps--) {
ret = nand_read_data_op(chip, buf, eccsize, false);
if (ret)
return ret;
buf += eccsize;
if (chip->ecc.prepad) {
ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
false);
if (ret)
return ret;
oob += chip->ecc.prepad;
}
ret = nand_read_data_op(chip, oob, eccbytes, false);
if (ret)
return ret;
oob += eccbytes;
if (chip->ecc.postpad) {
ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
false);
if (ret)
return ret;
oob += chip->ecc.postpad;
}
}
size = mtd->oobsize - (oob - chip->oob_poi);
if (size) {
ret = nand_read_data_op(chip, oob, size, false);
if (ret)
return ret;
}
return 0;
}
/**
* nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
* @chip: nand chip info structure
* @buf: buffer to store read data
* @oob_required: caller requires OOB data read to chip->oob_poi
* @page: page number to read
*/
static int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf,
int oob_required, int page)
{
struct mtd_info *mtd = nand_to_mtd(chip);
int i, eccsize = chip->ecc.size, ret;
int eccbytes = chip->ecc.bytes;
int eccsteps = chip->ecc.steps;
uint8_t *p = buf;
uint8_t *ecc_calc = chip->ecc.calc_buf;
uint8_t *ecc_code = chip->ecc.code_buf;
unsigned int max_bitflips = 0;
chip->ecc.read_page_raw(chip, buf, 1, page);
for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
chip->ecc.calculate(chip, p, &ecc_calc[i]);
ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
chip->ecc.total);
if (ret)
return ret;
eccsteps = chip->ecc.steps;
p = buf;
for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
int stat;
stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
if (stat < 0) {
mtd->ecc_stats.failed++;
} else {
mtd->ecc_stats.corrected += stat;
max_bitflips = max_t(unsigned int, max_bitflips, stat);
}
}
return max_bitflips;
}
/**
* nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
* @chip: nand chip info structure
* @data_offs: offset of requested data within the page
* @readlen: data length
* @bufpoi: buffer to store read data
* @page: page number to read
*/
static int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs,
uint32_t readlen, uint8_t *bufpoi, int page)
{
struct mtd_info *mtd = nand_to_mtd(chip);
int start_step, end_step, num_steps, ret;
uint8_t *p;
int data_col_addr, i, gaps = 0;
int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
int index, section = 0;
unsigned int max_bitflips = 0;
struct mtd_oob_region oobregion = { };
/* Column address within the page aligned to ECC size (256bytes) */
start_step = data_offs / chip->ecc.size;
end_step = (data_offs + readlen - 1) / chip->ecc.size;
num_steps = end_step - start_step + 1;
index = start_step * chip->ecc.bytes;
/* Data size aligned to ECC ecc.size */
datafrag_len = num_steps * chip->ecc.size;
eccfrag_len = num_steps * chip->ecc.bytes;
data_col_addr = start_step * chip->ecc.size;
/* If we read not a page aligned data */
p = bufpoi + data_col_addr;
ret = nand_read_page_op(chip, page, data_col_addr, p, datafrag_len);
if (ret)
return ret;
/* Calculate ECC */
for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
chip->ecc.calculate(chip, p, &chip->ecc.calc_buf[i]);
/*
* The performance is faster if we position offsets according to
* ecc.pos. Let's make sure that there are no gaps in ECC positions.
*/
ret = mtd_ooblayout_find_eccregion(mtd, index, &section, &oobregion);
if (ret)
return ret;
if (oobregion.length < eccfrag_len)
gaps = 1;
if (gaps) {
ret = nand_change_read_column_op(chip, mtd->writesize,
chip->oob_poi, mtd->oobsize,
false);
if (ret)
return ret;
} else {
/*
* Send the command to read the particular ECC bytes take care
* about buswidth alignment in read_buf.
*/
aligned_pos = oobregion.offset & ~(busw - 1);
aligned_len = eccfrag_len;
if (oobregion.offset & (busw - 1))
aligned_len++;
if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
(busw - 1))
aligned_len++;
ret = nand_change_read_column_op(chip,
mtd->writesize + aligned_pos,
&chip->oob_poi[aligned_pos],
aligned_len, false);
if (ret)
return ret;
}
ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
chip->oob_poi, index, eccfrag_len);
if (ret)
return ret;
p = bufpoi + data_col_addr;
for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
int stat;
stat = chip->ecc.correct(chip, p, &chip->ecc.code_buf[i],
&chip->ecc.calc_buf[i]);
if (stat == -EBADMSG &&
(chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
/* check for empty pages with bitflips */
stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
&chip->ecc.code_buf[i],
chip->ecc.bytes,
NULL, 0,
chip->ecc.strength);
}
if (stat < 0) {
mtd->ecc_stats.failed++;
} else {
mtd->ecc_stats.corrected += stat;
max_bitflips = max_t(unsigned int, max_bitflips, stat);
}
}
return max_bitflips;
}
/**
* nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
* @chip: nand chip info structure
* @buf: buffer to store read data
* @oob_required: caller requires OOB data read to chip->oob_poi
* @page: page number to read
*
* Not for syndrome calculating ECC controllers which need a special oob layout.
*/
static int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf,
int oob_required, int page)
{
struct mtd_info *mtd = nand_to_mtd(chip);
int i, eccsize = chip->ecc.size, ret;
int eccbytes = chip->ecc.bytes;
int eccsteps = chip->ecc.steps;
uint8_t *p = buf;
uint8_t *ecc_calc = chip->ecc.calc_buf;
uint8_t *ecc_code = chip->ecc.code_buf;
unsigned int max_bitflips = 0;
ret = nand_read_page_op(chip, page, 0, NULL, 0);
if (ret)
return ret;
for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
chip->ecc.hwctl(chip, NAND_ECC_READ);