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