# MTD NAND Driver Programming Interface

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> The generic NAND driver supports almost all NAND and AG-AND based chips and connects them to the Memory Technology Devices (MTD) subsystem of the Linux Kernel.

<a id="rst-mtd-nand-driver-programming-interface"></a>

**Author:** Thomas Gleixner

<a id="rst-introduction"></a>

## Introduction

The generic NAND driver supports almost all NAND and AG-AND based chips and connects them to the Memory Technology Devices (MTD) subsystem of the Linux Kernel.

This documentation is provided for developers who want to implement board drivers or filesystem drivers suitable for NAND devices.

<a id="rst-known-bugs-and-assumptions"></a>

## Known Bugs And Assumptions

None.

<a id="rst-documentation-hints"></a>

## Documentation hints

The function and structure docs are autogenerated. Each function and struct member has a short description which is marked with an \[XXX\] identifier. The following chapters explain the meaning of those identifiers.

<a id="rst-function-identifiers-xxx"></a>

### Function identifiers \[XXX\]

The functions are marked with \[XXX\] identifiers in the short comment. The identifiers explain the usage and scope of the functions. Following identifiers are used:

- \[MTD Interface\]

  These functions provide the interface to the MTD kernel API. They are not replaceable and provide functionality which is complete hardware independent.

- \[NAND Interface\]

  These functions are exported and provide the interface to the NAND kernel API.

- \[GENERIC\]

  Generic functions are not replaceable and provide functionality which is complete hardware independent.

- \[DEFAULT\]

  Default functions provide hardware related functionality which is suitable for most of the implementations. These functions can be replaced by the board driver if necessary. Those functions are called via pointers in the NAND chip description structure. The board driver can set the functions which should be replaced by board dependent functions before calling nand_scan(). If the function pointer is NULL on entry to nand_scan() then the pointer is set to the default function which is suitable for the detected chip type.

<a id="rst-struct-member-identifiers-xxx"></a>

### Struct member identifiers \[XXX\]

The struct members are marked with \[XXX\] identifiers in the comment. The identifiers explain the usage and scope of the members. Following identifiers are used:

- \[INTERN\]

  These members are for NAND driver internal use only and must not be modified. Most of these values are calculated from the chip geometry information which is evaluated during nand_scan().

- \[REPLACEABLE\]

  Replaceable members hold hardware related functions which can be provided by the board driver. The board driver can set the functions which should be replaced by board dependent functions before calling nand_scan(). If the function pointer is NULL on entry to nand_scan() then the pointer is set to the default function which is suitable for the detected chip type.

- \[BOARDSPECIFIC\]

  Board specific members hold hardware related information which must be provided by the board driver. The board driver must set the function pointers and datafields before calling nand_scan().

- \[OPTIONAL\]

  Optional members can hold information relevant for the board driver. The generic NAND driver code does not use this information.

<a id="rst-basic-board-driver"></a>

## Basic board driver

For most boards it will be sufficient to provide just the basic functions and fill out some really board dependent members in the nand chip description structure.

<a id="rst-basic-defines"></a>

### Basic defines

At least you have to provide a nand_chip structure and a storage for the ioremap'ed chip address. You can allocate the nand_chip structure using kmalloc or you can allocate it statically. The NAND chip structure embeds an mtd structure which will be registered to the MTD subsystem. You can extract a pointer to the mtd structure from a nand_chip pointer using the nand_to_mtd() helper.

Kmalloc based example



```text
static struct mtd_info *board_mtd;
static void __iomem *baseaddr;
```

Static example



```text
static struct nand_chip board_chip;
static void __iomem *baseaddr;
```

<a id="rst-partition-defines"></a>

### Partition defines

If you want to divide your device into partitions, then define a partitioning scheme suitable to your board.



```text
#define NUM_PARTITIONS 2
static struct mtd_partition partition_info[] = {
    { .name = "Flash partition 1",
      .offset =  0,
      .size =    8 * 1024 * 1024 },
    { .name = "Flash partition 2",
      .offset =  MTDPART_OFS_NEXT,
      .size =    MTDPART_SIZ_FULL },
};
```

<a id="rst-hardware-control-function"></a>

### Hardware control function

The hardware control function provides access to the control pins of the NAND chip(s). The access can be done by GPIO pins or by address lines. If you use address lines, make sure that the timing requirements are met.

*GPIO based example*



```text
static void board_hwcontrol(struct mtd_info *mtd, int cmd)
{
    switch(cmd){
        case NAND_CTL_SETCLE: /* Set CLE pin high */ break;
        case NAND_CTL_CLRCLE: /* Set CLE pin low */ break;
        case NAND_CTL_SETALE: /* Set ALE pin high */ break;
        case NAND_CTL_CLRALE: /* Set ALE pin low */ break;
        case NAND_CTL_SETNCE: /* Set nCE pin low */ break;
        case NAND_CTL_CLRNCE: /* Set nCE pin high */ break;
    }
}
```

*Address lines based example.* It's assumed that the nCE pin is driven by a chip select decoder.



```text
static void board_hwcontrol(struct mtd_info *mtd, int cmd)
{
    struct nand_chip *this = mtd_to_nand(mtd);
    switch(cmd){
        case NAND_CTL_SETCLE: this->legacy.IO_ADDR_W |= CLE_ADRR_BIT;  break;
        case NAND_CTL_CLRCLE: this->legacy.IO_ADDR_W &= ~CLE_ADRR_BIT; break;
        case NAND_CTL_SETALE: this->legacy.IO_ADDR_W |= ALE_ADRR_BIT;  break;
        case NAND_CTL_CLRALE: this->legacy.IO_ADDR_W &= ~ALE_ADRR_BIT; break;
    }
}
```

<a id="rst-device-ready-function"></a>

### Device ready function

If the hardware interface has the ready busy pin of the NAND chip connected to a GPIO or other accessible I/O pin, this function is used to read back the state of the pin. The function has no arguments and should return 0, if the device is busy (R/B pin is low) and 1, if the device is ready (R/B pin is high). If the hardware interface does not give access to the ready busy pin, then the function must not be defined and the function pointer this-&gt;legacy.dev_ready is set to NULL.

<a id="rst-init-function"></a>

### Init function

The init function allocates memory and sets up all the board specific parameters and function pointers. When everything is set up nand_scan() is called. This function tries to detect and identify then chip. If a chip is found all the internal data fields are initialized accordingly. The structure(s) have to be zeroed out first and then filled with the necessary information about the device.



```text
static int __init board_init (void)
{
    struct nand_chip *this;
    int err = 0;

    /* Allocate memory for MTD device structure and private data */
    this = kzalloc(sizeof(struct nand_chip), GFP_KERNEL);
    if (!this) {
        printk ("Unable to allocate NAND MTD device structure.\n");
        err = -ENOMEM;
        goto out;
    }

    board_mtd = nand_to_mtd(this);

    /* map physical address */
    baseaddr = ioremap(CHIP_PHYSICAL_ADDRESS, 1024);
    if (!baseaddr) {
        printk("Ioremap to access NAND chip failed\n");
        err = -EIO;
        goto out_mtd;
    }

    /* Set address of NAND IO lines */
    this->legacy.IO_ADDR_R = baseaddr;
    this->legacy.IO_ADDR_W = baseaddr;
    /* Reference hardware control function */
    this->hwcontrol = board_hwcontrol;
    /* Set command delay time, see datasheet for correct value */
    this->legacy.chip_delay = CHIP_DEPENDEND_COMMAND_DELAY;
    /* Assign the device ready function, if available */
    this->legacy.dev_ready = board_dev_ready;
    this->eccmode = NAND_ECC_SOFT;

    /* Scan to find existence of the device */
    if (nand_scan (this, 1)) {
        err = -ENXIO;
        goto out_ior;
    }

    add_mtd_partitions(board_mtd, partition_info, NUM_PARTITIONS);
    goto out;

out_ior:
    iounmap(baseaddr);
out_mtd:
    kfree (this);
out:
    return err;
}
module_init(board_init);
```

<a id="rst-exit-function"></a>

### Exit function

The exit function is only necessary if the driver is compiled as a module. It releases all resources which are held by the chip driver and unregisters the partitions in the MTD layer.



```text
#ifdef MODULE
static void __exit board_cleanup (void)
{
    /* Unregister device */
    WARN_ON(mtd_device_unregister(board_mtd));
    /* Release resources */
    nand_cleanup(mtd_to_nand(board_mtd));

    /* unmap physical address */
    iounmap(baseaddr);

    /* Free the MTD device structure */
    kfree (mtd_to_nand(board_mtd));
}
module_exit(board_cleanup);
#endif
```

<a id="rst-advanced-board-driver-functions"></a>

## Advanced board driver functions

This chapter describes the advanced functionality of the NAND driver. For a list of functions which can be overridden by the board driver see the documentation of the nand_chip structure.

<a id="rst-multiple-chip-control"></a>

### Multiple chip control

The nand driver can control chip arrays. Therefore the board driver must provide an own select_chip function. This function must (de)select the requested chip. The function pointer in the nand_chip structure must be set before calling nand_scan(). The maxchip parameter of nand_scan() defines the maximum number of chips to scan for. Make sure that the select_chip function can handle the requested number of chips.

The nand driver concatenates the chips to one virtual chip and provides this virtual chip to the MTD layer.

*Note: The driver can only handle linear chip arrays of equally sized chips. There is no support for parallel arrays which extend the buswidth.*

*GPIO based example*



```text
static void board_select_chip (struct mtd_info *mtd, int chip)
{
    /* Deselect all chips, set all nCE pins high */
    GPIO(BOARD_NAND_NCE) |= 0xff;
    if (chip >= 0)
        GPIO(BOARD_NAND_NCE) &= ~ (1 << chip);
}
```

*Address lines based example.* Its assumed that the nCE pins are connected to an address decoder.



```text
static void board_select_chip (struct mtd_info *mtd, int chip)
{
    struct nand_chip *this = mtd_to_nand(mtd);

    /* Deselect all chips */
    this->legacy.IO_ADDR_R &= ~BOARD_NAND_ADDR_MASK;
    this->legacy.IO_ADDR_W &= ~BOARD_NAND_ADDR_MASK;
    switch (chip) {
    case 0:
        this->legacy.IO_ADDR_R |= BOARD_NAND_ADDR_CHIP0;
        this->legacy.IO_ADDR_W |= BOARD_NAND_ADDR_CHIP0;
        break;
    ....
    case n:
        this->legacy.IO_ADDR_R |= BOARD_NAND_ADDR_CHIPn;
        this->legacy.IO_ADDR_W |= BOARD_NAND_ADDR_CHIPn;
        break;
    }
}
```

<a id="rst-hardware-ecc-support"></a>

### Hardware ECC support

<a id="rst-functions-and-constants"></a>

#### Functions and constants

The nand driver supports three different types of hardware ECC.

- NAND_ECC_HW3_256

  Hardware ECC generator providing 3 bytes ECC per 256 byte.

- NAND_ECC_HW3_512

  Hardware ECC generator providing 3 bytes ECC per 512 byte.

- NAND_ECC_HW6_512

  Hardware ECC generator providing 6 bytes ECC per 512 byte.

- NAND_ECC_HW8_512

  Hardware ECC generator providing 8 bytes ECC per 512 byte.

If your hardware generator has a different functionality add it at the appropriate place in nand_base.c

The board driver must provide following functions:

- enable_hwecc

  This function is called before reading / writing to the chip. Reset or initialize the hardware generator in this function. The function is called with an argument which let you distinguish between read and write operations.

- calculate_ecc

  This function is called after read / write from / to the chip. Transfer the ECC from the hardware to the buffer. If the option NAND_HWECC_SYNDROME is set then the function is only called on write. See below.

- correct_data

  In case of an ECC error this function is called for error detection and correction. Return 1 respectively 2 in case the error can be corrected. If the error is not correctable return -1. If your hardware generator matches the default algorithm of the nand_ecc software generator then use the correction function provided by nand_ecc instead of implementing duplicated code.

<a id="rst-hardware-ecc-with-syndrome-calculation"></a>

#### Hardware ECC with syndrome calculation

Many hardware ECC implementations provide Reed-Solomon codes and calculate an error syndrome on read. The syndrome must be converted to a standard Reed-Solomon syndrome before calling the error correction code in the generic Reed-Solomon library.

The ECC bytes must be placed immediately after the data bytes in order to make the syndrome generator work. This is contrary to the usual layout used by software ECC. The separation of data and out of band area is not longer possible. The nand driver code handles this layout and the remaining free bytes in the oob area are managed by the autoplacement code. Provide a matching oob-layout in this case. See rts_from4.c and diskonchip.c for implementation reference. In those cases we must also use bad block tables on FLASH, because the ECC layout is interfering with the bad block marker positions. See bad block table support for details.

<a id="rst-bad-block-table-support"></a>

### Bad block table support

Most NAND chips mark the bad blocks at a defined position in the spare area. Those blocks must not be erased under any circumstances as the bad block information would be lost. It is possible to check the bad block mark each time when the blocks are accessed by reading the spare area of the first page in the block. This is time consuming so a bad block table is used.

The nand driver supports various types of bad block tables.

- Per device

  The bad block table contains all bad block information of the device which can consist of multiple chips.

- Per chip

  A bad block table is used per chip and contains the bad block information for this particular chip.

- Fixed offset

  The bad block table is located at a fixed offset in the chip (device). This applies to various DiskOnChip devices.

- Automatic placed

  The bad block table is automatically placed and detected either at the end or at the beginning of a chip (device)

- Mirrored tables

  The bad block table is mirrored on the chip (device) to allow updates of the bad block table without data loss.

nand_scan() calls the function nand_default_bbt(). nand_default_bbt() selects appropriate default bad block table descriptors depending on the chip information which was retrieved by nand_scan().

The standard policy is scanning the device for bad blocks and build a ram based bad block table which allows faster access than always checking the bad block information on the flash chip itself.

<a id="rst-flash-based-tables"></a>

#### Flash based tables

It may be desired or necessary to keep a bad block table in FLASH. For AG-AND chips this is mandatory, as they have no factory marked bad blocks. They have factory marked good blocks. The marker pattern is erased when the block is erased to be reused. So in case of powerloss before writing the pattern back to the chip this block would be lost and added to the bad blocks. Therefore we scan the chip(s) when we detect them the first time for good blocks and store this information in a bad block table before erasing any of the blocks.

The blocks in which the tables are stored are protected against accidental access by marking them bad in the memory bad block table. The bad block table management functions are allowed to circumvent this protection.

The simplest way to activate the FLASH based bad block table support is to set the option NAND_BBT_USE_FLASH in the bbt_option field of the nand chip structure before calling nand_scan(). For AG-AND chips is this done by default. This activates the default FLASH based bad block table functionality of the NAND driver. The default bad block table options are

- Store bad block table per chip

- Use 2 bits per block

- Automatic placement at the end of the chip

- Use mirrored tables with version numbers

- Reserve 4 blocks at the end of the chip

<a id="rst-user-defined-tables"></a>

#### User defined tables

User defined tables are created by filling out a nand_bbt_descr structure and storing the pointer in the nand_chip structure member bbt_td before calling nand_scan(). If a mirror table is necessary a second structure must be created and a pointer to this structure must be stored in bbt_md inside the nand_chip structure. If the bbt_md member is set to NULL then only the main table is used and no scan for the mirrored table is performed.

The most important field in the nand_bbt_descr structure is the options field. The options define most of the table properties. Use the predefined constants from rawnand.h to define the options.

- Number of bits per block

  The supported number of bits is 1, 2, 4, 8.

- Table per chip

  Setting the constant NAND_BBT_PERCHIP selects that a bad block table is managed for each chip in a chip array. If this option is not set then a per device bad block table is used.

- Table location is absolute

  Use the option constant NAND_BBT_ABSPAGE and define the absolute page number where the bad block table starts in the field pages. If you have selected bad block tables per chip and you have a multi chip array then the start page must be given for each chip in the chip array. Note: there is no scan for a table ident pattern performed, so the fields pattern, veroffs, offs, len can be left uninitialized

- Table location is automatically detected

  The table can either be located in the first or the last good blocks of the chip (device). Set NAND_BBT_LASTBLOCK to place the bad block table at the end of the chip (device). The bad block tables are marked and identified by a pattern which is stored in the spare area of the first page in the block which holds the bad block table. Store a pointer to the pattern in the pattern field. Further the length of the pattern has to be stored in len and the offset in the spare area must be given in the offs member of the nand_bbt_descr structure. For mirrored bad block tables different patterns are mandatory.

- Table creation

  Set the option NAND_BBT_CREATE to enable the table creation if no table can be found during the scan. Usually this is done only once if a new chip is found.

- Table write support

  Set the option NAND_BBT_WRITE to enable the table write support. This allows the update of the bad block table(s) in case a block has to be marked bad due to wear. The MTD interface function block_markbad is calling the update function of the bad block table. If the write support is enabled then the table is updated on FLASH.

  Note: Write support should only be enabled for mirrored tables with version control.

- Table version control

  Set the option NAND_BBT_VERSION to enable the table version control. It's highly recommended to enable this for mirrored tables with write support. It makes sure that the risk of losing the bad block table information is reduced to the loss of the information about the one worn out block which should be marked bad. The version is stored in 4 consecutive bytes in the spare area of the device. The position of the version number is defined by the member veroffs in the bad block table descriptor.

- Save block contents on write

  In case that the block which holds the bad block table does contain other useful information, set the option NAND_BBT_SAVECONTENT. When the bad block table is written then the whole block is read the bad block table is updated and the block is erased and everything is written back. If this option is not set only the bad block table is written and everything else in the block is ignored and erased.

- Number of reserved blocks

  For automatic placement some blocks must be reserved for bad block table storage. The number of reserved blocks is defined in the maxblocks member of the bad block table description structure. Reserving 4 blocks for mirrored tables should be a reasonable number. This also limits the number of blocks which are scanned for the bad block table ident pattern.

<a id="rst-spare-area-auto-placement"></a>

### Spare area (auto)placement

The nand driver implements different possibilities for placement of filesystem data in the spare area,

- Placement defined by fs driver

- Automatic placement

The default placement function is automatic placement. The nand driver has built in default placement schemes for the various chiptypes. If due to hardware ECC functionality the default placement does not fit then the board driver can provide a own placement scheme.

File system drivers can provide a own placement scheme which is used instead of the default placement scheme.

Placement schemes are defined by a nand_oobinfo structure



```text
struct nand_oobinfo {
    int useecc;
    int eccbytes;
    int eccpos[24];
    int oobfree[8][2];
};
```

- useecc

  The useecc member controls the ecc and placement function. The header file include/mtd/mtd-abi.h contains constants to select ecc and placement. MTD_NANDECC_OFF switches off the ecc complete. This is not recommended and available for testing and diagnosis only. MTD_NANDECC_PLACE selects caller defined placement, MTD_NANDECC_AUTOPLACE selects automatic placement.

- eccbytes

  The eccbytes member defines the number of ecc bytes per page.

- eccpos

  The eccpos array holds the byte offsets in the spare area where the ecc codes are placed.

- oobfree

  The oobfree array defines the areas in the spare area which can be used for automatic placement. The information is given in the format \{offset, size\}. offset defines the start of the usable area, size the length in bytes. More than one area can be defined. The list is terminated by an \{0, 0\} entry.

<a id="rst-placement-defined-by-fs-driver"></a>

#### Placement defined by fs driver

The calling function provides a pointer to a nand_oobinfo structure which defines the ecc placement. For writes the caller must provide a spare area buffer along with the data buffer. The spare area buffer size is (number of pages) \* (size of spare area). For reads the buffer size is (number of pages) \* ((size of spare area) + (number of ecc steps per page) \* sizeof (int)). The driver stores the result of the ecc check for each tuple in the spare buffer. The storage sequence is:



```text
<spare data page 0><ecc result 0>...<ecc result n>

...

<spare data page n><ecc result 0>...<ecc result n>
```

This is a legacy mode used by YAFFS1.

If the spare area buffer is NULL then only the ECC placement is done according to the given scheme in the nand_oobinfo structure.

<a id="rst-automatic-placement"></a>

#### Automatic placement

Automatic placement uses the built in defaults to place the ecc bytes in the spare area. If filesystem data have to be stored / read into the spare area then the calling function must provide a buffer. The buffer size per page is determined by the oobfree array in the nand_oobinfo structure.

If the spare area buffer is NULL then only the ECC placement is done according to the default builtin scheme.

<a id="rst-spare-area-autoplacement-default-schemes"></a>

### Spare area autoplacement default schemes

<a id="rst-byte-pagesize"></a>

#### 256 byte pagesize


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Content

</th>
<th>


Comment

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x00

</td>
<td>


ECC byte 0

</td>
<td>


Error correction code byte 0

</td>
</tr>
<tr>
<td>


0x01

</td>
<td>


ECC byte 1

</td>
<td>


Error correction code byte 1

</td>
</tr>
<tr>
<td>


0x02

</td>
<td>


ECC byte 2

</td>
<td>


Error correction code byte 2

</td>
</tr>
<tr>
<td>


0x03

</td>
<td>


Autoplace 0

</td>
<td>




</td>
</tr>
<tr>
<td>


0x04

</td>
<td>


Autoplace 1

</td>
<td>




</td>
</tr>
<tr>
<td>


0x05

</td>
<td>


Bad block marker

</td>
<td>


If any bit in this byte is zero, then this block is bad. This applies only to the first page in a block. In the remaining pages this byte is reserved

</td>
</tr>
<tr>
<td>


0x06

</td>
<td>


Autoplace 2

</td>
<td>




</td>
</tr>
<tr>
<td>


0x07

</td>
<td>


Autoplace 3

</td>
<td>




</td>
</tr>
</tbody>
</table>

<a id="rst-byte-pagesize-1"></a>

#### 512 byte pagesize


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Content

</th>
<th>


Comment

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x00

</td>
<td>


ECC byte 0

</td>
<td>


Error correction code byte 0 of the lower 256 Byte data in this page

</td>
</tr>
<tr>
<td>


0x01

</td>
<td>


ECC byte 1

</td>
<td>


Error correction code byte 1 of the lower 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x02

</td>
<td>


ECC byte 2

</td>
<td>


Error correction code byte 2 of the lower 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x03

</td>
<td>


ECC byte 3

</td>
<td>


Error correction code byte 0 of the upper 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x04

</td>
<td>


reserved

</td>
<td>


reserved

</td>
</tr>
<tr>
<td>


0x05

</td>
<td>


Bad block marker

</td>
<td>


If any bit in this byte is zero, then this block is bad. This applies only to the first page in a block. In the remaining pages this byte is reserved

</td>
</tr>
<tr>
<td>


0x06

</td>
<td>


ECC byte 4

</td>
<td>


Error correction code byte 1 of the upper 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x07

</td>
<td>


ECC byte 5

</td>
<td>


Error correction code byte 2 of the upper 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x08 - 0x0F

</td>
<td>


Autoplace 0 - 7

</td>
<td>




</td>
</tr>
</tbody>
</table>

<a id="rst-byte-pagesize-2"></a>

#### 2048 byte pagesize


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Content

</th>
<th>


Comment

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x00

</td>
<td>


Bad block marker

</td>
<td>


If any bit in this byte is zero, then this block is bad. This applies only to the first page in a block. In the remaining pages this byte is reserved

</td>
</tr>
<tr>
<td>


0x01

</td>
<td>


Reserved

</td>
<td>


Reserved

</td>
</tr>
<tr>
<td>


0x02-0x27

</td>
<td>


Autoplace 0 - 37

</td>
<td>




</td>
</tr>
<tr>
<td>


0x28

</td>
<td>


ECC byte 0

</td>
<td>


Error correction code byte 0 of the first 256 Byte data in this page

</td>
</tr>
<tr>
<td>


0x29

</td>
<td>


ECC byte 1

</td>
<td>


Error correction code byte 1 of the first 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x2A

</td>
<td>


ECC byte 2

</td>
<td>


Error correction code byte 2 of the first 256 Bytes data in this page

</td>
</tr>
<tr>
<td>


0x2B

</td>
<td>


ECC byte 3

</td>
<td>


Error correction code byte 0 of the second 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x2C

</td>
<td>


ECC byte 4

</td>
<td>


Error correction code byte 1 of the second 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x2D

</td>
<td>


ECC byte 5

</td>
<td>


Error correction code byte 2 of the second 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x2E

</td>
<td>


ECC byte 6

</td>
<td>


Error correction code byte 0 of the third 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x2F

</td>
<td>


ECC byte 7

</td>
<td>


Error correction code byte 1 of the third 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x30

</td>
<td>


ECC byte 8

</td>
<td>


Error correction code byte 2 of the third 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x31

</td>
<td>


ECC byte 9

</td>
<td>


Error correction code byte 0 of the fourth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x32

</td>
<td>


ECC byte 10

</td>
<td>


Error correction code byte 1 of the fourth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x33

</td>
<td>


ECC byte 11

</td>
<td>


Error correction code byte 2 of the fourth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x34

</td>
<td>


ECC byte 12

</td>
<td>


Error correction code byte 0 of the fifth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x35

</td>
<td>


ECC byte 13

</td>
<td>


Error correction code byte 1 of the fifth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x36

</td>
<td>


ECC byte 14

</td>
<td>


Error correction code byte 2 of the fifth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x37

</td>
<td>


ECC byte 15

</td>
<td>


Error correction code byte 0 of the sixth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x38

</td>
<td>


ECC byte 16

</td>
<td>


Error correction code byte 1 of the sixth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x39

</td>
<td>


ECC byte 17

</td>
<td>


Error correction code byte 2 of the sixth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3A

</td>
<td>


ECC byte 18

</td>
<td>


Error correction code byte 0 of the seventh 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3B

</td>
<td>


ECC byte 19

</td>
<td>


Error correction code byte 1 of the seventh 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3C

</td>
<td>


ECC byte 20

</td>
<td>


Error correction code byte 2 of the seventh 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3D

</td>
<td>


ECC byte 21

</td>
<td>


Error correction code byte 0 of the eighth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3E

</td>
<td>


ECC byte 22

</td>
<td>


Error correction code byte 1 of the eighth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3F

</td>
<td>


ECC byte 23

</td>
<td>


Error correction code byte 2 of the eighth 256 Bytes of data in this page

</td>
</tr>
</tbody>
</table>

<a id="rst-filesystem-support"></a>

## Filesystem support

The NAND driver provides all necessary functions for a filesystem via the MTD interface.

Filesystems must be aware of the NAND peculiarities and restrictions. One major restrictions of NAND Flash is, that you cannot write as often as you want to a page. The consecutive writes to a page, before erasing it again, are restricted to 1-3 writes, depending on the manufacturers specifications. This applies similar to the spare area.

Therefore NAND aware filesystems must either write in page size chunks or hold a writebuffer to collect smaller writes until they sum up to pagesize. Available NAND aware filesystems: JFFS2, YAFFS.

The spare area usage to store filesystem data is controlled by the spare area placement functionality which is described in one of the earlier chapters.

<a id="rst-tools"></a>

## Tools

The MTD project provides a couple of helpful tools to handle NAND Flash.

- flasherase, flasheraseall: Erase and format FLASH partitions

- nandwrite: write filesystem images to NAND FLASH

- nanddump: dump the contents of a NAND FLASH partitions

These tools are aware of the NAND restrictions. Please use those tools instead of complaining about errors which are caused by non NAND aware access methods.

<a id="rst-constants"></a>

## Constants

This chapter describes the constants which might be relevant for a driver developer.

<a id="rst-chip-option-constants"></a>

### Chip option constants

<a id="rst-constants-for-chip-id-table"></a>

#### Constants for chip id table

These constants are defined in rawnand.h. They are OR-ed together to describe the chip functionality:



```text
/* Buswitdh is 16 bit */
#define NAND_BUSWIDTH_16    0x00000002
/* Device supports partial programming without padding */
#define NAND_NO_PADDING     0x00000004
/* Chip has cache program function */
#define NAND_CACHEPRG       0x00000008
/* Chip has copy back function */
#define NAND_COPYBACK       0x00000010
/* AND Chip which has 4 banks and a confusing page / block
 * assignment. See Renesas datasheet for further information */
#define NAND_IS_AND     0x00000020
/* Chip has a array of 4 pages which can be read without
 * additional ready /busy waits */
#define NAND_4PAGE_ARRAY    0x00000040
```

<a id="rst-constants-for-runtime-options"></a>

#### Constants for runtime options

These constants are defined in rawnand.h. They are OR-ed together to describe the functionality:



```text
/* The hw ecc generator provides a syndrome instead a ecc value on read
 * This can only work if we have the ecc bytes directly behind the
 * data bytes. Applies for DOC and AG-AND Renesas HW Reed Solomon generators */
#define NAND_HWECC_SYNDROME 0x00020000
```

<a id="rst-ecc-selection-constants"></a>

### ECC selection constants

Use these constants to select the ECC algorithm:



```text
/* No ECC. Usage is not recommended ! */
#define NAND_ECC_NONE       0
/* Software ECC 3 byte ECC per 256 Byte data */
#define NAND_ECC_SOFT       1
/* Hardware ECC 3 byte ECC per 256 Byte data */
#define NAND_ECC_HW3_256    2
/* Hardware ECC 3 byte ECC per 512 Byte data */
#define NAND_ECC_HW3_512    3
/* Hardware ECC 6 byte ECC per 512 Byte data */
#define NAND_ECC_HW6_512    4
/* Hardware ECC 8 byte ECC per 512 Byte data */
#define NAND_ECC_HW8_512    6
```

<a id="rst-hardware-control-related-constants"></a>

### Hardware control related constants

These constants describe the requested hardware access function when the boardspecific hardware control function is called:



```text
/* Select the chip by setting nCE to low */
#define NAND_CTL_SETNCE     1
/* Deselect the chip by setting nCE to high */
#define NAND_CTL_CLRNCE     2
/* Select the command latch by setting CLE to high */
#define NAND_CTL_SETCLE     3
/* Deselect the command latch by setting CLE to low */
#define NAND_CTL_CLRCLE     4
/* Select the address latch by setting ALE to high */
#define NAND_CTL_SETALE     5
/* Deselect the address latch by setting ALE to low */
#define NAND_CTL_CLRALE     6
/* Set write protection by setting WP to high. Not used! */
#define NAND_CTL_SETWP      7
/* Clear write protection by setting WP to low. Not used! */
#define NAND_CTL_CLRWP      8
```

<a id="rst-bad-block-table-related-constants"></a>

### Bad block table related constants

These constants describe the options used for bad block table descriptors:



```text
/* Options for the bad block table descriptors */

/* The number of bits used per block in the bbt on the device */
#define NAND_BBT_NRBITS_MSK 0x0000000F
#define NAND_BBT_1BIT       0x00000001
#define NAND_BBT_2BIT       0x00000002
#define NAND_BBT_4BIT       0x00000004
#define NAND_BBT_8BIT       0x00000008
/* The bad block table is in the last good block of the device */
#define NAND_BBT_LASTBLOCK  0x00000010
/* The bbt is at the given page, else we must scan for the bbt */
#define NAND_BBT_ABSPAGE    0x00000020
/* bbt is stored per chip on multichip devices */
#define NAND_BBT_PERCHIP    0x00000080
/* bbt has a version counter at offset veroffs */
#define NAND_BBT_VERSION    0x00000100
/* Create a bbt if none axists */
#define NAND_BBT_CREATE     0x00000200
/* Write bbt if necessary */
#define NAND_BBT_WRITE      0x00001000
/* Read and write back block contents when writing bbt */
#define NAND_BBT_SAVECONTENT    0x00002000
```

<a id="rst-structures"></a>

## Structures

This chapter contains the autogenerated documentation of the structures which are used in the NAND driver and might be relevant for a driver developer. Each struct member has a short description which is marked with an \[XXX\] identifier. See the chapter "Documentation hints" for an explanation.


#### <a id="c-struct-nand_parameters"></a>`struct nand_parameters`

NAND generic parameters from the parameter page

**Definition**

```c
struct nand_parameters {
    const char *model;
    bool supports_set_get_features;
    bool supports_read_cache;
    unsigned long set_feature_list[BITS_TO_LONGS(ONFI_FEATURE_NUMBER)];
    unsigned long get_feature_list[BITS_TO_LONGS(ONFI_FEATURE_NUMBER)];
    struct onfi_params *onfi;
};
```

**Members**

- `model`: Model name
- `supports_set_get_features`: The NAND chip supports setting/getting features
- `supports_read_cache`: The NAND chip supports read cache operations
- `set_feature_list`: Bitmap of features that can be set
- `get_feature_list`: Bitmap of features that can be get
- `onfi`: ONFI specific parameters

#### <a id="c-struct-nand_id"></a>`struct nand_id`

NAND id structure

**Definition**

```c
struct nand_id {
    u8 data[NAND_MAX_ID_LEN];
    int len;
};
```

**Members**

- `data`: buffer containing the id bytes.
- `len`: ID length.

#### <a id="c-struct-nand_ecc_step_info"></a>`struct nand_ecc_step_info`

ECC step information of ECC engine

**Definition**

```c
struct nand_ecc_step_info {
    int stepsize;
    const int *strengths;
    int nstrengths;
};
```

**Members**

- `stepsize`: data bytes per ECC step
- `strengths`: array of supported strengths
- `nstrengths`: number of supported strengths

#### <a id="c-struct-nand_ecc_caps"></a>`struct nand_ecc_caps`

capability of ECC engine

**Definition**

```c
struct nand_ecc_caps {
    const struct nand_ecc_step_info *stepinfos;
    int nstepinfos;
    int (*calc_ecc_bytes)(int step_size, int strength);
};
```

**Members**

- `stepinfos`: array of ECC step information
- `nstepinfos`: number of ECC step information
- `calc_ecc_bytes`: driver's hook to calculate ECC bytes per step

#### <a id="c-struct-nand_ecc_ctrl"></a>`struct nand_ecc_ctrl`

Control structure for ECC

**Definition**

```c
struct nand_ecc_ctrl {
    enum nand_ecc_engine_type engine_type;
    enum nand_ecc_placement placement;
    enum nand_ecc_algo algo;
    int steps;
    int size;
    int bytes;
    int total;
    int strength;
    int prepad;
    int postpad;
    unsigned int options;
    u8 *calc_buf;
    u8 *code_buf;
    void (*hwctl)(struct nand_chip *chip, int mode);
    int (*calculate)(struct nand_chip *chip, const uint8_t *dat, uint8_t *ecc_code);
    int (*correct)(struct nand_chip *chip, uint8_t *dat, uint8_t *read_ecc, uint8_t *calc_ecc);
    int (*read_page_raw)(struct nand_chip *chip, uint8_t *buf, int oob_required, int page);
    int (*write_page_raw)(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page);
    int (*read_page)(struct nand_chip *chip, uint8_t *buf, int oob_required, int page);
    int (*read_subpage)(struct nand_chip *chip, uint32_t offs, uint32_t len, uint8_t *buf, int page);
    int (*write_subpage)(struct nand_chip *chip, uint32_t offset, uint32_t data_len, const uint8_t *data_buf, int oob_required, int page);
    int (*write_page)(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page);
    int (*write_oob_raw)(struct nand_chip *chip, int page);
    int (*read_oob_raw)(struct nand_chip *chip, int page);
    int (*read_oob)(struct nand_chip *chip, int page);
    int (*write_oob)(struct nand_chip *chip, int page);
};
```

**Members**

- `engine_type`: ECC engine type
- `placement`: OOB bytes placement
- `algo`: ECC algorithm
- `steps`: number of ECC steps per page
- `size`: data bytes per ECC step
- `bytes`: ECC bytes per step
- `total`: total number of ECC bytes per page
- `strength`: max number of correctible bits per ECC step
- `prepad`: padding information for syndrome based ECC generators
- `postpad`: padding information for syndrome based ECC generators
- `options`: ECC specific options (see NAND_ECC_XXX flags defined above)
- `calc_buf`: buffer for calculated ECC, size is oobsize.
- `code_buf`: buffer for ECC read from flash, size is oobsize.
- `hwctl`: function to control hardware ECC generator. Must only
  be provided if an hardware ECC is available
- `calculate`: function for ECC calculation or readback from ECC hardware
- `correct`: function for ECC correction, matching to ECC generator (sw/hw).
  Should return a positive number representing the number of
  corrected bitflips, -EBADMSG if the number of bitflips exceed
  ECC strength, or any other error code if the error is not
  directly related to correction.
  If -EBADMSG is returned the input buffers should be left
  untouched.
- `read_page_raw`: function to read a raw page without ECC. This function
  should hide the specific layout used by the ECC
  controller and always return contiguous in-band and
  out-of-band data even if they're not stored
  contiguously on the NAND chip (e.g.
  NAND_ECC_PLACEMENT_INTERLEAVED interleaves in-band and
  out-of-band data).
- `write_page_raw`: function to write a raw page without ECC. This function
  should hide the specific layout used by the ECC
  controller and consider the passed data as contiguous
  in-band and out-of-band data. ECC controller is
  responsible for doing the appropriate transformations
  to adapt to its specific layout (e.g.
  NAND_ECC_PLACEMENT_INTERLEAVED interleaves in-band and
  out-of-band data).
- `read_page`: function to read a page according to the ECC generator
  requirements; returns maximum number of bitflips corrected in
  any single ECC step, -EIO hw error
- `read_subpage`: function to read parts of the page covered by ECC;
  returns same as `read_page()`
- `write_subpage`: function to write parts of the page covered by ECC.
- `write_page`: function to write a page according to the ECC generator
  requirements.
- `write_oob_raw`: function to write chip OOB data without ECC
- `read_oob_raw`: function to read chip OOB data without ECC
- `read_oob`: function to read chip OOB data
- `write_oob`: function to write chip OOB data

#### <a id="c-struct-nand_sdr_timings"></a>`struct nand_sdr_timings`

SDR NAND chip timings

**Definition**

```c
struct nand_sdr_timings {
    u64 tBERS_max;
    u32 tCCS_min;
    u64 tPROG_max;
    u64 tR_max;
    u32 tALH_min;
    u32 tADL_min;
    u32 tALS_min;
    u32 tAR_min;
    u32 tCEA_max;
    u32 tCEH_min;
    u32 tCH_min;
    u32 tCHZ_max;
    u32 tCLH_min;
    u32 tCLR_min;
    u32 tCLS_min;
    u32 tCOH_min;
    u32 tCS_min;
    u32 tDH_min;
    u32 tDS_min;
    u32 tFEAT_max;
    u32 tIR_min;
    u32 tITC_max;
    u32 tRC_min;
    u32 tREA_max;
    u32 tREH_min;
    u32 tRHOH_min;
    u32 tRHW_min;
    u32 tRHZ_max;
    u32 tRLOH_min;
    u32 tRP_min;
    u32 tRR_min;
    u64 tRST_max;
    u32 tWB_max;
    u32 tWC_min;
    u32 tWH_min;
    u32 tWHR_min;
    u32 tWP_min;
    u32 tWW_min;
};
```

**Members**

- `tBERS_max`: Block erase time
- `tCCS_min`: Change column setup time
- `tPROG_max`: Page program time
- `tR_max`: Page read time
- `tALH_min`: ALE hold time
- `tADL_min`: ALE to data loading time
- `tALS_min`: ALE setup time
- `tAR_min`: ALE to RE# delay
- `tCEA_max`: CE# access time
- `tCEH_min`: CE# high hold time
- `tCH_min`: CE# hold time
- `tCHZ_max`: CE# high to output hi-Z
- `tCLH_min`: CLE hold time
- `tCLR_min`: CLE to RE# delay
- `tCLS_min`: CLE setup time
- `tCOH_min`: CE# high to output hold
- `tCS_min`: CE# setup time
- `tDH_min`: Data hold time
- `tDS_min`: Data setup time
- `tFEAT_max`: Busy time for Set Features and Get Features
- `tIR_min`: Output hi-Z to RE# low
- `tITC_max`: Interface and Timing Mode Change time
- `tRC_min`: RE# cycle time
- `tREA_max`: RE# access time
- `tREH_min`: RE# high hold time
- `tRHOH_min`: RE# high to output hold
- `tRHW_min`: RE# high to WE# low
- `tRHZ_max`: RE# high to output hi-Z
- `tRLOH_min`: RE# low to output hold
- `tRP_min`: RE# pulse width
- `tRR_min`: Ready to RE# low (data only)
- `tRST_max`: Device reset time, measured from the falling edge of R/B# to the
  rising edge of R/B#.
- `tWB_max`: WE# high to SR\[6\] low
- `tWC_min`: WE# cycle time
- `tWH_min`: WE# high hold time
- `tWHR_min`: WE# high to RE# low
- `tWP_min`: WE# pulse width
- `tWW_min`: WP# transition to WE# low

**Description**

This struct defines the timing requirements of a SDR NAND chip.
These information can be found in every NAND datasheets and the timings
meaning are described in the ONFI specifications:
https://media-www.micron.com/-/media/client/onfi/specs/onfi_3_1_spec.pdf
(chapter 4.15 Timing Parameters)

All these timings are expressed in picoseconds.

#### <a id="c-struct-nand_nvddr_timings"></a>`struct nand_nvddr_timings`

NV-DDR NAND chip timings

**Definition**

```c
struct nand_nvddr_timings {
    u64 tBERS_max;
    u32 tCCS_min;
    u64 tPROG_max;
    u64 tR_max;
    u32 tAC_min;
    u32 tAC_max;
    u32 tADL_min;
    u32 tCAD_min;
    u32 tCAH_min;
    u32 tCALH_min;
    u32 tCALS_min;
    u32 tCAS_min;
    u32 tCEH_min;
    u32 tCH_min;
    u32 tCK_min;
    u32 tCS_min;
    u32 tDH_min;
    u32 tDQSCK_min;
    u32 tDQSCK_max;
    u32 tDQSD_min;
    u32 tDQSD_max;
    u32 tDQSHZ_max;
    u32 tDQSQ_max;
    u32 tDS_min;
    u32 tDSC_min;
    u32 tFEAT_max;
    u32 tITC_max;
    u32 tQHS_max;
    u32 tRHW_min;
    u32 tRR_min;
    u32 tRST_max;
    u32 tWB_max;
    u32 tWHR_min;
    u32 tWRCK_min;
    u32 tWW_min;
};
```

**Members**

- `tBERS_max`: Block erase time
- `tCCS_min`: Change column setup time
- `tPROG_max`: Page program time
- `tR_max`: Page read time
- `tAC_min`: Access window of DQ\[7:0\] from CLK
- `tAC_max`: Access window of DQ\[7:0\] from CLK
- `tADL_min`: ALE to data loading time
- `tCAD_min`: Command, Address, Data delay
- `tCAH_min`: Command/Address DQ hold time
- `tCALH_min`: W/R_n, CLE and ALE hold time
- `tCALS_min`: W/R_n, CLE and ALE setup time
- `tCAS_min`: Command/address DQ setup time
- `tCEH_min`: CE# high hold time
- `tCH_min`: CE# hold time
- `tCK_min`: Average clock cycle time
- `tCS_min`: CE# setup time
- `tDH_min`: Data hold time
- `tDQSCK_min`: Start of the access window of DQS from CLK
- `tDQSCK_max`: End of the access window of DQS from CLK
- `tDQSD_min`: Min W/R_n low to DQS/DQ driven by device
- `tDQSD_max`: Max W/R_n low to DQS/DQ driven by device
- `tDQSHZ_max`: W/R_n high to DQS/DQ tri-state by device
- `tDQSQ_max`: DQS-DQ skew, DQS to last DQ valid, per access
- `tDS_min`: Data setup time
- `tDSC_min`: DQS cycle time
- `tFEAT_max`: Busy time for Set Features and Get Features
- `tITC_max`: Interface and Timing Mode Change time
- `tQHS_max`: Data hold skew factor
- `tRHW_min`: Data output cycle to command, address, or data input cycle
- `tRR_min`: Ready to RE# low (data only)
- `tRST_max`: Device reset time, measured from the falling edge of R/B# to the
  rising edge of R/B#.
- `tWB_max`: WE# high to SR\[6\] low
- `tWHR_min`: WE# high to RE# low
- `tWRCK_min`: W/R_n low to data output cycle
- `tWW_min`: WP# transition to WE# low

**Description**

This struct defines the timing requirements of a NV-DDR NAND data interface.
These information can be found in every NAND datasheets and the timings
meaning are described in the ONFI specifications:
https://media-www.micron.com/-/media/client/onfi/specs/onfi_4_1_gold.pdf
(chapter 4.18.2 NV-DDR)

All these timings are expressed in picoseconds.

#### <a id="c-enum-nand_interface_type"></a>`enum nand_interface_type`

NAND interface type

**Constants**

- `NAND_SDR_IFACE`: Single Data Rate interface
- `NAND_NVDDR_IFACE`: Double Data Rate interface

#### <a id="c-struct-nand_interface_config"></a>`struct nand_interface_config`

NAND interface timing

**Definition**

```c
struct nand_interface_config {
    enum nand_interface_type type;
    struct nand_timings {
        unsigned int mode;
        union {
            struct nand_sdr_timings sdr;
            struct nand_nvddr_timings nvddr;
        };
    } timings;
};
```

**Members**

- `type`: type of the timing
- `timings`: The timing information
- `timings.mode`: Timing mode as defined in the specification
- `{unnamed_union}`: anonymous
- `timings.sdr`: Use it when **type** is `NAND_SDR_IFACE`.
- `timings.nvddr`: Use it when **type** is `NAND_NVDDR_IFACE`.

#### <a id="c-nand_interface_is_sdr"></a>`nand_interface_is_sdr()`

```c
bool nand_interface_is_sdr(const struct nand_interface_config *conf)
```

get the interface type

**Parameters**

- `const struct nand_interface_config *conf`: The data interface

#### <a id="c-nand_interface_is_nvddr"></a>`nand_interface_is_nvddr()`

```c
bool nand_interface_is_nvddr(const struct nand_interface_config *conf)
```

get the interface type

**Parameters**

- `const struct nand_interface_config *conf`: The data interface

#### <a id="c-nand_get_sdr_timings"></a>`nand_get_sdr_timings()`

```c
const struct nand_sdr_timings * nand_get_sdr_timings(const struct nand_interface_config *conf)
```

get SDR timing from data interface

**Parameters**

- `const struct nand_interface_config *conf`: The data interface

#### <a id="c-nand_get_nvddr_timings"></a>`nand_get_nvddr_timings()`

```c
const struct nand_nvddr_timings * nand_get_nvddr_timings(const struct nand_interface_config *conf)
```

get NV-DDR timing from data interface

**Parameters**

- `const struct nand_interface_config *conf`: The data interface

#### <a id="c-struct-nand_op_cmd_instr"></a>`struct nand_op_cmd_instr`

Definition of a command instruction

**Definition**

```c
struct nand_op_cmd_instr {
    u8 opcode;
};
```

**Members**

- `opcode`: the command to issue in one cycle

#### <a id="c-struct-nand_op_addr_instr"></a>`struct nand_op_addr_instr`

Definition of an address instruction

**Definition**

```c
struct nand_op_addr_instr {
    unsigned int naddrs;
    const u8 *addrs;
};
```

**Members**

- `naddrs`: length of the **addrs** array
- `addrs`: array containing the address cycles to issue

#### <a id="c-struct-nand_op_data_instr"></a>`struct nand_op_data_instr`

Definition of a data instruction

**Definition**

```c
struct nand_op_data_instr {
    unsigned int len;
    union {
        void *in;
        const void *out;
    } buf;
    bool force_8bit;
};
```

**Members**

- `len`: number of data bytes to move
- `buf`: buffer to fill
- `buf.in`: buffer to fill when reading from the NAND chip
- `buf.out`: buffer to read from when writing to the NAND chip
- `force_8bit`: force 8-bit access

**Description**

Please note that "in" and "out" are inverted from the ONFI specification
and are from the controller perspective, so a "in" is a read from the NAND
chip while a "out" is a write to the NAND chip.

#### <a id="c-struct-nand_op_waitrdy_instr"></a>`struct nand_op_waitrdy_instr`

Definition of a wait ready instruction

**Definition**

```c
struct nand_op_waitrdy_instr {
    unsigned int timeout_ms;
};
```

**Members**

- `timeout_ms`: maximum delay while waiting for the ready/busy pin in ms

#### <a id="c-enum-nand_op_instr_type"></a>`enum nand_op_instr_type`

Definition of all instruction types

**Constants**

- `NAND_OP_CMD_INSTR`: command instruction
- `NAND_OP_ADDR_INSTR`: address instruction
- `NAND_OP_DATA_IN_INSTR`: data in instruction
- `NAND_OP_DATA_OUT_INSTR`: data out instruction
- `NAND_OP_WAITRDY_INSTR`: wait ready instruction

#### <a id="c-struct-nand_op_instr"></a>`struct nand_op_instr`

Instruction object

**Definition**

```c
struct nand_op_instr {
    enum nand_op_instr_type type;
    union {
        struct nand_op_cmd_instr cmd;
        struct nand_op_addr_instr addr;
        struct nand_op_data_instr data;
        struct nand_op_waitrdy_instr waitrdy;
    } ctx;
    unsigned int delay_ns;
};
```

**Members**

- `type`: the instruction type
- `ctx`: extra data associated to the instruction. You'll have to use the
  appropriate element depending on **type**
- `ctx.cmd`: use it if **type** is `NAND_OP_CMD_INSTR`
- `ctx.addr`: use it if **type** is `NAND_OP_ADDR_INSTR`
- `ctx.data`: use it if **type** is `NAND_OP_DATA_IN_INSTR`
  or `NAND_OP_DATA_OUT_INSTR`
- `ctx.waitrdy`: use it if **type** is `NAND_OP_WAITRDY_INSTR`
- `delay_ns`: delay the controller should apply after the instruction has been
  issued on the bus. Most modern controllers have internal timings
  control logic, and in this case, the controller driver can ignore
  this field.

#### <a id="c-struct-nand_subop"></a>`struct nand_subop`

a sub operation

**Definition**

```c
struct nand_subop {
    unsigned int cs;
    const struct nand_op_instr *instrs;
    unsigned int ninstrs;
    unsigned int first_instr_start_off;
    unsigned int last_instr_end_off;
};
```

**Members**

- `cs`: the CS line to select for this NAND sub-operation
- `instrs`: array of instructions
- `ninstrs`: length of the **instrs** array
- `first_instr_start_off`: offset to start from for the first instruction
  of the sub-operation
- `last_instr_end_off`: offset to end at (excluded) for the last instruction
  of the sub-operation

**Description**

Both **first_instr_start_off** and **last_instr_end_off** only apply to data or
address instructions.

When an operation cannot be handled as is by the NAND controller, it will
be split by the parser into sub-operations which will be passed to the
controller driver.

#### <a id="c-struct-nand_op_parser_addr_constraints"></a>`struct nand_op_parser_addr_constraints`

Constraints for address instructions

**Definition**

```c
struct nand_op_parser_addr_constraints {
    unsigned int maxcycles;
};
```

**Members**

- `maxcycles`: maximum number of address cycles the controller can issue in a
  single step

#### <a id="c-struct-nand_op_parser_data_constraints"></a>`struct nand_op_parser_data_constraints`

Constraints for data instructions

**Definition**

```c
struct nand_op_parser_data_constraints {
    unsigned int maxlen;
};
```

**Members**

- `maxlen`: maximum data length that the controller can handle in a single step

#### <a id="c-struct-nand_op_parser_pattern_elem"></a>`struct nand_op_parser_pattern_elem`

One element of a pattern

**Definition**

```c
struct nand_op_parser_pattern_elem {
    enum nand_op_instr_type type;
    bool optional;
    union {
        struct nand_op_parser_addr_constraints addr;
        struct nand_op_parser_data_constraints data;
    } ctx;
};
```

**Members**

- `type`: the instructuction type
- `optional`: whether this element of the pattern is optional or mandatory
- `ctx`: address or data constraint
- `ctx.addr`: address constraint (number of cycles)
- `ctx.data`: data constraint (data length)

#### <a id="c-struct-nand_op_parser_pattern"></a>`struct nand_op_parser_pattern`

NAND sub-operation pattern descriptor

**Definition**

```c
struct nand_op_parser_pattern {
    const struct nand_op_parser_pattern_elem *elems;
    unsigned int nelems;
    int (*exec)(struct nand_chip *chip, const struct nand_subop *subop);
};
```

**Members**

- `elems`: array of pattern elements
- `nelems`: number of pattern elements in **elems** array
- `exec`: the function that will issue a sub-operation

**Description**

A pattern is a list of elements, each element reprensenting one instruction
with its constraints. The pattern itself is used by the core to match NAND
chip operation with NAND controller operations.
Once a match between a NAND controller operation pattern and a NAND chip
operation (or a sub-set of a NAND operation) is found, the pattern ->`exec()`
hook is called so that the controller driver can issue the operation on the
bus.

Controller drivers should declare as many patterns as they support and pass
this list of patterns (created with the help of the following macro) to
the [`nand_op_parser_exec_op()`](#c-nand_op_parser_exec_op) helper.

#### <a id="c-struct-nand_op_parser"></a>`struct nand_op_parser`

NAND controller operation parser descriptor

**Definition**

```c
struct nand_op_parser {
    const struct nand_op_parser_pattern *patterns;
    unsigned int npatterns;
};
```

**Members**

- `patterns`: array of supported patterns
- `npatterns`: length of the **patterns** array

**Description**

The parser descriptor is just an array of supported patterns which will be
iterated by [`nand_op_parser_exec_op()`](#c-nand_op_parser_exec_op) everytime it tries to execute an
NAND operation (or tries to determine if a specific operation is supported).

It is worth mentioning that patterns will be tested in their declaration
order, and the first match will be taken, so it's important to order patterns
appropriately so that simple/inefficient patterns are placed at the end of
the list. Usually, this is where you put single instruction patterns.

#### <a id="c-struct-nand_operation"></a>`struct nand_operation`

NAND operation descriptor

**Definition**

```c
struct nand_operation {
    unsigned int cs;
    bool deassert_wp;
    const struct nand_op_instr *instrs;
    unsigned int ninstrs;
};
```

**Members**

- `cs`: the CS line to select for this NAND operation
- `deassert_wp`: set to true when the operation requires the WP pin to be
  de-asserted (ERASE, PROG, ...)
- `instrs`: array of instructions to execute
- `ninstrs`: length of the **instrs** array

**Description**

The actual operation structure that will be passed to chip->`exec_op()`.

#### <a id="c-struct-nand_controller_ops"></a>`struct nand_controller_ops`

Controller operations

**Definition**

```c
struct nand_controller_ops {
    int (*attach_chip)(struct nand_chip *chip);
    void (*detach_chip)(struct nand_chip *chip);
    int (*exec_op)(struct nand_chip *chip, const struct nand_operation *op, bool check_only);
    int (*setup_interface)(struct nand_chip *chip, int chipnr, const struct nand_interface_config *conf);
};
```

**Members**

- `attach_chip`: this method is called after the NAND detection phase after
  flash ID and MTD fields such as erase size, page size and OOB
  size have been set up. ECC requirements are available if
  provided by the NAND chip or device tree. Typically used to
  choose the appropriate ECC configuration and allocate
  associated resources.
  This hook is optional.
- `detach_chip`: free all resources allocated/claimed in
  nand_controller_ops->`attach_chip()`.
  This hook is optional.
- `exec_op`: controller specific method to execute NAND operations.
  This method replaces chip->legacy.`cmdfunc()`,
  chip->legacy.{read,write}_{buf,byte,word}(),
  chip->legacy.`dev_ready()` and chip->legacy.`waitfunc()`.
- `setup_interface`: setup the data interface and timing. If chipnr is set to
  `NAND_DATA_IFACE_CHECK_ONLY` this means the configuration
  should not be applied but only checked.
  This hook is optional.

#### <a id="c-struct-nand_controller"></a>`struct nand_controller`

Structure used to describe a NAND controller

**Definition**

```c
struct nand_controller {
    struct mutex lock;
    const struct nand_controller_ops *ops;
    struct {
        unsigned int data_only_read: 1;
        unsigned int cont_read: 1;
    } supported_op;
    bool controller_wp;
};
```

**Members**

- `lock`: lock used to serialize accesses to the NAND controller
- `ops`: NAND controller operations.
- `supported_op`: NAND controller known-to-be-supported operations,
  only writable by the core after initial checking.
- `supported_op.data_only_read`: The controller supports reading more data from
  the bus without restarting an entire read operation nor
  changing the column.
- `supported_op.cont_read`: The controller supports sequential cache reads.
- `controller_wp`: the controller is in charge of handling the WP pin.

#### <a id="c-struct-nand_legacy"></a>`struct nand_legacy`

NAND chip legacy fields/hooks

**Definition**

```c
struct nand_legacy {
    void __iomem *IO_ADDR_R;
    void __iomem *IO_ADDR_W;
    void (*select_chip)(struct nand_chip *chip, int cs);
    u8 (*read_byte)(struct nand_chip *chip);
    void (*write_byte)(struct nand_chip *chip, u8 byte);
    void (*write_buf)(struct nand_chip *chip, const u8 *buf, int len);
    void (*read_buf)(struct nand_chip *chip, u8 *buf, int len);
    void (*cmd_ctrl)(struct nand_chip *chip, int dat, unsigned int ctrl);
    void (*cmdfunc)(struct nand_chip *chip, unsigned command, int column, int page_addr);
    int (*dev_ready)(struct nand_chip *chip);
    int (*waitfunc)(struct nand_chip *chip);
    int (*block_bad)(struct nand_chip *chip, loff_t ofs);
    int (*block_markbad)(struct nand_chip *chip, loff_t ofs);
    int (*set_features)(struct nand_chip *chip, int feature_addr, u8 *subfeature_para);
    int (*get_features)(struct nand_chip *chip, int feature_addr, u8 *subfeature_para);
    int chip_delay;
    struct nand_controller dummy_controller;
};
```

**Members**

- `IO_ADDR_R`: address to read the 8 I/O lines of the flash device
- `IO_ADDR_W`: address to write the 8 I/O lines of the flash device
- `select_chip`: select/deselect a specific target/die
- `read_byte`: read one byte from the chip
- `write_byte`: write a single byte to the chip on the low 8 I/O lines
- `write_buf`: write data from the buffer to the chip
- `read_buf`: read data from the chip into the buffer
- `cmd_ctrl`: hardware specific function for controlling ALE/CLE/nCE. Also used
  to write command and address
- `cmdfunc`: hardware specific function for writing commands to the chip.
- `dev_ready`: hardware specific function for accessing device ready/busy line.
  If set to NULL no access to ready/busy is available and the
  ready/busy information is read from the chip status register.
- `waitfunc`: hardware specific function for wait on ready.
- `block_bad`: check if a block is bad, using OOB markers
- `block_markbad`: mark a block bad
- `set_features`: set the NAND chip features
- `get_features`: get the NAND chip features
- `chip_delay`: chip dependent delay for transferring data from array to read
  regs (tR).
- `dummy_controller`: dummy controller implementation for drivers that can
  only control a single chip

**Description**

If you look at this structure you're already wrong. These fields/hooks are
all deprecated.

#### <a id="c-struct-nand_chip_ops"></a>`struct nand_chip_ops`

NAND chip operations

**Definition**

```c
struct nand_chip_ops {
    int (*suspend)(struct nand_chip *chip);
    void (*resume)(struct nand_chip *chip);
    int (*lock_area)(struct nand_chip *chip, loff_t ofs, uint64_t len);
    int (*unlock_area)(struct nand_chip *chip, loff_t ofs, uint64_t len);
    int (*setup_read_retry)(struct nand_chip *chip, int retry_mode);
    int (*choose_interface_config)(struct nand_chip *chip, struct nand_interface_config *iface);
};
```

**Members**

- `suspend`: Suspend operation
- `resume`: Resume operation
- `lock_area`: Lock operation
- `unlock_area`: Unlock operation
- `setup_read_retry`: Set the read-retry mode (mostly needed for MLC NANDs)
- `choose_interface_config`: Choose the best interface configuration

#### <a id="c-struct-nand_manufacturer"></a>`struct nand_manufacturer`

NAND manufacturer structure

**Definition**

```c
struct nand_manufacturer {
    const struct nand_manufacturer_desc *desc;
    void *priv;
};
```

**Members**

- `desc`: The manufacturer description
- `priv`: Private information for the manufacturer driver

#### <a id="c-struct-nand_secure_region"></a>`struct nand_secure_region`

NAND secure region structure

**Definition**

```c
struct nand_secure_region {
    u64 offset;
    u64 size;
};
```

**Members**

- `offset`: Offset of the start of the secure region
- `size`: Size of the secure region

#### <a id="c-struct-nand_chip"></a>`struct nand_chip`

NAND Private Flash Chip Data

**Definition**

```c
struct nand_chip {
    struct nand_device base;
    struct nand_id id;
    struct nand_parameters parameters;
    struct nand_manufacturer manufacturer;
    struct nand_chip_ops ops;
    struct nand_legacy legacy;
    unsigned int options;
    const struct nand_interface_config *current_interface_config;
    struct nand_interface_config *best_interface_config;
    unsigned int bbt_erase_shift;
    unsigned int bbt_options;
    unsigned int badblockpos;
    unsigned int badblockbits;
    struct nand_bbt_descr *bbt_td;
    struct nand_bbt_descr *bbt_md;
    struct nand_bbt_descr *badblock_pattern;
    u8 *bbt;
    unsigned int page_shift;
    unsigned int phys_erase_shift;
    unsigned int chip_shift;
    unsigned int pagemask;
    unsigned int subpagesize;
    u8 *data_buf;
    u8 *oob_poi;
    struct {
        unsigned int bitflips;
        int page;
    } pagecache;
    unsigned long buf_align;
    struct mutex lock;
    unsigned int suspended : 1;
    wait_queue_head_t resume_wq;
    int cur_cs;
    int read_retries;
    struct nand_secure_region *secure_regions;
    u8 nr_secure_regions;
    struct {
        bool ongoing;
        unsigned int first_page;
        unsigned int pause_page;
        unsigned int last_page;
    } cont_read;
    struct nand_controller *controller;
    struct nand_ecc_ctrl ecc;
    void *priv;
};
```

**Members**

- `base`: Inherit from the generic NAND device
- `id`: Holds NAND ID
- `parameters`: Holds generic parameters under an easily readable form
- `manufacturer`: Manufacturer information
- `ops`: NAND chip operations
- `legacy`: All legacy fields/hooks. If you develop a new driver, don't even try
  to use any of these fields/hooks, and if you're modifying an
  existing driver that is using those fields/hooks, you should
  consider reworking the driver and avoid using them.
- `options`: Various chip options. They can partly be set to inform nand_scan
  about special functionality. See the defines for further
  explanation.
- `current_interface_config`: The currently used NAND interface configuration
- `best_interface_config`: The best NAND interface configuration which fits both
  the NAND chip and NAND controller constraints. If
  unset, the default reset interface configuration must
  be used.
- `bbt_erase_shift`: Number of address bits in a bbt entry
- `bbt_options`: Bad block table specific options. All options used here must
  come from bbm.h. By default, these options will be copied to
  the appropriate nand_bbt_descr's.
- `badblockpos`: Bad block marker position in the oob area
- `badblockbits`: Minimum number of set bits in a good block's bad block marker
  position; i.e., BBM = 11110111b is good when badblockbits = 7
- `bbt_td`: Bad block table descriptor for flash lookup
- `bbt_md`: Bad block table mirror descriptor
- `badblock_pattern`: Bad block scan pattern used for initial bad block scan
- `bbt`: Bad block table pointer
- `page_shift`: Number of address bits in a page (column address bits)
- `phys_erase_shift`: Number of address bits in a physical eraseblock
- `chip_shift`: Number of address bits in one chip
- `pagemask`: Page number mask = number of (pages / chip) - 1
- `subpagesize`: Holds the subpagesize
- `data_buf`: Buffer for data, size is (page size + oobsize)
- `oob_poi`: pointer on the OOB area covered by data_buf
- `pagecache`: Structure containing page cache related fields
- `pagecache.bitflips`: Number of bitflips of the cached page
- `pagecache.page`: Page number currently in the cache. -1 means no page is
  currently cached
- `buf_align`: Minimum buffer alignment required by a platform
- `lock`: Lock protecting the suspended field. Also used to serialize accesses
  to the NAND device
- `suspended`: Set to 1 when the device is suspended, 0 when it's not
- `resume_wq`: wait queue to sleep if rawnand is in suspended state.
- `cur_cs`: Currently selected target. -1 means no target selected, otherwise we
  should always have cur_cs >= 0 && cur_cs \< `nanddev_ntargets()`.
  NAND Controller drivers should not modify this value, but they're
  allowed to read it.
- `read_retries`: The number of read retry modes supported
- `secure_regions`: Structure containing the secure regions info
- `nr_secure_regions`: Number of secure regions
- `cont_read`: Sequential page read internals
- `cont_read.ongoing`: Whether a continuous read is ongoing or not
- `cont_read.first_page`: Start of the continuous read operation
- `cont_read.pause_page`: End of the current sequential cache read operation
- `cont_read.last_page`: End of the continuous read operation
- `controller`: The hardware controller structure which is shared among multiple
  independent devices
- `ecc`: The ECC controller structure
- `priv`: Chip private data

#### <a id="c-nand_get_interface_config"></a>`nand_get_interface_config()`

```c
const struct nand_interface_config * nand_get_interface_config(struct nand_chip *chip)
```

Retrieve the current interface configuration of a NAND chip

**Parameters**

- `struct nand_chip *chip`: The NAND chip

#### <a id="c-struct-nand_flash_dev"></a>`struct nand_flash_dev`

NAND Flash Device ID Structure

**Definition**

```c
struct nand_flash_dev {
    char *name;
    union {
        struct {
            uint8_t mfr_id;
            uint8_t dev_id;
        };
        uint8_t id[NAND_MAX_ID_LEN];
    };
    unsigned int pagesize;
    unsigned int chipsize;
    unsigned int erasesize;
    unsigned int options;
    uint16_t id_len;
    uint16_t oobsize;
    struct {
        uint16_t strength_ds;
        uint16_t step_ds;
    } ecc;
};
```

**Members**

- `name`: a human-readable name of the NAND chip
- `{unnamed_union}`: anonymous
- `{unnamed_struct}`: anonymous
- `mfr_id`: manufacturer ID part of the full chip ID array (refers the same
  memory address as `id[0]`)
- `dev_id`: device ID part of the full chip ID array (refers the same memory
  address as `id[1]`)
- `id`: full device ID array
- `pagesize`: size of the NAND page in bytes; if 0, then the real page size (as
  well as the eraseblock size) is determined from the extended NAND
  chip ID array)
- `chipsize`: total chip size in MiB
- `erasesize`: eraseblock size in bytes (determined from the extended ID if 0)
- `options`: stores various chip bit options
- `id_len`: The valid length of the **id**.
- `oobsize`: OOB size
- `ecc`: ECC correctability and step information from the datasheet.
- `ecc.strength_ds`: The ECC correctability from the datasheet, same as the
  **ecc_strength_ds** in nand_chip{}.
- `ecc.step_ds`: The ECC step required by the **ecc.strength_ds**, same as the
  **ecc_step_ds** in nand_chip{}, also from the datasheet.
  For example, the "4bit ECC for each 512Byte" can be set with
  NAND_ECC_INFO(4, 512).

#### <a id="c-nand_opcode_8bits"></a>`nand_opcode_8bits()`

```c
int nand_opcode_8bits(unsigned int command)
```

Check if the opcode's address should be sent only on the lower 8 bits

**Parameters**

- `unsigned int command`: opcode to check

#### <a id="c-nand_get_data_buf"></a>`nand_get_data_buf()`

```c
void * nand_get_data_buf(struct nand_chip *chip)
```

Get the internal page buffer

**Parameters**

- `struct nand_chip *chip`: NAND chip object

**Description**

Returns the pre-allocated page buffer after invalidating the cache. This
function should be used by drivers that do not want to allocate their own
bounce buffer and still need such a buffer for specific operations (most
commonly when reading OOB data only).

Be careful to never call this function in the write/write_oob path, because
the core may have placed the data to be written out in this buffer.

**Return**

pointer to the page cache buffer


<a id="rst-public-functions-provided"></a>

## Public Functions Provided

This chapter contains the autogenerated documentation of the NAND kernel API functions which are exported. Each function has a short description which is marked with an \[XXX\] identifier. See the chapter "Documentation hints" for an explanation.


#### <a id="c-nand_extract_bits"></a>`nand_extract_bits()`

```c
void nand_extract_bits(u8 *dst, unsigned int dst_off, const u8 *src, unsigned int src_off, unsigned int nbits)
```

Copy unaligned bits from one buffer to another one

**Parameters**

- `u8 *dst`: destination buffer
- `unsigned int dst_off`: bit offset at which the writing starts
- `const u8 *src`: source buffer
- `unsigned int src_off`: bit offset at which the reading starts
- `unsigned int nbits`: number of bits to copy from **src** to **dst**

**Description**

Copy bits from one memory region to another (overlap authorized).

#### <a id="c-nand_select_target"></a>`nand_select_target()`

```c
void nand_select_target(struct nand_chip *chip, unsigned int cs)
```

Select a NAND target (A.K.A. die)

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `unsigned int cs`: the CS line to select. Note that this CS id is always from the chip
  PoV, not the controller one

**Description**

Select a NAND target so that further operations executed on **chip** go to the
selected NAND target.

#### <a id="c-nand_deselect_target"></a>`nand_deselect_target()`

```c
void nand_deselect_target(struct nand_chip *chip)
```

Deselect the currently selected target

**Parameters**

- `struct nand_chip *chip`: NAND chip object

**Description**

Deselect the currently selected NAND target. The result of operations
executed on **chip** after the target has been deselected is undefined.

#### <a id="c-nand_soft_waitrdy"></a>`nand_soft_waitrdy()`

```c
int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
```

Poll STATUS reg until RDY bit is set to 1

**Parameters**

- `struct nand_chip *chip`: NAND chip structure
- `unsigned long timeout_ms`: Timeout in ms

**Description**

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.

#### <a id="c-nand_gpio_waitrdy"></a>`nand_gpio_waitrdy()`

```c
int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod, unsigned long timeout_ms)
```

Poll R/B GPIO pin until ready

**Parameters**

- `struct nand_chip *chip`: NAND chip structure
- `struct gpio_desc *gpiod`: GPIO descriptor of R/B pin
- `unsigned long timeout_ms`: Timeout in ms

**Description**

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.

#### <a id="c-nand_read_page_op"></a>`nand_read_page_op()`

```c
int nand_read_page_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_page, void *buf, unsigned int len)
```

Do a READ PAGE operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int page`: page to read
- `unsigned int offset_in_page`: offset within the page
- `void *buf`: buffer used to store the data
- `unsigned int len`: length of the buffer

**Description**

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.

#### <a id="c-nand_change_read_column_op"></a>`nand_change_read_column_op()`

```c
int nand_change_read_column_op(struct nand_chip *chip, unsigned int offset_in_page, void *buf, unsigned int len, bool force_8bit)
```

Do a CHANGE READ COLUMN operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int offset_in_page`: offset within the page
- `void *buf`: buffer used to store the data
- `unsigned int len`: length of the buffer
- `bool force_8bit`: force 8-bit bus access

**Description**

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.

#### <a id="c-nand_read_oob_op"></a>`nand_read_oob_op()`

```c
int nand_read_oob_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_oob, void *buf, unsigned int len)
```

Do a READ OOB operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int page`: page to read
- `unsigned int offset_in_oob`: offset within the OOB area
- `void *buf`: buffer used to store the data
- `unsigned int len`: length of the buffer

**Description**

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.

#### <a id="c-nand_prog_page_begin_op"></a>`nand_prog_page_begin_op()`

```c
int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_page, const void *buf, unsigned int len)
```

starts a PROG PAGE operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int page`: page to write
- `unsigned int offset_in_page`: offset within the page
- `const void *buf`: buffer containing the data to write to the page
- `unsigned int len`: length of the buffer

**Description**

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.

#### <a id="c-nand_prog_page_end_op"></a>`nand_prog_page_end_op()`

```c
int nand_prog_page_end_op(struct nand_chip *chip)
```

ends a PROG PAGE operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip

**Description**

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.

#### <a id="c-nand_prog_page_op"></a>`nand_prog_page_op()`

```c
int nand_prog_page_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_page, const void *buf, unsigned int len)
```

Do a full PROG PAGE operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int page`: page to write
- `unsigned int offset_in_page`: offset within the page
- `const void *buf`: buffer containing the data to write to the page
- `unsigned int len`: length of the buffer

**Description**

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.

#### <a id="c-nand_change_write_column_op"></a>`nand_change_write_column_op()`

```c
int nand_change_write_column_op(struct nand_chip *chip, unsigned int offset_in_page, const void *buf, unsigned int len, bool force_8bit)
```

Do a CHANGE WRITE COLUMN operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int offset_in_page`: offset within the page
- `const void *buf`: buffer containing the data to send to the NAND
- `unsigned int len`: length of the buffer
- `bool force_8bit`: force 8-bit bus access

**Description**

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.

#### <a id="c-nand_readid_op"></a>`nand_readid_op()`

```c
int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf, unsigned int len)
```

Do a READID operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 addr`: address cycle to pass after the READID command
- `void *buf`: buffer used to store the ID
- `unsigned int len`: length of the buffer

**Description**

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.

#### <a id="c-nand_status_op"></a>`nand_status_op()`

```c
int nand_status_op(struct nand_chip *chip, u8 *status)
```

Do a STATUS operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 *status`: out variable to store the NAND status

**Description**

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.

#### <a id="c-nand_exit_status_op"></a>`nand_exit_status_op()`

```c
int nand_exit_status_op(struct nand_chip *chip)
```

Exit a STATUS operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip

**Description**

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.

#### <a id="c-nand_erase_op"></a>`nand_erase_op()`

```c
int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
```

Do an erase operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int eraseblock`: block to erase

**Description**

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.

#### <a id="c-nand_reset_op"></a>`nand_reset_op()`

```c
int nand_reset_op(struct nand_chip *chip)
```

Do a reset operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip

**Description**

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.

#### <a id="c-nand_read_data_op"></a>`nand_read_data_op()`

```c
int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len, bool force_8bit, bool check_only)
```

Read data from the NAND

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `void *buf`: buffer used to store the data
- `unsigned int len`: length of the buffer
- `bool force_8bit`: force 8-bit bus access
- `bool check_only`: do not actually run the command, only checks if the
  controller driver supports it

**Description**

This function does a raw data read on the bus. Usually used after launching
another NAND operation like [`nand_read_page_op()`](#c-nand_read_page_op).
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_write_data_op"></a>`nand_write_data_op()`

```c
int nand_write_data_op(struct nand_chip *chip, const void *buf, unsigned int len, bool force_8bit)
```

Write data from the NAND

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `const void *buf`: buffer containing the data to send on the bus
- `unsigned int len`: length of the buffer
- `bool force_8bit`: force 8-bit bus access

**Description**

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.

#### <a id="c-nand_op_parser_exec_op"></a>`nand_op_parser_exec_op()`

```c
int nand_op_parser_exec_op(struct nand_chip *chip, const struct nand_op_parser *parser, const struct nand_operation *op, bool check_only)
```

exec_op parser

**Parameters**

- `struct nand_chip *chip`: the NAND chip
- `const struct nand_op_parser *parser`: patterns description provided by the controller driver
- `const struct nand_operation *op`: the NAND operation to address
- `bool check_only`: when true, the function only checks if **op** can be handled but
  does not execute the operation

**Description**

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.

#### <a id="c-nand_subop_get_addr_start_off"></a>`nand_subop_get_addr_start_off()`

```c
unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop, unsigned int instr_idx)
```

Get the start offset in an address array

**Parameters**

- `const struct nand_subop *subop`: The entire sub-operation
- `unsigned int instr_idx`: Index of the instruction inside the sub-operation

**Description**

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.

#### <a id="c-nand_subop_get_num_addr_cyc"></a>`nand_subop_get_num_addr_cyc()`

```c
unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop, unsigned int instr_idx)
```

Get the remaining address cycles to assert

**Parameters**

- `const struct nand_subop *subop`: The entire sub-operation
- `unsigned int instr_idx`: Index of the instruction inside the sub-operation

**Description**

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.

#### <a id="c-nand_subop_get_data_start_off"></a>`nand_subop_get_data_start_off()`

```c
unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop, unsigned int instr_idx)
```

Get the start offset in a data array

**Parameters**

- `const struct nand_subop *subop`: The entire sub-operation
- `unsigned int instr_idx`: Index of the instruction inside the sub-operation

**Description**

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.

#### <a id="c-nand_subop_get_data_len"></a>`nand_subop_get_data_len()`

```c
unsigned int nand_subop_get_data_len(const struct nand_subop *subop, unsigned int instr_idx)
```

Get the number of bytes to retrieve

**Parameters**

- `const struct nand_subop *subop`: The entire sub-operation
- `unsigned int instr_idx`: Index of the instruction inside the sub-operation

**Description**

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.

#### <a id="c-nand_reset"></a>`nand_reset()`

```c
int nand_reset(struct nand_chip *chip, int chipnr)
```

Reset and initialize a NAND device

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `int chipnr`: Internal die id

**Description**

Save the timings data structure, then apply SDR timings mode 0 (see
nand_reset_interface for details), do the reset operation, and apply
back the previous timings.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_read_page_raw"></a>`nand_read_page_raw()`

```c
int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

\[INTERN\] read raw page data without ecc

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

Not for syndrome calculating ECC controllers, which use a special oob layout.

#### <a id="c-nand_monolithic_read_page_raw"></a>`nand_monolithic_read_page_raw()`

```c
int nand_monolithic_read_page_raw(struct nand_chip *chip, u8 *buf, int oob_required, int page)
```

Monolithic page read in raw mode

**Parameters**

- `struct nand_chip *chip`: NAND chip info structure
- `u8 *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

This is a raw page read, ie. without any error detection/correction.
Monolithic means we are requesting all the relevant data (main plus
eventually OOB) to be loaded in the NAND cache and sent over the
bus (from the NAND chip to the NAND controller) in a single
operation. This is an alternative to [`nand_read_page_raw()`](#c-nand_read_page_raw), which
first reads the main data, and if the OOB data is requested too,
then reads more data on the bus.

#### <a id="c-nand_read_page_hwecc_oob_first"></a>`nand_read_page_hwecc_oob_first()`

```c
int nand_read_page_hwecc_oob_first(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

Hardware ECC page read with ECC data read from OOB area

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

Hardware ECC for large page chips, which requires the ECC data to be
extracted from the OOB before the actual data is read.

#### <a id="c-nand_read_oob_std"></a>`nand_read_oob_std()`

```c
int nand_read_oob_std(struct nand_chip *chip, int page)
```

\[REPLACEABLE\] the most common OOB data read function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `int page`: page number to read

#### <a id="c-nand_write_oob_std"></a>`nand_write_oob_std()`

```c
int nand_write_oob_std(struct nand_chip *chip, int page)
```

\[REPLACEABLE\] the most common OOB data write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `int page`: page number to write

#### <a id="c-nand_write_page_raw"></a>`nand_write_page_raw()`

```c
int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)
```

\[INTERN\] raw page write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

**Description**

Not for syndrome calculating ECC controllers, which use a special oob layout.

#### <a id="c-nand_monolithic_write_page_raw"></a>`nand_monolithic_write_page_raw()`

```c
int nand_monolithic_write_page_raw(struct nand_chip *chip, const u8 *buf, int oob_required, int page)
```

Monolithic page write in raw mode

**Parameters**

- `struct nand_chip *chip`: NAND chip info structure
- `const u8 *buf`: data buffer to write
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

**Description**

This is a raw page write, ie. without any error detection/correction.
Monolithic means we are requesting all the relevant data (main plus
eventually OOB) to be sent over the bus and effectively programmed
into the NAND chip arrays in a single operation. This is an
alternative to [`nand_write_page_raw()`](#c-nand_write_page_raw), which first sends the main
data, then eventually send the OOB data by latching more data
cycles on the NAND bus, and finally sends the program command to
synchronyze the NAND chip cache.

#### <a id="c-rawnand_dt_parse_gpio_cs"></a>`rawnand_dt_parse_gpio_cs()`

```c
int rawnand_dt_parse_gpio_cs(struct device *dev, struct gpio_desc ***cs_array, unsigned int *ncs_array)
```

Parse the gpio-cs property of a controller

**Parameters**

- `struct device *dev`: Device that will be parsed. Also used for managed allocations.
- `struct gpio_desc ***cs_array`: Array of GPIO desc pointers allocated on success
- `unsigned int *ncs_array`: Number of entries in **cs_array** updated on success.
  **return** 0 on success, an error otherwise.

#### <a id="c-nand_ecc_choose_conf"></a>`nand_ecc_choose_conf()`

```c
int nand_ecc_choose_conf(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)
```

Set the ECC strength and ECC step size

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const struct nand_ecc_caps *caps`: ECC engine caps info structure
- `int oobavail`: OOB size that the ECC engine can use

**Description**

Choose the ECC configuration according to following logic.

1. If both ECC step size and ECC strength are already set (usually by DT)
   then check if it is supported by this controller.
2. If the user provided the nand-ecc-maximize property, then select maximum
   ECC strength.
3. Otherwise, try to match the ECC step size and ECC strength closest
   to the chip's requirement. If available OOB size can't fit the chip
   requirement then fallback to the maximum ECC step size and ECC strength.

On success, the chosen ECC settings are set.

#### <a id="c-nand_scan_with_ids"></a>`nand_scan_with_ids()`

```c
int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips, struct nand_flash_dev *ids)
```

\[NAND Interface\] Scan for the NAND device

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `unsigned int maxchips`: number of chips to scan for.
- `struct nand_flash_dev *ids`: optional flash IDs table

**Description**

This fills out all the uninitialized function pointers with the defaults.
The flash ID is read and the mtd/chip structures are filled with the
appropriate values.

#### <a id="c-nand_cleanup"></a>`nand_cleanup()`

```c
void nand_cleanup(struct nand_chip *chip)
```

\[NAND Interface\] Free resources held by the NAND device

**Parameters**

- `struct nand_chip *chip`: NAND chip object


<a id="rst-internal-functions-provided"></a>

## Internal Functions Provided

This chapter contains the autogenerated documentation of the NAND driver internal functions. Each function has a short description which is marked with an \[XXX\] identifier. See the chapter "Documentation hints" for an explanation. The functions marked with \[DEFAULT\] might be relevant for a board driver developer.


#### <a id="c-nand_release_device"></a>`nand_release_device()`

```c
void nand_release_device(struct nand_chip *chip)
```

\[GENERIC\] release chip

**Parameters**

- `struct nand_chip *chip`: NAND chip object

**Description**

Release chip lock and wake up anyone waiting on the device.

#### <a id="c-nand_bbm_get_next_page"></a>`nand_bbm_get_next_page()`

```c
int nand_bbm_get_next_page(struct nand_chip *chip, int page)
```

Get the next page for bad block markers

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `int page`: First page to start checking for bad block marker usage

**Description**

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.

#### <a id="c-nand_block_bad"></a>`nand_block_bad()`

```c
int nand_block_bad(struct nand_chip *chip, loff_t ofs)
```

\[DEFAULT\] Read bad block marker from the chip

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t ofs`: offset from device start

**Description**

Check, if the block is bad.

#### <a id="c-nand_region_is_secured"></a>`nand_region_is_secured()`

```c
bool nand_region_is_secured(struct nand_chip *chip, loff_t offset, u64 size)
```

Check if the region is secured

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t offset`: Offset of the region to check
- `u64 size`: Size of the region to check

**Description**

Checks if the region is secured by comparing the offset and size with the
list of secure regions obtained from DT. Returns true if the region is
secured else false.

#### <a id="c-nand_get_device"></a>`nand_get_device()`

```c
void nand_get_device(struct nand_chip *chip)
```

\[GENERIC\] Get chip for selected access

**Parameters**

- `struct nand_chip *chip`: NAND chip structure

**Description**

Lock the device and its controller for exclusive access

#### <a id="c-nand_check_wp"></a>`nand_check_wp()`

```c
int nand_check_wp(struct nand_chip *chip)
```

\[GENERIC\] check if the chip is write protected

**Parameters**

- `struct nand_chip *chip`: NAND chip object

**Description**

Check, if the device is write protected. The function expects, that the
device is already selected.

#### <a id="c-nand_fill_oob"></a>`nand_fill_oob()`

```c
uint8_t * nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len, struct mtd_oob_ops *ops)
```

\[INTERN\] Transfer client buffer to oob

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `uint8_t *oob`: oob data buffer
- `size_t len`: oob data write length
- `struct mtd_oob_ops *ops`: oob ops structure

#### <a id="c-nand_do_write_oob"></a>`nand_do_write_oob()`

```c
int nand_do_write_oob(struct nand_chip *chip, loff_t to, struct mtd_oob_ops *ops)
```

\[MTD Interface\] NAND write out-of-band

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t to`: offset to write to
- `struct mtd_oob_ops *ops`: oob operation description structure

**Description**

NAND write out-of-band.

#### <a id="c-nand_default_block_markbad"></a>`nand_default_block_markbad()`

```c
int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
```

\[DEFAULT\] mark a block bad via bad block marker

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t ofs`: offset from device start

**Description**

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.

#### <a id="c-nand_markbad_bbm"></a>`nand_markbad_bbm()`

```c
int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
```

mark a block by updating the BBM

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t ofs`: offset of the block to mark bad

#### <a id="c-nand_block_markbad_lowlevel"></a>`nand_block_markbad_lowlevel()`

```c
int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
```

mark a block bad

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t ofs`: offset from device start

**Description**

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.

#### <a id="c-nand_block_isreserved"></a>`nand_block_isreserved()`

```c
int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
```

\[GENERIC\] Check if a block is marked reserved.

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t ofs`: offset from device start

**Description**

Check if the block is marked as reserved.

#### <a id="c-nand_block_checkbad"></a>`nand_block_checkbad()`

```c
int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
```

\[GENERIC\] Check if a block is marked bad

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t ofs`: offset from device start
- `int allowbbt`: 1, if its allowed to access the bbt area

**Description**

Check, if the block is bad. Either by reading the bad block table or
calling of the scan function.

#### <a id="c-panic_nand_wait"></a>`panic_nand_wait()`

```c
void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
```

\[GENERIC\] wait until the command is done

**Parameters**

- `struct nand_chip *chip`: NAND chip structure
- `unsigned long timeo`: timeout

**Description**

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.

#### <a id="c-nand_reset_interface"></a>`nand_reset_interface()`

```c
int nand_reset_interface(struct nand_chip *chip, int chipnr)
```

Reset data interface and timings

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `int chipnr`: Internal die id

**Description**

Reset the Data interface and timings to ONFI mode 0.

Returns 0 for success or negative error code otherwise.

#### <a id="c-nand_setup_interface"></a>`nand_setup_interface()`

```c
int nand_setup_interface(struct nand_chip *chip, int chipnr)
```

Setup the best data interface and timings

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `int chipnr`: Internal die id

**Description**

Configure what has been reported to be the best data interface and NAND
timings supported by the chip and the driver.

Returns 0 for success or negative error code otherwise.

#### <a id="c-nand_choose_best_sdr_timings"></a>`nand_choose_best_sdr_timings()`

```c
int nand_choose_best_sdr_timings(struct nand_chip *chip, struct nand_interface_config *iface, struct nand_sdr_timings *spec_timings)
```

Pick up the best SDR timings that both the NAND controller and the NAND chip support

**Parameters**

- `struct nand_chip *chip`: the NAND chip
- `struct nand_interface_config *iface`: the interface configuration (can eventually be updated)
- `struct nand_sdr_timings *spec_timings`: specific timings, when not fitting the ONFI specification

**Description**

If specific timings are provided, use them. Otherwise, retrieve supported
timing modes from ONFI information.

#### <a id="c-nand_choose_best_nvddr_timings"></a>`nand_choose_best_nvddr_timings()`

```c
int nand_choose_best_nvddr_timings(struct nand_chip *chip, struct nand_interface_config *iface, struct nand_nvddr_timings *spec_timings)
```

Pick up the best NVDDR timings that both the NAND controller and the NAND chip support

**Parameters**

- `struct nand_chip *chip`: the NAND chip
- `struct nand_interface_config *iface`: the interface configuration (can eventually be updated)
- `struct nand_nvddr_timings *spec_timings`: specific timings, when not fitting the ONFI specification

**Description**

If specific timings are provided, use them. Otherwise, retrieve supported
timing modes from ONFI information.

#### <a id="c-nand_choose_best_timings"></a>`nand_choose_best_timings()`

```c
int nand_choose_best_timings(struct nand_chip *chip, struct nand_interface_config *iface)
```

Pick up the best NVDDR or SDR timings that both NAND controller and the NAND chip support

**Parameters**

- `struct nand_chip *chip`: the NAND chip
- `struct nand_interface_config *iface`: the interface configuration (can eventually be updated)

**Description**

If specific timings are provided, use them. Otherwise, retrieve supported
timing modes from ONFI information.

#### <a id="c-nand_choose_interface_config"></a>`nand_choose_interface_config()`

```c
int nand_choose_interface_config(struct nand_chip *chip)
```

find the best data interface and timings

**Parameters**

- `struct nand_chip *chip`: The NAND chip

**Description**

Find the best data interface and NAND timings supported by the chip
and the driver. Eventually let the NAND manufacturer driver propose his own
set of timings.

After this function nand_chip->interface_config is initialized with the best
timing mode available.

Returns 0 for success or negative error code otherwise.

#### <a id="c-nand_fill_column_cycles"></a>`nand_fill_column_cycles()`

```c
int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs, unsigned int offset_in_page)
```

fill the column cycles of an address

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 *addrs`: Array of address cycles to fill
- `unsigned int offset_in_page`: The offset in the page

**Description**

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.

#### <a id="c-nand_read_param_page_op"></a>`nand_read_param_page_op()`

```c
int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf, unsigned int len)
```

Do a READ PARAMETER PAGE operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 page`: parameter page to read
- `void *buf`: buffer used to store the data
- `unsigned int len`: length of the buffer

**Description**

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.

#### <a id="c-nand_set_features_op"></a>`nand_set_features_op()`

```c
int nand_set_features_op(struct nand_chip *chip, u8 feature, const void *data)
```

Do a SET FEATURES operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 feature`: feature id
- `const void *data`: 4 bytes of data

**Description**

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.

#### <a id="c-nand_get_features_op"></a>`nand_get_features_op()`

```c
int nand_get_features_op(struct nand_chip *chip, u8 feature, void *data)
```

Do a GET FEATURES operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 feature`: feature id
- `void *data`: 4 bytes of data

**Description**

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.

#### <a id="c-struct-nand_op_parser_ctx"></a>`struct nand_op_parser_ctx`

Context used by the parser

**Definition**

```c
struct nand_op_parser_ctx {
    const struct nand_op_instr *instrs;
    unsigned int ninstrs;
    struct nand_subop subop;
};
```

**Members**

- `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

**Description**

This structure is used by the core to split NAND operations into
sub-operations that can be handled by the NAND controller.

#### <a id="c-nand_op_parser_must_split_instr"></a>`nand_op_parser_must_split_instr()`

```c
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)
```

Checks if an instruction must be split

**Parameters**

- `const struct nand_op_parser_pattern_elem *pat`: the parser pattern element that matches **instr**
- `const struct nand_op_instr *instr`: pointer to the instruction to check
- `unsigned int *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.

**Description**

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).

#### <a id="c-nand_op_parser_match_pat"></a>`nand_op_parser_match_pat()`

```c
bool nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat, struct nand_op_parser_ctx *ctx)
```

Checks if a pattern matches the instructions remaining in the parser context

**Parameters**

- `const struct nand_op_parser_pattern *pat`: the pattern to test
- `struct nand_op_parser_ctx *ctx`: the parser context structure to match with the pattern **pat**

**Description**

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.

#### <a id="c-nand_get_features"></a>`nand_get_features()`

```c
int nand_get_features(struct nand_chip *chip, int addr, u8 *subfeature_param)
```

wrapper to perform a GET_FEATURE

**Parameters**

- `struct nand_chip *chip`: NAND chip info structure
- `int addr`: feature address
- `u8 *subfeature_param`: the subfeature parameters, a four bytes array

**Description**

Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
operation cannot be handled.

#### <a id="c-nand_set_features"></a>`nand_set_features()`

```c
int nand_set_features(struct nand_chip *chip, int addr, u8 *subfeature_param)
```

wrapper to perform a SET_FEATURE

**Parameters**

- `struct nand_chip *chip`: NAND chip info structure
- `int addr`: feature address
- `u8 *subfeature_param`: the subfeature parameters, a four bytes array

**Description**

Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
operation cannot be handled.

#### <a id="c-nand_read_page_raw_notsupp"></a>`nand_read_page_raw_notsupp()`

```c
int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf, int oob_required, int page)
```

dummy read raw page function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `u8 *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

Returns -ENOTSUPP unconditionally.

#### <a id="c-nand_read_page_raw_syndrome"></a>`nand_read_page_raw_syndrome()`

```c
int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

\[INTERN\] read raw page data without ecc

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

We need a special oob layout and handling even when OOB isn't used.

#### <a id="c-nand_read_page_swecc"></a>`nand_read_page_swecc()`

```c
int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] software ECC based page read function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

#### <a id="c-nand_read_subpage"></a>`nand_read_subpage()`

```c
int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi, int page)
```

\[REPLACEABLE\] ECC based sub-page read function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint32_t data_offs`: offset of requested data within the page
- `uint32_t readlen`: data length
- `uint8_t *bufpoi`: buffer to store read data
- `int page`: page number to read

#### <a id="c-nand_read_page_hwecc"></a>`nand_read_page_hwecc()`

```c
int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] hardware ECC based page read function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

Not for syndrome calculating ECC controllers which need a special oob layout.

#### <a id="c-nand_read_page_syndrome"></a>`nand_read_page_syndrome()`

```c
int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] hardware ECC syndrome based page read

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

The hw generator calculates the error syndrome automatically. Therefore we
need a special oob layout and handling.

#### <a id="c-nand_transfer_oob"></a>`nand_transfer_oob()`

```c
uint8_t * nand_transfer_oob(struct nand_chip *chip, uint8_t *oob, struct mtd_oob_ops *ops, size_t len)
```

\[INTERN\] Transfer oob to client buffer

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `uint8_t *oob`: oob destination address
- `struct mtd_oob_ops *ops`: oob ops structure
- `size_t len`: size of oob to transfer

#### <a id="c-nand_setup_read_retry"></a>`nand_setup_read_retry()`

```c
int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
```

\[INTERN\] Set the READ RETRY mode

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `int retry_mode`: the retry mode to use

**Description**

Some vendors supply a special command to shift the Vt threshold, to be used
when there are too many bitflips in a page (i.e., ECC error). After setting
a new threshold, the host should retry reading the page.

#### <a id="c-nand_do_read_ops"></a>`nand_do_read_ops()`

```c
int nand_do_read_ops(struct nand_chip *chip, loff_t from, struct mtd_oob_ops *ops)
```

\[INTERN\] Read data with ECC

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t from`: offset to read from
- `struct mtd_oob_ops *ops`: oob ops structure

**Description**

Internal function. Called with chip held.

#### <a id="c-nand_read_oob_syndrome"></a>`nand_read_oob_syndrome()`

```c
int nand_read_oob_syndrome(struct nand_chip *chip, int page)
```

\[REPLACEABLE\] OOB data read function for HW ECC with syndromes

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `int page`: page number to read

#### <a id="c-nand_write_oob_syndrome"></a>`nand_write_oob_syndrome()`

```c
int nand_write_oob_syndrome(struct nand_chip *chip, int page)
```

\[REPLACEABLE\] OOB data write function for HW ECC with syndrome - only for large page flash

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `int page`: page number to write

#### <a id="c-nand_do_read_oob"></a>`nand_do_read_oob()`

```c
int nand_do_read_oob(struct nand_chip *chip, loff_t from, struct mtd_oob_ops *ops)
```

\[INTERN\] NAND read out-of-band

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t from`: offset to read from
- `struct mtd_oob_ops *ops`: oob operations description structure

**Description**

NAND read out-of-band data from the spare area.

#### <a id="c-nand_read_oob"></a>`nand_read_oob()`

```c
int nand_read_oob(struct mtd_info *mtd, loff_t from, struct mtd_oob_ops *ops)
```

\[MTD Interface\] NAND read data and/or out-of-band

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t from`: offset to read from
- `struct mtd_oob_ops *ops`: oob operation description structure

**Description**

NAND read data and/or out-of-band data.

#### <a id="c-nand_write_page_raw_notsupp"></a>`nand_write_page_raw_notsupp()`

```c
int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf, int oob_required, int page)
```

dummy raw page write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const u8 *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

**Description**

Returns -ENOTSUPP unconditionally.

#### <a id="c-nand_write_page_raw_syndrome"></a>`nand_write_page_raw_syndrome()`

```c
int nand_write_page_raw_syndrome(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)
```

\[INTERN\] raw page write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

**Description**

We need a special oob layout and handling even when ECC isn't checked.

#### <a id="c-nand_write_page_swecc"></a>`nand_write_page_swecc()`

```c
int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] software ECC based page write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

#### <a id="c-nand_write_page_hwecc"></a>`nand_write_page_hwecc()`

```c
int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] hardware ECC based page write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

#### <a id="c-nand_write_subpage_hwecc"></a>`nand_write_subpage_hwecc()`

```c
int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset, uint32_t data_len, const uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] hardware ECC based subpage write

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint32_t offset`: column address of subpage within the page
- `uint32_t data_len`: data length
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

#### <a id="c-nand_write_page_syndrome"></a>`nand_write_page_syndrome()`

```c
int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] hardware ECC syndrome based page write

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

**Description**

The hw generator calculates the error syndrome automatically. Therefore we
need a special oob layout and handling.

#### <a id="c-nand_write_page"></a>`nand_write_page()`

```c
int nand_write_page(struct nand_chip *chip, uint32_t offset, int data_len, const uint8_t *buf, int oob_required, int page, int raw)
```

write one page

**Parameters**

- `struct nand_chip *chip`: NAND chip descriptor
- `uint32_t offset`: address offset within the page
- `int data_len`: length of actual data to be written
- `const uint8_t *buf`: the data to write
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write
- `int raw`: use _raw version of write_page

#### <a id="c-nand_do_write_ops"></a>`nand_do_write_ops()`

```c
int nand_do_write_ops(struct nand_chip *chip, loff_t to, struct mtd_oob_ops *ops)
```

\[INTERN\] NAND write with ECC

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t to`: offset to write to
- `struct mtd_oob_ops *ops`: oob operations description structure

**Description**

NAND write with ECC.

#### <a id="c-panic_nand_write"></a>`panic_nand_write()`

```c
int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen, const uint8_t *buf)
```

\[MTD Interface\] NAND write with ECC

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t to`: offset to write to
- `size_t len`: number of bytes to write
- `size_t *retlen`: pointer to variable to store the number of written bytes
- `const uint8_t *buf`: the data to write

**Description**

NAND write with ECC. Used when performing writes in interrupt context, this
may for example be called by mtdoops when writing an oops while in panic.

#### <a id="c-nand_write_oob"></a>`nand_write_oob()`

```c
int nand_write_oob(struct mtd_info *mtd, loff_t to, struct mtd_oob_ops *ops)
```

\[MTD Interface\] NAND write data and/or out-of-band

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t to`: offset to write to
- `struct mtd_oob_ops *ops`: oob operation description structure

#### <a id="c-nand_erase"></a>`nand_erase()`

```c
int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
```

\[MTD Interface\] erase block(s)

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `struct erase_info *instr`: erase instruction

**Description**

Erase one ore more blocks.

#### <a id="c-nand_erase_nand"></a>`nand_erase_nand()`

```c
int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr, int allowbbt)
```

\[INTERN\] erase block(s)

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `struct erase_info *instr`: erase instruction
- `int allowbbt`: allow erasing the bbt area

**Description**

Erase one ore more blocks.

#### <a id="c-nand_sync"></a>`nand_sync()`

```c
void nand_sync(struct mtd_info *mtd)
```

\[MTD Interface\] sync

**Parameters**

- `struct mtd_info *mtd`: MTD device structure

**Description**

Sync is actually a wait for chip ready function.

#### <a id="c-nand_block_isbad"></a>`nand_block_isbad()`

```c
int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
```

\[MTD Interface\] Check if block at offset is bad

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t offs`: offset relative to mtd start

#### <a id="c-nand_block_markbad"></a>`nand_block_markbad()`

```c
int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
```

\[MTD Interface\] Mark block at the given offset as bad

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t ofs`: offset relative to mtd start

#### <a id="c-nand_suspend"></a>`nand_suspend()`

```c
int nand_suspend(struct mtd_info *mtd)
```

\[MTD Interface\] Suspend the NAND flash

**Parameters**

- `struct mtd_info *mtd`: MTD device structure

**Description**

Returns 0 for success or negative error code otherwise.

#### <a id="c-nand_resume"></a>`nand_resume()`

```c
void nand_resume(struct mtd_info *mtd)
```

\[MTD Interface\] Resume the NAND flash

**Parameters**

- `struct mtd_info *mtd`: MTD device structure

#### <a id="c-nand_shutdown"></a>`nand_shutdown()`

```c
void nand_shutdown(struct mtd_info *mtd)
```

\[MTD Interface\] Finish the current NAND operation and prevent further operations

**Parameters**

- `struct mtd_info *mtd`: MTD device structure

#### <a id="c-nand_lock"></a>`nand_lock()`

```c
int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
```

\[MTD Interface\] Lock the NAND flash

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t ofs`: offset byte address
- `uint64_t len`: number of bytes to lock (must be a multiple of block/page size)

#### <a id="c-nand_unlock"></a>`nand_unlock()`

```c
int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
```

\[MTD Interface\] Unlock the NAND flash

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t ofs`: offset byte address
- `uint64_t len`: number of bytes to unlock (must be a multiple of block/page size)

#### <a id="c-nand_scan_ident"></a>`nand_scan_ident()`

```c
int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips, struct nand_flash_dev *table)
```

Scan for the NAND device

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `unsigned int maxchips`: number of chips to scan for
- `struct nand_flash_dev *table`: alternative NAND ID table

**Description**

This is the first phase of the normal `nand_scan()` function. It reads the
flash ID and sets up MTD fields accordingly.

This helper used to be called directly from controller drivers that needed
to tweak some ECC-related parameters before [`nand_scan_tail()`](#c-nand_scan_tail). This separation
prevented dynamic allocations during this phase which was unconvenient and
as been banned for the benefit of the ->`init_ecc()`/`cleanup_ecc()` hooks.

#### <a id="c-nand_check_ecc_caps"></a>`nand_check_ecc_caps()`

```c
int nand_check_ecc_caps(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)
```

check the sanity of preset ECC settings

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const struct nand_ecc_caps *caps`: ECC caps info structure
- `int oobavail`: OOB size that the ECC engine can use

**Description**

When ECC step size and strength are already set, check if they are supported
by the controller and the calculated ECC bytes fit within the chip's OOB.
On success, the calculated ECC bytes is set.

#### <a id="c-nand_match_ecc_req"></a>`nand_match_ecc_req()`

```c
int nand_match_ecc_req(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)
```

meet the chip's requirement with least ECC bytes

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const struct nand_ecc_caps *caps`: ECC engine caps info structure
- `int oobavail`: OOB size that the ECC engine can use

**Description**

If a chip's ECC requirement is provided, try to meet it with the least
number of ECC bytes (i.e. with the largest number of OOB-free bytes).
On success, the chosen ECC settings are set.

#### <a id="c-nand_maximize_ecc"></a>`nand_maximize_ecc()`

```c
int nand_maximize_ecc(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)
```

choose the max ECC strength available

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const struct nand_ecc_caps *caps`: ECC engine caps info structure
- `int oobavail`: OOB size that the ECC engine can use

**Description**

Choose the max ECC strength that is supported on the controller, and can fit
within the chip's OOB.  On success, the chosen ECC settings are set.

#### <a id="c-nand_scan_tail"></a>`nand_scan_tail()`

```c
int nand_scan_tail(struct nand_chip *chip)
```

Scan for the NAND device

**Parameters**

- `struct nand_chip *chip`: NAND chip object

**Description**

This is the second phase of the normal `nand_scan()` function. It fills out
all the uninitialized function pointers with the defaults and scans for a
bad block table if appropriate.



#### <a id="c-check_pattern"></a>`check_pattern()`

```c
int check_pattern(uint8_t *buf, int len, int paglen, struct nand_bbt_descr *td)
```

\[GENERIC\] check if a pattern is in the buffer

**Parameters**

- `uint8_t *buf`: the buffer to search
- `int len`: the length of buffer to search
- `int paglen`: the pagelength
- `struct nand_bbt_descr *td`: search pattern descriptor

**Description**

Check for a pattern at the given place. Used to search bad block tables and
good / bad block identifiers.

#### <a id="c-check_short_pattern"></a>`check_short_pattern()`

```c
int check_short_pattern(uint8_t *buf, struct nand_bbt_descr *td)
```

\[GENERIC\] check if a pattern is in the buffer

**Parameters**

- `uint8_t *buf`: the buffer to search
- `struct nand_bbt_descr *td`: search pattern descriptor

**Description**

Check for a pattern at the given place. Used to search bad block tables and
good / bad block identifiers. Same as check_pattern, but no optional empty
check.

#### <a id="c-add_marker_len"></a>`add_marker_len()`

```c
u32 add_marker_len(struct nand_bbt_descr *td)
```

compute the length of the marker in data area

**Parameters**

- `struct nand_bbt_descr *td`: BBT descriptor used for computation

**Description**

The length will be 0 if the marker is located in OOB area.

#### <a id="c-read_bbt"></a>`read_bbt()`

```c
int read_bbt(struct nand_chip *this, uint8_t *buf, int page, int num, struct nand_bbt_descr *td, int offs)
```

\[GENERIC\] Read the bad block table starting from page

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `int page`: the starting page
- `int num`: the number of bbt descriptors to read
- `struct nand_bbt_descr *td`: the bbt describtion table
- `int offs`: block number offset in the table

**Description**

Read the bad block table starting from page.

#### <a id="c-read_abs_bbt"></a>`read_abs_bbt()`

```c
int read_abs_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, int chip)
```

\[GENERIC\] Read the bad block table starting at a given page

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *td`: descriptor for the bad block table
- `int chip`: read the table for a specific chip, -1 read all chips; applies only if
  NAND_BBT_PERCHIP option is set

**Description**

Read the bad block table for all chips starting at a given page. We assume
that the bbt bits are in consecutive order.

#### <a id="c-scan_read_oob"></a>`scan_read_oob()`

```c
int scan_read_oob(struct nand_chip *this, uint8_t *buf, loff_t offs, size_t len)
```

\[GENERIC\] Scan data+OOB region to buffer

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `loff_t offs`: offset at which to scan
- `size_t len`: length of data region to read

**Description**

Scan read data from data+OOB. May traverse multiple pages, interleaving
page,OOB,page,OOB,... in buf. Completes transfer and returns the "strongest"
ECC condition (error or bitflip). May quit on the first (non-ECC) error.

#### <a id="c-read_abs_bbts"></a>`read_abs_bbts()`

```c
void read_abs_bbts(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, struct nand_bbt_descr *md)
```

\[GENERIC\] Read the bad block table(s) for all chips starting at a given page

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *td`: descriptor for the bad block table
- `struct nand_bbt_descr *md`: descriptor for the bad block table mirror

**Description**

Read the bad block table(s) for all chips starting at a given page. We
assume that the bbt bits are in consecutive order.

#### <a id="c-create_bbt"></a>`create_bbt()`

```c
int create_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *bd, int chip)
```

\[GENERIC\] Create a bad block table by scanning the device

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *bd`: descriptor for the good/bad block search pattern
- `int chip`: create the table for a specific chip, -1 read all chips; applies only
  if NAND_BBT_PERCHIP option is set

**Description**

Create a bad block table by scanning the device for the given good/bad block
identify pattern.

#### <a id="c-search_bbt"></a>`search_bbt()`

```c
int search_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td)
```

\[GENERIC\] scan the device for a specific bad block table

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *td`: descriptor for the bad block table

**Description**

Read the bad block table by searching for a given ident pattern. Search is
preformed either from the beginning up or from the end of the device
downwards. The search starts always at the start of a block. If the option
NAND_BBT_PERCHIP is given, each chip is searched for a bbt, which contains
the bad block information of this chip. This is necessary to provide support
for certain DOC devices.

The bbt ident pattern resides in the oob area of the first page in a block.

#### <a id="c-search_read_bbts"></a>`search_read_bbts()`

```c
void search_read_bbts(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, struct nand_bbt_descr *md)
```

\[GENERIC\] scan the device for bad block table(s)

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *td`: descriptor for the bad block table
- `struct nand_bbt_descr *md`: descriptor for the bad block table mirror

**Description**

Search and read the bad block table(s).

#### <a id="c-get_bbt_block"></a>`get_bbt_block()`

```c
int get_bbt_block(struct nand_chip *this, struct nand_bbt_descr *td, struct nand_bbt_descr *md, int chip)
```

Get the first valid eraseblock suitable to store a BBT

**Parameters**

- `struct nand_chip *this`: the NAND device
- `struct nand_bbt_descr *td`: the BBT description
- `struct nand_bbt_descr *md`: the mirror BBT descriptor
- `int chip`: the CHIP selector

**Description**

This functions returns a positive block number pointing a valid eraseblock
suitable to store a BBT (i.e. in the range reserved for BBT), or -ENOSPC if
all blocks are already used of marked bad. If td->pages\[chip\] was already
pointing to a valid block we re-use it, otherwise we search for the next
valid one.

#### <a id="c-mark_bbt_block_bad"></a>`mark_bbt_block_bad()`

```c
void mark_bbt_block_bad(struct nand_chip *this, struct nand_bbt_descr *td, int chip, int block)
```

Mark one of the block reserved for BBT bad

**Parameters**

- `struct nand_chip *this`: the NAND device
- `struct nand_bbt_descr *td`: the BBT description
- `int chip`: the CHIP selector
- `int block`: the BBT block to mark

**Description**

Blocks reserved for BBT can become bad. This functions is an helper to mark
such blocks as bad. It takes care of updating the in-memory BBT, marking the
block as bad using a bad block marker and invalidating the associated
td->pages\[\] entry.

#### <a id="c-write_bbt"></a>`write_bbt()`

```c
int write_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, struct nand_bbt_descr *md, int chipsel)
```

\[GENERIC\] (Re)write the bad block table

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *td`: descriptor for the bad block table
- `struct nand_bbt_descr *md`: descriptor for the bad block table mirror
- `int chipsel`: selector for a specific chip, -1 for all

**Description**

(Re)write the bad block table.

#### <a id="c-nand_memory_bbt"></a>`nand_memory_bbt()`

```c
int nand_memory_bbt(struct nand_chip *this, struct nand_bbt_descr *bd)
```

\[GENERIC\] create a memory based bad block table

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `struct nand_bbt_descr *bd`: descriptor for the good/bad block search pattern

**Description**

The function creates a memory based bbt by scanning the device for
manufacturer / software marked good / bad blocks.

#### <a id="c-check_create"></a>`check_create()`

```c
int check_create(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *bd)
```

\[GENERIC\] create and write bbt(s) if necessary

**Parameters**

- `struct nand_chip *this`: the NAND device
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *bd`: descriptor for the good/bad block search pattern

**Description**

The function checks the results of the previous call to read_bbt and creates
/ updates the bbt(s) if necessary. Creation is necessary if no bbt was found
for the chip/device. Update is necessary if one of the tables is missing or
the version nr. of one table is less than the other.

#### <a id="c-nand_update_bbt"></a>`nand_update_bbt()`

```c
int nand_update_bbt(struct nand_chip *this, loff_t offs)
```

update bad block table(s)

**Parameters**

- `struct nand_chip *this`: the NAND device
- `loff_t offs`: the offset of the newly marked block

**Description**

The function updates the bad block table(s).

#### <a id="c-mark_bbt_region"></a>`mark_bbt_region()`

```c
void mark_bbt_region(struct nand_chip *this, struct nand_bbt_descr *td)
```

\[GENERIC\] mark the bad block table regions

**Parameters**

- `struct nand_chip *this`: the NAND device
- `struct nand_bbt_descr *td`: bad block table descriptor

**Description**

The bad block table regions are marked as "bad" to prevent accidental
erasures / writes. The regions are identified by the mark 0x02.

#### <a id="c-verify_bbt_descr"></a>`verify_bbt_descr()`

```c
void verify_bbt_descr(struct nand_chip *this, struct nand_bbt_descr *bd)
```

verify the bad block description

**Parameters**

- `struct nand_chip *this`: the NAND device
- `struct nand_bbt_descr *bd`: the table to verify

**Description**

This functions performs a few sanity checks on the bad block description
table.

#### <a id="c-nand_scan_bbt"></a>`nand_scan_bbt()`

```c
int nand_scan_bbt(struct nand_chip *this, struct nand_bbt_descr *bd)
```

\[NAND Interface\] scan, find, read and maybe create bad block table(s)

**Parameters**

- `struct nand_chip *this`: the NAND device
- `struct nand_bbt_descr *bd`: descriptor for the good/bad block search pattern

**Description**

The function checks, if a bad block table(s) is/are already available. If
not it scans the device for manufacturer marked good / bad blocks and writes
the bad block table(s) to the selected place.

The bad block table memory is allocated here. It must be freed by calling
the nand_free_bbt function.

#### <a id="c-nand_create_badblock_pattern"></a>`nand_create_badblock_pattern()`

```c
int nand_create_badblock_pattern(struct nand_chip *this)
```

\[INTERN\] Creates a BBT descriptor structure

**Parameters**

- `struct nand_chip *this`: NAND chip to create descriptor for

**Description**

This function allocates and initializes a nand_bbt_descr for BBM detection
based on the properties of **this**. The new descriptor is stored in
this->badblock_pattern. Thus, this->badblock_pattern should be NULL when
passed to this function.

#### <a id="c-nand_isreserved_bbt"></a>`nand_isreserved_bbt()`

```c
int nand_isreserved_bbt(struct nand_chip *this, loff_t offs)
```

\[NAND Interface\] Check if a block is reserved

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `loff_t offs`: offset in the device

#### <a id="c-nand_isbad_bbt"></a>`nand_isbad_bbt()`

```c
int nand_isbad_bbt(struct nand_chip *this, loff_t offs, int allowbbt)
```

\[NAND Interface\] Check if a block is bad

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `loff_t offs`: offset in the device
- `int allowbbt`: allow access to bad block table region

#### <a id="c-nand_markbad_bbt"></a>`nand_markbad_bbt()`

```c
int nand_markbad_bbt(struct nand_chip *this, loff_t offs)
```

\[NAND Interface\] Mark a block bad in the BBT

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `loff_t offs`: offset of the bad block


<a id="rst-credits"></a>

## Credits

The following people have contributed to the NAND driver:

1. Steven J. Hill[sjhill@realitydiluted.com](<mailto:sjhill@realitydiluted.com>)

2. David Woodhouse[dwmw2@infradead.org](<mailto:dwmw2@infradead.org>)

3. Thomas Gleixner[tglx@kernel.org](<mailto:tglx@kernel.org>)

A lot of users have provided bugfixes, improvements and helping hands for testing. Thanks a lot.

The following people have contributed to this document:

1. Thomas Gleixner[tglx@kernel.org](<mailto:tglx@kernel.org>)
