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