mtd: rawnand: Add a kernel doc to the ECC algorithm enumeration
[linux-2.6-microblaze.git] / include / linux / mtd / rawnand.h
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /*
3  *  Copyright © 2000-2010 David Woodhouse <dwmw2@infradead.org>
4  *                        Steven J. Hill <sjhill@realitydiluted.com>
5  *                        Thomas Gleixner <tglx@linutronix.de>
6  *
7  * Info:
8  *      Contains standard defines and IDs for NAND flash devices
9  *
10  * Changelog:
11  *      See git changelog.
12  */
13 #ifndef __LINUX_MTD_RAWNAND_H
14 #define __LINUX_MTD_RAWNAND_H
15
16 #include <linux/mtd/mtd.h>
17 #include <linux/mtd/flashchip.h>
18 #include <linux/mtd/bbm.h>
19 #include <linux/mtd/jedec.h>
20 #include <linux/mtd/nand.h>
21 #include <linux/mtd/onfi.h>
22 #include <linux/mutex.h>
23 #include <linux/of.h>
24 #include <linux/types.h>
25
26 struct nand_chip;
27
28 /* The maximum number of NAND chips in an array */
29 #define NAND_MAX_CHIPS          8
30
31 /*
32  * Constants for hardware specific CLE/ALE/NCE function
33  *
34  * These are bits which can be or'ed to set/clear multiple
35  * bits in one go.
36  */
37 /* Select the chip by setting nCE to low */
38 #define NAND_NCE                0x01
39 /* Select the command latch by setting CLE to high */
40 #define NAND_CLE                0x02
41 /* Select the address latch by setting ALE to high */
42 #define NAND_ALE                0x04
43
44 #define NAND_CTRL_CLE           (NAND_NCE | NAND_CLE)
45 #define NAND_CTRL_ALE           (NAND_NCE | NAND_ALE)
46 #define NAND_CTRL_CHANGE        0x80
47
48 /*
49  * Standard NAND flash commands
50  */
51 #define NAND_CMD_READ0          0
52 #define NAND_CMD_READ1          1
53 #define NAND_CMD_RNDOUT         5
54 #define NAND_CMD_PAGEPROG       0x10
55 #define NAND_CMD_READOOB        0x50
56 #define NAND_CMD_ERASE1         0x60
57 #define NAND_CMD_STATUS         0x70
58 #define NAND_CMD_SEQIN          0x80
59 #define NAND_CMD_RNDIN          0x85
60 #define NAND_CMD_READID         0x90
61 #define NAND_CMD_ERASE2         0xd0
62 #define NAND_CMD_PARAM          0xec
63 #define NAND_CMD_GET_FEATURES   0xee
64 #define NAND_CMD_SET_FEATURES   0xef
65 #define NAND_CMD_RESET          0xff
66
67 /* Extended commands for large page devices */
68 #define NAND_CMD_READSTART      0x30
69 #define NAND_CMD_RNDOUTSTART    0xE0
70 #define NAND_CMD_CACHEDPROG     0x15
71
72 #define NAND_CMD_NONE           -1
73
74 /* Status bits */
75 #define NAND_STATUS_FAIL        0x01
76 #define NAND_STATUS_FAIL_N1     0x02
77 #define NAND_STATUS_TRUE_READY  0x20
78 #define NAND_STATUS_READY       0x40
79 #define NAND_STATUS_WP          0x80
80
81 #define NAND_DATA_IFACE_CHECK_ONLY      -1
82
83 /*
84  * Constants for ECC_MODES
85  */
86 enum nand_ecc_mode {
87         NAND_ECC_INVALID,
88         NAND_ECC_NONE,
89         NAND_ECC_SOFT,
90         NAND_ECC_HW,
91         NAND_ECC_HW_SYNDROME,
92         NAND_ECC_ON_DIE,
93 };
94
95 /**
96  * enum nand_ecc_algo - NAND ECC algorithm
97  * @NAND_ECC_UNKNOWN: Unknown algorithm
98  * @NAND_ECC_HAMMING: Hamming algorithm
99  * @NAND_ECC_BCH: Bose-Chaudhuri-Hocquenghem algorithm
100  * @NAND_ECC_RS: Reed-Solomon algorithm
101  */
102 enum nand_ecc_algo {
103         NAND_ECC_UNKNOWN,
104         NAND_ECC_HAMMING,
105         NAND_ECC_BCH,
106         NAND_ECC_RS,
107 };
108
109 /*
110  * Constants for Hardware ECC
111  */
112 /* Reset Hardware ECC for read */
113 #define NAND_ECC_READ           0
114 /* Reset Hardware ECC for write */
115 #define NAND_ECC_WRITE          1
116 /* Enable Hardware ECC before syndrome is read back from flash */
117 #define NAND_ECC_READSYN        2
118
119 /*
120  * Enable generic NAND 'page erased' check. This check is only done when
121  * ecc.correct() returns -EBADMSG.
122  * Set this flag if your implementation does not fix bitflips in erased
123  * pages and you want to rely on the default implementation.
124  */
125 #define NAND_ECC_GENERIC_ERASED_CHECK   BIT(0)
126 #define NAND_ECC_MAXIMIZE               BIT(1)
127
128 /*
129  * Option constants for bizarre disfunctionality and real
130  * features.
131  */
132
133 /* Buswidth is 16 bit */
134 #define NAND_BUSWIDTH_16        BIT(1)
135
136 /*
137  * When using software implementation of Hamming, we can specify which byte
138  * ordering should be used.
139  */
140 #define NAND_ECC_SOFT_HAMMING_SM_ORDER  BIT(2)
141
142 /* Chip has cache program function */
143 #define NAND_CACHEPRG           BIT(3)
144 /* Options valid for Samsung large page devices */
145 #define NAND_SAMSUNG_LP_OPTIONS NAND_CACHEPRG
146
147 /*
148  * Chip requires ready check on read (for auto-incremented sequential read).
149  * True only for small page devices; large page devices do not support
150  * autoincrement.
151  */
152 #define NAND_NEED_READRDY       BIT(8)
153
154 /* Chip does not allow subpage writes */
155 #define NAND_NO_SUBPAGE_WRITE   BIT(9)
156
157 /* Device is one of 'new' xD cards that expose fake nand command set */
158 #define NAND_BROKEN_XD          BIT(10)
159
160 /* Device behaves just like nand, but is readonly */
161 #define NAND_ROM                BIT(11)
162
163 /* Device supports subpage reads */
164 #define NAND_SUBPAGE_READ       BIT(12)
165 /* Macros to identify the above */
166 #define NAND_HAS_SUBPAGE_READ(chip) ((chip->options & NAND_SUBPAGE_READ))
167
168 /*
169  * Some MLC NANDs need data scrambling to limit bitflips caused by repeated
170  * patterns.
171  */
172 #define NAND_NEED_SCRAMBLING    BIT(13)
173
174 /* Device needs 3rd row address cycle */
175 #define NAND_ROW_ADDR_3         BIT(14)
176
177 /* Non chip related options */
178 /* This option skips the bbt scan during initialization. */
179 #define NAND_SKIP_BBTSCAN       BIT(16)
180 /* Chip may not exist, so silence any errors in scan */
181 #define NAND_SCAN_SILENT_NODEV  BIT(18)
182
183 /*
184  * Autodetect nand buswidth with readid/onfi.
185  * This suppose the driver will configure the hardware in 8 bits mode
186  * when calling nand_scan_ident, and update its configuration
187  * before calling nand_scan_tail.
188  */
189 #define NAND_BUSWIDTH_AUTO      BIT(19)
190
191 /*
192  * This option could be defined by controller drivers to protect against
193  * kmap'ed, vmalloc'ed highmem buffers being passed from upper layers
194  */
195 #define NAND_USES_DMA           BIT(20)
196
197 /*
198  * In case your controller is implementing ->legacy.cmd_ctrl() and is relying
199  * on the default ->cmdfunc() implementation, you may want to let the core
200  * handle the tCCS delay which is required when a column change (RNDIN or
201  * RNDOUT) is requested.
202  * If your controller already takes care of this delay, you don't need to set
203  * this flag.
204  */
205 #define NAND_WAIT_TCCS          BIT(21)
206
207 /*
208  * Whether the NAND chip is a boot medium. Drivers might use this information
209  * to select ECC algorithms supported by the boot ROM or similar restrictions.
210  */
211 #define NAND_IS_BOOT_MEDIUM     BIT(22)
212
213 /*
214  * Do not try to tweak the timings at runtime. This is needed when the
215  * controller initializes the timings on itself or when it relies on
216  * configuration done by the bootloader.
217  */
218 #define NAND_KEEP_TIMINGS       BIT(23)
219
220 /*
221  * There are different places where the manufacturer stores the factory bad
222  * block markers.
223  *
224  * Position within the block: Each of these pages needs to be checked for a
225  * bad block marking pattern.
226  */
227 #define NAND_BBM_FIRSTPAGE      BIT(24)
228 #define NAND_BBM_SECONDPAGE     BIT(25)
229 #define NAND_BBM_LASTPAGE       BIT(26)
230
231 /*
232  * Some controllers with pipelined ECC engines override the BBM marker with
233  * data or ECC bytes, thus making bad block detection through bad block marker
234  * impossible. Let's flag those chips so the core knows it shouldn't check the
235  * BBM and consider all blocks good.
236  */
237 #define NAND_NO_BBM_QUIRK       BIT(27)
238
239 /* Cell info constants */
240 #define NAND_CI_CHIPNR_MSK      0x03
241 #define NAND_CI_CELLTYPE_MSK    0x0C
242 #define NAND_CI_CELLTYPE_SHIFT  2
243
244 /* Position within the OOB data of the page */
245 #define NAND_BBM_POS_SMALL              5
246 #define NAND_BBM_POS_LARGE              0
247
248 /**
249  * struct nand_parameters - NAND generic parameters from the parameter page
250  * @model: Model name
251  * @supports_set_get_features: The NAND chip supports setting/getting features
252  * @set_feature_list: Bitmap of features that can be set
253  * @get_feature_list: Bitmap of features that can be get
254  * @onfi: ONFI specific parameters
255  */
256 struct nand_parameters {
257         /* Generic parameters */
258         const char *model;
259         bool supports_set_get_features;
260         DECLARE_BITMAP(set_feature_list, ONFI_FEATURE_NUMBER);
261         DECLARE_BITMAP(get_feature_list, ONFI_FEATURE_NUMBER);
262
263         /* ONFI parameters */
264         struct onfi_params *onfi;
265 };
266
267 /* The maximum expected count of bytes in the NAND ID sequence */
268 #define NAND_MAX_ID_LEN 8
269
270 /**
271  * struct nand_id - NAND id structure
272  * @data: buffer containing the id bytes.
273  * @len: ID length.
274  */
275 struct nand_id {
276         u8 data[NAND_MAX_ID_LEN];
277         int len;
278 };
279
280 /**
281  * struct nand_ecc_step_info - ECC step information of ECC engine
282  * @stepsize: data bytes per ECC step
283  * @strengths: array of supported strengths
284  * @nstrengths: number of supported strengths
285  */
286 struct nand_ecc_step_info {
287         int stepsize;
288         const int *strengths;
289         int nstrengths;
290 };
291
292 /**
293  * struct nand_ecc_caps - capability of ECC engine
294  * @stepinfos: array of ECC step information
295  * @nstepinfos: number of ECC step information
296  * @calc_ecc_bytes: driver's hook to calculate ECC bytes per step
297  */
298 struct nand_ecc_caps {
299         const struct nand_ecc_step_info *stepinfos;
300         int nstepinfos;
301         int (*calc_ecc_bytes)(int step_size, int strength);
302 };
303
304 /* a shorthand to generate struct nand_ecc_caps with only one ECC stepsize */
305 #define NAND_ECC_CAPS_SINGLE(__name, __calc, __step, ...)       \
306 static const int __name##_strengths[] = { __VA_ARGS__ };        \
307 static const struct nand_ecc_step_info __name##_stepinfo = {    \
308         .stepsize = __step,                                     \
309         .strengths = __name##_strengths,                        \
310         .nstrengths = ARRAY_SIZE(__name##_strengths),           \
311 };                                                              \
312 static const struct nand_ecc_caps __name = {                    \
313         .stepinfos = &__name##_stepinfo,                        \
314         .nstepinfos = 1,                                        \
315         .calc_ecc_bytes = __calc,                               \
316 }
317
318 /**
319  * struct nand_ecc_ctrl - Control structure for ECC
320  * @mode:       ECC mode
321  * @algo:       ECC algorithm
322  * @steps:      number of ECC steps per page
323  * @size:       data bytes per ECC step
324  * @bytes:      ECC bytes per step
325  * @strength:   max number of correctible bits per ECC step
326  * @total:      total number of ECC bytes per page
327  * @prepad:     padding information for syndrome based ECC generators
328  * @postpad:    padding information for syndrome based ECC generators
329  * @options:    ECC specific options (see NAND_ECC_XXX flags defined above)
330  * @priv:       pointer to private ECC control data
331  * @calc_buf:   buffer for calculated ECC, size is oobsize.
332  * @code_buf:   buffer for ECC read from flash, size is oobsize.
333  * @hwctl:      function to control hardware ECC generator. Must only
334  *              be provided if an hardware ECC is available
335  * @calculate:  function for ECC calculation or readback from ECC hardware
336  * @correct:    function for ECC correction, matching to ECC generator (sw/hw).
337  *              Should return a positive number representing the number of
338  *              corrected bitflips, -EBADMSG if the number of bitflips exceed
339  *              ECC strength, or any other error code if the error is not
340  *              directly related to correction.
341  *              If -EBADMSG is returned the input buffers should be left
342  *              untouched.
343  * @read_page_raw:      function to read a raw page without ECC. This function
344  *                      should hide the specific layout used by the ECC
345  *                      controller and always return contiguous in-band and
346  *                      out-of-band data even if they're not stored
347  *                      contiguously on the NAND chip (e.g.
348  *                      NAND_ECC_HW_SYNDROME interleaves in-band and
349  *                      out-of-band data).
350  * @write_page_raw:     function to write a raw page without ECC. This function
351  *                      should hide the specific layout used by the ECC
352  *                      controller and consider the passed data as contiguous
353  *                      in-band and out-of-band data. ECC controller is
354  *                      responsible for doing the appropriate transformations
355  *                      to adapt to its specific layout (e.g.
356  *                      NAND_ECC_HW_SYNDROME interleaves in-band and
357  *                      out-of-band data).
358  * @read_page:  function to read a page according to the ECC generator
359  *              requirements; returns maximum number of bitflips corrected in
360  *              any single ECC step, -EIO hw error
361  * @read_subpage:       function to read parts of the page covered by ECC;
362  *                      returns same as read_page()
363  * @write_subpage:      function to write parts of the page covered by ECC.
364  * @write_page: function to write a page according to the ECC generator
365  *              requirements.
366  * @write_oob_raw:      function to write chip OOB data without ECC
367  * @read_oob_raw:       function to read chip OOB data without ECC
368  * @read_oob:   function to read chip OOB data
369  * @write_oob:  function to write chip OOB data
370  */
371 struct nand_ecc_ctrl {
372         enum nand_ecc_mode mode;
373         enum nand_ecc_algo algo;
374         int steps;
375         int size;
376         int bytes;
377         int total;
378         int strength;
379         int prepad;
380         int postpad;
381         unsigned int options;
382         void *priv;
383         u8 *calc_buf;
384         u8 *code_buf;
385         void (*hwctl)(struct nand_chip *chip, int mode);
386         int (*calculate)(struct nand_chip *chip, const uint8_t *dat,
387                          uint8_t *ecc_code);
388         int (*correct)(struct nand_chip *chip, uint8_t *dat, uint8_t *read_ecc,
389                        uint8_t *calc_ecc);
390         int (*read_page_raw)(struct nand_chip *chip, uint8_t *buf,
391                              int oob_required, int page);
392         int (*write_page_raw)(struct nand_chip *chip, const uint8_t *buf,
393                               int oob_required, int page);
394         int (*read_page)(struct nand_chip *chip, uint8_t *buf,
395                          int oob_required, int page);
396         int (*read_subpage)(struct nand_chip *chip, uint32_t offs,
397                             uint32_t len, uint8_t *buf, int page);
398         int (*write_subpage)(struct nand_chip *chip, uint32_t offset,
399                              uint32_t data_len, const uint8_t *data_buf,
400                              int oob_required, int page);
401         int (*write_page)(struct nand_chip *chip, const uint8_t *buf,
402                           int oob_required, int page);
403         int (*write_oob_raw)(struct nand_chip *chip, int page);
404         int (*read_oob_raw)(struct nand_chip *chip, int page);
405         int (*read_oob)(struct nand_chip *chip, int page);
406         int (*write_oob)(struct nand_chip *chip, int page);
407 };
408
409 /**
410  * struct nand_sdr_timings - SDR NAND chip timings
411  *
412  * This struct defines the timing requirements of a SDR NAND chip.
413  * These information can be found in every NAND datasheets and the timings
414  * meaning are described in the ONFI specifications:
415  * www.onfi.org/~/media/ONFI/specs/onfi_3_1_spec.pdf (chapter 4.15 Timing
416  * Parameters)
417  *
418  * All these timings are expressed in picoseconds.
419  *
420  * @tBERS_max: Block erase time
421  * @tCCS_min: Change column setup time
422  * @tPROG_max: Page program time
423  * @tR_max: Page read time
424  * @tALH_min: ALE hold time
425  * @tADL_min: ALE to data loading time
426  * @tALS_min: ALE setup time
427  * @tAR_min: ALE to RE# delay
428  * @tCEA_max: CE# access time
429  * @tCEH_min: CE# high hold time
430  * @tCH_min:  CE# hold time
431  * @tCHZ_max: CE# high to output hi-Z
432  * @tCLH_min: CLE hold time
433  * @tCLR_min: CLE to RE# delay
434  * @tCLS_min: CLE setup time
435  * @tCOH_min: CE# high to output hold
436  * @tCS_min: CE# setup time
437  * @tDH_min: Data hold time
438  * @tDS_min: Data setup time
439  * @tFEAT_max: Busy time for Set Features and Get Features
440  * @tIR_min: Output hi-Z to RE# low
441  * @tITC_max: Interface and Timing Mode Change time
442  * @tRC_min: RE# cycle time
443  * @tREA_max: RE# access time
444  * @tREH_min: RE# high hold time
445  * @tRHOH_min: RE# high to output hold
446  * @tRHW_min: RE# high to WE# low
447  * @tRHZ_max: RE# high to output hi-Z
448  * @tRLOH_min: RE# low to output hold
449  * @tRP_min: RE# pulse width
450  * @tRR_min: Ready to RE# low (data only)
451  * @tRST_max: Device reset time, measured from the falling edge of R/B# to the
452  *            rising edge of R/B#.
453  * @tWB_max: WE# high to SR[6] low
454  * @tWC_min: WE# cycle time
455  * @tWH_min: WE# high hold time
456  * @tWHR_min: WE# high to RE# low
457  * @tWP_min: WE# pulse width
458  * @tWW_min: WP# transition to WE# low
459  */
460 struct nand_sdr_timings {
461         u64 tBERS_max;
462         u32 tCCS_min;
463         u64 tPROG_max;
464         u64 tR_max;
465         u32 tALH_min;
466         u32 tADL_min;
467         u32 tALS_min;
468         u32 tAR_min;
469         u32 tCEA_max;
470         u32 tCEH_min;
471         u32 tCH_min;
472         u32 tCHZ_max;
473         u32 tCLH_min;
474         u32 tCLR_min;
475         u32 tCLS_min;
476         u32 tCOH_min;
477         u32 tCS_min;
478         u32 tDH_min;
479         u32 tDS_min;
480         u32 tFEAT_max;
481         u32 tIR_min;
482         u32 tITC_max;
483         u32 tRC_min;
484         u32 tREA_max;
485         u32 tREH_min;
486         u32 tRHOH_min;
487         u32 tRHW_min;
488         u32 tRHZ_max;
489         u32 tRLOH_min;
490         u32 tRP_min;
491         u32 tRR_min;
492         u64 tRST_max;
493         u32 tWB_max;
494         u32 tWC_min;
495         u32 tWH_min;
496         u32 tWHR_min;
497         u32 tWP_min;
498         u32 tWW_min;
499 };
500
501 /**
502  * enum nand_interface_type - NAND interface type
503  * @NAND_SDR_IFACE:     Single Data Rate interface
504  */
505 enum nand_interface_type {
506         NAND_SDR_IFACE,
507 };
508
509 /**
510  * struct nand_interface_config - NAND interface timing
511  * @type:        type of the timing
512  * @timings:     The timing information
513  * @timings.mode: Timing mode as defined in the specification
514  * @timings.sdr: Use it when @type is %NAND_SDR_IFACE.
515  */
516 struct nand_interface_config {
517         enum nand_interface_type type;
518         struct nand_timings {
519                 unsigned int mode;
520                 union {
521                         struct nand_sdr_timings sdr;
522                 };
523         } timings;
524 };
525
526 /**
527  * nand_get_sdr_timings - get SDR timing from data interface
528  * @conf:       The data interface
529  */
530 static inline const struct nand_sdr_timings *
531 nand_get_sdr_timings(const struct nand_interface_config *conf)
532 {
533         if (conf->type != NAND_SDR_IFACE)
534                 return ERR_PTR(-EINVAL);
535
536         return &conf->timings.sdr;
537 }
538
539 /**
540  * struct nand_op_cmd_instr - Definition of a command instruction
541  * @opcode: the command to issue in one cycle
542  */
543 struct nand_op_cmd_instr {
544         u8 opcode;
545 };
546
547 /**
548  * struct nand_op_addr_instr - Definition of an address instruction
549  * @naddrs: length of the @addrs array
550  * @addrs: array containing the address cycles to issue
551  */
552 struct nand_op_addr_instr {
553         unsigned int naddrs;
554         const u8 *addrs;
555 };
556
557 /**
558  * struct nand_op_data_instr - Definition of a data instruction
559  * @len: number of data bytes to move
560  * @buf: buffer to fill
561  * @buf.in: buffer to fill when reading from the NAND chip
562  * @buf.out: buffer to read from when writing to the NAND chip
563  * @force_8bit: force 8-bit access
564  *
565  * Please note that "in" and "out" are inverted from the ONFI specification
566  * and are from the controller perspective, so a "in" is a read from the NAND
567  * chip while a "out" is a write to the NAND chip.
568  */
569 struct nand_op_data_instr {
570         unsigned int len;
571         union {
572                 void *in;
573                 const void *out;
574         } buf;
575         bool force_8bit;
576 };
577
578 /**
579  * struct nand_op_waitrdy_instr - Definition of a wait ready instruction
580  * @timeout_ms: maximum delay while waiting for the ready/busy pin in ms
581  */
582 struct nand_op_waitrdy_instr {
583         unsigned int timeout_ms;
584 };
585
586 /**
587  * enum nand_op_instr_type - Definition of all instruction types
588  * @NAND_OP_CMD_INSTR: command instruction
589  * @NAND_OP_ADDR_INSTR: address instruction
590  * @NAND_OP_DATA_IN_INSTR: data in instruction
591  * @NAND_OP_DATA_OUT_INSTR: data out instruction
592  * @NAND_OP_WAITRDY_INSTR: wait ready instruction
593  */
594 enum nand_op_instr_type {
595         NAND_OP_CMD_INSTR,
596         NAND_OP_ADDR_INSTR,
597         NAND_OP_DATA_IN_INSTR,
598         NAND_OP_DATA_OUT_INSTR,
599         NAND_OP_WAITRDY_INSTR,
600 };
601
602 /**
603  * struct nand_op_instr - Instruction object
604  * @type: the instruction type
605  * @ctx:  extra data associated to the instruction. You'll have to use the
606  *        appropriate element depending on @type
607  * @ctx.cmd: use it if @type is %NAND_OP_CMD_INSTR
608  * @ctx.addr: use it if @type is %NAND_OP_ADDR_INSTR
609  * @ctx.data: use it if @type is %NAND_OP_DATA_IN_INSTR
610  *            or %NAND_OP_DATA_OUT_INSTR
611  * @ctx.waitrdy: use it if @type is %NAND_OP_WAITRDY_INSTR
612  * @delay_ns: delay the controller should apply after the instruction has been
613  *            issued on the bus. Most modern controllers have internal timings
614  *            control logic, and in this case, the controller driver can ignore
615  *            this field.
616  */
617 struct nand_op_instr {
618         enum nand_op_instr_type type;
619         union {
620                 struct nand_op_cmd_instr cmd;
621                 struct nand_op_addr_instr addr;
622                 struct nand_op_data_instr data;
623                 struct nand_op_waitrdy_instr waitrdy;
624         } ctx;
625         unsigned int delay_ns;
626 };
627
628 /*
629  * Special handling must be done for the WAITRDY timeout parameter as it usually
630  * is either tPROG (after a prog), tR (before a read), tRST (during a reset) or
631  * tBERS (during an erase) which all of them are u64 values that cannot be
632  * divided by usual kernel macros and must be handled with the special
633  * DIV_ROUND_UP_ULL() macro.
634  *
635  * Cast to type of dividend is needed here to guarantee that the result won't
636  * be an unsigned long long when the dividend is an unsigned long (or smaller),
637  * which is what the compiler does when it sees ternary operator with 2
638  * different return types (picks the largest type to make sure there's no
639  * loss).
640  */
641 #define __DIVIDE(dividend, divisor) ({                                          \
642         (__typeof__(dividend))(sizeof(dividend) <= sizeof(unsigned long) ?      \
643                                DIV_ROUND_UP(dividend, divisor) :                \
644                                DIV_ROUND_UP_ULL(dividend, divisor));            \
645         })
646 #define PSEC_TO_NSEC(x) __DIVIDE(x, 1000)
647 #define PSEC_TO_MSEC(x) __DIVIDE(x, 1000000000)
648
649 #define NAND_OP_CMD(id, ns)                                             \
650         {                                                               \
651                 .type = NAND_OP_CMD_INSTR,                              \
652                 .ctx.cmd.opcode = id,                                   \
653                 .delay_ns = ns,                                         \
654         }
655
656 #define NAND_OP_ADDR(ncycles, cycles, ns)                               \
657         {                                                               \
658                 .type = NAND_OP_ADDR_INSTR,                             \
659                 .ctx.addr = {                                           \
660                         .naddrs = ncycles,                              \
661                         .addrs = cycles,                                \
662                 },                                                      \
663                 .delay_ns = ns,                                         \
664         }
665
666 #define NAND_OP_DATA_IN(l, b, ns)                                       \
667         {                                                               \
668                 .type = NAND_OP_DATA_IN_INSTR,                          \
669                 .ctx.data = {                                           \
670                         .len = l,                                       \
671                         .buf.in = b,                                    \
672                         .force_8bit = false,                            \
673                 },                                                      \
674                 .delay_ns = ns,                                         \
675         }
676
677 #define NAND_OP_DATA_OUT(l, b, ns)                                      \
678         {                                                               \
679                 .type = NAND_OP_DATA_OUT_INSTR,                         \
680                 .ctx.data = {                                           \
681                         .len = l,                                       \
682                         .buf.out = b,                                   \
683                         .force_8bit = false,                            \
684                 },                                                      \
685                 .delay_ns = ns,                                         \
686         }
687
688 #define NAND_OP_8BIT_DATA_IN(l, b, ns)                                  \
689         {                                                               \
690                 .type = NAND_OP_DATA_IN_INSTR,                          \
691                 .ctx.data = {                                           \
692                         .len = l,                                       \
693                         .buf.in = b,                                    \
694                         .force_8bit = true,                             \
695                 },                                                      \
696                 .delay_ns = ns,                                         \
697         }
698
699 #define NAND_OP_8BIT_DATA_OUT(l, b, ns)                                 \
700         {                                                               \
701                 .type = NAND_OP_DATA_OUT_INSTR,                         \
702                 .ctx.data = {                                           \
703                         .len = l,                                       \
704                         .buf.out = b,                                   \
705                         .force_8bit = true,                             \
706                 },                                                      \
707                 .delay_ns = ns,                                         \
708         }
709
710 #define NAND_OP_WAIT_RDY(tout_ms, ns)                                   \
711         {                                                               \
712                 .type = NAND_OP_WAITRDY_INSTR,                          \
713                 .ctx.waitrdy.timeout_ms = tout_ms,                      \
714                 .delay_ns = ns,                                         \
715         }
716
717 /**
718  * struct nand_subop - a sub operation
719  * @cs: the CS line to select for this NAND sub-operation
720  * @instrs: array of instructions
721  * @ninstrs: length of the @instrs array
722  * @first_instr_start_off: offset to start from for the first instruction
723  *                         of the sub-operation
724  * @last_instr_end_off: offset to end at (excluded) for the last instruction
725  *                      of the sub-operation
726  *
727  * Both @first_instr_start_off and @last_instr_end_off only apply to data or
728  * address instructions.
729  *
730  * When an operation cannot be handled as is by the NAND controller, it will
731  * be split by the parser into sub-operations which will be passed to the
732  * controller driver.
733  */
734 struct nand_subop {
735         unsigned int cs;
736         const struct nand_op_instr *instrs;
737         unsigned int ninstrs;
738         unsigned int first_instr_start_off;
739         unsigned int last_instr_end_off;
740 };
741
742 unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
743                                            unsigned int op_id);
744 unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
745                                          unsigned int op_id);
746 unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
747                                            unsigned int op_id);
748 unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
749                                      unsigned int op_id);
750
751 /**
752  * struct nand_op_parser_addr_constraints - Constraints for address instructions
753  * @maxcycles: maximum number of address cycles the controller can issue in a
754  *             single step
755  */
756 struct nand_op_parser_addr_constraints {
757         unsigned int maxcycles;
758 };
759
760 /**
761  * struct nand_op_parser_data_constraints - Constraints for data instructions
762  * @maxlen: maximum data length that the controller can handle in a single step
763  */
764 struct nand_op_parser_data_constraints {
765         unsigned int maxlen;
766 };
767
768 /**
769  * struct nand_op_parser_pattern_elem - One element of a pattern
770  * @type: the instructuction type
771  * @optional: whether this element of the pattern is optional or mandatory
772  * @ctx: address or data constraint
773  * @ctx.addr: address constraint (number of cycles)
774  * @ctx.data: data constraint (data length)
775  */
776 struct nand_op_parser_pattern_elem {
777         enum nand_op_instr_type type;
778         bool optional;
779         union {
780                 struct nand_op_parser_addr_constraints addr;
781                 struct nand_op_parser_data_constraints data;
782         } ctx;
783 };
784
785 #define NAND_OP_PARSER_PAT_CMD_ELEM(_opt)                       \
786         {                                                       \
787                 .type = NAND_OP_CMD_INSTR,                      \
788                 .optional = _opt,                               \
789         }
790
791 #define NAND_OP_PARSER_PAT_ADDR_ELEM(_opt, _maxcycles)          \
792         {                                                       \
793                 .type = NAND_OP_ADDR_INSTR,                     \
794                 .optional = _opt,                               \
795                 .ctx.addr.maxcycles = _maxcycles,               \
796         }
797
798 #define NAND_OP_PARSER_PAT_DATA_IN_ELEM(_opt, _maxlen)          \
799         {                                                       \
800                 .type = NAND_OP_DATA_IN_INSTR,                  \
801                 .optional = _opt,                               \
802                 .ctx.data.maxlen = _maxlen,                     \
803         }
804
805 #define NAND_OP_PARSER_PAT_DATA_OUT_ELEM(_opt, _maxlen)         \
806         {                                                       \
807                 .type = NAND_OP_DATA_OUT_INSTR,                 \
808                 .optional = _opt,                               \
809                 .ctx.data.maxlen = _maxlen,                     \
810         }
811
812 #define NAND_OP_PARSER_PAT_WAITRDY_ELEM(_opt)                   \
813         {                                                       \
814                 .type = NAND_OP_WAITRDY_INSTR,                  \
815                 .optional = _opt,                               \
816         }
817
818 /**
819  * struct nand_op_parser_pattern - NAND sub-operation pattern descriptor
820  * @elems: array of pattern elements
821  * @nelems: number of pattern elements in @elems array
822  * @exec: the function that will issue a sub-operation
823  *
824  * A pattern is a list of elements, each element reprensenting one instruction
825  * with its constraints. The pattern itself is used by the core to match NAND
826  * chip operation with NAND controller operations.
827  * Once a match between a NAND controller operation pattern and a NAND chip
828  * operation (or a sub-set of a NAND operation) is found, the pattern ->exec()
829  * hook is called so that the controller driver can issue the operation on the
830  * bus.
831  *
832  * Controller drivers should declare as many patterns as they support and pass
833  * this list of patterns (created with the help of the following macro) to
834  * the nand_op_parser_exec_op() helper.
835  */
836 struct nand_op_parser_pattern {
837         const struct nand_op_parser_pattern_elem *elems;
838         unsigned int nelems;
839         int (*exec)(struct nand_chip *chip, const struct nand_subop *subop);
840 };
841
842 #define NAND_OP_PARSER_PATTERN(_exec, ...)                                                      \
843         {                                                                                       \
844                 .exec = _exec,                                                                  \
845                 .elems = (const struct nand_op_parser_pattern_elem[]) { __VA_ARGS__ },          \
846                 .nelems = sizeof((struct nand_op_parser_pattern_elem[]) { __VA_ARGS__ }) /      \
847                           sizeof(struct nand_op_parser_pattern_elem),                           \
848         }
849
850 /**
851  * struct nand_op_parser - NAND controller operation parser descriptor
852  * @patterns: array of supported patterns
853  * @npatterns: length of the @patterns array
854  *
855  * The parser descriptor is just an array of supported patterns which will be
856  * iterated by nand_op_parser_exec_op() everytime it tries to execute an
857  * NAND operation (or tries to determine if a specific operation is supported).
858  *
859  * It is worth mentioning that patterns will be tested in their declaration
860  * order, and the first match will be taken, so it's important to order patterns
861  * appropriately so that simple/inefficient patterns are placed at the end of
862  * the list. Usually, this is where you put single instruction patterns.
863  */
864 struct nand_op_parser {
865         const struct nand_op_parser_pattern *patterns;
866         unsigned int npatterns;
867 };
868
869 #define NAND_OP_PARSER(...)                                                                     \
870         {                                                                                       \
871                 .patterns = (const struct nand_op_parser_pattern[]) { __VA_ARGS__ },            \
872                 .npatterns = sizeof((struct nand_op_parser_pattern[]) { __VA_ARGS__ }) /        \
873                              sizeof(struct nand_op_parser_pattern),                             \
874         }
875
876 /**
877  * struct nand_operation - NAND operation descriptor
878  * @cs: the CS line to select for this NAND operation
879  * @instrs: array of instructions to execute
880  * @ninstrs: length of the @instrs array
881  *
882  * The actual operation structure that will be passed to chip->exec_op().
883  */
884 struct nand_operation {
885         unsigned int cs;
886         const struct nand_op_instr *instrs;
887         unsigned int ninstrs;
888 };
889
890 #define NAND_OPERATION(_cs, _instrs)                            \
891         {                                                       \
892                 .cs = _cs,                                      \
893                 .instrs = _instrs,                              \
894                 .ninstrs = ARRAY_SIZE(_instrs),                 \
895         }
896
897 int nand_op_parser_exec_op(struct nand_chip *chip,
898                            const struct nand_op_parser *parser,
899                            const struct nand_operation *op, bool check_only);
900
901 static inline void nand_op_trace(const char *prefix,
902                                  const struct nand_op_instr *instr)
903 {
904 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
905         switch (instr->type) {
906         case NAND_OP_CMD_INSTR:
907                 pr_debug("%sCMD      [0x%02x]\n", prefix,
908                          instr->ctx.cmd.opcode);
909                 break;
910         case NAND_OP_ADDR_INSTR:
911                 pr_debug("%sADDR     [%d cyc: %*ph]\n", prefix,
912                          instr->ctx.addr.naddrs,
913                          instr->ctx.addr.naddrs < 64 ?
914                          instr->ctx.addr.naddrs : 64,
915                          instr->ctx.addr.addrs);
916                 break;
917         case NAND_OP_DATA_IN_INSTR:
918                 pr_debug("%sDATA_IN  [%d B%s]\n", prefix,
919                          instr->ctx.data.len,
920                          instr->ctx.data.force_8bit ?
921                          ", force 8-bit" : "");
922                 break;
923         case NAND_OP_DATA_OUT_INSTR:
924                 pr_debug("%sDATA_OUT [%d B%s]\n", prefix,
925                          instr->ctx.data.len,
926                          instr->ctx.data.force_8bit ?
927                          ", force 8-bit" : "");
928                 break;
929         case NAND_OP_WAITRDY_INSTR:
930                 pr_debug("%sWAITRDY  [max %d ms]\n", prefix,
931                          instr->ctx.waitrdy.timeout_ms);
932                 break;
933         }
934 #endif
935 }
936
937 /**
938  * struct nand_controller_ops - Controller operations
939  *
940  * @attach_chip: this method is called after the NAND detection phase after
941  *               flash ID and MTD fields such as erase size, page size and OOB
942  *               size have been set up. ECC requirements are available if
943  *               provided by the NAND chip or device tree. Typically used to
944  *               choose the appropriate ECC configuration and allocate
945  *               associated resources.
946  *               This hook is optional.
947  * @detach_chip: free all resources allocated/claimed in
948  *               nand_controller_ops->attach_chip().
949  *               This hook is optional.
950  * @exec_op:     controller specific method to execute NAND operations.
951  *               This method replaces chip->legacy.cmdfunc(),
952  *               chip->legacy.{read,write}_{buf,byte,word}(),
953  *               chip->legacy.dev_ready() and chip->legacy.waifunc().
954  * @setup_interface: setup the data interface and timing. If chipnr is set to
955  *                   %NAND_DATA_IFACE_CHECK_ONLY this means the configuration
956  *                   should not be applied but only checked.
957  *                   This hook is optional.
958  */
959 struct nand_controller_ops {
960         int (*attach_chip)(struct nand_chip *chip);
961         void (*detach_chip)(struct nand_chip *chip);
962         int (*exec_op)(struct nand_chip *chip,
963                        const struct nand_operation *op,
964                        bool check_only);
965         int (*setup_interface)(struct nand_chip *chip, int chipnr,
966                                const struct nand_interface_config *conf);
967 };
968
969 /**
970  * struct nand_controller - Structure used to describe a NAND controller
971  *
972  * @lock:               lock used to serialize accesses to the NAND controller
973  * @ops:                NAND controller operations.
974  */
975 struct nand_controller {
976         struct mutex lock;
977         const struct nand_controller_ops *ops;
978 };
979
980 static inline void nand_controller_init(struct nand_controller *nfc)
981 {
982         mutex_init(&nfc->lock);
983 }
984
985 /**
986  * struct nand_legacy - NAND chip legacy fields/hooks
987  * @IO_ADDR_R: address to read the 8 I/O lines of the flash device
988  * @IO_ADDR_W: address to write the 8 I/O lines of the flash device
989  * @select_chip: select/deselect a specific target/die
990  * @read_byte: read one byte from the chip
991  * @write_byte: write a single byte to the chip on the low 8 I/O lines
992  * @write_buf: write data from the buffer to the chip
993  * @read_buf: read data from the chip into the buffer
994  * @cmd_ctrl: hardware specific function for controlling ALE/CLE/nCE. Also used
995  *            to write command and address
996  * @cmdfunc: hardware specific function for writing commands to the chip.
997  * @dev_ready: hardware specific function for accessing device ready/busy line.
998  *             If set to NULL no access to ready/busy is available and the
999  *             ready/busy information is read from the chip status register.
1000  * @waitfunc: hardware specific function for wait on ready.
1001  * @block_bad: check if a block is bad, using OOB markers
1002  * @block_markbad: mark a block bad
1003  * @set_features: set the NAND chip features
1004  * @get_features: get the NAND chip features
1005  * @chip_delay: chip dependent delay for transferring data from array to read
1006  *              regs (tR).
1007  * @dummy_controller: dummy controller implementation for drivers that can
1008  *                    only control a single chip
1009  *
1010  * If you look at this structure you're already wrong. These fields/hooks are
1011  * all deprecated.
1012  */
1013 struct nand_legacy {
1014         void __iomem *IO_ADDR_R;
1015         void __iomem *IO_ADDR_W;
1016         void (*select_chip)(struct nand_chip *chip, int cs);
1017         u8 (*read_byte)(struct nand_chip *chip);
1018         void (*write_byte)(struct nand_chip *chip, u8 byte);
1019         void (*write_buf)(struct nand_chip *chip, const u8 *buf, int len);
1020         void (*read_buf)(struct nand_chip *chip, u8 *buf, int len);
1021         void (*cmd_ctrl)(struct nand_chip *chip, int dat, unsigned int ctrl);
1022         void (*cmdfunc)(struct nand_chip *chip, unsigned command, int column,
1023                         int page_addr);
1024         int (*dev_ready)(struct nand_chip *chip);
1025         int (*waitfunc)(struct nand_chip *chip);
1026         int (*block_bad)(struct nand_chip *chip, loff_t ofs);
1027         int (*block_markbad)(struct nand_chip *chip, loff_t ofs);
1028         int (*set_features)(struct nand_chip *chip, int feature_addr,
1029                             u8 *subfeature_para);
1030         int (*get_features)(struct nand_chip *chip, int feature_addr,
1031                             u8 *subfeature_para);
1032         int chip_delay;
1033         struct nand_controller dummy_controller;
1034 };
1035
1036 /**
1037  * struct nand_chip_ops - NAND chip operations
1038  * @suspend: Suspend operation
1039  * @resume: Resume operation
1040  * @lock_area: Lock operation
1041  * @unlock_area: Unlock operation
1042  * @setup_read_retry: Set the read-retry mode (mostly needed for MLC NANDs)
1043  * @choose_interface_config: Choose the best interface configuration
1044  */
1045 struct nand_chip_ops {
1046         int (*suspend)(struct nand_chip *chip);
1047         void (*resume)(struct nand_chip *chip);
1048         int (*lock_area)(struct nand_chip *chip, loff_t ofs, uint64_t len);
1049         int (*unlock_area)(struct nand_chip *chip, loff_t ofs, uint64_t len);
1050         int (*setup_read_retry)(struct nand_chip *chip, int retry_mode);
1051         int (*choose_interface_config)(struct nand_chip *chip,
1052                                        struct nand_interface_config *iface);
1053 };
1054
1055 /**
1056  * struct nand_manufacturer - NAND manufacturer structure
1057  * @desc: The manufacturer description
1058  * @priv: Private information for the manufacturer driver
1059  */
1060 struct nand_manufacturer {
1061         const struct nand_manufacturer_desc *desc;
1062         void *priv;
1063 };
1064
1065 /**
1066  * struct nand_chip - NAND Private Flash Chip Data
1067  * @base: Inherit from the generic NAND device
1068  * @id: Holds NAND ID
1069  * @parameters: Holds generic parameters under an easily readable form
1070  * @manufacturer: Manufacturer information
1071  * @ops: NAND chip operations
1072  * @legacy: All legacy fields/hooks. If you develop a new driver, don't even try
1073  *          to use any of these fields/hooks, and if you're modifying an
1074  *          existing driver that is using those fields/hooks, you should
1075  *          consider reworking the driver and avoid using them.
1076  * @options: Various chip options. They can partly be set to inform nand_scan
1077  *           about special functionality. See the defines for further
1078  *           explanation.
1079  * @current_interface_config: The currently used NAND interface configuration
1080  * @best_interface_config: The best NAND interface configuration which fits both
1081  *                         the NAND chip and NAND controller constraints. If
1082  *                         unset, the default reset interface configuration must
1083  *                         be used.
1084  * @bbt_erase_shift: Number of address bits in a bbt entry
1085  * @bbt_options: Bad block table specific options. All options used here must
1086  *               come from bbm.h. By default, these options will be copied to
1087  *               the appropriate nand_bbt_descr's.
1088  * @badblockpos: Bad block marker position in the oob area
1089  * @badblockbits: Minimum number of set bits in a good block's bad block marker
1090  *                position; i.e., BBM = 11110111b is good when badblockbits = 7
1091  * @bbt_td: Bad block table descriptor for flash lookup
1092  * @bbt_md: Bad block table mirror descriptor
1093  * @badblock_pattern: Bad block scan pattern used for initial bad block scan
1094  * @bbt: Bad block table pointer
1095  * @page_shift: Number of address bits in a page (column address bits)
1096  * @phys_erase_shift: Number of address bits in a physical eraseblock
1097  * @chip_shift: Number of address bits in one chip
1098  * @pagemask: Page number mask = number of (pages / chip) - 1
1099  * @subpagesize: Holds the subpagesize
1100  * @data_buf: Buffer for data, size is (page size + oobsize)
1101  * @oob_poi: pointer on the OOB area covered by data_buf
1102  * @pagecache: Structure containing page cache related fields
1103  * @pagecache.bitflips: Number of bitflips of the cached page
1104  * @pagecache.page: Page number currently in the cache. -1 means no page is
1105  *                  currently cached
1106  * @buf_align: Minimum buffer alignment required by a platform
1107  * @lock: Lock protecting the suspended field. Also used to serialize accesses
1108  *        to the NAND device
1109  * @suspended: Set to 1 when the device is suspended, 0 when it's not
1110  * @cur_cs: Currently selected target. -1 means no target selected, otherwise we
1111  *          should always have cur_cs >= 0 && cur_cs < nanddev_ntargets().
1112  *          NAND Controller drivers should not modify this value, but they're
1113  *          allowed to read it.
1114  * @read_retries: The number of read retry modes supported
1115  * @controller: The hardware controller structure which is shared among multiple
1116  *              independent devices
1117  * @ecc: The ECC controller structure
1118  * @priv: Chip private data
1119  */
1120 struct nand_chip {
1121         struct nand_device base;
1122         struct nand_id id;
1123         struct nand_parameters parameters;
1124         struct nand_manufacturer manufacturer;
1125         struct nand_chip_ops ops;
1126         struct nand_legacy legacy;
1127         unsigned int options;
1128
1129         /* Data interface */
1130         const struct nand_interface_config *current_interface_config;
1131         struct nand_interface_config *best_interface_config;
1132
1133         /* Bad block information */
1134         unsigned int bbt_erase_shift;
1135         unsigned int bbt_options;
1136         unsigned int badblockpos;
1137         unsigned int badblockbits;
1138         struct nand_bbt_descr *bbt_td;
1139         struct nand_bbt_descr *bbt_md;
1140         struct nand_bbt_descr *badblock_pattern;
1141         u8 *bbt;
1142
1143         /* Device internal layout */
1144         unsigned int page_shift;
1145         unsigned int phys_erase_shift;
1146         unsigned int chip_shift;
1147         unsigned int pagemask;
1148         unsigned int subpagesize;
1149
1150         /* Buffers */
1151         u8 *data_buf;
1152         u8 *oob_poi;
1153         struct {
1154                 unsigned int bitflips;
1155                 int page;
1156         } pagecache;
1157         unsigned long buf_align;
1158
1159         /* Internals */
1160         struct mutex lock;
1161         unsigned int suspended : 1;
1162         int cur_cs;
1163         int read_retries;
1164
1165         /* Externals */
1166         struct nand_controller *controller;
1167         struct nand_ecc_ctrl ecc;
1168         void *priv;
1169 };
1170
1171 extern const struct mtd_ooblayout_ops nand_ooblayout_sp_ops;
1172 extern const struct mtd_ooblayout_ops nand_ooblayout_lp_ops;
1173
1174 static inline struct nand_chip *mtd_to_nand(struct mtd_info *mtd)
1175 {
1176         return container_of(mtd, struct nand_chip, base.mtd);
1177 }
1178
1179 static inline struct mtd_info *nand_to_mtd(struct nand_chip *chip)
1180 {
1181         return &chip->base.mtd;
1182 }
1183
1184 static inline void *nand_get_controller_data(struct nand_chip *chip)
1185 {
1186         return chip->priv;
1187 }
1188
1189 static inline void nand_set_controller_data(struct nand_chip *chip, void *priv)
1190 {
1191         chip->priv = priv;
1192 }
1193
1194 static inline void nand_set_manufacturer_data(struct nand_chip *chip,
1195                                               void *priv)
1196 {
1197         chip->manufacturer.priv = priv;
1198 }
1199
1200 static inline void *nand_get_manufacturer_data(struct nand_chip *chip)
1201 {
1202         return chip->manufacturer.priv;
1203 }
1204
1205 static inline void nand_set_flash_node(struct nand_chip *chip,
1206                                        struct device_node *np)
1207 {
1208         mtd_set_of_node(nand_to_mtd(chip), np);
1209 }
1210
1211 static inline struct device_node *nand_get_flash_node(struct nand_chip *chip)
1212 {
1213         return mtd_get_of_node(nand_to_mtd(chip));
1214 }
1215
1216 /**
1217  * nand_get_interface_config - Retrieve the current interface configuration
1218  *                             of a NAND chip
1219  * @chip: The NAND chip
1220  */
1221 static inline const struct nand_interface_config *
1222 nand_get_interface_config(struct nand_chip *chip)
1223 {
1224         return chip->current_interface_config;
1225 }
1226
1227 /*
1228  * A helper for defining older NAND chips where the second ID byte fully
1229  * defined the chip, including the geometry (chip size, eraseblock size, page
1230  * size). All these chips have 512 bytes NAND page size.
1231  */
1232 #define LEGACY_ID_NAND(nm, devid, chipsz, erasesz, opts)          \
1233         { .name = (nm), {{ .dev_id = (devid) }}, .pagesize = 512, \
1234           .chipsize = (chipsz), .erasesize = (erasesz), .options = (opts) }
1235
1236 /*
1237  * A helper for defining newer chips which report their page size and
1238  * eraseblock size via the extended ID bytes.
1239  *
1240  * The real difference between LEGACY_ID_NAND and EXTENDED_ID_NAND is that with
1241  * EXTENDED_ID_NAND, manufacturers overloaded the same device ID so that the
1242  * device ID now only represented a particular total chip size (and voltage,
1243  * buswidth), and the page size, eraseblock size, and OOB size could vary while
1244  * using the same device ID.
1245  */
1246 #define EXTENDED_ID_NAND(nm, devid, chipsz, opts)                      \
1247         { .name = (nm), {{ .dev_id = (devid) }}, .chipsize = (chipsz), \
1248           .options = (opts) }
1249
1250 #define NAND_ECC_INFO(_strength, _step) \
1251                         { .strength_ds = (_strength), .step_ds = (_step) }
1252 #define NAND_ECC_STRENGTH(type)         ((type)->ecc.strength_ds)
1253 #define NAND_ECC_STEP(type)             ((type)->ecc.step_ds)
1254
1255 /**
1256  * struct nand_flash_dev - NAND Flash Device ID Structure
1257  * @name: a human-readable name of the NAND chip
1258  * @dev_id: the device ID (the second byte of the full chip ID array)
1259  * @mfr_id: manufacturer ID part of the full chip ID array (refers the same
1260  *          memory address as ``id[0]``)
1261  * @dev_id: device ID part of the full chip ID array (refers the same memory
1262  *          address as ``id[1]``)
1263  * @id: full device ID array
1264  * @pagesize: size of the NAND page in bytes; if 0, then the real page size (as
1265  *            well as the eraseblock size) is determined from the extended NAND
1266  *            chip ID array)
1267  * @chipsize: total chip size in MiB
1268  * @erasesize: eraseblock size in bytes (determined from the extended ID if 0)
1269  * @options: stores various chip bit options
1270  * @id_len: The valid length of the @id.
1271  * @oobsize: OOB size
1272  * @ecc: ECC correctability and step information from the datasheet.
1273  * @ecc.strength_ds: The ECC correctability from the datasheet, same as the
1274  *                   @ecc_strength_ds in nand_chip{}.
1275  * @ecc.step_ds: The ECC step required by the @ecc.strength_ds, same as the
1276  *               @ecc_step_ds in nand_chip{}, also from the datasheet.
1277  *               For example, the "4bit ECC for each 512Byte" can be set with
1278  *               NAND_ECC_INFO(4, 512).
1279  */
1280 struct nand_flash_dev {
1281         char *name;
1282         union {
1283                 struct {
1284                         uint8_t mfr_id;
1285                         uint8_t dev_id;
1286                 };
1287                 uint8_t id[NAND_MAX_ID_LEN];
1288         };
1289         unsigned int pagesize;
1290         unsigned int chipsize;
1291         unsigned int erasesize;
1292         unsigned int options;
1293         uint16_t id_len;
1294         uint16_t oobsize;
1295         struct {
1296                 uint16_t strength_ds;
1297                 uint16_t step_ds;
1298         } ecc;
1299 };
1300
1301 int nand_create_bbt(struct nand_chip *chip);
1302
1303 /*
1304  * Check if it is a SLC nand.
1305  * The !nand_is_slc() can be used to check the MLC/TLC nand chips.
1306  * We do not distinguish the MLC and TLC now.
1307  */
1308 static inline bool nand_is_slc(struct nand_chip *chip)
1309 {
1310         WARN(nanddev_bits_per_cell(&chip->base) == 0,
1311              "chip->bits_per_cell is used uninitialized\n");
1312         return nanddev_bits_per_cell(&chip->base) == 1;
1313 }
1314
1315 /**
1316  * Check if the opcode's address should be sent only on the lower 8 bits
1317  * @command: opcode to check
1318  */
1319 static inline int nand_opcode_8bits(unsigned int command)
1320 {
1321         switch (command) {
1322         case NAND_CMD_READID:
1323         case NAND_CMD_PARAM:
1324         case NAND_CMD_GET_FEATURES:
1325         case NAND_CMD_SET_FEATURES:
1326                 return 1;
1327         default:
1328                 break;
1329         }
1330         return 0;
1331 }
1332
1333 int nand_check_erased_ecc_chunk(void *data, int datalen,
1334                                 void *ecc, int ecclen,
1335                                 void *extraoob, int extraooblen,
1336                                 int threshold);
1337
1338 int nand_ecc_choose_conf(struct nand_chip *chip,
1339                          const struct nand_ecc_caps *caps, int oobavail);
1340
1341 /* Default write_oob implementation */
1342 int nand_write_oob_std(struct nand_chip *chip, int page);
1343
1344 /* Default read_oob implementation */
1345 int nand_read_oob_std(struct nand_chip *chip, int page);
1346
1347 /* Stub used by drivers that do not support GET/SET FEATURES operations */
1348 int nand_get_set_features_notsupp(struct nand_chip *chip, int addr,
1349                                   u8 *subfeature_param);
1350
1351 /* read_page_raw implementations */
1352 int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
1353                        int page);
1354 int nand_monolithic_read_page_raw(struct nand_chip *chip, uint8_t *buf,
1355                                   int oob_required, int page);
1356
1357 /* write_page_raw implementations */
1358 int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
1359                         int oob_required, int page);
1360 int nand_monolithic_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
1361                                    int oob_required, int page);
1362
1363 /* Reset and initialize a NAND device */
1364 int nand_reset(struct nand_chip *chip, int chipnr);
1365
1366 /* NAND operation helpers */
1367 int nand_reset_op(struct nand_chip *chip);
1368 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1369                    unsigned int len);
1370 int nand_status_op(struct nand_chip *chip, u8 *status);
1371 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock);
1372 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1373                       unsigned int offset_in_page, void *buf, unsigned int len);
1374 int nand_change_read_column_op(struct nand_chip *chip,
1375                                unsigned int offset_in_page, void *buf,
1376                                unsigned int len, bool force_8bit);
1377 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1378                      unsigned int offset_in_page, void *buf, unsigned int len);
1379 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1380                             unsigned int offset_in_page, const void *buf,
1381                             unsigned int len);
1382 int nand_prog_page_end_op(struct nand_chip *chip);
1383 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1384                       unsigned int offset_in_page, const void *buf,
1385                       unsigned int len);
1386 int nand_change_write_column_op(struct nand_chip *chip,
1387                                 unsigned int offset_in_page, const void *buf,
1388                                 unsigned int len, bool force_8bit);
1389 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
1390                       bool force_8bit, bool check_only);
1391 int nand_write_data_op(struct nand_chip *chip, const void *buf,
1392                        unsigned int len, bool force_8bit);
1393
1394 /* Scan and identify a NAND device */
1395 int nand_scan_with_ids(struct nand_chip *chip, unsigned int max_chips,
1396                        struct nand_flash_dev *ids);
1397
1398 static inline int nand_scan(struct nand_chip *chip, unsigned int max_chips)
1399 {
1400         return nand_scan_with_ids(chip, max_chips, NULL);
1401 }
1402
1403 /* Internal helper for board drivers which need to override command function */
1404 void nand_wait_ready(struct nand_chip *chip);
1405
1406 /*
1407  * Free resources held by the NAND device, must be called on error after a
1408  * sucessful nand_scan().
1409  */
1410 void nand_cleanup(struct nand_chip *chip);
1411
1412 /*
1413  * External helper for controller drivers that have to implement the WAITRDY
1414  * instruction and have no physical pin to check it.
1415  */
1416 int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms);
1417 struct gpio_desc;
1418 int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
1419                       unsigned long timeout_ms);
1420
1421 /* Select/deselect a NAND target. */
1422 void nand_select_target(struct nand_chip *chip, unsigned int cs);
1423 void nand_deselect_target(struct nand_chip *chip);
1424
1425 /* Bitops */
1426 void nand_extract_bits(u8 *dst, unsigned int dst_off, const u8 *src,
1427                        unsigned int src_off, unsigned int nbits);
1428
1429 /**
1430  * nand_get_data_buf() - Get the internal page buffer
1431  * @chip: NAND chip object
1432  *
1433  * Returns the pre-allocated page buffer after invalidating the cache. This
1434  * function should be used by drivers that do not want to allocate their own
1435  * bounce buffer and still need such a buffer for specific operations (most
1436  * commonly when reading OOB data only).
1437  *
1438  * Be careful to never call this function in the write/write_oob path, because
1439  * the core may have placed the data to be written out in this buffer.
1440  *
1441  * Return: pointer to the page cache buffer
1442  */
1443 static inline void *nand_get_data_buf(struct nand_chip *chip)
1444 {
1445         chip->pagecache.page = -1;
1446
1447         return chip->data_buf;
1448 }
1449
1450 #endif /* __LINUX_MTD_RAWNAND_H */