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