Back to home page

OSCL-LXR

 
 

    


0001 /* SPDX-License-Identifier: GPL-2.0-only */
0002 /*
0003  *  Copyright © 2000-2010 David Woodhouse <dwmw2@infradead.org>
0004  *                        Steven J. Hill <sjhill@realitydiluted.com>
0005  *                Thomas Gleixner <tglx@linutronix.de>
0006  *
0007  * Info:
0008  *  Contains standard defines and IDs for NAND flash devices
0009  *
0010  * Changelog:
0011  *  See git changelog.
0012  */
0013 #ifndef __LINUX_MTD_RAWNAND_H
0014 #define __LINUX_MTD_RAWNAND_H
0015 
0016 #include <linux/mtd/mtd.h>
0017 #include <linux/mtd/nand.h>
0018 #include <linux/mtd/flashchip.h>
0019 #include <linux/mtd/bbm.h>
0020 #include <linux/mtd/jedec.h>
0021 #include <linux/mtd/onfi.h>
0022 #include <linux/mutex.h>
0023 #include <linux/of.h>
0024 #include <linux/types.h>
0025 
0026 struct nand_chip;
0027 struct gpio_desc;
0028 
0029 /* The maximum number of NAND chips in an array */
0030 #define NAND_MAX_CHIPS      8
0031 
0032 /*
0033  * Constants for hardware specific CLE/ALE/NCE function
0034  *
0035  * These are bits which can be or'ed to set/clear multiple
0036  * bits in one go.
0037  */
0038 /* Select the chip by setting nCE to low */
0039 #define NAND_NCE        0x01
0040 /* Select the command latch by setting CLE to high */
0041 #define NAND_CLE        0x02
0042 /* Select the address latch by setting ALE to high */
0043 #define NAND_ALE        0x04
0044 
0045 #define NAND_CTRL_CLE       (NAND_NCE | NAND_CLE)
0046 #define NAND_CTRL_ALE       (NAND_NCE | NAND_ALE)
0047 #define NAND_CTRL_CHANGE    0x80
0048 
0049 /*
0050  * Standard NAND flash commands
0051  */
0052 #define NAND_CMD_READ0      0
0053 #define NAND_CMD_READ1      1
0054 #define NAND_CMD_RNDOUT     5
0055 #define NAND_CMD_PAGEPROG   0x10
0056 #define NAND_CMD_READOOB    0x50
0057 #define NAND_CMD_ERASE1     0x60
0058 #define NAND_CMD_STATUS     0x70
0059 #define NAND_CMD_SEQIN      0x80
0060 #define NAND_CMD_RNDIN      0x85
0061 #define NAND_CMD_READID     0x90
0062 #define NAND_CMD_ERASE2     0xd0
0063 #define NAND_CMD_PARAM      0xec
0064 #define NAND_CMD_GET_FEATURES   0xee
0065 #define NAND_CMD_SET_FEATURES   0xef
0066 #define NAND_CMD_RESET      0xff
0067 
0068 /* Extended commands for large page devices */
0069 #define NAND_CMD_READSTART  0x30
0070 #define NAND_CMD_RNDOUTSTART    0xE0
0071 #define NAND_CMD_CACHEDPROG 0x15
0072 
0073 #define NAND_CMD_NONE       -1
0074 
0075 /* Status bits */
0076 #define NAND_STATUS_FAIL    0x01
0077 #define NAND_STATUS_FAIL_N1 0x02
0078 #define NAND_STATUS_TRUE_READY  0x20
0079 #define NAND_STATUS_READY   0x40
0080 #define NAND_STATUS_WP      0x80
0081 
0082 #define NAND_DATA_IFACE_CHECK_ONLY  -1
0083 
0084 /*
0085  * Constants for Hardware ECC
0086  */
0087 /* Reset Hardware ECC for read */
0088 #define NAND_ECC_READ       0
0089 /* Reset Hardware ECC for write */
0090 #define NAND_ECC_WRITE      1
0091 /* Enable Hardware ECC before syndrome is read back from flash */
0092 #define NAND_ECC_READSYN    2
0093 
0094 /*
0095  * Enable generic NAND 'page erased' check. This check is only done when
0096  * ecc.correct() returns -EBADMSG.
0097  * Set this flag if your implementation does not fix bitflips in erased
0098  * pages and you want to rely on the default implementation.
0099  */
0100 #define NAND_ECC_GENERIC_ERASED_CHECK   BIT(0)
0101 
0102 /*
0103  * Option constants for bizarre disfunctionality and real
0104  * features.
0105  */
0106 
0107 /* Buswidth is 16 bit */
0108 #define NAND_BUSWIDTH_16    BIT(1)
0109 
0110 /*
0111  * When using software implementation of Hamming, we can specify which byte
0112  * ordering should be used.
0113  */
0114 #define NAND_ECC_SOFT_HAMMING_SM_ORDER  BIT(2)
0115 
0116 /* Chip has cache program function */
0117 #define NAND_CACHEPRG       BIT(3)
0118 /* Options valid for Samsung large page devices */
0119 #define NAND_SAMSUNG_LP_OPTIONS NAND_CACHEPRG
0120 
0121 /*
0122  * Chip requires ready check on read (for auto-incremented sequential read).
0123  * True only for small page devices; large page devices do not support
0124  * autoincrement.
0125  */
0126 #define NAND_NEED_READRDY   BIT(8)
0127 
0128 /* Chip does not allow subpage writes */
0129 #define NAND_NO_SUBPAGE_WRITE   BIT(9)
0130 
0131 /* Device is one of 'new' xD cards that expose fake nand command set */
0132 #define NAND_BROKEN_XD      BIT(10)
0133 
0134 /* Device behaves just like nand, but is readonly */
0135 #define NAND_ROM        BIT(11)
0136 
0137 /* Device supports subpage reads */
0138 #define NAND_SUBPAGE_READ   BIT(12)
0139 /* Macros to identify the above */
0140 #define NAND_HAS_SUBPAGE_READ(chip) ((chip->options & NAND_SUBPAGE_READ))
0141 
0142 /*
0143  * Some MLC NANDs need data scrambling to limit bitflips caused by repeated
0144  * patterns.
0145  */
0146 #define NAND_NEED_SCRAMBLING    BIT(13)
0147 
0148 /* Device needs 3rd row address cycle */
0149 #define NAND_ROW_ADDR_3     BIT(14)
0150 
0151 /* Non chip related options */
0152 /* This option skips the bbt scan during initialization. */
0153 #define NAND_SKIP_BBTSCAN   BIT(16)
0154 /* Chip may not exist, so silence any errors in scan */
0155 #define NAND_SCAN_SILENT_NODEV  BIT(18)
0156 
0157 /*
0158  * Autodetect nand buswidth with readid/onfi.
0159  * This suppose the driver will configure the hardware in 8 bits mode
0160  * when calling nand_scan_ident, and update its configuration
0161  * before calling nand_scan_tail.
0162  */
0163 #define NAND_BUSWIDTH_AUTO      BIT(19)
0164 
0165 /*
0166  * This option could be defined by controller drivers to protect against
0167  * kmap'ed, vmalloc'ed highmem buffers being passed from upper layers
0168  */
0169 #define NAND_USES_DMA       BIT(20)
0170 
0171 /*
0172  * In case your controller is implementing ->legacy.cmd_ctrl() and is relying
0173  * on the default ->cmdfunc() implementation, you may want to let the core
0174  * handle the tCCS delay which is required when a column change (RNDIN or
0175  * RNDOUT) is requested.
0176  * If your controller already takes care of this delay, you don't need to set
0177  * this flag.
0178  */
0179 #define NAND_WAIT_TCCS      BIT(21)
0180 
0181 /*
0182  * Whether the NAND chip is a boot medium. Drivers might use this information
0183  * to select ECC algorithms supported by the boot ROM or similar restrictions.
0184  */
0185 #define NAND_IS_BOOT_MEDIUM BIT(22)
0186 
0187 /*
0188  * Do not try to tweak the timings at runtime. This is needed when the
0189  * controller initializes the timings on itself or when it relies on
0190  * configuration done by the bootloader.
0191  */
0192 #define NAND_KEEP_TIMINGS   BIT(23)
0193 
0194 /*
0195  * There are different places where the manufacturer stores the factory bad
0196  * block markers.
0197  *
0198  * Position within the block: Each of these pages needs to be checked for a
0199  * bad block marking pattern.
0200  */
0201 #define NAND_BBM_FIRSTPAGE  BIT(24)
0202 #define NAND_BBM_SECONDPAGE BIT(25)
0203 #define NAND_BBM_LASTPAGE   BIT(26)
0204 
0205 /*
0206  * Some controllers with pipelined ECC engines override the BBM marker with
0207  * data or ECC bytes, thus making bad block detection through bad block marker
0208  * impossible. Let's flag those chips so the core knows it shouldn't check the
0209  * BBM and consider all blocks good.
0210  */
0211 #define NAND_NO_BBM_QUIRK   BIT(27)
0212 
0213 /* Cell info constants */
0214 #define NAND_CI_CHIPNR_MSK  0x03
0215 #define NAND_CI_CELLTYPE_MSK    0x0C
0216 #define NAND_CI_CELLTYPE_SHIFT  2
0217 
0218 /* Position within the OOB data of the page */
0219 #define NAND_BBM_POS_SMALL      5
0220 #define NAND_BBM_POS_LARGE      0
0221 
0222 /**
0223  * struct nand_parameters - NAND generic parameters from the parameter page
0224  * @model: Model name
0225  * @supports_set_get_features: The NAND chip supports setting/getting features
0226  * @set_feature_list: Bitmap of features that can be set
0227  * @get_feature_list: Bitmap of features that can be get
0228  * @onfi: ONFI specific parameters
0229  */
0230 struct nand_parameters {
0231     /* Generic parameters */
0232     const char *model;
0233     bool supports_set_get_features;
0234     DECLARE_BITMAP(set_feature_list, ONFI_FEATURE_NUMBER);
0235     DECLARE_BITMAP(get_feature_list, ONFI_FEATURE_NUMBER);
0236 
0237     /* ONFI parameters */
0238     struct onfi_params *onfi;
0239 };
0240 
0241 /* The maximum expected count of bytes in the NAND ID sequence */
0242 #define NAND_MAX_ID_LEN 8
0243 
0244 /**
0245  * struct nand_id - NAND id structure
0246  * @data: buffer containing the id bytes.
0247  * @len: ID length.
0248  */
0249 struct nand_id {
0250     u8 data[NAND_MAX_ID_LEN];
0251     int len;
0252 };
0253 
0254 /**
0255  * struct nand_ecc_step_info - ECC step information of ECC engine
0256  * @stepsize: data bytes per ECC step
0257  * @strengths: array of supported strengths
0258  * @nstrengths: number of supported strengths
0259  */
0260 struct nand_ecc_step_info {
0261     int stepsize;
0262     const int *strengths;
0263     int nstrengths;
0264 };
0265 
0266 /**
0267  * struct nand_ecc_caps - capability of ECC engine
0268  * @stepinfos: array of ECC step information
0269  * @nstepinfos: number of ECC step information
0270  * @calc_ecc_bytes: driver's hook to calculate ECC bytes per step
0271  */
0272 struct nand_ecc_caps {
0273     const struct nand_ecc_step_info *stepinfos;
0274     int nstepinfos;
0275     int (*calc_ecc_bytes)(int step_size, int strength);
0276 };
0277 
0278 /* a shorthand to generate struct nand_ecc_caps with only one ECC stepsize */
0279 #define NAND_ECC_CAPS_SINGLE(__name, __calc, __step, ...)   \
0280 static const int __name##_strengths[] = { __VA_ARGS__ };    \
0281 static const struct nand_ecc_step_info __name##_stepinfo = {    \
0282     .stepsize = __step,                 \
0283     .strengths = __name##_strengths,            \
0284     .nstrengths = ARRAY_SIZE(__name##_strengths),       \
0285 };                              \
0286 static const struct nand_ecc_caps __name = {            \
0287     .stepinfos = &__name##_stepinfo,            \
0288     .nstepinfos = 1,                    \
0289     .calc_ecc_bytes = __calc,               \
0290 }
0291 
0292 /**
0293  * struct nand_ecc_ctrl - Control structure for ECC
0294  * @engine_type: ECC engine type
0295  * @placement:  OOB bytes placement
0296  * @algo:   ECC algorithm
0297  * @steps:  number of ECC steps per page
0298  * @size:   data bytes per ECC step
0299  * @bytes:  ECC bytes per step
0300  * @strength:   max number of correctible bits per ECC step
0301  * @total:  total number of ECC bytes per page
0302  * @prepad: padding information for syndrome based ECC generators
0303  * @postpad:    padding information for syndrome based ECC generators
0304  * @options:    ECC specific options (see NAND_ECC_XXX flags defined above)
0305  * @calc_buf:   buffer for calculated ECC, size is oobsize.
0306  * @code_buf:   buffer for ECC read from flash, size is oobsize.
0307  * @hwctl:  function to control hardware ECC generator. Must only
0308  *      be provided if an hardware ECC is available
0309  * @calculate:  function for ECC calculation or readback from ECC hardware
0310  * @correct:    function for ECC correction, matching to ECC generator (sw/hw).
0311  *      Should return a positive number representing the number of
0312  *      corrected bitflips, -EBADMSG if the number of bitflips exceed
0313  *      ECC strength, or any other error code if the error is not
0314  *      directly related to correction.
0315  *      If -EBADMSG is returned the input buffers should be left
0316  *      untouched.
0317  * @read_page_raw:  function to read a raw page without ECC. This function
0318  *          should hide the specific layout used by the ECC
0319  *          controller and always return contiguous in-band and
0320  *          out-of-band data even if they're not stored
0321  *          contiguously on the NAND chip (e.g.
0322  *          NAND_ECC_PLACEMENT_INTERLEAVED interleaves in-band and
0323  *          out-of-band data).
0324  * @write_page_raw: function to write a raw page without ECC. This function
0325  *          should hide the specific layout used by the ECC
0326  *          controller and consider the passed data as contiguous
0327  *          in-band and out-of-band data. ECC controller is
0328  *          responsible for doing the appropriate transformations
0329  *          to adapt to its specific layout (e.g.
0330  *          NAND_ECC_PLACEMENT_INTERLEAVED interleaves in-band and
0331  *          out-of-band data).
0332  * @read_page:  function to read a page according to the ECC generator
0333  *      requirements; returns maximum number of bitflips corrected in
0334  *      any single ECC step, -EIO hw error
0335  * @read_subpage:   function to read parts of the page covered by ECC;
0336  *          returns same as read_page()
0337  * @write_subpage:  function to write parts of the page covered by ECC.
0338  * @write_page: function to write a page according to the ECC generator
0339  *      requirements.
0340  * @write_oob_raw:  function to write chip OOB data without ECC
0341  * @read_oob_raw:   function to read chip OOB data without ECC
0342  * @read_oob:   function to read chip OOB data
0343  * @write_oob:  function to write chip OOB data
0344  */
0345 struct nand_ecc_ctrl {
0346     enum nand_ecc_engine_type engine_type;
0347     enum nand_ecc_placement placement;
0348     enum nand_ecc_algo algo;
0349     int steps;
0350     int size;
0351     int bytes;
0352     int total;
0353     int strength;
0354     int prepad;
0355     int postpad;
0356     unsigned int options;
0357     u8 *calc_buf;
0358     u8 *code_buf;
0359     void (*hwctl)(struct nand_chip *chip, int mode);
0360     int (*calculate)(struct nand_chip *chip, const uint8_t *dat,
0361              uint8_t *ecc_code);
0362     int (*correct)(struct nand_chip *chip, uint8_t *dat, uint8_t *read_ecc,
0363                uint8_t *calc_ecc);
0364     int (*read_page_raw)(struct nand_chip *chip, uint8_t *buf,
0365                  int oob_required, int page);
0366     int (*write_page_raw)(struct nand_chip *chip, const uint8_t *buf,
0367                   int oob_required, int page);
0368     int (*read_page)(struct nand_chip *chip, uint8_t *buf,
0369              int oob_required, int page);
0370     int (*read_subpage)(struct nand_chip *chip, uint32_t offs,
0371                 uint32_t len, uint8_t *buf, int page);
0372     int (*write_subpage)(struct nand_chip *chip, uint32_t offset,
0373                  uint32_t data_len, const uint8_t *data_buf,
0374                  int oob_required, int page);
0375     int (*write_page)(struct nand_chip *chip, const uint8_t *buf,
0376               int oob_required, int page);
0377     int (*write_oob_raw)(struct nand_chip *chip, int page);
0378     int (*read_oob_raw)(struct nand_chip *chip, int page);
0379     int (*read_oob)(struct nand_chip *chip, int page);
0380     int (*write_oob)(struct nand_chip *chip, int page);
0381 };
0382 
0383 /**
0384  * struct nand_sdr_timings - SDR NAND chip timings
0385  *
0386  * This struct defines the timing requirements of a SDR NAND chip.
0387  * These information can be found in every NAND datasheets and the timings
0388  * meaning are described in the ONFI specifications:
0389  * https://media-www.micron.com/-/media/client/onfi/specs/onfi_3_1_spec.pdf
0390  * (chapter 4.15 Timing Parameters)
0391  *
0392  * All these timings are expressed in picoseconds.
0393  *
0394  * @tBERS_max: Block erase time
0395  * @tCCS_min: Change column setup time
0396  * @tPROG_max: Page program time
0397  * @tR_max: Page read time
0398  * @tALH_min: ALE hold time
0399  * @tADL_min: ALE to data loading time
0400  * @tALS_min: ALE setup time
0401  * @tAR_min: ALE to RE# delay
0402  * @tCEA_max: CE# access time
0403  * @tCEH_min: CE# high hold time
0404  * @tCH_min:  CE# hold time
0405  * @tCHZ_max: CE# high to output hi-Z
0406  * @tCLH_min: CLE hold time
0407  * @tCLR_min: CLE to RE# delay
0408  * @tCLS_min: CLE setup time
0409  * @tCOH_min: CE# high to output hold
0410  * @tCS_min: CE# setup time
0411  * @tDH_min: Data hold time
0412  * @tDS_min: Data setup time
0413  * @tFEAT_max: Busy time for Set Features and Get Features
0414  * @tIR_min: Output hi-Z to RE# low
0415  * @tITC_max: Interface and Timing Mode Change time
0416  * @tRC_min: RE# cycle time
0417  * @tREA_max: RE# access time
0418  * @tREH_min: RE# high hold time
0419  * @tRHOH_min: RE# high to output hold
0420  * @tRHW_min: RE# high to WE# low
0421  * @tRHZ_max: RE# high to output hi-Z
0422  * @tRLOH_min: RE# low to output hold
0423  * @tRP_min: RE# pulse width
0424  * @tRR_min: Ready to RE# low (data only)
0425  * @tRST_max: Device reset time, measured from the falling edge of R/B# to the
0426  *        rising edge of R/B#.
0427  * @tWB_max: WE# high to SR[6] low
0428  * @tWC_min: WE# cycle time
0429  * @tWH_min: WE# high hold time
0430  * @tWHR_min: WE# high to RE# low
0431  * @tWP_min: WE# pulse width
0432  * @tWW_min: WP# transition to WE# low
0433  */
0434 struct nand_sdr_timings {
0435     u64 tBERS_max;
0436     u32 tCCS_min;
0437     u64 tPROG_max;
0438     u64 tR_max;
0439     u32 tALH_min;
0440     u32 tADL_min;
0441     u32 tALS_min;
0442     u32 tAR_min;
0443     u32 tCEA_max;
0444     u32 tCEH_min;
0445     u32 tCH_min;
0446     u32 tCHZ_max;
0447     u32 tCLH_min;
0448     u32 tCLR_min;
0449     u32 tCLS_min;
0450     u32 tCOH_min;
0451     u32 tCS_min;
0452     u32 tDH_min;
0453     u32 tDS_min;
0454     u32 tFEAT_max;
0455     u32 tIR_min;
0456     u32 tITC_max;
0457     u32 tRC_min;
0458     u32 tREA_max;
0459     u32 tREH_min;
0460     u32 tRHOH_min;
0461     u32 tRHW_min;
0462     u32 tRHZ_max;
0463     u32 tRLOH_min;
0464     u32 tRP_min;
0465     u32 tRR_min;
0466     u64 tRST_max;
0467     u32 tWB_max;
0468     u32 tWC_min;
0469     u32 tWH_min;
0470     u32 tWHR_min;
0471     u32 tWP_min;
0472     u32 tWW_min;
0473 };
0474 
0475 /**
0476  * struct nand_nvddr_timings - NV-DDR NAND chip timings
0477  *
0478  * This struct defines the timing requirements of a NV-DDR NAND data interface.
0479  * These information can be found in every NAND datasheets and the timings
0480  * meaning are described in the ONFI specifications:
0481  * https://media-www.micron.com/-/media/client/onfi/specs/onfi_4_1_gold.pdf
0482  * (chapter 4.18.2 NV-DDR)
0483  *
0484  * All these timings are expressed in picoseconds.
0485  *
0486  * @tBERS_max: Block erase time
0487  * @tCCS_min: Change column setup time
0488  * @tPROG_max: Page program time
0489  * @tR_max: Page read time
0490  * @tAC_min: Access window of DQ[7:0] from CLK
0491  * @tAC_max: Access window of DQ[7:0] from CLK
0492  * @tADL_min: ALE to data loading time
0493  * @tCAD_min: Command, Address, Data delay
0494  * @tCAH_min: Command/Address DQ hold time
0495  * @tCALH_min: W/R_n, CLE and ALE hold time
0496  * @tCALS_min: W/R_n, CLE and ALE setup time
0497  * @tCAS_min: Command/address DQ setup time
0498  * @tCEH_min: CE# high hold time
0499  * @tCH_min:  CE# hold time
0500  * @tCK_min: Average clock cycle time
0501  * @tCS_min: CE# setup time
0502  * @tDH_min: Data hold time
0503  * @tDQSCK_min: Start of the access window of DQS from CLK
0504  * @tDQSCK_max: End of the access window of DQS from CLK
0505  * @tDQSD_min: Min W/R_n low to DQS/DQ driven by device
0506  * @tDQSD_max: Max W/R_n low to DQS/DQ driven by device
0507  * @tDQSHZ_max: W/R_n high to DQS/DQ tri-state by device
0508  * @tDQSQ_max: DQS-DQ skew, DQS to last DQ valid, per access
0509  * @tDS_min: Data setup time
0510  * @tDSC_min: DQS cycle time
0511  * @tFEAT_max: Busy time for Set Features and Get Features
0512  * @tITC_max: Interface and Timing Mode Change time
0513  * @tQHS_max: Data hold skew factor
0514  * @tRHW_min: Data output cycle to command, address, or data input cycle
0515  * @tRR_min: Ready to RE# low (data only)
0516  * @tRST_max: Device reset time, measured from the falling edge of R/B# to the
0517  *        rising edge of R/B#.
0518  * @tWB_max: WE# high to SR[6] low
0519  * @tWHR_min: WE# high to RE# low
0520  * @tWRCK_min: W/R_n low to data output cycle
0521  * @tWW_min: WP# transition to WE# low
0522  */
0523 struct nand_nvddr_timings {
0524     u64 tBERS_max;
0525     u32 tCCS_min;
0526     u64 tPROG_max;
0527     u64 tR_max;
0528     u32 tAC_min;
0529     u32 tAC_max;
0530     u32 tADL_min;
0531     u32 tCAD_min;
0532     u32 tCAH_min;
0533     u32 tCALH_min;
0534     u32 tCALS_min;
0535     u32 tCAS_min;
0536     u32 tCEH_min;
0537     u32 tCH_min;
0538     u32 tCK_min;
0539     u32 tCS_min;
0540     u32 tDH_min;
0541     u32 tDQSCK_min;
0542     u32 tDQSCK_max;
0543     u32 tDQSD_min;
0544     u32 tDQSD_max;
0545     u32 tDQSHZ_max;
0546     u32 tDQSQ_max;
0547     u32 tDS_min;
0548     u32 tDSC_min;
0549     u32 tFEAT_max;
0550     u32 tITC_max;
0551     u32 tQHS_max;
0552     u32 tRHW_min;
0553     u32 tRR_min;
0554     u32 tRST_max;
0555     u32 tWB_max;
0556     u32 tWHR_min;
0557     u32 tWRCK_min;
0558     u32 tWW_min;
0559 };
0560 
0561 /*
0562  * While timings related to the data interface itself are mostly different
0563  * between SDR and NV-DDR, timings related to the internal chip behavior are
0564  * common. IOW, the following entries which describe the internal delays have
0565  * the same definition and are shared in both SDR and NV-DDR timing structures:
0566  * - tADL_min
0567  * - tBERS_max
0568  * - tCCS_min
0569  * - tFEAT_max
0570  * - tPROG_max
0571  * - tR_max
0572  * - tRR_min
0573  * - tRST_max
0574  * - tWB_max
0575  *
0576  * The below macros return the value of a given timing, no matter the interface.
0577  */
0578 #define NAND_COMMON_TIMING_PS(conf, timing_name)        \
0579     nand_interface_is_sdr(conf) ?               \
0580         nand_get_sdr_timings(conf)->timing_name :   \
0581         nand_get_nvddr_timings(conf)->timing_name
0582 
0583 #define NAND_COMMON_TIMING_MS(conf, timing_name) \
0584     PSEC_TO_MSEC(NAND_COMMON_TIMING_PS((conf), timing_name))
0585 
0586 #define NAND_COMMON_TIMING_NS(conf, timing_name) \
0587     PSEC_TO_NSEC(NAND_COMMON_TIMING_PS((conf), timing_name))
0588 
0589 /**
0590  * enum nand_interface_type - NAND interface type
0591  * @NAND_SDR_IFACE: Single Data Rate interface
0592  * @NAND_NVDDR_IFACE:   Double Data Rate interface
0593  */
0594 enum nand_interface_type {
0595     NAND_SDR_IFACE,
0596     NAND_NVDDR_IFACE,
0597 };
0598 
0599 /**
0600  * struct nand_interface_config - NAND interface timing
0601  * @type:    type of the timing
0602  * @timings:     The timing information
0603  * @timings.mode: Timing mode as defined in the specification
0604  * @timings.sdr: Use it when @type is %NAND_SDR_IFACE.
0605  * @timings.nvddr: Use it when @type is %NAND_NVDDR_IFACE.
0606  */
0607 struct nand_interface_config {
0608     enum nand_interface_type type;
0609     struct nand_timings {
0610         unsigned int mode;
0611         union {
0612             struct nand_sdr_timings sdr;
0613             struct nand_nvddr_timings nvddr;
0614         };
0615     } timings;
0616 };
0617 
0618 /**
0619  * nand_interface_is_sdr - get the interface type
0620  * @conf:   The data interface
0621  */
0622 static bool nand_interface_is_sdr(const struct nand_interface_config *conf)
0623 {
0624     return conf->type == NAND_SDR_IFACE;
0625 }
0626 
0627 /**
0628  * nand_interface_is_nvddr - get the interface type
0629  * @conf:   The data interface
0630  */
0631 static bool nand_interface_is_nvddr(const struct nand_interface_config *conf)
0632 {
0633     return conf->type == NAND_NVDDR_IFACE;
0634 }
0635 
0636 /**
0637  * nand_get_sdr_timings - get SDR timing from data interface
0638  * @conf:   The data interface
0639  */
0640 static inline const struct nand_sdr_timings *
0641 nand_get_sdr_timings(const struct nand_interface_config *conf)
0642 {
0643     if (!nand_interface_is_sdr(conf))
0644         return ERR_PTR(-EINVAL);
0645 
0646     return &conf->timings.sdr;
0647 }
0648 
0649 /**
0650  * nand_get_nvddr_timings - get NV-DDR timing from data interface
0651  * @conf:   The data interface
0652  */
0653 static inline const struct nand_nvddr_timings *
0654 nand_get_nvddr_timings(const struct nand_interface_config *conf)
0655 {
0656     if (!nand_interface_is_nvddr(conf))
0657         return ERR_PTR(-EINVAL);
0658 
0659     return &conf->timings.nvddr;
0660 }
0661 
0662 /**
0663  * struct nand_op_cmd_instr - Definition of a command instruction
0664  * @opcode: the command to issue in one cycle
0665  */
0666 struct nand_op_cmd_instr {
0667     u8 opcode;
0668 };
0669 
0670 /**
0671  * struct nand_op_addr_instr - Definition of an address instruction
0672  * @naddrs: length of the @addrs array
0673  * @addrs: array containing the address cycles to issue
0674  */
0675 struct nand_op_addr_instr {
0676     unsigned int naddrs;
0677     const u8 *addrs;
0678 };
0679 
0680 /**
0681  * struct nand_op_data_instr - Definition of a data instruction
0682  * @len: number of data bytes to move
0683  * @buf: buffer to fill
0684  * @buf.in: buffer to fill when reading from the NAND chip
0685  * @buf.out: buffer to read from when writing to the NAND chip
0686  * @force_8bit: force 8-bit access
0687  *
0688  * Please note that "in" and "out" are inverted from the ONFI specification
0689  * and are from the controller perspective, so a "in" is a read from the NAND
0690  * chip while a "out" is a write to the NAND chip.
0691  */
0692 struct nand_op_data_instr {
0693     unsigned int len;
0694     union {
0695         void *in;
0696         const void *out;
0697     } buf;
0698     bool force_8bit;
0699 };
0700 
0701 /**
0702  * struct nand_op_waitrdy_instr - Definition of a wait ready instruction
0703  * @timeout_ms: maximum delay while waiting for the ready/busy pin in ms
0704  */
0705 struct nand_op_waitrdy_instr {
0706     unsigned int timeout_ms;
0707 };
0708 
0709 /**
0710  * enum nand_op_instr_type - Definition of all instruction types
0711  * @NAND_OP_CMD_INSTR: command instruction
0712  * @NAND_OP_ADDR_INSTR: address instruction
0713  * @NAND_OP_DATA_IN_INSTR: data in instruction
0714  * @NAND_OP_DATA_OUT_INSTR: data out instruction
0715  * @NAND_OP_WAITRDY_INSTR: wait ready instruction
0716  */
0717 enum nand_op_instr_type {
0718     NAND_OP_CMD_INSTR,
0719     NAND_OP_ADDR_INSTR,
0720     NAND_OP_DATA_IN_INSTR,
0721     NAND_OP_DATA_OUT_INSTR,
0722     NAND_OP_WAITRDY_INSTR,
0723 };
0724 
0725 /**
0726  * struct nand_op_instr - Instruction object
0727  * @type: the instruction type
0728  * @ctx:  extra data associated to the instruction. You'll have to use the
0729  *        appropriate element depending on @type
0730  * @ctx.cmd: use it if @type is %NAND_OP_CMD_INSTR
0731  * @ctx.addr: use it if @type is %NAND_OP_ADDR_INSTR
0732  * @ctx.data: use it if @type is %NAND_OP_DATA_IN_INSTR
0733  *        or %NAND_OP_DATA_OUT_INSTR
0734  * @ctx.waitrdy: use it if @type is %NAND_OP_WAITRDY_INSTR
0735  * @delay_ns: delay the controller should apply after the instruction has been
0736  *        issued on the bus. Most modern controllers have internal timings
0737  *        control logic, and in this case, the controller driver can ignore
0738  *        this field.
0739  */
0740 struct nand_op_instr {
0741     enum nand_op_instr_type type;
0742     union {
0743         struct nand_op_cmd_instr cmd;
0744         struct nand_op_addr_instr addr;
0745         struct nand_op_data_instr data;
0746         struct nand_op_waitrdy_instr waitrdy;
0747     } ctx;
0748     unsigned int delay_ns;
0749 };
0750 
0751 /*
0752  * Special handling must be done for the WAITRDY timeout parameter as it usually
0753  * is either tPROG (after a prog), tR (before a read), tRST (during a reset) or
0754  * tBERS (during an erase) which all of them are u64 values that cannot be
0755  * divided by usual kernel macros and must be handled with the special
0756  * DIV_ROUND_UP_ULL() macro.
0757  *
0758  * Cast to type of dividend is needed here to guarantee that the result won't
0759  * be an unsigned long long when the dividend is an unsigned long (or smaller),
0760  * which is what the compiler does when it sees ternary operator with 2
0761  * different return types (picks the largest type to make sure there's no
0762  * loss).
0763  */
0764 #define __DIVIDE(dividend, divisor) ({                      \
0765     (__typeof__(dividend))(sizeof(dividend) <= sizeof(unsigned long) ?  \
0766                    DIV_ROUND_UP(dividend, divisor) :        \
0767                    DIV_ROUND_UP_ULL(dividend, divisor));        \
0768     })
0769 #define PSEC_TO_NSEC(x) __DIVIDE(x, 1000)
0770 #define PSEC_TO_MSEC(x) __DIVIDE(x, 1000000000)
0771 
0772 #define NAND_OP_CMD(id, ns)                     \
0773     {                               \
0774         .type = NAND_OP_CMD_INSTR,              \
0775         .ctx.cmd.opcode = id,                   \
0776         .delay_ns = ns,                     \
0777     }
0778 
0779 #define NAND_OP_ADDR(ncycles, cycles, ns)               \
0780     {                               \
0781         .type = NAND_OP_ADDR_INSTR,             \
0782         .ctx.addr = {                       \
0783             .naddrs = ncycles,              \
0784             .addrs = cycles,                \
0785         },                          \
0786         .delay_ns = ns,                     \
0787     }
0788 
0789 #define NAND_OP_DATA_IN(l, b, ns)                   \
0790     {                               \
0791         .type = NAND_OP_DATA_IN_INSTR,              \
0792         .ctx.data = {                       \
0793             .len = l,                   \
0794             .buf.in = b,                    \
0795             .force_8bit = false,                \
0796         },                          \
0797         .delay_ns = ns,                     \
0798     }
0799 
0800 #define NAND_OP_DATA_OUT(l, b, ns)                  \
0801     {                               \
0802         .type = NAND_OP_DATA_OUT_INSTR,             \
0803         .ctx.data = {                       \
0804             .len = l,                   \
0805             .buf.out = b,                   \
0806             .force_8bit = false,                \
0807         },                          \
0808         .delay_ns = ns,                     \
0809     }
0810 
0811 #define NAND_OP_8BIT_DATA_IN(l, b, ns)                  \
0812     {                               \
0813         .type = NAND_OP_DATA_IN_INSTR,              \
0814         .ctx.data = {                       \
0815             .len = l,                   \
0816             .buf.in = b,                    \
0817             .force_8bit = true,             \
0818         },                          \
0819         .delay_ns = ns,                     \
0820     }
0821 
0822 #define NAND_OP_8BIT_DATA_OUT(l, b, ns)                 \
0823     {                               \
0824         .type = NAND_OP_DATA_OUT_INSTR,             \
0825         .ctx.data = {                       \
0826             .len = l,                   \
0827             .buf.out = b,                   \
0828             .force_8bit = true,             \
0829         },                          \
0830         .delay_ns = ns,                     \
0831     }
0832 
0833 #define NAND_OP_WAIT_RDY(tout_ms, ns)                   \
0834     {                               \
0835         .type = NAND_OP_WAITRDY_INSTR,              \
0836         .ctx.waitrdy.timeout_ms = tout_ms,          \
0837         .delay_ns = ns,                     \
0838     }
0839 
0840 /**
0841  * struct nand_subop - a sub operation
0842  * @cs: the CS line to select for this NAND sub-operation
0843  * @instrs: array of instructions
0844  * @ninstrs: length of the @instrs array
0845  * @first_instr_start_off: offset to start from for the first instruction
0846  *             of the sub-operation
0847  * @last_instr_end_off: offset to end at (excluded) for the last instruction
0848  *          of the sub-operation
0849  *
0850  * Both @first_instr_start_off and @last_instr_end_off only apply to data or
0851  * address instructions.
0852  *
0853  * When an operation cannot be handled as is by the NAND controller, it will
0854  * be split by the parser into sub-operations which will be passed to the
0855  * controller driver.
0856  */
0857 struct nand_subop {
0858     unsigned int cs;
0859     const struct nand_op_instr *instrs;
0860     unsigned int ninstrs;
0861     unsigned int first_instr_start_off;
0862     unsigned int last_instr_end_off;
0863 };
0864 
0865 unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
0866                        unsigned int op_id);
0867 unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
0868                      unsigned int op_id);
0869 unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
0870                        unsigned int op_id);
0871 unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
0872                      unsigned int op_id);
0873 
0874 /**
0875  * struct nand_op_parser_addr_constraints - Constraints for address instructions
0876  * @maxcycles: maximum number of address cycles the controller can issue in a
0877  *         single step
0878  */
0879 struct nand_op_parser_addr_constraints {
0880     unsigned int maxcycles;
0881 };
0882 
0883 /**
0884  * struct nand_op_parser_data_constraints - Constraints for data instructions
0885  * @maxlen: maximum data length that the controller can handle in a single step
0886  */
0887 struct nand_op_parser_data_constraints {
0888     unsigned int maxlen;
0889 };
0890 
0891 /**
0892  * struct nand_op_parser_pattern_elem - One element of a pattern
0893  * @type: the instructuction type
0894  * @optional: whether this element of the pattern is optional or mandatory
0895  * @ctx: address or data constraint
0896  * @ctx.addr: address constraint (number of cycles)
0897  * @ctx.data: data constraint (data length)
0898  */
0899 struct nand_op_parser_pattern_elem {
0900     enum nand_op_instr_type type;
0901     bool optional;
0902     union {
0903         struct nand_op_parser_addr_constraints addr;
0904         struct nand_op_parser_data_constraints data;
0905     } ctx;
0906 };
0907 
0908 #define NAND_OP_PARSER_PAT_CMD_ELEM(_opt)           \
0909     {                           \
0910         .type = NAND_OP_CMD_INSTR,          \
0911         .optional = _opt,               \
0912     }
0913 
0914 #define NAND_OP_PARSER_PAT_ADDR_ELEM(_opt, _maxcycles)      \
0915     {                           \
0916         .type = NAND_OP_ADDR_INSTR,         \
0917         .optional = _opt,               \
0918         .ctx.addr.maxcycles = _maxcycles,       \
0919     }
0920 
0921 #define NAND_OP_PARSER_PAT_DATA_IN_ELEM(_opt, _maxlen)      \
0922     {                           \
0923         .type = NAND_OP_DATA_IN_INSTR,          \
0924         .optional = _opt,               \
0925         .ctx.data.maxlen = _maxlen,         \
0926     }
0927 
0928 #define NAND_OP_PARSER_PAT_DATA_OUT_ELEM(_opt, _maxlen)     \
0929     {                           \
0930         .type = NAND_OP_DATA_OUT_INSTR,         \
0931         .optional = _opt,               \
0932         .ctx.data.maxlen = _maxlen,         \
0933     }
0934 
0935 #define NAND_OP_PARSER_PAT_WAITRDY_ELEM(_opt)           \
0936     {                           \
0937         .type = NAND_OP_WAITRDY_INSTR,          \
0938         .optional = _opt,               \
0939     }
0940 
0941 /**
0942  * struct nand_op_parser_pattern - NAND sub-operation pattern descriptor
0943  * @elems: array of pattern elements
0944  * @nelems: number of pattern elements in @elems array
0945  * @exec: the function that will issue a sub-operation
0946  *
0947  * A pattern is a list of elements, each element reprensenting one instruction
0948  * with its constraints. The pattern itself is used by the core to match NAND
0949  * chip operation with NAND controller operations.
0950  * Once a match between a NAND controller operation pattern and a NAND chip
0951  * operation (or a sub-set of a NAND operation) is found, the pattern ->exec()
0952  * hook is called so that the controller driver can issue the operation on the
0953  * bus.
0954  *
0955  * Controller drivers should declare as many patterns as they support and pass
0956  * this list of patterns (created with the help of the following macro) to
0957  * the nand_op_parser_exec_op() helper.
0958  */
0959 struct nand_op_parser_pattern {
0960     const struct nand_op_parser_pattern_elem *elems;
0961     unsigned int nelems;
0962     int (*exec)(struct nand_chip *chip, const struct nand_subop *subop);
0963 };
0964 
0965 #define NAND_OP_PARSER_PATTERN(_exec, ...)                          \
0966     {                                           \
0967         .exec = _exec,                                  \
0968         .elems = (const struct nand_op_parser_pattern_elem[]) { __VA_ARGS__ },      \
0969         .nelems = sizeof((struct nand_op_parser_pattern_elem[]) { __VA_ARGS__ }) /  \
0970               sizeof(struct nand_op_parser_pattern_elem),               \
0971     }
0972 
0973 /**
0974  * struct nand_op_parser - NAND controller operation parser descriptor
0975  * @patterns: array of supported patterns
0976  * @npatterns: length of the @patterns array
0977  *
0978  * The parser descriptor is just an array of supported patterns which will be
0979  * iterated by nand_op_parser_exec_op() everytime it tries to execute an
0980  * NAND operation (or tries to determine if a specific operation is supported).
0981  *
0982  * It is worth mentioning that patterns will be tested in their declaration
0983  * order, and the first match will be taken, so it's important to order patterns
0984  * appropriately so that simple/inefficient patterns are placed at the end of
0985  * the list. Usually, this is where you put single instruction patterns.
0986  */
0987 struct nand_op_parser {
0988     const struct nand_op_parser_pattern *patterns;
0989     unsigned int npatterns;
0990 };
0991 
0992 #define NAND_OP_PARSER(...)                                 \
0993     {                                           \
0994         .patterns = (const struct nand_op_parser_pattern[]) { __VA_ARGS__ },        \
0995         .npatterns = sizeof((struct nand_op_parser_pattern[]) { __VA_ARGS__ }) /    \
0996                  sizeof(struct nand_op_parser_pattern),             \
0997     }
0998 
0999 /**
1000  * struct nand_operation - NAND operation descriptor
1001  * @cs: the CS line to select for this NAND operation
1002  * @instrs: array of instructions to execute
1003  * @ninstrs: length of the @instrs array
1004  *
1005  * The actual operation structure that will be passed to chip->exec_op().
1006  */
1007 struct nand_operation {
1008     unsigned int cs;
1009     const struct nand_op_instr *instrs;
1010     unsigned int ninstrs;
1011 };
1012 
1013 #define NAND_OPERATION(_cs, _instrs)                \
1014     {                           \
1015         .cs = _cs,                  \
1016         .instrs = _instrs,              \
1017         .ninstrs = ARRAY_SIZE(_instrs),         \
1018     }
1019 
1020 int nand_op_parser_exec_op(struct nand_chip *chip,
1021                const struct nand_op_parser *parser,
1022                const struct nand_operation *op, bool check_only);
1023 
1024 static inline void nand_op_trace(const char *prefix,
1025                  const struct nand_op_instr *instr)
1026 {
1027 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
1028     switch (instr->type) {
1029     case NAND_OP_CMD_INSTR:
1030         pr_debug("%sCMD      [0x%02x]\n", prefix,
1031              instr->ctx.cmd.opcode);
1032         break;
1033     case NAND_OP_ADDR_INSTR:
1034         pr_debug("%sADDR     [%d cyc: %*ph]\n", prefix,
1035              instr->ctx.addr.naddrs,
1036              instr->ctx.addr.naddrs < 64 ?
1037              instr->ctx.addr.naddrs : 64,
1038              instr->ctx.addr.addrs);
1039         break;
1040     case NAND_OP_DATA_IN_INSTR:
1041         pr_debug("%sDATA_IN  [%d B%s]\n", prefix,
1042              instr->ctx.data.len,
1043              instr->ctx.data.force_8bit ?
1044              ", force 8-bit" : "");
1045         break;
1046     case NAND_OP_DATA_OUT_INSTR:
1047         pr_debug("%sDATA_OUT [%d B%s]\n", prefix,
1048              instr->ctx.data.len,
1049              instr->ctx.data.force_8bit ?
1050              ", force 8-bit" : "");
1051         break;
1052     case NAND_OP_WAITRDY_INSTR:
1053         pr_debug("%sWAITRDY  [max %d ms]\n", prefix,
1054              instr->ctx.waitrdy.timeout_ms);
1055         break;
1056     }
1057 #endif
1058 }
1059 
1060 /**
1061  * struct nand_controller_ops - Controller operations
1062  *
1063  * @attach_chip: this method is called after the NAND detection phase after
1064  *       flash ID and MTD fields such as erase size, page size and OOB
1065  *       size have been set up. ECC requirements are available if
1066  *       provided by the NAND chip or device tree. Typically used to
1067  *       choose the appropriate ECC configuration and allocate
1068  *       associated resources.
1069  *       This hook is optional.
1070  * @detach_chip: free all resources allocated/claimed in
1071  *       nand_controller_ops->attach_chip().
1072  *       This hook is optional.
1073  * @exec_op:     controller specific method to execute NAND operations.
1074  *       This method replaces chip->legacy.cmdfunc(),
1075  *       chip->legacy.{read,write}_{buf,byte,word}(),
1076  *       chip->legacy.dev_ready() and chip->legacy.waifunc().
1077  * @setup_interface: setup the data interface and timing. If chipnr is set to
1078  *           %NAND_DATA_IFACE_CHECK_ONLY this means the configuration
1079  *           should not be applied but only checked.
1080  *           This hook is optional.
1081  */
1082 struct nand_controller_ops {
1083     int (*attach_chip)(struct nand_chip *chip);
1084     void (*detach_chip)(struct nand_chip *chip);
1085     int (*exec_op)(struct nand_chip *chip,
1086                const struct nand_operation *op,
1087                bool check_only);
1088     int (*setup_interface)(struct nand_chip *chip, int chipnr,
1089                    const struct nand_interface_config *conf);
1090 };
1091 
1092 /**
1093  * struct nand_controller - Structure used to describe a NAND controller
1094  *
1095  * @lock:       lock used to serialize accesses to the NAND controller
1096  * @ops:        NAND controller operations.
1097  */
1098 struct nand_controller {
1099     struct mutex lock;
1100     const struct nand_controller_ops *ops;
1101 };
1102 
1103 static inline void nand_controller_init(struct nand_controller *nfc)
1104 {
1105     mutex_init(&nfc->lock);
1106 }
1107 
1108 /**
1109  * struct nand_legacy - NAND chip legacy fields/hooks
1110  * @IO_ADDR_R: address to read the 8 I/O lines of the flash device
1111  * @IO_ADDR_W: address to write the 8 I/O lines of the flash device
1112  * @select_chip: select/deselect a specific target/die
1113  * @read_byte: read one byte from the chip
1114  * @write_byte: write a single byte to the chip on the low 8 I/O lines
1115  * @write_buf: write data from the buffer to the chip
1116  * @read_buf: read data from the chip into the buffer
1117  * @cmd_ctrl: hardware specific function for controlling ALE/CLE/nCE. Also used
1118  *        to write command and address
1119  * @cmdfunc: hardware specific function for writing commands to the chip.
1120  * @dev_ready: hardware specific function for accessing device ready/busy line.
1121  *         If set to NULL no access to ready/busy is available and the
1122  *         ready/busy information is read from the chip status register.
1123  * @waitfunc: hardware specific function for wait on ready.
1124  * @block_bad: check if a block is bad, using OOB markers
1125  * @block_markbad: mark a block bad
1126  * @set_features: set the NAND chip features
1127  * @get_features: get the NAND chip features
1128  * @chip_delay: chip dependent delay for transferring data from array to read
1129  *      regs (tR).
1130  * @dummy_controller: dummy controller implementation for drivers that can
1131  *            only control a single chip
1132  *
1133  * If you look at this structure you're already wrong. These fields/hooks are
1134  * all deprecated.
1135  */
1136 struct nand_legacy {
1137     void __iomem *IO_ADDR_R;
1138     void __iomem *IO_ADDR_W;
1139     void (*select_chip)(struct nand_chip *chip, int cs);
1140     u8 (*read_byte)(struct nand_chip *chip);
1141     void (*write_byte)(struct nand_chip *chip, u8 byte);
1142     void (*write_buf)(struct nand_chip *chip, const u8 *buf, int len);
1143     void (*read_buf)(struct nand_chip *chip, u8 *buf, int len);
1144     void (*cmd_ctrl)(struct nand_chip *chip, int dat, unsigned int ctrl);
1145     void (*cmdfunc)(struct nand_chip *chip, unsigned command, int column,
1146             int page_addr);
1147     int (*dev_ready)(struct nand_chip *chip);
1148     int (*waitfunc)(struct nand_chip *chip);
1149     int (*block_bad)(struct nand_chip *chip, loff_t ofs);
1150     int (*block_markbad)(struct nand_chip *chip, loff_t ofs);
1151     int (*set_features)(struct nand_chip *chip, int feature_addr,
1152                 u8 *subfeature_para);
1153     int (*get_features)(struct nand_chip *chip, int feature_addr,
1154                 u8 *subfeature_para);
1155     int chip_delay;
1156     struct nand_controller dummy_controller;
1157 };
1158 
1159 /**
1160  * struct nand_chip_ops - NAND chip operations
1161  * @suspend: Suspend operation
1162  * @resume: Resume operation
1163  * @lock_area: Lock operation
1164  * @unlock_area: Unlock operation
1165  * @setup_read_retry: Set the read-retry mode (mostly needed for MLC NANDs)
1166  * @choose_interface_config: Choose the best interface configuration
1167  */
1168 struct nand_chip_ops {
1169     int (*suspend)(struct nand_chip *chip);
1170     void (*resume)(struct nand_chip *chip);
1171     int (*lock_area)(struct nand_chip *chip, loff_t ofs, uint64_t len);
1172     int (*unlock_area)(struct nand_chip *chip, loff_t ofs, uint64_t len);
1173     int (*setup_read_retry)(struct nand_chip *chip, int retry_mode);
1174     int (*choose_interface_config)(struct nand_chip *chip,
1175                        struct nand_interface_config *iface);
1176 };
1177 
1178 /**
1179  * struct nand_manufacturer - NAND manufacturer structure
1180  * @desc: The manufacturer description
1181  * @priv: Private information for the manufacturer driver
1182  */
1183 struct nand_manufacturer {
1184     const struct nand_manufacturer_desc *desc;
1185     void *priv;
1186 };
1187 
1188 /**
1189  * struct nand_secure_region - NAND secure region structure
1190  * @offset: Offset of the start of the secure region
1191  * @size: Size of the secure region
1192  */
1193 struct nand_secure_region {
1194     u64 offset;
1195     u64 size;
1196 };
1197 
1198 /**
1199  * struct nand_chip - NAND Private Flash Chip Data
1200  * @base: Inherit from the generic NAND device
1201  * @id: Holds NAND ID
1202  * @parameters: Holds generic parameters under an easily readable form
1203  * @manufacturer: Manufacturer information
1204  * @ops: NAND chip operations
1205  * @legacy: All legacy fields/hooks. If you develop a new driver, don't even try
1206  *          to use any of these fields/hooks, and if you're modifying an
1207  *          existing driver that is using those fields/hooks, you should
1208  *          consider reworking the driver and avoid using them.
1209  * @options: Various chip options. They can partly be set to inform nand_scan
1210  *           about special functionality. See the defines for further
1211  *           explanation.
1212  * @current_interface_config: The currently used NAND interface configuration
1213  * @best_interface_config: The best NAND interface configuration which fits both
1214  *                         the NAND chip and NAND controller constraints. If
1215  *                         unset, the default reset interface configuration must
1216  *                         be used.
1217  * @bbt_erase_shift: Number of address bits in a bbt entry
1218  * @bbt_options: Bad block table specific options. All options used here must
1219  *               come from bbm.h. By default, these options will be copied to
1220  *               the appropriate nand_bbt_descr's.
1221  * @badblockpos: Bad block marker position in the oob area
1222  * @badblockbits: Minimum number of set bits in a good block's bad block marker
1223  *                position; i.e., BBM = 11110111b is good when badblockbits = 7
1224  * @bbt_td: Bad block table descriptor for flash lookup
1225  * @bbt_md: Bad block table mirror descriptor
1226  * @badblock_pattern: Bad block scan pattern used for initial bad block scan
1227  * @bbt: Bad block table pointer
1228  * @page_shift: Number of address bits in a page (column address bits)
1229  * @phys_erase_shift: Number of address bits in a physical eraseblock
1230  * @chip_shift: Number of address bits in one chip
1231  * @pagemask: Page number mask = number of (pages / chip) - 1
1232  * @subpagesize: Holds the subpagesize
1233  * @data_buf: Buffer for data, size is (page size + oobsize)
1234  * @oob_poi: pointer on the OOB area covered by data_buf
1235  * @pagecache: Structure containing page cache related fields
1236  * @pagecache.bitflips: Number of bitflips of the cached page
1237  * @pagecache.page: Page number currently in the cache. -1 means no page is
1238  *                  currently cached
1239  * @buf_align: Minimum buffer alignment required by a platform
1240  * @lock: Lock protecting the suspended field. Also used to serialize accesses
1241  *        to the NAND device
1242  * @suspended: Set to 1 when the device is suspended, 0 when it's not
1243  * @resume_wq: wait queue to sleep if rawnand is in suspended state.
1244  * @cur_cs: Currently selected target. -1 means no target selected, otherwise we
1245  *          should always have cur_cs >= 0 && cur_cs < nanddev_ntargets().
1246  *          NAND Controller drivers should not modify this value, but they're
1247  *          allowed to read it.
1248  * @read_retries: The number of read retry modes supported
1249  * @secure_regions: Structure containing the secure regions info
1250  * @nr_secure_regions: Number of secure regions
1251  * @controller: The hardware controller structure which is shared among multiple
1252  *              independent devices
1253  * @ecc: The ECC controller structure
1254  * @priv: Chip private data
1255  */
1256 struct nand_chip {
1257     struct nand_device base;
1258     struct nand_id id;
1259     struct nand_parameters parameters;
1260     struct nand_manufacturer manufacturer;
1261     struct nand_chip_ops ops;
1262     struct nand_legacy legacy;
1263     unsigned int options;
1264 
1265     /* Data interface */
1266     const struct nand_interface_config *current_interface_config;
1267     struct nand_interface_config *best_interface_config;
1268 
1269     /* Bad block information */
1270     unsigned int bbt_erase_shift;
1271     unsigned int bbt_options;
1272     unsigned int badblockpos;
1273     unsigned int badblockbits;
1274     struct nand_bbt_descr *bbt_td;
1275     struct nand_bbt_descr *bbt_md;
1276     struct nand_bbt_descr *badblock_pattern;
1277     u8 *bbt;
1278 
1279     /* Device internal layout */
1280     unsigned int page_shift;
1281     unsigned int phys_erase_shift;
1282     unsigned int chip_shift;
1283     unsigned int pagemask;
1284     unsigned int subpagesize;
1285 
1286     /* Buffers */
1287     u8 *data_buf;
1288     u8 *oob_poi;
1289     struct {
1290         unsigned int bitflips;
1291         int page;
1292     } pagecache;
1293     unsigned long buf_align;
1294 
1295     /* Internals */
1296     struct mutex lock;
1297     unsigned int suspended : 1;
1298     wait_queue_head_t resume_wq;
1299     int cur_cs;
1300     int read_retries;
1301     struct nand_secure_region *secure_regions;
1302     u8 nr_secure_regions;
1303 
1304     /* Externals */
1305     struct nand_controller *controller;
1306     struct nand_ecc_ctrl ecc;
1307     void *priv;
1308 };
1309 
1310 static inline struct nand_chip *mtd_to_nand(struct mtd_info *mtd)
1311 {
1312     return container_of(mtd, struct nand_chip, base.mtd);
1313 }
1314 
1315 static inline struct mtd_info *nand_to_mtd(struct nand_chip *chip)
1316 {
1317     return &chip->base.mtd;
1318 }
1319 
1320 static inline void *nand_get_controller_data(struct nand_chip *chip)
1321 {
1322     return chip->priv;
1323 }
1324 
1325 static inline void nand_set_controller_data(struct nand_chip *chip, void *priv)
1326 {
1327     chip->priv = priv;
1328 }
1329 
1330 static inline void nand_set_manufacturer_data(struct nand_chip *chip,
1331                           void *priv)
1332 {
1333     chip->manufacturer.priv = priv;
1334 }
1335 
1336 static inline void *nand_get_manufacturer_data(struct nand_chip *chip)
1337 {
1338     return chip->manufacturer.priv;
1339 }
1340 
1341 static inline void nand_set_flash_node(struct nand_chip *chip,
1342                        struct device_node *np)
1343 {
1344     mtd_set_of_node(nand_to_mtd(chip), np);
1345 }
1346 
1347 static inline struct device_node *nand_get_flash_node(struct nand_chip *chip)
1348 {
1349     return mtd_get_of_node(nand_to_mtd(chip));
1350 }
1351 
1352 /**
1353  * nand_get_interface_config - Retrieve the current interface configuration
1354  *                             of a NAND chip
1355  * @chip: The NAND chip
1356  */
1357 static inline const struct nand_interface_config *
1358 nand_get_interface_config(struct nand_chip *chip)
1359 {
1360     return chip->current_interface_config;
1361 }
1362 
1363 /*
1364  * A helper for defining older NAND chips where the second ID byte fully
1365  * defined the chip, including the geometry (chip size, eraseblock size, page
1366  * size). All these chips have 512 bytes NAND page size.
1367  */
1368 #define LEGACY_ID_NAND(nm, devid, chipsz, erasesz, opts)          \
1369     { .name = (nm), {{ .dev_id = (devid) }}, .pagesize = 512, \
1370       .chipsize = (chipsz), .erasesize = (erasesz), .options = (opts) }
1371 
1372 /*
1373  * A helper for defining newer chips which report their page size and
1374  * eraseblock size via the extended ID bytes.
1375  *
1376  * The real difference between LEGACY_ID_NAND and EXTENDED_ID_NAND is that with
1377  * EXTENDED_ID_NAND, manufacturers overloaded the same device ID so that the
1378  * device ID now only represented a particular total chip size (and voltage,
1379  * buswidth), and the page size, eraseblock size, and OOB size could vary while
1380  * using the same device ID.
1381  */
1382 #define EXTENDED_ID_NAND(nm, devid, chipsz, opts)                      \
1383     { .name = (nm), {{ .dev_id = (devid) }}, .chipsize = (chipsz), \
1384       .options = (opts) }
1385 
1386 #define NAND_ECC_INFO(_strength, _step) \
1387             { .strength_ds = (_strength), .step_ds = (_step) }
1388 #define NAND_ECC_STRENGTH(type)     ((type)->ecc.strength_ds)
1389 #define NAND_ECC_STEP(type)     ((type)->ecc.step_ds)
1390 
1391 /**
1392  * struct nand_flash_dev - NAND Flash Device ID Structure
1393  * @name: a human-readable name of the NAND chip
1394  * @dev_id: the device ID (the second byte of the full chip ID array)
1395  * @mfr_id: manufacturer ID part of the full chip ID array (refers the same
1396  *          memory address as ``id[0]``)
1397  * @dev_id: device ID part of the full chip ID array (refers the same memory
1398  *          address as ``id[1]``)
1399  * @id: full device ID array
1400  * @pagesize: size of the NAND page in bytes; if 0, then the real page size (as
1401  *            well as the eraseblock size) is determined from the extended NAND
1402  *            chip ID array)
1403  * @chipsize: total chip size in MiB
1404  * @erasesize: eraseblock size in bytes (determined from the extended ID if 0)
1405  * @options: stores various chip bit options
1406  * @id_len: The valid length of the @id.
1407  * @oobsize: OOB size
1408  * @ecc: ECC correctability and step information from the datasheet.
1409  * @ecc.strength_ds: The ECC correctability from the datasheet, same as the
1410  *                   @ecc_strength_ds in nand_chip{}.
1411  * @ecc.step_ds: The ECC step required by the @ecc.strength_ds, same as the
1412  *               @ecc_step_ds in nand_chip{}, also from the datasheet.
1413  *               For example, the "4bit ECC for each 512Byte" can be set with
1414  *               NAND_ECC_INFO(4, 512).
1415  */
1416 struct nand_flash_dev {
1417     char *name;
1418     union {
1419         struct {
1420             uint8_t mfr_id;
1421             uint8_t dev_id;
1422         };
1423         uint8_t id[NAND_MAX_ID_LEN];
1424     };
1425     unsigned int pagesize;
1426     unsigned int chipsize;
1427     unsigned int erasesize;
1428     unsigned int options;
1429     uint16_t id_len;
1430     uint16_t oobsize;
1431     struct {
1432         uint16_t strength_ds;
1433         uint16_t step_ds;
1434     } ecc;
1435 };
1436 
1437 int nand_create_bbt(struct nand_chip *chip);
1438 
1439 /*
1440  * Check if it is a SLC nand.
1441  * The !nand_is_slc() can be used to check the MLC/TLC nand chips.
1442  * We do not distinguish the MLC and TLC now.
1443  */
1444 static inline bool nand_is_slc(struct nand_chip *chip)
1445 {
1446     WARN(nanddev_bits_per_cell(&chip->base) == 0,
1447          "chip->bits_per_cell is used uninitialized\n");
1448     return nanddev_bits_per_cell(&chip->base) == 1;
1449 }
1450 
1451 /**
1452  * nand_opcode_8bits - Check if the opcode's address should be sent only on the
1453  *  lower 8 bits
1454  * @command: opcode to check
1455  */
1456 static inline int nand_opcode_8bits(unsigned int command)
1457 {
1458     switch (command) {
1459     case NAND_CMD_READID:
1460     case NAND_CMD_PARAM:
1461     case NAND_CMD_GET_FEATURES:
1462     case NAND_CMD_SET_FEATURES:
1463         return 1;
1464     default:
1465         break;
1466     }
1467     return 0;
1468 }
1469 
1470 int rawnand_sw_hamming_init(struct nand_chip *chip);
1471 int rawnand_sw_hamming_calculate(struct nand_chip *chip,
1472                  const unsigned char *buf,
1473                  unsigned char *code);
1474 int rawnand_sw_hamming_correct(struct nand_chip *chip,
1475                    unsigned char *buf,
1476                    unsigned char *read_ecc,
1477                    unsigned char *calc_ecc);
1478 void rawnand_sw_hamming_cleanup(struct nand_chip *chip);
1479 int rawnand_sw_bch_init(struct nand_chip *chip);
1480 int rawnand_sw_bch_correct(struct nand_chip *chip, unsigned char *buf,
1481                unsigned char *read_ecc, unsigned char *calc_ecc);
1482 void rawnand_sw_bch_cleanup(struct nand_chip *chip);
1483 
1484 int nand_check_erased_ecc_chunk(void *data, int datalen,
1485                 void *ecc, int ecclen,
1486                 void *extraoob, int extraooblen,
1487                 int threshold);
1488 
1489 int nand_ecc_choose_conf(struct nand_chip *chip,
1490              const struct nand_ecc_caps *caps, int oobavail);
1491 
1492 /* Default write_oob implementation */
1493 int nand_write_oob_std(struct nand_chip *chip, int page);
1494 
1495 /* Default read_oob implementation */
1496 int nand_read_oob_std(struct nand_chip *chip, int page);
1497 
1498 /* Stub used by drivers that do not support GET/SET FEATURES operations */
1499 int nand_get_set_features_notsupp(struct nand_chip *chip, int addr,
1500                   u8 *subfeature_param);
1501 
1502 /* read_page_raw implementations */
1503 int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
1504                int page);
1505 int nand_monolithic_read_page_raw(struct nand_chip *chip, uint8_t *buf,
1506                   int oob_required, int page);
1507 
1508 /* write_page_raw implementations */
1509 int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
1510             int oob_required, int page);
1511 int nand_monolithic_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
1512                    int oob_required, int page);
1513 
1514 /* Reset and initialize a NAND device */
1515 int nand_reset(struct nand_chip *chip, int chipnr);
1516 
1517 /* NAND operation helpers */
1518 int nand_reset_op(struct nand_chip *chip);
1519 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1520            unsigned int len);
1521 int nand_status_op(struct nand_chip *chip, u8 *status);
1522 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock);
1523 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1524               unsigned int offset_in_page, void *buf, unsigned int len);
1525 int nand_change_read_column_op(struct nand_chip *chip,
1526                    unsigned int offset_in_page, void *buf,
1527                    unsigned int len, bool force_8bit);
1528 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1529              unsigned int offset_in_page, void *buf, unsigned int len);
1530 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1531                 unsigned int offset_in_page, const void *buf,
1532                 unsigned int len);
1533 int nand_prog_page_end_op(struct nand_chip *chip);
1534 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1535               unsigned int offset_in_page, const void *buf,
1536               unsigned int len);
1537 int nand_change_write_column_op(struct nand_chip *chip,
1538                 unsigned int offset_in_page, const void *buf,
1539                 unsigned int len, bool force_8bit);
1540 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
1541               bool force_8bit, bool check_only);
1542 int nand_write_data_op(struct nand_chip *chip, const void *buf,
1543                unsigned int len, bool force_8bit);
1544 int nand_read_page_hwecc_oob_first(struct nand_chip *chip, uint8_t *buf,
1545                    int oob_required, int page);
1546 
1547 /* Scan and identify a NAND device */
1548 int nand_scan_with_ids(struct nand_chip *chip, unsigned int max_chips,
1549                struct nand_flash_dev *ids);
1550 
1551 static inline int nand_scan(struct nand_chip *chip, unsigned int max_chips)
1552 {
1553     return nand_scan_with_ids(chip, max_chips, NULL);
1554 }
1555 
1556 /* Internal helper for board drivers which need to override command function */
1557 void nand_wait_ready(struct nand_chip *chip);
1558 
1559 /*
1560  * Free resources held by the NAND device, must be called on error after a
1561  * sucessful nand_scan().
1562  */
1563 void nand_cleanup(struct nand_chip *chip);
1564 
1565 /*
1566  * External helper for controller drivers that have to implement the WAITRDY
1567  * instruction and have no physical pin to check it.
1568  */
1569 int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms);
1570 int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
1571               unsigned long timeout_ms);
1572 
1573 /* Select/deselect a NAND target. */
1574 void nand_select_target(struct nand_chip *chip, unsigned int cs);
1575 void nand_deselect_target(struct nand_chip *chip);
1576 
1577 /* Bitops */
1578 void nand_extract_bits(u8 *dst, unsigned int dst_off, const u8 *src,
1579                unsigned int src_off, unsigned int nbits);
1580 
1581 /**
1582  * nand_get_data_buf() - Get the internal page buffer
1583  * @chip: NAND chip object
1584  *
1585  * Returns the pre-allocated page buffer after invalidating the cache. This
1586  * function should be used by drivers that do not want to allocate their own
1587  * bounce buffer and still need such a buffer for specific operations (most
1588  * commonly when reading OOB data only).
1589  *
1590  * Be careful to never call this function in the write/write_oob path, because
1591  * the core may have placed the data to be written out in this buffer.
1592  *
1593  * Return: pointer to the page cache buffer
1594  */
1595 static inline void *nand_get_data_buf(struct nand_chip *chip)
1596 {
1597     chip->pagecache.page = -1;
1598 
1599     return chip->data_buf;
1600 }
1601 
1602 /* Parse the gpio-cs property */
1603 int rawnand_dt_parse_gpio_cs(struct device *dev, struct gpio_desc ***cs_array,
1604                  unsigned int *ncs_array);
1605 
1606 #endif /* __LINUX_MTD_RAWNAND_H */