1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Marvell NAND flash controller driver
4  *
5  * Copyright (C) 2017 Marvell
6  * Author: Miquel RAYNAL <miquel.raynal@free-electrons.com>
7  *
8  *
9  * This NAND controller driver handles two versions of the hardware,
10  * one is called NFCv1 and is available on PXA SoCs and the other is
11  * called NFCv2 and is available on Armada SoCs.
12  *
13  * The main visible difference is that NFCv1 only has Hamming ECC
14  * capabilities, while NFCv2 also embeds a BCH ECC engine. Also, DMA
15  * is not used with NFCv2.
16  *
17  * The ECC layouts are depicted in details in Marvell AN-379, but here
18  * is a brief description.
19  *
20  * When using Hamming, the data is split in 512B chunks (either 1, 2
21  * or 4) and each chunk will have its own ECC "digest" of 6B at the
22  * beginning of the OOB area and eventually the remaining free OOB
23  * bytes (also called "spare" bytes in the driver). This engine
24  * corrects up to 1 bit per chunk and detects reliably an error if
25  * there are at most 2 bitflips. Here is the page layout used by the
26  * controller when Hamming is chosen:
27  *
28  * +-------------------------------------------------------------+
29  * | Data 1 | ... | Data N | ECC 1 | ... | ECCN | Free OOB bytes |
30  * +-------------------------------------------------------------+
31  *
32  * When using the BCH engine, there are N identical (data + free OOB +
33  * ECC) sections and potentially an extra one to deal with
34  * configurations where the chosen (data + free OOB + ECC) sizes do
35  * not align with the page (data + OOB) size. ECC bytes are always
36  * 30B per ECC chunk. Here is the page layout used by the controller
37  * when BCH is chosen:
38  *
39  * +-----------------------------------------
40  * | Data 1 | Free OOB bytes 1 | ECC 1 | ...
41  * +-----------------------------------------
42  *
43  *      -------------------------------------------
44  *       ... | Data N | Free OOB bytes N | ECC N |
45  *      -------------------------------------------
46  *
47  *           --------------------------------------------+
48  *            Last Data | Last Free OOB bytes | Last ECC |
49  *           --------------------------------------------+
50  *
51  * In both cases, the layout seen by the user is always: all data
52  * first, then all free OOB bytes and finally all ECC bytes. With BCH,
53  * ECC bytes are 30B long and are padded with 0xFF to align on 32
54  * bytes.
55  *
56  * The controller has certain limitations that are handled by the
57  * driver:
58  *   - It can only read 2k at a time. To overcome this limitation, the
59  *     driver issues data cycles on the bus, without issuing new
60  *     CMD + ADDR cycles. The Marvell term is "naked" operations.
61  *   - The ECC strength in BCH mode cannot be tuned. It is fixed 16
62  *     bits. What can be tuned is the ECC block size as long as it
63  *     stays between 512B and 2kiB. It's usually chosen based on the
64  *     chip ECC requirements. For instance, using 2kiB ECC chunks
65  *     provides 4b/512B correctability.
66  *   - The controller will always treat data bytes, free OOB bytes
67  *     and ECC bytes in that order, no matter what the real layout is
68  *     (which is usually all data then all OOB bytes). The
69  *     marvell_nfc_layouts array below contains the currently
70  *     supported layouts.
71  *   - Because of these weird layouts, the Bad Block Markers can be
72  *     located in data section. In this case, the NAND_BBT_NO_OOB_BBM
73  *     option must be set to prevent scanning/writing bad block
74  *     markers.
75  */
76 
77 #include <linux/module.h>
78 #include <linux/clk.h>
79 #include <linux/mtd/rawnand.h>
80 #include <linux/of_platform.h>
81 #include <linux/iopoll.h>
82 #include <linux/interrupt.h>
83 #include <linux/slab.h>
84 #include <linux/mfd/syscon.h>
85 #include <linux/regmap.h>
86 #include <asm/unaligned.h>
87 
88 #include <linux/dmaengine.h>
89 #include <linux/dma-mapping.h>
90 #include <linux/dma/pxa-dma.h>
91 #include <linux/platform_data/mtd-nand-pxa3xx.h>
92 
93 /* Data FIFO granularity, FIFO reads/writes must be a multiple of this length */
94 #define FIFO_DEPTH		8
95 #define FIFO_REP(x)		(x / sizeof(u32))
96 #define BCH_SEQ_READS		(32 / FIFO_DEPTH)
97 /* NFC does not support transfers of larger chunks at a time */
98 #define MAX_CHUNK_SIZE		2112
99 /* NFCv1 cannot read more that 7 bytes of ID */
100 #define NFCV1_READID_LEN	7
101 /* Polling is done at a pace of POLL_PERIOD us until POLL_TIMEOUT is reached */
102 #define POLL_PERIOD		0
103 #define POLL_TIMEOUT		100000
104 /* Interrupt maximum wait period in ms */
105 #define IRQ_TIMEOUT		1000
106 /* Latency in clock cycles between SoC pins and NFC logic */
107 #define MIN_RD_DEL_CNT		3
108 /* Maximum number of contiguous address cycles */
109 #define MAX_ADDRESS_CYC_NFCV1	5
110 #define MAX_ADDRESS_CYC_NFCV2	7
111 /* System control registers/bits to enable the NAND controller on some SoCs */
112 #define GENCONF_SOC_DEVICE_MUX	0x208
113 #define GENCONF_SOC_DEVICE_MUX_NFC_EN BIT(0)
114 #define GENCONF_SOC_DEVICE_MUX_ECC_CLK_RST BIT(20)
115 #define GENCONF_SOC_DEVICE_MUX_ECC_CORE_RST BIT(21)
116 #define GENCONF_SOC_DEVICE_MUX_NFC_INT_EN BIT(25)
117 #define GENCONF_SOC_DEVICE_MUX_NFC_DEVBUS_ARB_EN BIT(27)
118 #define GENCONF_CLK_GATING_CTRL	0x220
119 #define GENCONF_CLK_GATING_CTRL_ND_GATE BIT(2)
120 #define GENCONF_ND_CLK_CTRL	0x700
121 #define GENCONF_ND_CLK_CTRL_EN	BIT(0)
122 
123 /* NAND controller data flash control register */
124 #define NDCR			0x00
125 #define NDCR_ALL_INT		GENMASK(11, 0)
126 #define NDCR_CS1_CMDDM		BIT(7)
127 #define NDCR_CS0_CMDDM		BIT(8)
128 #define NDCR_RDYM		BIT(11)
129 #define NDCR_ND_ARB_EN		BIT(12)
130 #define NDCR_RA_START		BIT(15)
131 #define NDCR_RD_ID_CNT(x)	(min_t(unsigned int, x, 0x7) << 16)
132 #define NDCR_PAGE_SZ(x)		(x >= 2048 ? BIT(24) : 0)
133 #define NDCR_DWIDTH_M		BIT(26)
134 #define NDCR_DWIDTH_C		BIT(27)
135 #define NDCR_ND_RUN		BIT(28)
136 #define NDCR_DMA_EN		BIT(29)
137 #define NDCR_ECC_EN		BIT(30)
138 #define NDCR_SPARE_EN		BIT(31)
139 #define NDCR_GENERIC_FIELDS_MASK (~(NDCR_RA_START | NDCR_PAGE_SZ(2048) | \
140 				    NDCR_DWIDTH_M | NDCR_DWIDTH_C))
141 
142 /* NAND interface timing parameter 0 register */
143 #define NDTR0			0x04
144 #define NDTR0_TRP(x)		((min_t(unsigned int, x, 0xF) & 0x7) << 0)
145 #define NDTR0_TRH(x)		(min_t(unsigned int, x, 0x7) << 3)
146 #define NDTR0_ETRP(x)		((min_t(unsigned int, x, 0xF) & 0x8) << 3)
147 #define NDTR0_SEL_NRE_EDGE	BIT(7)
148 #define NDTR0_TWP(x)		(min_t(unsigned int, x, 0x7) << 8)
149 #define NDTR0_TWH(x)		(min_t(unsigned int, x, 0x7) << 11)
150 #define NDTR0_TCS(x)		(min_t(unsigned int, x, 0x7) << 16)
151 #define NDTR0_TCH(x)		(min_t(unsigned int, x, 0x7) << 19)
152 #define NDTR0_RD_CNT_DEL(x)	(min_t(unsigned int, x, 0xF) << 22)
153 #define NDTR0_SELCNTR		BIT(26)
154 #define NDTR0_TADL(x)		(min_t(unsigned int, x, 0x1F) << 27)
155 
156 /* NAND interface timing parameter 1 register */
157 #define NDTR1			0x0C
158 #define NDTR1_TAR(x)		(min_t(unsigned int, x, 0xF) << 0)
159 #define NDTR1_TWHR(x)		(min_t(unsigned int, x, 0xF) << 4)
160 #define NDTR1_TRHW(x)		(min_t(unsigned int, x / 16, 0x3) << 8)
161 #define NDTR1_PRESCALE		BIT(14)
162 #define NDTR1_WAIT_MODE		BIT(15)
163 #define NDTR1_TR(x)		(min_t(unsigned int, x, 0xFFFF) << 16)
164 
165 /* NAND controller status register */
166 #define NDSR			0x14
167 #define NDSR_WRCMDREQ		BIT(0)
168 #define NDSR_RDDREQ		BIT(1)
169 #define NDSR_WRDREQ		BIT(2)
170 #define NDSR_CORERR		BIT(3)
171 #define NDSR_UNCERR		BIT(4)
172 #define NDSR_CMDD(cs)		BIT(8 - cs)
173 #define NDSR_RDY(rb)		BIT(11 + rb)
174 #define NDSR_ERRCNT(x)		((x >> 16) & 0x1F)
175 
176 /* NAND ECC control register */
177 #define NDECCCTRL		0x28
178 #define NDECCCTRL_BCH_EN	BIT(0)
179 
180 /* NAND controller data buffer register */
181 #define NDDB			0x40
182 
183 /* NAND controller command buffer 0 register */
184 #define NDCB0			0x48
185 #define NDCB0_CMD1(x)		((x & 0xFF) << 0)
186 #define NDCB0_CMD2(x)		((x & 0xFF) << 8)
187 #define NDCB0_ADDR_CYC(x)	((x & 0x7) << 16)
188 #define NDCB0_ADDR_GET_NUM_CYC(x) (((x) >> 16) & 0x7)
189 #define NDCB0_DBC		BIT(19)
190 #define NDCB0_CMD_TYPE(x)	((x & 0x7) << 21)
191 #define NDCB0_CSEL		BIT(24)
192 #define NDCB0_RDY_BYP		BIT(27)
193 #define NDCB0_LEN_OVRD		BIT(28)
194 #define NDCB0_CMD_XTYPE(x)	((x & 0x7) << 29)
195 
196 /* NAND controller command buffer 1 register */
197 #define NDCB1			0x4C
198 #define NDCB1_COLS(x)		((x & 0xFFFF) << 0)
199 #define NDCB1_ADDRS_PAGE(x)	(x << 16)
200 
201 /* NAND controller command buffer 2 register */
202 #define NDCB2			0x50
203 #define NDCB2_ADDR5_PAGE(x)	(((x >> 16) & 0xFF) << 0)
204 #define NDCB2_ADDR5_CYC(x)	((x & 0xFF) << 0)
205 
206 /* NAND controller command buffer 3 register */
207 #define NDCB3			0x54
208 #define NDCB3_ADDR6_CYC(x)	((x & 0xFF) << 16)
209 #define NDCB3_ADDR7_CYC(x)	((x & 0xFF) << 24)
210 
211 /* NAND controller command buffer 0 register 'type' and 'xtype' fields */
212 #define TYPE_READ		0
213 #define TYPE_WRITE		1
214 #define TYPE_ERASE		2
215 #define TYPE_READ_ID		3
216 #define TYPE_STATUS		4
217 #define TYPE_RESET		5
218 #define TYPE_NAKED_CMD		6
219 #define TYPE_NAKED_ADDR		7
220 #define TYPE_MASK		7
221 #define XTYPE_MONOLITHIC_RW	0
222 #define XTYPE_LAST_NAKED_RW	1
223 #define XTYPE_FINAL_COMMAND	3
224 #define XTYPE_READ		4
225 #define XTYPE_WRITE_DISPATCH	4
226 #define XTYPE_NAKED_RW		5
227 #define XTYPE_COMMAND_DISPATCH	6
228 #define XTYPE_MASK		7
229 
230 /**
231  * struct marvell_hw_ecc_layout - layout of Marvell ECC
232  *
233  * Marvell ECC engine works differently than the others, in order to limit the
234  * size of the IP, hardware engineers chose to set a fixed strength at 16 bits
235  * per subpage, and depending on a the desired strength needed by the NAND chip,
236  * a particular layout mixing data/spare/ecc is defined, with a possible last
237  * chunk smaller that the others.
238  *
239  * @writesize:		Full page size on which the layout applies
240  * @chunk:		Desired ECC chunk size on which the layout applies
241  * @strength:		Desired ECC strength (per chunk size bytes) on which the
242  *			layout applies
243  * @nchunks:		Total number of chunks
244  * @full_chunk_cnt:	Number of full-sized chunks, which is the number of
245  *			repetitions of the pattern:
246  *			(data_bytes + spare_bytes + ecc_bytes).
247  * @data_bytes:		Number of data bytes per chunk
248  * @spare_bytes:	Number of spare bytes per chunk
249  * @ecc_bytes:		Number of ecc bytes per chunk
250  * @last_data_bytes:	Number of data bytes in the last chunk
251  * @last_spare_bytes:	Number of spare bytes in the last chunk
252  * @last_ecc_bytes:	Number of ecc bytes in the last chunk
253  */
254 struct marvell_hw_ecc_layout {
255 	/* Constraints */
256 	int writesize;
257 	int chunk;
258 	int strength;
259 	/* Corresponding layout */
260 	int nchunks;
261 	int full_chunk_cnt;
262 	int data_bytes;
263 	int spare_bytes;
264 	int ecc_bytes;
265 	int last_data_bytes;
266 	int last_spare_bytes;
267 	int last_ecc_bytes;
268 };
269 
270 #define MARVELL_LAYOUT(ws, dc, ds, nc, fcc, db, sb, eb, ldb, lsb, leb)	\
271 	{								\
272 		.writesize = ws,					\
273 		.chunk = dc,						\
274 		.strength = ds,						\
275 		.nchunks = nc,						\
276 		.full_chunk_cnt = fcc,					\
277 		.data_bytes = db,					\
278 		.spare_bytes = sb,					\
279 		.ecc_bytes = eb,					\
280 		.last_data_bytes = ldb,					\
281 		.last_spare_bytes = lsb,				\
282 		.last_ecc_bytes = leb,					\
283 	}
284 
285 /* Layouts explained in AN-379_Marvell_SoC_NFC_ECC */
286 static const struct marvell_hw_ecc_layout marvell_nfc_layouts[] = {
287 	MARVELL_LAYOUT(  512,   512,  1,  1,  1,  512,  8,  8,  0,  0,  0),
288 	MARVELL_LAYOUT( 2048,   512,  1,  1,  1, 2048, 40, 24,  0,  0,  0),
289 	MARVELL_LAYOUT( 2048,   512,  4,  1,  1, 2048, 32, 30,  0,  0,  0),
290 	MARVELL_LAYOUT( 2048,   512,  8,  2,  1, 1024,  0, 30,1024,32, 30),
291 	MARVELL_LAYOUT( 4096,   512,  4,  2,  2, 2048, 32, 30,  0,  0,  0),
292 	MARVELL_LAYOUT( 4096,   512,  8,  5,  4, 1024,  0, 30,  0, 64, 30),
293 	MARVELL_LAYOUT( 8192,   512,  4,  4,  4, 2048,  0, 30,  0,  0,  0),
294 	MARVELL_LAYOUT( 8192,   512,  8,  9,  8, 1024,  0, 30,  0, 160, 30),
295 };
296 
297 /**
298  * struct marvell_nand_chip_sel - CS line description
299  *
300  * The Nand Flash Controller has up to 4 CE and 2 RB pins. The CE selection
301  * is made by a field in NDCB0 register, and in another field in NDCB2 register.
302  * The datasheet describes the logic with an error: ADDR5 field is once
303  * declared at the beginning of NDCB2, and another time at its end. Because the
304  * ADDR5 field of NDCB2 may be used by other bytes, it would be more logical
305  * to use the last bit of this field instead of the first ones.
306  *
307  * @cs:			Wanted CE lane.
308  * @ndcb0_csel:		Value of the NDCB0 register with or without the flag
309  *			selecting the wanted CE lane. This is set once when
310  *			the Device Tree is probed.
311  * @rb:			Ready/Busy pin for the flash chip
312  */
313 struct marvell_nand_chip_sel {
314 	unsigned int cs;
315 	u32 ndcb0_csel;
316 	unsigned int rb;
317 };
318 
319 /**
320  * struct marvell_nand_chip - stores NAND chip device related information
321  *
322  * @chip:		Base NAND chip structure
323  * @node:		Used to store NAND chips into a list
324  * @layout:		NAND layout when using hardware ECC
325  * @ndcr:		Controller register value for this NAND chip
326  * @ndtr0:		Timing registers 0 value for this NAND chip
327  * @ndtr1:		Timing registers 1 value for this NAND chip
328  * @addr_cyc:		Amount of cycles needed to pass column address
329  * @selected_die:	Current active CS
330  * @nsels:		Number of CS lines required by the NAND chip
331  * @sels:		Array of CS lines descriptions
332  */
333 struct marvell_nand_chip {
334 	struct nand_chip chip;
335 	struct list_head node;
336 	const struct marvell_hw_ecc_layout *layout;
337 	u32 ndcr;
338 	u32 ndtr0;
339 	u32 ndtr1;
340 	int addr_cyc;
341 	int selected_die;
342 	unsigned int nsels;
343 	struct marvell_nand_chip_sel sels[];
344 };
345 
346 static inline struct marvell_nand_chip *to_marvell_nand(struct nand_chip *chip)
347 {
348 	return container_of(chip, struct marvell_nand_chip, chip);
349 }
350 
351 static inline struct marvell_nand_chip_sel *to_nand_sel(struct marvell_nand_chip
352 							*nand)
353 {
354 	return &nand->sels[nand->selected_die];
355 }
356 
357 /**
358  * struct marvell_nfc_caps - NAND controller capabilities for distinction
359  *                           between compatible strings
360  *
361  * @max_cs_nb:		Number of Chip Select lines available
362  * @max_rb_nb:		Number of Ready/Busy lines available
363  * @need_system_controller: Indicates if the SoC needs to have access to the
364  *                      system controller (ie. to enable the NAND controller)
365  * @legacy_of_bindings:	Indicates if DT parsing must be done using the old
366  *			fashion way
367  * @is_nfcv2:		NFCv2 has numerous enhancements compared to NFCv1, ie.
368  *			BCH error detection and correction algorithm,
369  *			NDCB3 register has been added
370  * @use_dma:		Use dma for data transfers
371  */
372 struct marvell_nfc_caps {
373 	unsigned int max_cs_nb;
374 	unsigned int max_rb_nb;
375 	bool need_system_controller;
376 	bool legacy_of_bindings;
377 	bool is_nfcv2;
378 	bool use_dma;
379 };
380 
381 /**
382  * struct marvell_nfc - stores Marvell NAND controller information
383  *
384  * @controller:		Base controller structure
385  * @dev:		Parent device (used to print error messages)
386  * @regs:		NAND controller registers
387  * @core_clk:		Core clock
388  * @reg_clk:		Registers clock
389  * @complete:		Completion object to wait for NAND controller events
390  * @assigned_cs:	Bitmask describing already assigned CS lines
391  * @chips:		List containing all the NAND chips attached to
392  *			this NAND controller
393  * @selected_chip:	Currently selected target chip
394  * @caps:		NAND controller capabilities for each compatible string
395  * @use_dma:		Whetner DMA is used
396  * @dma_chan:		DMA channel (NFCv1 only)
397  * @dma_buf:		32-bit aligned buffer for DMA transfers (NFCv1 only)
398  */
399 struct marvell_nfc {
400 	struct nand_controller controller;
401 	struct device *dev;
402 	void __iomem *regs;
403 	struct clk *core_clk;
404 	struct clk *reg_clk;
405 	struct completion complete;
406 	unsigned long assigned_cs;
407 	struct list_head chips;
408 	struct nand_chip *selected_chip;
409 	const struct marvell_nfc_caps *caps;
410 
411 	/* DMA (NFCv1 only) */
412 	bool use_dma;
413 	struct dma_chan *dma_chan;
414 	u8 *dma_buf;
415 };
416 
417 static inline struct marvell_nfc *to_marvell_nfc(struct nand_controller *ctrl)
418 {
419 	return container_of(ctrl, struct marvell_nfc, controller);
420 }
421 
422 /**
423  * struct marvell_nfc_timings - NAND controller timings expressed in NAND
424  *                              Controller clock cycles
425  *
426  * @tRP:		ND_nRE pulse width
427  * @tRH:		ND_nRE high duration
428  * @tWP:		ND_nWE pulse time
429  * @tWH:		ND_nWE high duration
430  * @tCS:		Enable signal setup time
431  * @tCH:		Enable signal hold time
432  * @tADL:		Address to write data delay
433  * @tAR:		ND_ALE low to ND_nRE low delay
434  * @tWHR:		ND_nWE high to ND_nRE low for status read
435  * @tRHW:		ND_nRE high duration, read to write delay
436  * @tR:			ND_nWE high to ND_nRE low for read
437  */
438 struct marvell_nfc_timings {
439 	/* NDTR0 fields */
440 	unsigned int tRP;
441 	unsigned int tRH;
442 	unsigned int tWP;
443 	unsigned int tWH;
444 	unsigned int tCS;
445 	unsigned int tCH;
446 	unsigned int tADL;
447 	/* NDTR1 fields */
448 	unsigned int tAR;
449 	unsigned int tWHR;
450 	unsigned int tRHW;
451 	unsigned int tR;
452 };
453 
454 /**
455  * TO_CYCLES() - Derives a duration in numbers of clock cycles.
456  *
457  * @ps: Duration in pico-seconds
458  * @period_ns:  Clock period in nano-seconds
459  *
460  * Convert the duration in nano-seconds, then divide by the period and
461  * return the number of clock periods.
462  */
463 #define TO_CYCLES(ps, period_ns) (DIV_ROUND_UP(ps / 1000, period_ns))
464 #define TO_CYCLES64(ps, period_ns) (DIV_ROUND_UP_ULL(div_u64(ps, 1000), \
465 						     period_ns))
466 
467 /**
468  * struct marvell_nfc_op - filled during the parsing of the ->exec_op()
469  *                         subop subset of instructions.
470  *
471  * @ndcb:		Array of values written to NDCBx registers
472  * @cle_ale_delay_ns:	Optional delay after the last CMD or ADDR cycle
473  * @rdy_timeout_ms:	Timeout for waits on Ready/Busy pin
474  * @rdy_delay_ns:	Optional delay after waiting for the RB pin
475  * @data_delay_ns:	Optional delay after the data xfer
476  * @data_instr_idx:	Index of the data instruction in the subop
477  * @data_instr:		Pointer to the data instruction in the subop
478  */
479 struct marvell_nfc_op {
480 	u32 ndcb[4];
481 	unsigned int cle_ale_delay_ns;
482 	unsigned int rdy_timeout_ms;
483 	unsigned int rdy_delay_ns;
484 	unsigned int data_delay_ns;
485 	unsigned int data_instr_idx;
486 	const struct nand_op_instr *data_instr;
487 };
488 
489 /*
490  * Internal helper to conditionnally apply a delay (from the above structure,
491  * most of the time).
492  */
493 static void cond_delay(unsigned int ns)
494 {
495 	if (!ns)
496 		return;
497 
498 	if (ns < 10000)
499 		ndelay(ns);
500 	else
501 		udelay(DIV_ROUND_UP(ns, 1000));
502 }
503 
504 /*
505  * The controller has many flags that could generate interrupts, most of them
506  * are disabled and polling is used. For the very slow signals, using interrupts
507  * may relax the CPU charge.
508  */
509 static void marvell_nfc_disable_int(struct marvell_nfc *nfc, u32 int_mask)
510 {
511 	u32 reg;
512 
513 	/* Writing 1 disables the interrupt */
514 	reg = readl_relaxed(nfc->regs + NDCR);
515 	writel_relaxed(reg | int_mask, nfc->regs + NDCR);
516 }
517 
518 static void marvell_nfc_enable_int(struct marvell_nfc *nfc, u32 int_mask)
519 {
520 	u32 reg;
521 
522 	/* Writing 0 enables the interrupt */
523 	reg = readl_relaxed(nfc->regs + NDCR);
524 	writel_relaxed(reg & ~int_mask, nfc->regs + NDCR);
525 }
526 
527 static u32 marvell_nfc_clear_int(struct marvell_nfc *nfc, u32 int_mask)
528 {
529 	u32 reg;
530 
531 	reg = readl_relaxed(nfc->regs + NDSR);
532 	writel_relaxed(int_mask, nfc->regs + NDSR);
533 
534 	return reg & int_mask;
535 }
536 
537 static void marvell_nfc_force_byte_access(struct nand_chip *chip,
538 					  bool force_8bit)
539 {
540 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
541 	u32 ndcr;
542 
543 	/*
544 	 * Callers of this function do not verify if the NAND is using a 16-bit
545 	 * an 8-bit bus for normal operations, so we need to take care of that
546 	 * here by leaving the configuration unchanged if the NAND does not have
547 	 * the NAND_BUSWIDTH_16 flag set.
548 	 */
549 	if (!(chip->options & NAND_BUSWIDTH_16))
550 		return;
551 
552 	ndcr = readl_relaxed(nfc->regs + NDCR);
553 
554 	if (force_8bit)
555 		ndcr &= ~(NDCR_DWIDTH_M | NDCR_DWIDTH_C);
556 	else
557 		ndcr |= NDCR_DWIDTH_M | NDCR_DWIDTH_C;
558 
559 	writel_relaxed(ndcr, nfc->regs + NDCR);
560 }
561 
562 static int marvell_nfc_wait_ndrun(struct nand_chip *chip)
563 {
564 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
565 	u32 val;
566 	int ret;
567 
568 	/*
569 	 * The command is being processed, wait for the ND_RUN bit to be
570 	 * cleared by the NFC. If not, we must clear it by hand.
571 	 */
572 	ret = readl_relaxed_poll_timeout(nfc->regs + NDCR, val,
573 					 (val & NDCR_ND_RUN) == 0,
574 					 POLL_PERIOD, POLL_TIMEOUT);
575 	if (ret) {
576 		dev_err(nfc->dev, "Timeout on NAND controller run mode\n");
577 		writel_relaxed(readl(nfc->regs + NDCR) & ~NDCR_ND_RUN,
578 			       nfc->regs + NDCR);
579 		return ret;
580 	}
581 
582 	return 0;
583 }
584 
585 /*
586  * Any time a command has to be sent to the controller, the following sequence
587  * has to be followed:
588  * - call marvell_nfc_prepare_cmd()
589  *      -> activate the ND_RUN bit that will kind of 'start a job'
590  *      -> wait the signal indicating the NFC is waiting for a command
591  * - send the command (cmd and address cycles)
592  * - enventually send or receive the data
593  * - call marvell_nfc_end_cmd() with the corresponding flag
594  *      -> wait the flag to be triggered or cancel the job with a timeout
595  *
596  * The following helpers are here to factorize the code a bit so that
597  * specialized functions responsible for executing the actual NAND
598  * operations do not have to replicate the same code blocks.
599  */
600 static int marvell_nfc_prepare_cmd(struct nand_chip *chip)
601 {
602 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
603 	u32 ndcr, val;
604 	int ret;
605 
606 	/* Poll ND_RUN and clear NDSR before issuing any command */
607 	ret = marvell_nfc_wait_ndrun(chip);
608 	if (ret) {
609 		dev_err(nfc->dev, "Last operation did not succeed\n");
610 		return ret;
611 	}
612 
613 	ndcr = readl_relaxed(nfc->regs + NDCR);
614 	writel_relaxed(readl(nfc->regs + NDSR), nfc->regs + NDSR);
615 
616 	/* Assert ND_RUN bit and wait the NFC to be ready */
617 	writel_relaxed(ndcr | NDCR_ND_RUN, nfc->regs + NDCR);
618 	ret = readl_relaxed_poll_timeout(nfc->regs + NDSR, val,
619 					 val & NDSR_WRCMDREQ,
620 					 POLL_PERIOD, POLL_TIMEOUT);
621 	if (ret) {
622 		dev_err(nfc->dev, "Timeout on WRCMDRE\n");
623 		return -ETIMEDOUT;
624 	}
625 
626 	/* Command may be written, clear WRCMDREQ status bit */
627 	writel_relaxed(NDSR_WRCMDREQ, nfc->regs + NDSR);
628 
629 	return 0;
630 }
631 
632 static void marvell_nfc_send_cmd(struct nand_chip *chip,
633 				 struct marvell_nfc_op *nfc_op)
634 {
635 	struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
636 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
637 
638 	dev_dbg(nfc->dev, "\nNDCR:  0x%08x\n"
639 		"NDCB0: 0x%08x\nNDCB1: 0x%08x\nNDCB2: 0x%08x\nNDCB3: 0x%08x\n",
640 		(u32)readl_relaxed(nfc->regs + NDCR), nfc_op->ndcb[0],
641 		nfc_op->ndcb[1], nfc_op->ndcb[2], nfc_op->ndcb[3]);
642 
643 	writel_relaxed(to_nand_sel(marvell_nand)->ndcb0_csel | nfc_op->ndcb[0],
644 		       nfc->regs + NDCB0);
645 	writel_relaxed(nfc_op->ndcb[1], nfc->regs + NDCB0);
646 	writel(nfc_op->ndcb[2], nfc->regs + NDCB0);
647 
648 	/*
649 	 * Write NDCB0 four times only if LEN_OVRD is set or if ADDR6 or ADDR7
650 	 * fields are used (only available on NFCv2).
651 	 */
652 	if (nfc_op->ndcb[0] & NDCB0_LEN_OVRD ||
653 	    NDCB0_ADDR_GET_NUM_CYC(nfc_op->ndcb[0]) >= 6) {
654 		if (!WARN_ON_ONCE(!nfc->caps->is_nfcv2))
655 			writel(nfc_op->ndcb[3], nfc->regs + NDCB0);
656 	}
657 }
658 
659 static int marvell_nfc_end_cmd(struct nand_chip *chip, int flag,
660 			       const char *label)
661 {
662 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
663 	u32 val;
664 	int ret;
665 
666 	ret = readl_relaxed_poll_timeout(nfc->regs + NDSR, val,
667 					 val & flag,
668 					 POLL_PERIOD, POLL_TIMEOUT);
669 
670 	if (ret) {
671 		dev_err(nfc->dev, "Timeout on %s (NDSR: 0x%08x)\n",
672 			label, val);
673 		if (nfc->dma_chan)
674 			dmaengine_terminate_all(nfc->dma_chan);
675 		return ret;
676 	}
677 
678 	/*
679 	 * DMA function uses this helper to poll on CMDD bits without wanting
680 	 * them to be cleared.
681 	 */
682 	if (nfc->use_dma && (readl_relaxed(nfc->regs + NDCR) & NDCR_DMA_EN))
683 		return 0;
684 
685 	writel_relaxed(flag, nfc->regs + NDSR);
686 
687 	return 0;
688 }
689 
690 static int marvell_nfc_wait_cmdd(struct nand_chip *chip)
691 {
692 	struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
693 	int cs_flag = NDSR_CMDD(to_nand_sel(marvell_nand)->ndcb0_csel);
694 
695 	return marvell_nfc_end_cmd(chip, cs_flag, "CMDD");
696 }
697 
698 static int marvell_nfc_poll_status(struct marvell_nfc *nfc, u32 mask,
699 				   u32 expected_val, unsigned long timeout_ms)
700 {
701 	unsigned long limit;
702 	u32 st;
703 
704 	limit = jiffies + msecs_to_jiffies(timeout_ms);
705 	do {
706 		st = readl_relaxed(nfc->regs + NDSR);
707 		if (st & NDSR_RDY(1))
708 			st |= NDSR_RDY(0);
709 
710 		if ((st & mask) == expected_val)
711 			return 0;
712 
713 		cpu_relax();
714 	} while (time_after(limit, jiffies));
715 
716 	return -ETIMEDOUT;
717 }
718 
719 static int marvell_nfc_wait_op(struct nand_chip *chip, unsigned int timeout_ms)
720 {
721 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
722 	struct mtd_info *mtd = nand_to_mtd(chip);
723 	u32 pending;
724 	int ret;
725 
726 	/* Timeout is expressed in ms */
727 	if (!timeout_ms)
728 		timeout_ms = IRQ_TIMEOUT;
729 
730 	if (mtd->oops_panic_write) {
731 		ret = marvell_nfc_poll_status(nfc, NDSR_RDY(0),
732 					      NDSR_RDY(0),
733 					      timeout_ms);
734 	} else {
735 		init_completion(&nfc->complete);
736 
737 		marvell_nfc_enable_int(nfc, NDCR_RDYM);
738 		ret = wait_for_completion_timeout(&nfc->complete,
739 						  msecs_to_jiffies(timeout_ms));
740 		marvell_nfc_disable_int(nfc, NDCR_RDYM);
741 	}
742 	pending = marvell_nfc_clear_int(nfc, NDSR_RDY(0) | NDSR_RDY(1));
743 
744 	/*
745 	 * In case the interrupt was not served in the required time frame,
746 	 * check if the ISR was not served or if something went actually wrong.
747 	 */
748 	if (!ret && !pending) {
749 		dev_err(nfc->dev, "Timeout waiting for RB signal\n");
750 		return -ETIMEDOUT;
751 	}
752 
753 	return 0;
754 }
755 
756 static void marvell_nfc_select_target(struct nand_chip *chip,
757 				      unsigned int die_nr)
758 {
759 	struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
760 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
761 	u32 ndcr_generic;
762 
763 	/*
764 	 * Reset the NDCR register to a clean state for this particular chip,
765 	 * also clear ND_RUN bit.
766 	 */
767 	ndcr_generic = readl_relaxed(nfc->regs + NDCR) &
768 		       NDCR_GENERIC_FIELDS_MASK & ~NDCR_ND_RUN;
769 	writel_relaxed(ndcr_generic | marvell_nand->ndcr, nfc->regs + NDCR);
770 
771 	/* Also reset the interrupt status register */
772 	marvell_nfc_clear_int(nfc, NDCR_ALL_INT);
773 
774 	if (chip == nfc->selected_chip && die_nr == marvell_nand->selected_die)
775 		return;
776 
777 	writel_relaxed(marvell_nand->ndtr0, nfc->regs + NDTR0);
778 	writel_relaxed(marvell_nand->ndtr1, nfc->regs + NDTR1);
779 
780 	nfc->selected_chip = chip;
781 	marvell_nand->selected_die = die_nr;
782 }
783 
784 static irqreturn_t marvell_nfc_isr(int irq, void *dev_id)
785 {
786 	struct marvell_nfc *nfc = dev_id;
787 	u32 st = readl_relaxed(nfc->regs + NDSR);
788 	u32 ien = (~readl_relaxed(nfc->regs + NDCR)) & NDCR_ALL_INT;
789 
790 	/*
791 	 * RDY interrupt mask is one bit in NDCR while there are two status
792 	 * bit in NDSR (RDY[cs0/cs2] and RDY[cs1/cs3]).
793 	 */
794 	if (st & NDSR_RDY(1))
795 		st |= NDSR_RDY(0);
796 
797 	if (!(st & ien))
798 		return IRQ_NONE;
799 
800 	marvell_nfc_disable_int(nfc, st & NDCR_ALL_INT);
801 
802 	if (st & (NDSR_RDY(0) | NDSR_RDY(1)))
803 		complete(&nfc->complete);
804 
805 	return IRQ_HANDLED;
806 }
807 
808 /* HW ECC related functions */
809 static void marvell_nfc_enable_hw_ecc(struct nand_chip *chip)
810 {
811 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
812 	u32 ndcr = readl_relaxed(nfc->regs + NDCR);
813 
814 	if (!(ndcr & NDCR_ECC_EN)) {
815 		writel_relaxed(ndcr | NDCR_ECC_EN, nfc->regs + NDCR);
816 
817 		/*
818 		 * When enabling BCH, set threshold to 0 to always know the
819 		 * number of corrected bitflips.
820 		 */
821 		if (chip->ecc.algo == NAND_ECC_ALGO_BCH)
822 			writel_relaxed(NDECCCTRL_BCH_EN, nfc->regs + NDECCCTRL);
823 	}
824 }
825 
826 static void marvell_nfc_disable_hw_ecc(struct nand_chip *chip)
827 {
828 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
829 	u32 ndcr = readl_relaxed(nfc->regs + NDCR);
830 
831 	if (ndcr & NDCR_ECC_EN) {
832 		writel_relaxed(ndcr & ~NDCR_ECC_EN, nfc->regs + NDCR);
833 		if (chip->ecc.algo == NAND_ECC_ALGO_BCH)
834 			writel_relaxed(0, nfc->regs + NDECCCTRL);
835 	}
836 }
837 
838 /* DMA related helpers */
839 static void marvell_nfc_enable_dma(struct marvell_nfc *nfc)
840 {
841 	u32 reg;
842 
843 	reg = readl_relaxed(nfc->regs + NDCR);
844 	writel_relaxed(reg | NDCR_DMA_EN, nfc->regs + NDCR);
845 }
846 
847 static void marvell_nfc_disable_dma(struct marvell_nfc *nfc)
848 {
849 	u32 reg;
850 
851 	reg = readl_relaxed(nfc->regs + NDCR);
852 	writel_relaxed(reg & ~NDCR_DMA_EN, nfc->regs + NDCR);
853 }
854 
855 /* Read/write PIO/DMA accessors */
856 static int marvell_nfc_xfer_data_dma(struct marvell_nfc *nfc,
857 				     enum dma_data_direction direction,
858 				     unsigned int len)
859 {
860 	unsigned int dma_len = min_t(int, ALIGN(len, 32), MAX_CHUNK_SIZE);
861 	struct dma_async_tx_descriptor *tx;
862 	struct scatterlist sg;
863 	dma_cookie_t cookie;
864 	int ret;
865 
866 	marvell_nfc_enable_dma(nfc);
867 	/* Prepare the DMA transfer */
868 	sg_init_one(&sg, nfc->dma_buf, dma_len);
869 	ret = dma_map_sg(nfc->dma_chan->device->dev, &sg, 1, direction);
870 	if (!ret) {
871 		dev_err(nfc->dev, "Could not map DMA S/G list\n");
872 		return -ENXIO;
873 	}
874 
875 	tx = dmaengine_prep_slave_sg(nfc->dma_chan, &sg, 1,
876 				     direction == DMA_FROM_DEVICE ?
877 				     DMA_DEV_TO_MEM : DMA_MEM_TO_DEV,
878 				     DMA_PREP_INTERRUPT);
879 	if (!tx) {
880 		dev_err(nfc->dev, "Could not prepare DMA S/G list\n");
881 		dma_unmap_sg(nfc->dma_chan->device->dev, &sg, 1, direction);
882 		return -ENXIO;
883 	}
884 
885 	/* Do the task and wait for it to finish */
886 	cookie = dmaengine_submit(tx);
887 	ret = dma_submit_error(cookie);
888 	if (ret)
889 		return -EIO;
890 
891 	dma_async_issue_pending(nfc->dma_chan);
892 	ret = marvell_nfc_wait_cmdd(nfc->selected_chip);
893 	dma_unmap_sg(nfc->dma_chan->device->dev, &sg, 1, direction);
894 	marvell_nfc_disable_dma(nfc);
895 	if (ret) {
896 		dev_err(nfc->dev, "Timeout waiting for DMA (status: %d)\n",
897 			dmaengine_tx_status(nfc->dma_chan, cookie, NULL));
898 		dmaengine_terminate_all(nfc->dma_chan);
899 		return -ETIMEDOUT;
900 	}
901 
902 	return 0;
903 }
904 
905 static int marvell_nfc_xfer_data_in_pio(struct marvell_nfc *nfc, u8 *in,
906 					unsigned int len)
907 {
908 	unsigned int last_len = len % FIFO_DEPTH;
909 	unsigned int last_full_offset = round_down(len, FIFO_DEPTH);
910 	int i;
911 
912 	for (i = 0; i < last_full_offset; i += FIFO_DEPTH)
913 		ioread32_rep(nfc->regs + NDDB, in + i, FIFO_REP(FIFO_DEPTH));
914 
915 	if (last_len) {
916 		u8 tmp_buf[FIFO_DEPTH];
917 
918 		ioread32_rep(nfc->regs + NDDB, tmp_buf, FIFO_REP(FIFO_DEPTH));
919 		memcpy(in + last_full_offset, tmp_buf, last_len);
920 	}
921 
922 	return 0;
923 }
924 
925 static int marvell_nfc_xfer_data_out_pio(struct marvell_nfc *nfc, const u8 *out,
926 					 unsigned int len)
927 {
928 	unsigned int last_len = len % FIFO_DEPTH;
929 	unsigned int last_full_offset = round_down(len, FIFO_DEPTH);
930 	int i;
931 
932 	for (i = 0; i < last_full_offset; i += FIFO_DEPTH)
933 		iowrite32_rep(nfc->regs + NDDB, out + i, FIFO_REP(FIFO_DEPTH));
934 
935 	if (last_len) {
936 		u8 tmp_buf[FIFO_DEPTH];
937 
938 		memcpy(tmp_buf, out + last_full_offset, last_len);
939 		iowrite32_rep(nfc->regs + NDDB, tmp_buf, FIFO_REP(FIFO_DEPTH));
940 	}
941 
942 	return 0;
943 }
944 
945 static void marvell_nfc_check_empty_chunk(struct nand_chip *chip,
946 					  u8 *data, int data_len,
947 					  u8 *spare, int spare_len,
948 					  u8 *ecc, int ecc_len,
949 					  unsigned int *max_bitflips)
950 {
951 	struct mtd_info *mtd = nand_to_mtd(chip);
952 	int bf;
953 
954 	/*
955 	 * Blank pages (all 0xFF) that have not been written may be recognized
956 	 * as bad if bitflips occur, so whenever an uncorrectable error occurs,
957 	 * check if the entire page (with ECC bytes) is actually blank or not.
958 	 */
959 	if (!data)
960 		data_len = 0;
961 	if (!spare)
962 		spare_len = 0;
963 	if (!ecc)
964 		ecc_len = 0;
965 
966 	bf = nand_check_erased_ecc_chunk(data, data_len, ecc, ecc_len,
967 					 spare, spare_len, chip->ecc.strength);
968 	if (bf < 0) {
969 		mtd->ecc_stats.failed++;
970 		return;
971 	}
972 
973 	/* Update the stats and max_bitflips */
974 	mtd->ecc_stats.corrected += bf;
975 	*max_bitflips = max_t(unsigned int, *max_bitflips, bf);
976 }
977 
978 /*
979  * Check if a chunk is correct or not according to the hardware ECC engine.
980  * mtd->ecc_stats.corrected is updated, as well as max_bitflips, however
981  * mtd->ecc_stats.failure is not, the function will instead return a non-zero
982  * value indicating that a check on the emptyness of the subpage must be
983  * performed before actually declaring the subpage as "corrupted".
984  */
985 static int marvell_nfc_hw_ecc_check_bitflips(struct nand_chip *chip,
986 					     unsigned int *max_bitflips)
987 {
988 	struct mtd_info *mtd = nand_to_mtd(chip);
989 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
990 	int bf = 0;
991 	u32 ndsr;
992 
993 	ndsr = readl_relaxed(nfc->regs + NDSR);
994 
995 	/* Check uncorrectable error flag */
996 	if (ndsr & NDSR_UNCERR) {
997 		writel_relaxed(ndsr, nfc->regs + NDSR);
998 
999 		/*
1000 		 * Do not increment ->ecc_stats.failed now, instead, return a
1001 		 * non-zero value to indicate that this chunk was apparently
1002 		 * bad, and it should be check to see if it empty or not. If
1003 		 * the chunk (with ECC bytes) is not declared empty, the calling
1004 		 * function must increment the failure count.
1005 		 */
1006 		return -EBADMSG;
1007 	}
1008 
1009 	/* Check correctable error flag */
1010 	if (ndsr & NDSR_CORERR) {
1011 		writel_relaxed(ndsr, nfc->regs + NDSR);
1012 
1013 		if (chip->ecc.algo == NAND_ECC_ALGO_BCH)
1014 			bf = NDSR_ERRCNT(ndsr);
1015 		else
1016 			bf = 1;
1017 	}
1018 
1019 	/* Update the stats and max_bitflips */
1020 	mtd->ecc_stats.corrected += bf;
1021 	*max_bitflips = max_t(unsigned int, *max_bitflips, bf);
1022 
1023 	return 0;
1024 }
1025 
1026 /* Hamming read helpers */
1027 static int marvell_nfc_hw_ecc_hmg_do_read_page(struct nand_chip *chip,
1028 					       u8 *data_buf, u8 *oob_buf,
1029 					       bool raw, int page)
1030 {
1031 	struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
1032 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1033 	const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1034 	struct marvell_nfc_op nfc_op = {
1035 		.ndcb[0] = NDCB0_CMD_TYPE(TYPE_READ) |
1036 			   NDCB0_ADDR_CYC(marvell_nand->addr_cyc) |
1037 			   NDCB0_DBC |
1038 			   NDCB0_CMD1(NAND_CMD_READ0) |
1039 			   NDCB0_CMD2(NAND_CMD_READSTART),
1040 		.ndcb[1] = NDCB1_ADDRS_PAGE(page),
1041 		.ndcb[2] = NDCB2_ADDR5_PAGE(page),
1042 	};
1043 	unsigned int oob_bytes = lt->spare_bytes + (raw ? lt->ecc_bytes : 0);
1044 	int ret;
1045 
1046 	/* NFCv2 needs more information about the operation being executed */
1047 	if (nfc->caps->is_nfcv2)
1048 		nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_MONOLITHIC_RW);
1049 
1050 	ret = marvell_nfc_prepare_cmd(chip);
1051 	if (ret)
1052 		return ret;
1053 
1054 	marvell_nfc_send_cmd(chip, &nfc_op);
1055 	ret = marvell_nfc_end_cmd(chip, NDSR_RDDREQ,
1056 				  "RDDREQ while draining FIFO (data/oob)");
1057 	if (ret)
1058 		return ret;
1059 
1060 	/*
1061 	 * Read the page then the OOB area. Unlike what is shown in current
1062 	 * documentation, spare bytes are protected by the ECC engine, and must
1063 	 * be at the beginning of the OOB area or running this driver on legacy
1064 	 * systems will prevent the discovery of the BBM/BBT.
1065 	 */
1066 	if (nfc->use_dma) {
1067 		marvell_nfc_xfer_data_dma(nfc, DMA_FROM_DEVICE,
1068 					  lt->data_bytes + oob_bytes);
1069 		memcpy(data_buf, nfc->dma_buf, lt->data_bytes);
1070 		memcpy(oob_buf, nfc->dma_buf + lt->data_bytes, oob_bytes);
1071 	} else {
1072 		marvell_nfc_xfer_data_in_pio(nfc, data_buf, lt->data_bytes);
1073 		marvell_nfc_xfer_data_in_pio(nfc, oob_buf, oob_bytes);
1074 	}
1075 
1076 	ret = marvell_nfc_wait_cmdd(chip);
1077 	return ret;
1078 }
1079 
1080 static int marvell_nfc_hw_ecc_hmg_read_page_raw(struct nand_chip *chip, u8 *buf,
1081 						int oob_required, int page)
1082 {
1083 	marvell_nfc_select_target(chip, chip->cur_cs);
1084 	return marvell_nfc_hw_ecc_hmg_do_read_page(chip, buf, chip->oob_poi,
1085 						   true, page);
1086 }
1087 
1088 static int marvell_nfc_hw_ecc_hmg_read_page(struct nand_chip *chip, u8 *buf,
1089 					    int oob_required, int page)
1090 {
1091 	const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1092 	unsigned int full_sz = lt->data_bytes + lt->spare_bytes + lt->ecc_bytes;
1093 	int max_bitflips = 0, ret;
1094 	u8 *raw_buf;
1095 
1096 	marvell_nfc_select_target(chip, chip->cur_cs);
1097 	marvell_nfc_enable_hw_ecc(chip);
1098 	marvell_nfc_hw_ecc_hmg_do_read_page(chip, buf, chip->oob_poi, false,
1099 					    page);
1100 	ret = marvell_nfc_hw_ecc_check_bitflips(chip, &max_bitflips);
1101 	marvell_nfc_disable_hw_ecc(chip);
1102 
1103 	if (!ret)
1104 		return max_bitflips;
1105 
1106 	/*
1107 	 * When ECC failures are detected, check if the full page has been
1108 	 * written or not. Ignore the failure if it is actually empty.
1109 	 */
1110 	raw_buf = kmalloc(full_sz, GFP_KERNEL);
1111 	if (!raw_buf)
1112 		return -ENOMEM;
1113 
1114 	marvell_nfc_hw_ecc_hmg_do_read_page(chip, raw_buf, raw_buf +
1115 					    lt->data_bytes, true, page);
1116 	marvell_nfc_check_empty_chunk(chip, raw_buf, full_sz, NULL, 0, NULL, 0,
1117 				      &max_bitflips);
1118 	kfree(raw_buf);
1119 
1120 	return max_bitflips;
1121 }
1122 
1123 /*
1124  * Spare area in Hamming layouts is not protected by the ECC engine (even if
1125  * it appears before the ECC bytes when reading), the ->read_oob_raw() function
1126  * also stands for ->read_oob().
1127  */
1128 static int marvell_nfc_hw_ecc_hmg_read_oob_raw(struct nand_chip *chip, int page)
1129 {
1130 	u8 *buf = nand_get_data_buf(chip);
1131 
1132 	marvell_nfc_select_target(chip, chip->cur_cs);
1133 	return marvell_nfc_hw_ecc_hmg_do_read_page(chip, buf, chip->oob_poi,
1134 						   true, page);
1135 }
1136 
1137 /* Hamming write helpers */
1138 static int marvell_nfc_hw_ecc_hmg_do_write_page(struct nand_chip *chip,
1139 						const u8 *data_buf,
1140 						const u8 *oob_buf, bool raw,
1141 						int page)
1142 {
1143 	const struct nand_sdr_timings *sdr =
1144 		nand_get_sdr_timings(nand_get_interface_config(chip));
1145 	struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
1146 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1147 	const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1148 	struct marvell_nfc_op nfc_op = {
1149 		.ndcb[0] = NDCB0_CMD_TYPE(TYPE_WRITE) |
1150 			   NDCB0_ADDR_CYC(marvell_nand->addr_cyc) |
1151 			   NDCB0_CMD1(NAND_CMD_SEQIN) |
1152 			   NDCB0_CMD2(NAND_CMD_PAGEPROG) |
1153 			   NDCB0_DBC,
1154 		.ndcb[1] = NDCB1_ADDRS_PAGE(page),
1155 		.ndcb[2] = NDCB2_ADDR5_PAGE(page),
1156 	};
1157 	unsigned int oob_bytes = lt->spare_bytes + (raw ? lt->ecc_bytes : 0);
1158 	int ret;
1159 
1160 	/* NFCv2 needs more information about the operation being executed */
1161 	if (nfc->caps->is_nfcv2)
1162 		nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_MONOLITHIC_RW);
1163 
1164 	ret = marvell_nfc_prepare_cmd(chip);
1165 	if (ret)
1166 		return ret;
1167 
1168 	marvell_nfc_send_cmd(chip, &nfc_op);
1169 	ret = marvell_nfc_end_cmd(chip, NDSR_WRDREQ,
1170 				  "WRDREQ while loading FIFO (data)");
1171 	if (ret)
1172 		return ret;
1173 
1174 	/* Write the page then the OOB area */
1175 	if (nfc->use_dma) {
1176 		memcpy(nfc->dma_buf, data_buf, lt->data_bytes);
1177 		memcpy(nfc->dma_buf + lt->data_bytes, oob_buf, oob_bytes);
1178 		marvell_nfc_xfer_data_dma(nfc, DMA_TO_DEVICE, lt->data_bytes +
1179 					  lt->ecc_bytes + lt->spare_bytes);
1180 	} else {
1181 		marvell_nfc_xfer_data_out_pio(nfc, data_buf, lt->data_bytes);
1182 		marvell_nfc_xfer_data_out_pio(nfc, oob_buf, oob_bytes);
1183 	}
1184 
1185 	ret = marvell_nfc_wait_cmdd(chip);
1186 	if (ret)
1187 		return ret;
1188 
1189 	ret = marvell_nfc_wait_op(chip,
1190 				  PSEC_TO_MSEC(sdr->tPROG_max));
1191 	return ret;
1192 }
1193 
1194 static int marvell_nfc_hw_ecc_hmg_write_page_raw(struct nand_chip *chip,
1195 						 const u8 *buf,
1196 						 int oob_required, int page)
1197 {
1198 	marvell_nfc_select_target(chip, chip->cur_cs);
1199 	return marvell_nfc_hw_ecc_hmg_do_write_page(chip, buf, chip->oob_poi,
1200 						    true, page);
1201 }
1202 
1203 static int marvell_nfc_hw_ecc_hmg_write_page(struct nand_chip *chip,
1204 					     const u8 *buf,
1205 					     int oob_required, int page)
1206 {
1207 	int ret;
1208 
1209 	marvell_nfc_select_target(chip, chip->cur_cs);
1210 	marvell_nfc_enable_hw_ecc(chip);
1211 	ret = marvell_nfc_hw_ecc_hmg_do_write_page(chip, buf, chip->oob_poi,
1212 						   false, page);
1213 	marvell_nfc_disable_hw_ecc(chip);
1214 
1215 	return ret;
1216 }
1217 
1218 /*
1219  * Spare area in Hamming layouts is not protected by the ECC engine (even if
1220  * it appears before the ECC bytes when reading), the ->write_oob_raw() function
1221  * also stands for ->write_oob().
1222  */
1223 static int marvell_nfc_hw_ecc_hmg_write_oob_raw(struct nand_chip *chip,
1224 						int page)
1225 {
1226 	struct mtd_info *mtd = nand_to_mtd(chip);
1227 	u8 *buf = nand_get_data_buf(chip);
1228 
1229 	memset(buf, 0xFF, mtd->writesize);
1230 
1231 	marvell_nfc_select_target(chip, chip->cur_cs);
1232 	return marvell_nfc_hw_ecc_hmg_do_write_page(chip, buf, chip->oob_poi,
1233 						    true, page);
1234 }
1235 
1236 /* BCH read helpers */
1237 static int marvell_nfc_hw_ecc_bch_read_page_raw(struct nand_chip *chip, u8 *buf,
1238 						int oob_required, int page)
1239 {
1240 	struct mtd_info *mtd = nand_to_mtd(chip);
1241 	const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1242 	u8 *oob = chip->oob_poi;
1243 	int chunk_size = lt->data_bytes + lt->spare_bytes + lt->ecc_bytes;
1244 	int ecc_offset = (lt->full_chunk_cnt * lt->spare_bytes) +
1245 		lt->last_spare_bytes;
1246 	int data_len = lt->data_bytes;
1247 	int spare_len = lt->spare_bytes;
1248 	int ecc_len = lt->ecc_bytes;
1249 	int chunk;
1250 
1251 	marvell_nfc_select_target(chip, chip->cur_cs);
1252 
1253 	if (oob_required)
1254 		memset(chip->oob_poi, 0xFF, mtd->oobsize);
1255 
1256 	nand_read_page_op(chip, page, 0, NULL, 0);
1257 
1258 	for (chunk = 0; chunk < lt->nchunks; chunk++) {
1259 		/* Update last chunk length */
1260 		if (chunk >= lt->full_chunk_cnt) {
1261 			data_len = lt->last_data_bytes;
1262 			spare_len = lt->last_spare_bytes;
1263 			ecc_len = lt->last_ecc_bytes;
1264 		}
1265 
1266 		/* Read data bytes*/
1267 		nand_change_read_column_op(chip, chunk * chunk_size,
1268 					   buf + (lt->data_bytes * chunk),
1269 					   data_len, false);
1270 
1271 		/* Read spare bytes */
1272 		nand_read_data_op(chip, oob + (lt->spare_bytes * chunk),
1273 				  spare_len, false, false);
1274 
1275 		/* Read ECC bytes */
1276 		nand_read_data_op(chip, oob + ecc_offset +
1277 				  (ALIGN(lt->ecc_bytes, 32) * chunk),
1278 				  ecc_len, false, false);
1279 	}
1280 
1281 	return 0;
1282 }
1283 
1284 static void marvell_nfc_hw_ecc_bch_read_chunk(struct nand_chip *chip, int chunk,
1285 					      u8 *data, unsigned int data_len,
1286 					      u8 *spare, unsigned int spare_len,
1287 					      int page)
1288 {
1289 	struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
1290 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1291 	const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1292 	int i, ret;
1293 	struct marvell_nfc_op nfc_op = {
1294 		.ndcb[0] = NDCB0_CMD_TYPE(TYPE_READ) |
1295 			   NDCB0_ADDR_CYC(marvell_nand->addr_cyc) |
1296 			   NDCB0_LEN_OVRD,
1297 		.ndcb[1] = NDCB1_ADDRS_PAGE(page),
1298 		.ndcb[2] = NDCB2_ADDR5_PAGE(page),
1299 		.ndcb[3] = data_len + spare_len,
1300 	};
1301 
1302 	ret = marvell_nfc_prepare_cmd(chip);
1303 	if (ret)
1304 		return;
1305 
1306 	if (chunk == 0)
1307 		nfc_op.ndcb[0] |= NDCB0_DBC |
1308 				  NDCB0_CMD1(NAND_CMD_READ0) |
1309 				  NDCB0_CMD2(NAND_CMD_READSTART);
1310 
1311 	/*
1312 	 * Trigger the monolithic read on the first chunk, then naked read on
1313 	 * intermediate chunks and finally a last naked read on the last chunk.
1314 	 */
1315 	if (chunk == 0)
1316 		nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_MONOLITHIC_RW);
1317 	else if (chunk < lt->nchunks - 1)
1318 		nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_NAKED_RW);
1319 	else
1320 		nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_LAST_NAKED_RW);
1321 
1322 	marvell_nfc_send_cmd(chip, &nfc_op);
1323 
1324 	/*
1325 	 * According to the datasheet, when reading from NDDB
1326 	 * with BCH enabled, after each 32 bytes reads, we
1327 	 * have to make sure that the NDSR.RDDREQ bit is set.
1328 	 *
1329 	 * Drain the FIFO, 8 32-bit reads at a time, and skip
1330 	 * the polling on the last read.
1331 	 *
1332 	 * Length is a multiple of 32 bytes, hence it is a multiple of 8 too.
1333 	 */
1334 	for (i = 0; i < data_len; i += FIFO_DEPTH * BCH_SEQ_READS) {
1335 		marvell_nfc_end_cmd(chip, NDSR_RDDREQ,
1336 				    "RDDREQ while draining FIFO (data)");
1337 		marvell_nfc_xfer_data_in_pio(nfc, data,
1338 					     FIFO_DEPTH * BCH_SEQ_READS);
1339 		data += FIFO_DEPTH * BCH_SEQ_READS;
1340 	}
1341 
1342 	for (i = 0; i < spare_len; i += FIFO_DEPTH * BCH_SEQ_READS) {
1343 		marvell_nfc_end_cmd(chip, NDSR_RDDREQ,
1344 				    "RDDREQ while draining FIFO (OOB)");
1345 		marvell_nfc_xfer_data_in_pio(nfc, spare,
1346 					     FIFO_DEPTH * BCH_SEQ_READS);
1347 		spare += FIFO_DEPTH * BCH_SEQ_READS;
1348 	}
1349 }
1350 
1351 static int marvell_nfc_hw_ecc_bch_read_page(struct nand_chip *chip,
1352 					    u8 *buf, int oob_required,
1353 					    int page)
1354 {
1355 	struct mtd_info *mtd = nand_to_mtd(chip);
1356 	const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1357 	int data_len = lt->data_bytes, spare_len = lt->spare_bytes;
1358 	u8 *data = buf, *spare = chip->oob_poi;
1359 	int max_bitflips = 0;
1360 	u32 failure_mask = 0;
1361 	int chunk, ret;
1362 
1363 	marvell_nfc_select_target(chip, chip->cur_cs);
1364 
1365 	/*
1366 	 * With BCH, OOB is not fully used (and thus not read entirely), not
1367 	 * expected bytes could show up at the end of the OOB buffer if not
1368 	 * explicitly erased.
1369 	 */
1370 	if (oob_required)
1371 		memset(chip->oob_poi, 0xFF, mtd->oobsize);
1372 
1373 	marvell_nfc_enable_hw_ecc(chip);
1374 
1375 	for (chunk = 0; chunk < lt->nchunks; chunk++) {
1376 		/* Update length for the last chunk */
1377 		if (chunk >= lt->full_chunk_cnt) {
1378 			data_len = lt->last_data_bytes;
1379 			spare_len = lt->last_spare_bytes;
1380 		}
1381 
1382 		/* Read the chunk and detect number of bitflips */
1383 		marvell_nfc_hw_ecc_bch_read_chunk(chip, chunk, data, data_len,
1384 						  spare, spare_len, page);
1385 		ret = marvell_nfc_hw_ecc_check_bitflips(chip, &max_bitflips);
1386 		if (ret)
1387 			failure_mask |= BIT(chunk);
1388 
1389 		data += data_len;
1390 		spare += spare_len;
1391 	}
1392 
1393 	marvell_nfc_disable_hw_ecc(chip);
1394 
1395 	if (!failure_mask)
1396 		return max_bitflips;
1397 
1398 	/*
1399 	 * Please note that dumping the ECC bytes during a normal read with OOB
1400 	 * area would add a significant overhead as ECC bytes are "consumed" by
1401 	 * the controller in normal mode and must be re-read in raw mode. To
1402 	 * avoid dropping the performances, we prefer not to include them. The
1403 	 * user should re-read the page in raw mode if ECC bytes are required.
1404 	 */
1405 
1406 	/*
1407 	 * In case there is any subpage read error, we usually re-read only ECC
1408 	 * bytes in raw mode and check if the whole page is empty. In this case,
1409 	 * it is normal that the ECC check failed and we just ignore the error.
1410 	 *
1411 	 * However, it has been empirically observed that for some layouts (e.g
1412 	 * 2k page, 8b strength per 512B chunk), the controller tries to correct
1413 	 * bits and may create itself bitflips in the erased area. To overcome
1414 	 * this strange behavior, the whole page is re-read in raw mode, not
1415 	 * only the ECC bytes.
1416 	 */
1417 	for (chunk = 0; chunk < lt->nchunks; chunk++) {
1418 		int data_off_in_page, spare_off_in_page, ecc_off_in_page;
1419 		int data_off, spare_off, ecc_off;
1420 		int data_len, spare_len, ecc_len;
1421 
1422 		/* No failure reported for this chunk, move to the next one */
1423 		if (!(failure_mask & BIT(chunk)))
1424 			continue;
1425 
1426 		data_off_in_page = chunk * (lt->data_bytes + lt->spare_bytes +
1427 					    lt->ecc_bytes);
1428 		spare_off_in_page = data_off_in_page +
1429 			(chunk < lt->full_chunk_cnt ? lt->data_bytes :
1430 						      lt->last_data_bytes);
1431 		ecc_off_in_page = spare_off_in_page +
1432 			(chunk < lt->full_chunk_cnt ? lt->spare_bytes :
1433 						      lt->last_spare_bytes);
1434 
1435 		data_off = chunk * lt->data_bytes;
1436 		spare_off = chunk * lt->spare_bytes;
1437 		ecc_off = (lt->full_chunk_cnt * lt->spare_bytes) +
1438 			  lt->last_spare_bytes +
1439 			  (chunk * (lt->ecc_bytes + 2));
1440 
1441 		data_len = chunk < lt->full_chunk_cnt ? lt->data_bytes :
1442 							lt->last_data_bytes;
1443 		spare_len = chunk < lt->full_chunk_cnt ? lt->spare_bytes :
1444 							 lt->last_spare_bytes;
1445 		ecc_len = chunk < lt->full_chunk_cnt ? lt->ecc_bytes :
1446 						       lt->last_ecc_bytes;
1447 
1448 		/*
1449 		 * Only re-read the ECC bytes, unless we are using the 2k/8b
1450 		 * layout which is buggy in the sense that the ECC engine will
1451 		 * try to correct data bytes anyway, creating bitflips. In this
1452 		 * case, re-read the entire page.
1453 		 */
1454 		if (lt->writesize == 2048 && lt->strength == 8) {
1455 			nand_change_read_column_op(chip, data_off_in_page,
1456 						   buf + data_off, data_len,
1457 						   false);
1458 			nand_change_read_column_op(chip, spare_off_in_page,
1459 						   chip->oob_poi + spare_off, spare_len,
1460 						   false);
1461 		}
1462 
1463 		nand_change_read_column_op(chip, ecc_off_in_page,
1464 					   chip->oob_poi + ecc_off, ecc_len,
1465 					   false);
1466 
1467 		/* Check the entire chunk (data + spare + ecc) for emptyness */
1468 		marvell_nfc_check_empty_chunk(chip, buf + data_off, data_len,
1469 					      chip->oob_poi + spare_off, spare_len,
1470 					      chip->oob_poi + ecc_off, ecc_len,
1471 					      &max_bitflips);
1472 	}
1473 
1474 	return max_bitflips;
1475 }
1476 
1477 static int marvell_nfc_hw_ecc_bch_read_oob_raw(struct nand_chip *chip, int page)
1478 {
1479 	u8 *buf = nand_get_data_buf(chip);
1480 
1481 	return chip->ecc.read_page_raw(chip, buf, true, page);
1482 }
1483 
1484 static int marvell_nfc_hw_ecc_bch_read_oob(struct nand_chip *chip, int page)
1485 {
1486 	u8 *buf = nand_get_data_buf(chip);
1487 
1488 	return chip->ecc.read_page(chip, buf, true, page);
1489 }
1490 
1491 /* BCH write helpers */
1492 static int marvell_nfc_hw_ecc_bch_write_page_raw(struct nand_chip *chip,
1493 						 const u8 *buf,
1494 						 int oob_required, int page)
1495 {
1496 	const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1497 	int full_chunk_size = lt->data_bytes + lt->spare_bytes + lt->ecc_bytes;
1498 	int data_len = lt->data_bytes;
1499 	int spare_len = lt->spare_bytes;
1500 	int ecc_len = lt->ecc_bytes;
1501 	int spare_offset = 0;
1502 	int ecc_offset = (lt->full_chunk_cnt * lt->spare_bytes) +
1503 		lt->last_spare_bytes;
1504 	int chunk;
1505 
1506 	marvell_nfc_select_target(chip, chip->cur_cs);
1507 
1508 	nand_prog_page_begin_op(chip, page, 0, NULL, 0);
1509 
1510 	for (chunk = 0; chunk < lt->nchunks; chunk++) {
1511 		if (chunk >= lt->full_chunk_cnt) {
1512 			data_len = lt->last_data_bytes;
1513 			spare_len = lt->last_spare_bytes;
1514 			ecc_len = lt->last_ecc_bytes;
1515 		}
1516 
1517 		/* Point to the column of the next chunk */
1518 		nand_change_write_column_op(chip, chunk * full_chunk_size,
1519 					    NULL, 0, false);
1520 
1521 		/* Write the data */
1522 		nand_write_data_op(chip, buf + (chunk * lt->data_bytes),
1523 				   data_len, false);
1524 
1525 		if (!oob_required)
1526 			continue;
1527 
1528 		/* Write the spare bytes */
1529 		if (spare_len)
1530 			nand_write_data_op(chip, chip->oob_poi + spare_offset,
1531 					   spare_len, false);
1532 
1533 		/* Write the ECC bytes */
1534 		if (ecc_len)
1535 			nand_write_data_op(chip, chip->oob_poi + ecc_offset,
1536 					   ecc_len, false);
1537 
1538 		spare_offset += spare_len;
1539 		ecc_offset += ALIGN(ecc_len, 32);
1540 	}
1541 
1542 	return nand_prog_page_end_op(chip);
1543 }
1544 
1545 static int
1546 marvell_nfc_hw_ecc_bch_write_chunk(struct nand_chip *chip, int chunk,
1547 				   const u8 *data, unsigned int data_len,
1548 				   const u8 *spare, unsigned int spare_len,
1549 				   int page)
1550 {
1551 	struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
1552 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1553 	const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1554 	u32 xtype;
1555 	int ret;
1556 	struct marvell_nfc_op nfc_op = {
1557 		.ndcb[0] = NDCB0_CMD_TYPE(TYPE_WRITE) | NDCB0_LEN_OVRD,
1558 		.ndcb[3] = data_len + spare_len,
1559 	};
1560 
1561 	/*
1562 	 * First operation dispatches the CMD_SEQIN command, issue the address
1563 	 * cycles and asks for the first chunk of data.
1564 	 * All operations in the middle (if any) will issue a naked write and
1565 	 * also ask for data.
1566 	 * Last operation (if any) asks for the last chunk of data through a
1567 	 * last naked write.
1568 	 */
1569 	if (chunk == 0) {
1570 		if (lt->nchunks == 1)
1571 			xtype = XTYPE_MONOLITHIC_RW;
1572 		else
1573 			xtype = XTYPE_WRITE_DISPATCH;
1574 
1575 		nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(xtype) |
1576 				  NDCB0_ADDR_CYC(marvell_nand->addr_cyc) |
1577 				  NDCB0_CMD1(NAND_CMD_SEQIN);
1578 		nfc_op.ndcb[1] |= NDCB1_ADDRS_PAGE(page);
1579 		nfc_op.ndcb[2] |= NDCB2_ADDR5_PAGE(page);
1580 	} else if (chunk < lt->nchunks - 1) {
1581 		nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_NAKED_RW);
1582 	} else {
1583 		nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_LAST_NAKED_RW);
1584 	}
1585 
1586 	/* Always dispatch the PAGEPROG command on the last chunk */
1587 	if (chunk == lt->nchunks - 1)
1588 		nfc_op.ndcb[0] |= NDCB0_CMD2(NAND_CMD_PAGEPROG) | NDCB0_DBC;
1589 
1590 	ret = marvell_nfc_prepare_cmd(chip);
1591 	if (ret)
1592 		return ret;
1593 
1594 	marvell_nfc_send_cmd(chip, &nfc_op);
1595 	ret = marvell_nfc_end_cmd(chip, NDSR_WRDREQ,
1596 				  "WRDREQ while loading FIFO (data)");
1597 	if (ret)
1598 		return ret;
1599 
1600 	/* Transfer the contents */
1601 	iowrite32_rep(nfc->regs + NDDB, data, FIFO_REP(data_len));
1602 	iowrite32_rep(nfc->regs + NDDB, spare, FIFO_REP(spare_len));
1603 
1604 	return 0;
1605 }
1606 
1607 static int marvell_nfc_hw_ecc_bch_write_page(struct nand_chip *chip,
1608 					     const u8 *buf,
1609 					     int oob_required, int page)
1610 {
1611 	const struct nand_sdr_timings *sdr =
1612 		nand_get_sdr_timings(nand_get_interface_config(chip));
1613 	struct mtd_info *mtd = nand_to_mtd(chip);
1614 	const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1615 	const u8 *data = buf;
1616 	const u8 *spare = chip->oob_poi;
1617 	int data_len = lt->data_bytes;
1618 	int spare_len = lt->spare_bytes;
1619 	int chunk, ret;
1620 
1621 	marvell_nfc_select_target(chip, chip->cur_cs);
1622 
1623 	/* Spare data will be written anyway, so clear it to avoid garbage */
1624 	if (!oob_required)
1625 		memset(chip->oob_poi, 0xFF, mtd->oobsize);
1626 
1627 	marvell_nfc_enable_hw_ecc(chip);
1628 
1629 	for (chunk = 0; chunk < lt->nchunks; chunk++) {
1630 		if (chunk >= lt->full_chunk_cnt) {
1631 			data_len = lt->last_data_bytes;
1632 			spare_len = lt->last_spare_bytes;
1633 		}
1634 
1635 		marvell_nfc_hw_ecc_bch_write_chunk(chip, chunk, data, data_len,
1636 						   spare, spare_len, page);
1637 		data += data_len;
1638 		spare += spare_len;
1639 
1640 		/*
1641 		 * Waiting only for CMDD or PAGED is not enough, ECC are
1642 		 * partially written. No flag is set once the operation is
1643 		 * really finished but the ND_RUN bit is cleared, so wait for it
1644 		 * before stepping into the next command.
1645 		 */
1646 		marvell_nfc_wait_ndrun(chip);
1647 	}
1648 
1649 	ret = marvell_nfc_wait_op(chip, PSEC_TO_MSEC(sdr->tPROG_max));
1650 
1651 	marvell_nfc_disable_hw_ecc(chip);
1652 
1653 	if (ret)
1654 		return ret;
1655 
1656 	return 0;
1657 }
1658 
1659 static int marvell_nfc_hw_ecc_bch_write_oob_raw(struct nand_chip *chip,
1660 						int page)
1661 {
1662 	struct mtd_info *mtd = nand_to_mtd(chip);
1663 	u8 *buf = nand_get_data_buf(chip);
1664 
1665 	memset(buf, 0xFF, mtd->writesize);
1666 
1667 	return chip->ecc.write_page_raw(chip, buf, true, page);
1668 }
1669 
1670 static int marvell_nfc_hw_ecc_bch_write_oob(struct nand_chip *chip, int page)
1671 {
1672 	struct mtd_info *mtd = nand_to_mtd(chip);
1673 	u8 *buf = nand_get_data_buf(chip);
1674 
1675 	memset(buf, 0xFF, mtd->writesize);
1676 
1677 	return chip->ecc.write_page(chip, buf, true, page);
1678 }
1679 
1680 /* NAND framework ->exec_op() hooks and related helpers */
1681 static void marvell_nfc_parse_instructions(struct nand_chip *chip,
1682 					   const struct nand_subop *subop,
1683 					   struct marvell_nfc_op *nfc_op)
1684 {
1685 	const struct nand_op_instr *instr = NULL;
1686 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1687 	bool first_cmd = true;
1688 	unsigned int op_id;
1689 	int i;
1690 
1691 	/* Reset the input structure as most of its fields will be OR'ed */
1692 	memset(nfc_op, 0, sizeof(struct marvell_nfc_op));
1693 
1694 	for (op_id = 0; op_id < subop->ninstrs; op_id++) {
1695 		unsigned int offset, naddrs;
1696 		const u8 *addrs;
1697 		int len;
1698 
1699 		instr = &subop->instrs[op_id];
1700 
1701 		switch (instr->type) {
1702 		case NAND_OP_CMD_INSTR:
1703 			if (first_cmd)
1704 				nfc_op->ndcb[0] |=
1705 					NDCB0_CMD1(instr->ctx.cmd.opcode);
1706 			else
1707 				nfc_op->ndcb[0] |=
1708 					NDCB0_CMD2(instr->ctx.cmd.opcode) |
1709 					NDCB0_DBC;
1710 
1711 			nfc_op->cle_ale_delay_ns = instr->delay_ns;
1712 			first_cmd = false;
1713 			break;
1714 
1715 		case NAND_OP_ADDR_INSTR:
1716 			offset = nand_subop_get_addr_start_off(subop, op_id);
1717 			naddrs = nand_subop_get_num_addr_cyc(subop, op_id);
1718 			addrs = &instr->ctx.addr.addrs[offset];
1719 
1720 			nfc_op->ndcb[0] |= NDCB0_ADDR_CYC(naddrs);
1721 
1722 			for (i = 0; i < min_t(unsigned int, 4, naddrs); i++)
1723 				nfc_op->ndcb[1] |= addrs[i] << (8 * i);
1724 
1725 			if (naddrs >= 5)
1726 				nfc_op->ndcb[2] |= NDCB2_ADDR5_CYC(addrs[4]);
1727 			if (naddrs >= 6)
1728 				nfc_op->ndcb[3] |= NDCB3_ADDR6_CYC(addrs[5]);
1729 			if (naddrs == 7)
1730 				nfc_op->ndcb[3] |= NDCB3_ADDR7_CYC(addrs[6]);
1731 
1732 			nfc_op->cle_ale_delay_ns = instr->delay_ns;
1733 			break;
1734 
1735 		case NAND_OP_DATA_IN_INSTR:
1736 			nfc_op->data_instr = instr;
1737 			nfc_op->data_instr_idx = op_id;
1738 			nfc_op->ndcb[0] |= NDCB0_CMD_TYPE(TYPE_READ);
1739 			if (nfc->caps->is_nfcv2) {
1740 				nfc_op->ndcb[0] |=
1741 					NDCB0_CMD_XTYPE(XTYPE_MONOLITHIC_RW) |
1742 					NDCB0_LEN_OVRD;
1743 				len = nand_subop_get_data_len(subop, op_id);
1744 				nfc_op->ndcb[3] |= round_up(len, FIFO_DEPTH);
1745 			}
1746 			nfc_op->data_delay_ns = instr->delay_ns;
1747 			break;
1748 
1749 		case NAND_OP_DATA_OUT_INSTR:
1750 			nfc_op->data_instr = instr;
1751 			nfc_op->data_instr_idx = op_id;
1752 			nfc_op->ndcb[0] |= NDCB0_CMD_TYPE(TYPE_WRITE);
1753 			if (nfc->caps->is_nfcv2) {
1754 				nfc_op->ndcb[0] |=
1755 					NDCB0_CMD_XTYPE(XTYPE_MONOLITHIC_RW) |
1756 					NDCB0_LEN_OVRD;
1757 				len = nand_subop_get_data_len(subop, op_id);
1758 				nfc_op->ndcb[3] |= round_up(len, FIFO_DEPTH);
1759 			}
1760 			nfc_op->data_delay_ns = instr->delay_ns;
1761 			break;
1762 
1763 		case NAND_OP_WAITRDY_INSTR:
1764 			nfc_op->rdy_timeout_ms = instr->ctx.waitrdy.timeout_ms;
1765 			nfc_op->rdy_delay_ns = instr->delay_ns;
1766 			break;
1767 		}
1768 	}
1769 }
1770 
1771 static int marvell_nfc_xfer_data_pio(struct nand_chip *chip,
1772 				     const struct nand_subop *subop,
1773 				     struct marvell_nfc_op *nfc_op)
1774 {
1775 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1776 	const struct nand_op_instr *instr = nfc_op->data_instr;
1777 	unsigned int op_id = nfc_op->data_instr_idx;
1778 	unsigned int len = nand_subop_get_data_len(subop, op_id);
1779 	unsigned int offset = nand_subop_get_data_start_off(subop, op_id);
1780 	bool reading = (instr->type == NAND_OP_DATA_IN_INSTR);
1781 	int ret;
1782 
1783 	if (instr->ctx.data.force_8bit)
1784 		marvell_nfc_force_byte_access(chip, true);
1785 
1786 	if (reading) {
1787 		u8 *in = instr->ctx.data.buf.in + offset;
1788 
1789 		ret = marvell_nfc_xfer_data_in_pio(nfc, in, len);
1790 	} else {
1791 		const u8 *out = instr->ctx.data.buf.out + offset;
1792 
1793 		ret = marvell_nfc_xfer_data_out_pio(nfc, out, len);
1794 	}
1795 
1796 	if (instr->ctx.data.force_8bit)
1797 		marvell_nfc_force_byte_access(chip, false);
1798 
1799 	return ret;
1800 }
1801 
1802 static int marvell_nfc_monolithic_access_exec(struct nand_chip *chip,
1803 					      const struct nand_subop *subop)
1804 {
1805 	struct marvell_nfc_op nfc_op;
1806 	bool reading;
1807 	int ret;
1808 
1809 	marvell_nfc_parse_instructions(chip, subop, &nfc_op);
1810 	reading = (nfc_op.data_instr->type == NAND_OP_DATA_IN_INSTR);
1811 
1812 	ret = marvell_nfc_prepare_cmd(chip);
1813 	if (ret)
1814 		return ret;
1815 
1816 	marvell_nfc_send_cmd(chip, &nfc_op);
1817 	ret = marvell_nfc_end_cmd(chip, NDSR_RDDREQ | NDSR_WRDREQ,
1818 				  "RDDREQ/WRDREQ while draining raw data");
1819 	if (ret)
1820 		return ret;
1821 
1822 	cond_delay(nfc_op.cle_ale_delay_ns);
1823 
1824 	if (reading) {
1825 		if (nfc_op.rdy_timeout_ms) {
1826 			ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
1827 			if (ret)
1828 				return ret;
1829 		}
1830 
1831 		cond_delay(nfc_op.rdy_delay_ns);
1832 	}
1833 
1834 	marvell_nfc_xfer_data_pio(chip, subop, &nfc_op);
1835 	ret = marvell_nfc_wait_cmdd(chip);
1836 	if (ret)
1837 		return ret;
1838 
1839 	cond_delay(nfc_op.data_delay_ns);
1840 
1841 	if (!reading) {
1842 		if (nfc_op.rdy_timeout_ms) {
1843 			ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
1844 			if (ret)
1845 				return ret;
1846 		}
1847 
1848 		cond_delay(nfc_op.rdy_delay_ns);
1849 	}
1850 
1851 	/*
1852 	 * NDCR ND_RUN bit should be cleared automatically at the end of each
1853 	 * operation but experience shows that the behavior is buggy when it
1854 	 * comes to writes (with LEN_OVRD). Clear it by hand in this case.
1855 	 */
1856 	if (!reading) {
1857 		struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1858 
1859 		writel_relaxed(readl(nfc->regs + NDCR) & ~NDCR_ND_RUN,
1860 			       nfc->regs + NDCR);
1861 	}
1862 
1863 	return 0;
1864 }
1865 
1866 static int marvell_nfc_naked_access_exec(struct nand_chip *chip,
1867 					 const struct nand_subop *subop)
1868 {
1869 	struct marvell_nfc_op nfc_op;
1870 	int ret;
1871 
1872 	marvell_nfc_parse_instructions(chip, subop, &nfc_op);
1873 
1874 	/*
1875 	 * Naked access are different in that they need to be flagged as naked
1876 	 * by the controller. Reset the controller registers fields that inform
1877 	 * on the type and refill them according to the ongoing operation.
1878 	 */
1879 	nfc_op.ndcb[0] &= ~(NDCB0_CMD_TYPE(TYPE_MASK) |
1880 			    NDCB0_CMD_XTYPE(XTYPE_MASK));
1881 	switch (subop->instrs[0].type) {
1882 	case NAND_OP_CMD_INSTR:
1883 		nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_NAKED_CMD);
1884 		break;
1885 	case NAND_OP_ADDR_INSTR:
1886 		nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_NAKED_ADDR);
1887 		break;
1888 	case NAND_OP_DATA_IN_INSTR:
1889 		nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_READ) |
1890 				  NDCB0_CMD_XTYPE(XTYPE_LAST_NAKED_RW);
1891 		break;
1892 	case NAND_OP_DATA_OUT_INSTR:
1893 		nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_WRITE) |
1894 				  NDCB0_CMD_XTYPE(XTYPE_LAST_NAKED_RW);
1895 		break;
1896 	default:
1897 		/* This should never happen */
1898 		break;
1899 	}
1900 
1901 	ret = marvell_nfc_prepare_cmd(chip);
1902 	if (ret)
1903 		return ret;
1904 
1905 	marvell_nfc_send_cmd(chip, &nfc_op);
1906 
1907 	if (!nfc_op.data_instr) {
1908 		ret = marvell_nfc_wait_cmdd(chip);
1909 		cond_delay(nfc_op.cle_ale_delay_ns);
1910 		return ret;
1911 	}
1912 
1913 	ret = marvell_nfc_end_cmd(chip, NDSR_RDDREQ | NDSR_WRDREQ,
1914 				  "RDDREQ/WRDREQ while draining raw data");
1915 	if (ret)
1916 		return ret;
1917 
1918 	marvell_nfc_xfer_data_pio(chip, subop, &nfc_op);
1919 	ret = marvell_nfc_wait_cmdd(chip);
1920 	if (ret)
1921 		return ret;
1922 
1923 	/*
1924 	 * NDCR ND_RUN bit should be cleared automatically at the end of each
1925 	 * operation but experience shows that the behavior is buggy when it
1926 	 * comes to writes (with LEN_OVRD). Clear it by hand in this case.
1927 	 */
1928 	if (subop->instrs[0].type == NAND_OP_DATA_OUT_INSTR) {
1929 		struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1930 
1931 		writel_relaxed(readl(nfc->regs + NDCR) & ~NDCR_ND_RUN,
1932 			       nfc->regs + NDCR);
1933 	}
1934 
1935 	return 0;
1936 }
1937 
1938 static int marvell_nfc_naked_waitrdy_exec(struct nand_chip *chip,
1939 					  const struct nand_subop *subop)
1940 {
1941 	struct marvell_nfc_op nfc_op;
1942 	int ret;
1943 
1944 	marvell_nfc_parse_instructions(chip, subop, &nfc_op);
1945 
1946 	ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
1947 	cond_delay(nfc_op.rdy_delay_ns);
1948 
1949 	return ret;
1950 }
1951 
1952 static int marvell_nfc_read_id_type_exec(struct nand_chip *chip,
1953 					 const struct nand_subop *subop)
1954 {
1955 	struct marvell_nfc_op nfc_op;
1956 	int ret;
1957 
1958 	marvell_nfc_parse_instructions(chip, subop, &nfc_op);
1959 	nfc_op.ndcb[0] &= ~NDCB0_CMD_TYPE(TYPE_READ);
1960 	nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_READ_ID);
1961 
1962 	ret = marvell_nfc_prepare_cmd(chip);
1963 	if (ret)
1964 		return ret;
1965 
1966 	marvell_nfc_send_cmd(chip, &nfc_op);
1967 	ret = marvell_nfc_end_cmd(chip, NDSR_RDDREQ,
1968 				  "RDDREQ while reading ID");
1969 	if (ret)
1970 		return ret;
1971 
1972 	cond_delay(nfc_op.cle_ale_delay_ns);
1973 
1974 	if (nfc_op.rdy_timeout_ms) {
1975 		ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
1976 		if (ret)
1977 			return ret;
1978 	}
1979 
1980 	cond_delay(nfc_op.rdy_delay_ns);
1981 
1982 	marvell_nfc_xfer_data_pio(chip, subop, &nfc_op);
1983 	ret = marvell_nfc_wait_cmdd(chip);
1984 	if (ret)
1985 		return ret;
1986 
1987 	cond_delay(nfc_op.data_delay_ns);
1988 
1989 	return 0;
1990 }
1991 
1992 static int marvell_nfc_read_status_exec(struct nand_chip *chip,
1993 					const struct nand_subop *subop)
1994 {
1995 	struct marvell_nfc_op nfc_op;
1996 	int ret;
1997 
1998 	marvell_nfc_parse_instructions(chip, subop, &nfc_op);
1999 	nfc_op.ndcb[0] &= ~NDCB0_CMD_TYPE(TYPE_READ);
2000 	nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_STATUS);
2001 
2002 	ret = marvell_nfc_prepare_cmd(chip);
2003 	if (ret)
2004 		return ret;
2005 
2006 	marvell_nfc_send_cmd(chip, &nfc_op);
2007 	ret = marvell_nfc_end_cmd(chip, NDSR_RDDREQ,
2008 				  "RDDREQ while reading status");
2009 	if (ret)
2010 		return ret;
2011 
2012 	cond_delay(nfc_op.cle_ale_delay_ns);
2013 
2014 	if (nfc_op.rdy_timeout_ms) {
2015 		ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
2016 		if (ret)
2017 			return ret;
2018 	}
2019 
2020 	cond_delay(nfc_op.rdy_delay_ns);
2021 
2022 	marvell_nfc_xfer_data_pio(chip, subop, &nfc_op);
2023 	ret = marvell_nfc_wait_cmdd(chip);
2024 	if (ret)
2025 		return ret;
2026 
2027 	cond_delay(nfc_op.data_delay_ns);
2028 
2029 	return 0;
2030 }
2031 
2032 static int marvell_nfc_reset_cmd_type_exec(struct nand_chip *chip,
2033 					   const struct nand_subop *subop)
2034 {
2035 	struct marvell_nfc_op nfc_op;
2036 	int ret;
2037 
2038 	marvell_nfc_parse_instructions(chip, subop, &nfc_op);
2039 	nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_RESET);
2040 
2041 	ret = marvell_nfc_prepare_cmd(chip);
2042 	if (ret)
2043 		return ret;
2044 
2045 	marvell_nfc_send_cmd(chip, &nfc_op);
2046 	ret = marvell_nfc_wait_cmdd(chip);
2047 	if (ret)
2048 		return ret;
2049 
2050 	cond_delay(nfc_op.cle_ale_delay_ns);
2051 
2052 	ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
2053 	if (ret)
2054 		return ret;
2055 
2056 	cond_delay(nfc_op.rdy_delay_ns);
2057 
2058 	return 0;
2059 }
2060 
2061 static int marvell_nfc_erase_cmd_type_exec(struct nand_chip *chip,
2062 					   const struct nand_subop *subop)
2063 {
2064 	struct marvell_nfc_op nfc_op;
2065 	int ret;
2066 
2067 	marvell_nfc_parse_instructions(chip, subop, &nfc_op);
2068 	nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_ERASE);
2069 
2070 	ret = marvell_nfc_prepare_cmd(chip);
2071 	if (ret)
2072 		return ret;
2073 
2074 	marvell_nfc_send_cmd(chip, &nfc_op);
2075 	ret = marvell_nfc_wait_cmdd(chip);
2076 	if (ret)
2077 		return ret;
2078 
2079 	cond_delay(nfc_op.cle_ale_delay_ns);
2080 
2081 	ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
2082 	if (ret)
2083 		return ret;
2084 
2085 	cond_delay(nfc_op.rdy_delay_ns);
2086 
2087 	return 0;
2088 }
2089 
2090 static const struct nand_op_parser marvell_nfcv2_op_parser = NAND_OP_PARSER(
2091 	/* Monolithic reads/writes */
2092 	NAND_OP_PARSER_PATTERN(
2093 		marvell_nfc_monolithic_access_exec,
2094 		NAND_OP_PARSER_PAT_CMD_ELEM(false),
2095 		NAND_OP_PARSER_PAT_ADDR_ELEM(true, MAX_ADDRESS_CYC_NFCV2),
2096 		NAND_OP_PARSER_PAT_CMD_ELEM(true),
2097 		NAND_OP_PARSER_PAT_WAITRDY_ELEM(true),
2098 		NAND_OP_PARSER_PAT_DATA_IN_ELEM(false, MAX_CHUNK_SIZE)),
2099 	NAND_OP_PARSER_PATTERN(
2100 		marvell_nfc_monolithic_access_exec,
2101 		NAND_OP_PARSER_PAT_CMD_ELEM(false),
2102 		NAND_OP_PARSER_PAT_ADDR_ELEM(false, MAX_ADDRESS_CYC_NFCV2),
2103 		NAND_OP_PARSER_PAT_DATA_OUT_ELEM(false, MAX_CHUNK_SIZE),
2104 		NAND_OP_PARSER_PAT_CMD_ELEM(true),
2105 		NAND_OP_PARSER_PAT_WAITRDY_ELEM(true)),
2106 	/* Naked commands */
2107 	NAND_OP_PARSER_PATTERN(
2108 		marvell_nfc_naked_access_exec,
2109 		NAND_OP_PARSER_PAT_CMD_ELEM(false)),
2110 	NAND_OP_PARSER_PATTERN(
2111 		marvell_nfc_naked_access_exec,
2112 		NAND_OP_PARSER_PAT_ADDR_ELEM(false, MAX_ADDRESS_CYC_NFCV2)),
2113 	NAND_OP_PARSER_PATTERN(
2114 		marvell_nfc_naked_access_exec,
2115 		NAND_OP_PARSER_PAT_DATA_IN_ELEM(false, MAX_CHUNK_SIZE)),
2116 	NAND_OP_PARSER_PATTERN(
2117 		marvell_nfc_naked_access_exec,
2118 		NAND_OP_PARSER_PAT_DATA_OUT_ELEM(false, MAX_CHUNK_SIZE)),
2119 	NAND_OP_PARSER_PATTERN(
2120 		marvell_nfc_naked_waitrdy_exec,
2121 		NAND_OP_PARSER_PAT_WAITRDY_ELEM(false)),
2122 	);
2123 
2124 static const struct nand_op_parser marvell_nfcv1_op_parser = NAND_OP_PARSER(
2125 	/* Naked commands not supported, use a function for each pattern */
2126 	NAND_OP_PARSER_PATTERN(
2127 		marvell_nfc_read_id_type_exec,
2128 		NAND_OP_PARSER_PAT_CMD_ELEM(false),
2129 		NAND_OP_PARSER_PAT_ADDR_ELEM(false, MAX_ADDRESS_CYC_NFCV1),
2130 		NAND_OP_PARSER_PAT_DATA_IN_ELEM(false, 8)),
2131 	NAND_OP_PARSER_PATTERN(
2132 		marvell_nfc_erase_cmd_type_exec,
2133 		NAND_OP_PARSER_PAT_CMD_ELEM(false),
2134 		NAND_OP_PARSER_PAT_ADDR_ELEM(false, MAX_ADDRESS_CYC_NFCV1),
2135 		NAND_OP_PARSER_PAT_CMD_ELEM(false),
2136 		NAND_OP_PARSER_PAT_WAITRDY_ELEM(false)),
2137 	NAND_OP_PARSER_PATTERN(
2138 		marvell_nfc_read_status_exec,
2139 		NAND_OP_PARSER_PAT_CMD_ELEM(false),
2140 		NAND_OP_PARSER_PAT_DATA_IN_ELEM(false, 1)),
2141 	NAND_OP_PARSER_PATTERN(
2142 		marvell_nfc_reset_cmd_type_exec,
2143 		NAND_OP_PARSER_PAT_CMD_ELEM(false),
2144 		NAND_OP_PARSER_PAT_WAITRDY_ELEM(false)),
2145 	NAND_OP_PARSER_PATTERN(
2146 		marvell_nfc_naked_waitrdy_exec,
2147 		NAND_OP_PARSER_PAT_WAITRDY_ELEM(false)),
2148 	);
2149 
2150 static int marvell_nfc_exec_op(struct nand_chip *chip,
2151 			       const struct nand_operation *op,
2152 			       bool check_only)
2153 {
2154 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
2155 
2156 	if (!check_only)
2157 		marvell_nfc_select_target(chip, op->cs);
2158 
2159 	if (nfc->caps->is_nfcv2)
2160 		return nand_op_parser_exec_op(chip, &marvell_nfcv2_op_parser,
2161 					      op, check_only);
2162 	else
2163 		return nand_op_parser_exec_op(chip, &marvell_nfcv1_op_parser,
2164 					      op, check_only);
2165 }
2166 
2167 /*
2168  * Layouts were broken in old pxa3xx_nand driver, these are supposed to be
2169  * usable.
2170  */
2171 static int marvell_nand_ooblayout_ecc(struct mtd_info *mtd, int section,
2172 				      struct mtd_oob_region *oobregion)
2173 {
2174 	struct nand_chip *chip = mtd_to_nand(mtd);
2175 	const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
2176 
2177 	if (section)
2178 		return -ERANGE;
2179 
2180 	oobregion->length = (lt->full_chunk_cnt * lt->ecc_bytes) +
2181 			    lt->last_ecc_bytes;
2182 	oobregion->offset = mtd->oobsize - oobregion->length;
2183 
2184 	return 0;
2185 }
2186 
2187 static int marvell_nand_ooblayout_free(struct mtd_info *mtd, int section,
2188 				       struct mtd_oob_region *oobregion)
2189 {
2190 	struct nand_chip *chip = mtd_to_nand(mtd);
2191 	const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
2192 
2193 	if (section)
2194 		return -ERANGE;
2195 
2196 	/*
2197 	 * Bootrom looks in bytes 0 & 5 for bad blocks for the
2198 	 * 4KB page / 4bit BCH combination.
2199 	 */
2200 	if (mtd->writesize == SZ_4K && lt->data_bytes == SZ_2K)
2201 		oobregion->offset = 6;
2202 	else
2203 		oobregion->offset = 2;
2204 
2205 	oobregion->length = (lt->full_chunk_cnt * lt->spare_bytes) +
2206 			    lt->last_spare_bytes - oobregion->offset;
2207 
2208 	return 0;
2209 }
2210 
2211 static const struct mtd_ooblayout_ops marvell_nand_ooblayout_ops = {
2212 	.ecc = marvell_nand_ooblayout_ecc,
2213 	.free = marvell_nand_ooblayout_free,
2214 };
2215 
2216 static int marvell_nand_hw_ecc_controller_init(struct mtd_info *mtd,
2217 					       struct nand_ecc_ctrl *ecc)
2218 {
2219 	struct nand_chip *chip = mtd_to_nand(mtd);
2220 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
2221 	const struct marvell_hw_ecc_layout *l;
2222 	int i;
2223 
2224 	if (!nfc->caps->is_nfcv2 &&
2225 	    (mtd->writesize + mtd->oobsize > MAX_CHUNK_SIZE)) {
2226 		dev_err(nfc->dev,
2227 			"NFCv1: writesize (%d) cannot be bigger than a chunk (%d)\n",
2228 			mtd->writesize, MAX_CHUNK_SIZE - mtd->oobsize);
2229 		return -ENOTSUPP;
2230 	}
2231 
2232 	to_marvell_nand(chip)->layout = NULL;
2233 	for (i = 0; i < ARRAY_SIZE(marvell_nfc_layouts); i++) {
2234 		l = &marvell_nfc_layouts[i];
2235 		if (mtd->writesize == l->writesize &&
2236 		    ecc->size == l->chunk && ecc->strength == l->strength) {
2237 			to_marvell_nand(chip)->layout = l;
2238 			break;
2239 		}
2240 	}
2241 
2242 	if (!to_marvell_nand(chip)->layout ||
2243 	    (!nfc->caps->is_nfcv2 && ecc->strength > 1)) {
2244 		dev_err(nfc->dev,
2245 			"ECC strength %d at page size %d is not supported\n",
2246 			ecc->strength, mtd->writesize);
2247 		return -ENOTSUPP;
2248 	}
2249 
2250 	/* Special care for the layout 2k/8-bit/512B  */
2251 	if (l->writesize == 2048 && l->strength == 8) {
2252 		if (mtd->oobsize < 128) {
2253 			dev_err(nfc->dev, "Requested layout needs at least 128 OOB bytes\n");
2254 			return -ENOTSUPP;
2255 		} else {
2256 			chip->bbt_options |= NAND_BBT_NO_OOB_BBM;
2257 		}
2258 	}
2259 
2260 	mtd_set_ooblayout(mtd, &marvell_nand_ooblayout_ops);
2261 	ecc->steps = l->nchunks;
2262 	ecc->size = l->data_bytes;
2263 
2264 	if (ecc->strength == 1) {
2265 		chip->ecc.algo = NAND_ECC_ALGO_HAMMING;
2266 		ecc->read_page_raw = marvell_nfc_hw_ecc_hmg_read_page_raw;
2267 		ecc->read_page = marvell_nfc_hw_ecc_hmg_read_page;
2268 		ecc->read_oob_raw = marvell_nfc_hw_ecc_hmg_read_oob_raw;
2269 		ecc->read_oob = ecc->read_oob_raw;
2270 		ecc->write_page_raw = marvell_nfc_hw_ecc_hmg_write_page_raw;
2271 		ecc->write_page = marvell_nfc_hw_ecc_hmg_write_page;
2272 		ecc->write_oob_raw = marvell_nfc_hw_ecc_hmg_write_oob_raw;
2273 		ecc->write_oob = ecc->write_oob_raw;
2274 	} else {
2275 		chip->ecc.algo = NAND_ECC_ALGO_BCH;
2276 		ecc->strength = 16;
2277 		ecc->read_page_raw = marvell_nfc_hw_ecc_bch_read_page_raw;
2278 		ecc->read_page = marvell_nfc_hw_ecc_bch_read_page;
2279 		ecc->read_oob_raw = marvell_nfc_hw_ecc_bch_read_oob_raw;
2280 		ecc->read_oob = marvell_nfc_hw_ecc_bch_read_oob;
2281 		ecc->write_page_raw = marvell_nfc_hw_ecc_bch_write_page_raw;
2282 		ecc->write_page = marvell_nfc_hw_ecc_bch_write_page;
2283 		ecc->write_oob_raw = marvell_nfc_hw_ecc_bch_write_oob_raw;
2284 		ecc->write_oob = marvell_nfc_hw_ecc_bch_write_oob;
2285 	}
2286 
2287 	return 0;
2288 }
2289 
2290 static int marvell_nand_ecc_init(struct mtd_info *mtd,
2291 				 struct nand_ecc_ctrl *ecc)
2292 {
2293 	struct nand_chip *chip = mtd_to_nand(mtd);
2294 	const struct nand_ecc_props *requirements =
2295 		nanddev_get_ecc_requirements(&chip->base);
2296 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
2297 	int ret;
2298 
2299 	if (ecc->engine_type != NAND_ECC_ENGINE_TYPE_NONE &&
2300 	    (!ecc->size || !ecc->strength)) {
2301 		if (requirements->step_size && requirements->strength) {
2302 			ecc->size = requirements->step_size;
2303 			ecc->strength = requirements->strength;
2304 		} else {
2305 			dev_info(nfc->dev,
2306 				 "No minimum ECC strength, using 1b/512B\n");
2307 			ecc->size = 512;
2308 			ecc->strength = 1;
2309 		}
2310 	}
2311 
2312 	switch (ecc->engine_type) {
2313 	case NAND_ECC_ENGINE_TYPE_ON_HOST:
2314 		ret = marvell_nand_hw_ecc_controller_init(mtd, ecc);
2315 		if (ret)
2316 			return ret;
2317 		break;
2318 	case NAND_ECC_ENGINE_TYPE_NONE:
2319 	case NAND_ECC_ENGINE_TYPE_SOFT:
2320 	case NAND_ECC_ENGINE_TYPE_ON_DIE:
2321 		if (!nfc->caps->is_nfcv2 && mtd->writesize != SZ_512 &&
2322 		    mtd->writesize != SZ_2K) {
2323 			dev_err(nfc->dev, "NFCv1 cannot write %d bytes pages\n",
2324 				mtd->writesize);
2325 			return -EINVAL;
2326 		}
2327 		break;
2328 	default:
2329 		return -EINVAL;
2330 	}
2331 
2332 	return 0;
2333 }
2334 
2335 static u8 bbt_pattern[] = {'M', 'V', 'B', 'b', 't', '0' };
2336 static u8 bbt_mirror_pattern[] = {'1', 't', 'b', 'B', 'V', 'M' };
2337 
2338 static struct nand_bbt_descr bbt_main_descr = {
2339 	.options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE |
2340 		   NAND_BBT_2BIT | NAND_BBT_VERSION,
2341 	.offs =	8,
2342 	.len = 6,
2343 	.veroffs = 14,
2344 	.maxblocks = 8,	/* Last 8 blocks in each chip */
2345 	.pattern = bbt_pattern
2346 };
2347 
2348 static struct nand_bbt_descr bbt_mirror_descr = {
2349 	.options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE |
2350 		   NAND_BBT_2BIT | NAND_BBT_VERSION,
2351 	.offs =	8,
2352 	.len = 6,
2353 	.veroffs = 14,
2354 	.maxblocks = 8,	/* Last 8 blocks in each chip */
2355 	.pattern = bbt_mirror_pattern
2356 };
2357 
2358 static int marvell_nfc_setup_interface(struct nand_chip *chip, int chipnr,
2359 				       const struct nand_interface_config *conf)
2360 {
2361 	struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
2362 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
2363 	unsigned int period_ns = 1000000000 / clk_get_rate(nfc->core_clk) * 2;
2364 	const struct nand_sdr_timings *sdr;
2365 	struct marvell_nfc_timings nfc_tmg;
2366 	int read_delay;
2367 
2368 	sdr = nand_get_sdr_timings(conf);
2369 	if (IS_ERR(sdr))
2370 		return PTR_ERR(sdr);
2371 
2372 	/*
2373 	 * SDR timings are given in pico-seconds while NFC timings must be
2374 	 * expressed in NAND controller clock cycles, which is half of the
2375 	 * frequency of the accessible ECC clock retrieved by clk_get_rate().
2376 	 * This is not written anywhere in the datasheet but was observed
2377 	 * with an oscilloscope.
2378 	 *
2379 	 * NFC datasheet gives equations from which thoses calculations
2380 	 * are derived, they tend to be slightly more restrictives than the
2381 	 * given core timings and may improve the overall speed.
2382 	 */
2383 	nfc_tmg.tRP = TO_CYCLES(DIV_ROUND_UP(sdr->tRC_min, 2), period_ns) - 1;
2384 	nfc_tmg.tRH = nfc_tmg.tRP;
2385 	nfc_tmg.tWP = TO_CYCLES(DIV_ROUND_UP(sdr->tWC_min, 2), period_ns) - 1;
2386 	nfc_tmg.tWH = nfc_tmg.tWP;
2387 	nfc_tmg.tCS = TO_CYCLES(sdr->tCS_min, period_ns);
2388 	nfc_tmg.tCH = TO_CYCLES(sdr->tCH_min, period_ns) - 1;
2389 	nfc_tmg.tADL = TO_CYCLES(sdr->tADL_min, period_ns);
2390 	/*
2391 	 * Read delay is the time of propagation from SoC pins to NFC internal
2392 	 * logic. With non-EDO timings, this is MIN_RD_DEL_CNT clock cycles. In
2393 	 * EDO mode, an additional delay of tRH must be taken into account so
2394 	 * the data is sampled on the falling edge instead of the rising edge.
2395 	 */
2396 	read_delay = sdr->tRC_min >= 30000 ?
2397 		MIN_RD_DEL_CNT : MIN_RD_DEL_CNT + nfc_tmg.tRH;
2398 
2399 	nfc_tmg.tAR = TO_CYCLES(sdr->tAR_min, period_ns);
2400 	/*
2401 	 * tWHR and tRHW are supposed to be read to write delays (and vice
2402 	 * versa) but in some cases, ie. when doing a change column, they must
2403 	 * be greater than that to be sure tCCS delay is respected.
2404 	 */
2405 	nfc_tmg.tWHR = TO_CYCLES(max_t(int, sdr->tWHR_min, sdr->tCCS_min),
2406 				 period_ns) - 2;
2407 	nfc_tmg.tRHW = TO_CYCLES(max_t(int, sdr->tRHW_min, sdr->tCCS_min),
2408 				 period_ns);
2409 
2410 	/*
2411 	 * NFCv2: Use WAIT_MODE (wait for RB line), do not rely only on delays.
2412 	 * NFCv1: No WAIT_MODE, tR must be maximal.
2413 	 */
2414 	if (nfc->caps->is_nfcv2) {
2415 		nfc_tmg.tR = TO_CYCLES(sdr->tWB_max, period_ns);
2416 	} else {
2417 		nfc_tmg.tR = TO_CYCLES64(sdr->tWB_max + sdr->tR_max,
2418 					 period_ns);
2419 		if (nfc_tmg.tR + 3 > nfc_tmg.tCH)
2420 			nfc_tmg.tR = nfc_tmg.tCH - 3;
2421 		else
2422 			nfc_tmg.tR = 0;
2423 	}
2424 
2425 	if (chipnr < 0)
2426 		return 0;
2427 
2428 	marvell_nand->ndtr0 =
2429 		NDTR0_TRP(nfc_tmg.tRP) |
2430 		NDTR0_TRH(nfc_tmg.tRH) |
2431 		NDTR0_ETRP(nfc_tmg.tRP) |
2432 		NDTR0_TWP(nfc_tmg.tWP) |
2433 		NDTR0_TWH(nfc_tmg.tWH) |
2434 		NDTR0_TCS(nfc_tmg.tCS) |
2435 		NDTR0_TCH(nfc_tmg.tCH);
2436 
2437 	marvell_nand->ndtr1 =
2438 		NDTR1_TAR(nfc_tmg.tAR) |
2439 		NDTR1_TWHR(nfc_tmg.tWHR) |
2440 		NDTR1_TR(nfc_tmg.tR);
2441 
2442 	if (nfc->caps->is_nfcv2) {
2443 		marvell_nand->ndtr0 |=
2444 			NDTR0_RD_CNT_DEL(read_delay) |
2445 			NDTR0_SELCNTR |
2446 			NDTR0_TADL(nfc_tmg.tADL);
2447 
2448 		marvell_nand->ndtr1 |=
2449 			NDTR1_TRHW(nfc_tmg.tRHW) |
2450 			NDTR1_WAIT_MODE;
2451 	}
2452 
2453 	return 0;
2454 }
2455 
2456 static int marvell_nand_attach_chip(struct nand_chip *chip)
2457 {
2458 	struct mtd_info *mtd = nand_to_mtd(chip);
2459 	struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
2460 	struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
2461 	struct pxa3xx_nand_platform_data *pdata = dev_get_platdata(nfc->dev);
2462 	int ret;
2463 
2464 	if (pdata && pdata->flash_bbt)
2465 		chip->bbt_options |= NAND_BBT_USE_FLASH;
2466 
2467 	if (chip->bbt_options & NAND_BBT_USE_FLASH) {
2468 		/*
2469 		 * We'll use a bad block table stored in-flash and don't
2470 		 * allow writing the bad block marker to the flash.
2471 		 */
2472 		chip->bbt_options |= NAND_BBT_NO_OOB_BBM;
2473 		chip->bbt_td = &bbt_main_descr;
2474 		chip->bbt_md = &bbt_mirror_descr;
2475 	}
2476 
2477 	/* Save the chip-specific fields of NDCR */
2478 	marvell_nand->ndcr = NDCR_PAGE_SZ(mtd->writesize);
2479 	if (chip->options & NAND_BUSWIDTH_16)
2480 		marvell_nand->ndcr |= NDCR_DWIDTH_M | NDCR_DWIDTH_C;
2481 
2482 	/*
2483 	 * On small page NANDs, only one cycle is needed to pass the
2484 	 * column address.
2485 	 */
2486 	if (mtd->writesize <= 512) {
2487 		marvell_nand->addr_cyc = 1;
2488 	} else {
2489 		marvell_nand->addr_cyc = 2;
2490 		marvell_nand->ndcr |= NDCR_RA_START;
2491 	}
2492 
2493 	/*
2494 	 * Now add the number of cycles needed to pass the row
2495 	 * address.
2496 	 *
2497 	 * Addressing a chip using CS 2 or 3 should also need the third row
2498 	 * cycle but due to inconsistance in the documentation and lack of
2499 	 * hardware to test this situation, this case is not supported.
2500 	 */
2501 	if (chip->options & NAND_ROW_ADDR_3)
2502 		marvell_nand->addr_cyc += 3;
2503 	else
2504 		marvell_nand->addr_cyc += 2;
2505 
2506 	if (pdata) {
2507 		chip->ecc.size = pdata->ecc_step_size;
2508 		chip->ecc.strength = pdata->ecc_strength;
2509 	}
2510 
2511 	ret = marvell_nand_ecc_init(mtd, &chip->ecc);
2512 	if (ret) {
2513 		dev_err(nfc->dev, "ECC init failed: %d\n", ret);
2514 		return ret;
2515 	}
2516 
2517 	if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_ON_HOST) {
2518 		/*
2519 		 * Subpage write not available with hardware ECC, prohibit also
2520 		 * subpage read as in userspace subpage access would still be
2521 		 * allowed and subpage write, if used, would lead to numerous
2522 		 * uncorrectable ECC errors.
2523 		 */
2524 		chip->options |= NAND_NO_SUBPAGE_WRITE;
2525 	}
2526 
2527 	if (pdata || nfc->caps->legacy_of_bindings) {
2528 		/*
2529 		 * We keep the MTD name unchanged to avoid breaking platforms
2530 		 * where the MTD cmdline parser is used and the bootloader
2531 		 * has not been updated to use the new naming scheme.
2532 		 */
2533 		mtd->name = "pxa3xx_nand-0";
2534 	} else if (!mtd->name) {
2535 		/*
2536 		 * If the new bindings are used and the bootloader has not been
2537 		 * updated to pass a new mtdparts parameter on the cmdline, you
2538 		 * should define the following property in your NAND node, ie:
2539 		 *
2540 		 *	label = "main-storage";
2541 		 *
2542 		 * This way, mtd->name will be set by the core when
2543 		 * nand_set_flash_node() is called.
2544 		 */
2545 		mtd->name = devm_kasprintf(nfc->dev, GFP_KERNEL,
2546 					   "%s:nand.%d", dev_name(nfc->dev),
2547 					   marvell_nand->sels[0].cs);
2548 		if (!mtd->name) {
2549 			dev_err(nfc->dev, "Failed to allocate mtd->name\n");
2550 			return -ENOMEM;
2551 		}
2552 	}
2553 
2554 	return 0;
2555 }
2556 
2557 static const struct nand_controller_ops marvell_nand_controller_ops = {
2558 	.attach_chip = marvell_nand_attach_chip,
2559 	.exec_op = marvell_nfc_exec_op,
2560 	.setup_interface = marvell_nfc_setup_interface,
2561 };
2562 
2563 static int marvell_nand_chip_init(struct device *dev, struct marvell_nfc *nfc,
2564 				  struct device_node *np)
2565 {
2566 	struct pxa3xx_nand_platform_data *pdata = dev_get_platdata(dev);
2567 	struct marvell_nand_chip *marvell_nand;
2568 	struct mtd_info *mtd;
2569 	struct nand_chip *chip;
2570 	int nsels, ret, i;
2571 	u32 cs, rb;
2572 
2573 	/*
2574 	 * The legacy "num-cs" property indicates the number of CS on the only
2575 	 * chip connected to the controller (legacy bindings does not support
2576 	 * more than one chip). The CS and RB pins are always the #0.
2577 	 *
2578 	 * When not using legacy bindings, a couple of "reg" and "nand-rb"
2579 	 * properties must be filled. For each chip, expressed as a subnode,
2580 	 * "reg" points to the CS lines and "nand-rb" to the RB line.
2581 	 */
2582 	if (pdata || nfc->caps->legacy_of_bindings) {
2583 		nsels = 1;
2584 	} else {
2585 		nsels = of_property_count_elems_of_size(np, "reg", sizeof(u32));
2586 		if (nsels <= 0) {
2587 			dev_err(dev, "missing/invalid reg property\n");
2588 			return -EINVAL;
2589 		}
2590 	}
2591 
2592 	/* Alloc the nand chip structure */
2593 	marvell_nand = devm_kzalloc(dev,
2594 				    struct_size(marvell_nand, sels, nsels),
2595 				    GFP_KERNEL);
2596 	if (!marvell_nand) {
2597 		dev_err(dev, "could not allocate chip structure\n");
2598 		return -ENOMEM;
2599 	}
2600 
2601 	marvell_nand->nsels = nsels;
2602 	marvell_nand->selected_die = -1;
2603 
2604 	for (i = 0; i < nsels; i++) {
2605 		if (pdata || nfc->caps->legacy_of_bindings) {
2606 			/*
2607 			 * Legacy bindings use the CS lines in natural
2608 			 * order (0, 1, ...)
2609 			 */
2610 			cs = i;
2611 		} else {
2612 			/* Retrieve CS id */
2613 			ret = of_property_read_u32_index(np, "reg", i, &cs);
2614 			if (ret) {
2615 				dev_err(dev, "could not retrieve reg property: %d\n",
2616 					ret);
2617 				return ret;
2618 			}
2619 		}
2620 
2621 		if (cs >= nfc->caps->max_cs_nb) {
2622 			dev_err(dev, "invalid reg value: %u (max CS = %d)\n",
2623 				cs, nfc->caps->max_cs_nb);
2624 			return -EINVAL;
2625 		}
2626 
2627 		if (test_and_set_bit(cs, &nfc->assigned_cs)) {
2628 			dev_err(dev, "CS %d already assigned\n", cs);
2629 			return -EINVAL;
2630 		}
2631 
2632 		/*
2633 		 * The cs variable represents the chip select id, which must be
2634 		 * converted in bit fields for NDCB0 and NDCB2 to select the
2635 		 * right chip. Unfortunately, due to a lack of information on
2636 		 * the subject and incoherent documentation, the user should not
2637 		 * use CS1 and CS3 at all as asserting them is not supported in
2638 		 * a reliable way (due to multiplexing inside ADDR5 field).
2639 		 */
2640 		marvell_nand->sels[i].cs = cs;
2641 		switch (cs) {
2642 		case 0:
2643 		case 2:
2644 			marvell_nand->sels[i].ndcb0_csel = 0;
2645 			break;
2646 		case 1:
2647 		case 3:
2648 			marvell_nand->sels[i].ndcb0_csel = NDCB0_CSEL;
2649 			break;
2650 		default:
2651 			return -EINVAL;
2652 		}
2653 
2654 		/* Retrieve RB id */
2655 		if (pdata || nfc->caps->legacy_of_bindings) {
2656 			/* Legacy bindings always use RB #0 */
2657 			rb = 0;
2658 		} else {
2659 			ret = of_property_read_u32_index(np, "nand-rb", i,
2660 							 &rb);
2661 			if (ret) {
2662 				dev_err(dev,
2663 					"could not retrieve RB property: %d\n",
2664 					ret);
2665 				return ret;
2666 			}
2667 		}
2668 
2669 		if (rb >= nfc->caps->max_rb_nb) {
2670 			dev_err(dev, "invalid reg value: %u (max RB = %d)\n",
2671 				rb, nfc->caps->max_rb_nb);
2672 			return -EINVAL;
2673 		}
2674 
2675 		marvell_nand->sels[i].rb = rb;
2676 	}
2677 
2678 	chip = &marvell_nand->chip;
2679 	chip->controller = &nfc->controller;
2680 	nand_set_flash_node(chip, np);
2681 
2682 	if (of_property_read_bool(np, "marvell,nand-keep-config"))
2683 		chip->options |= NAND_KEEP_TIMINGS;
2684 
2685 	mtd = nand_to_mtd(chip);
2686 	mtd->dev.parent = dev;
2687 
2688 	/*
2689 	 * Save a reference value for timing registers before
2690 	 * ->setup_interface() is called.
2691 	 */
2692 	marvell_nand->ndtr0 = readl_relaxed(nfc->regs + NDTR0);
2693 	marvell_nand->ndtr1 = readl_relaxed(nfc->regs + NDTR1);
2694 
2695 	chip->options |= NAND_BUSWIDTH_AUTO;
2696 
2697 	ret = nand_scan(chip, marvell_nand->nsels);
2698 	if (ret) {
2699 		dev_err(dev, "could not scan the nand chip\n");
2700 		return ret;
2701 	}
2702 
2703 	if (pdata)
2704 		/* Legacy bindings support only one chip */
2705 		ret = mtd_device_register(mtd, pdata->parts, pdata->nr_parts);
2706 	else
2707 		ret = mtd_device_register(mtd, NULL, 0);
2708 	if (ret) {
2709 		dev_err(dev, "failed to register mtd device: %d\n", ret);
2710 		nand_cleanup(chip);
2711 		return ret;
2712 	}
2713 
2714 	list_add_tail(&marvell_nand->node, &nfc->chips);
2715 
2716 	return 0;
2717 }
2718 
2719 static void marvell_nand_chips_cleanup(struct marvell_nfc *nfc)
2720 {
2721 	struct marvell_nand_chip *entry, *temp;
2722 	struct nand_chip *chip;
2723 	int ret;
2724 
2725 	list_for_each_entry_safe(entry, temp, &nfc->chips, node) {
2726 		chip = &entry->chip;
2727 		ret = mtd_device_unregister(nand_to_mtd(chip));
2728 		WARN_ON(ret);
2729 		nand_cleanup(chip);
2730 		list_del(&entry->node);
2731 	}
2732 }
2733 
2734 static int marvell_nand_chips_init(struct device *dev, struct marvell_nfc *nfc)
2735 {
2736 	struct device_node *np = dev->of_node;
2737 	struct device_node *nand_np;
2738 	int max_cs = nfc->caps->max_cs_nb;
2739 	int nchips;
2740 	int ret;
2741 
2742 	if (!np)
2743 		nchips = 1;
2744 	else
2745 		nchips = of_get_child_count(np);
2746 
2747 	if (nchips > max_cs) {
2748 		dev_err(dev, "too many NAND chips: %d (max = %d CS)\n", nchips,
2749 			max_cs);
2750 		return -EINVAL;
2751 	}
2752 
2753 	/*
2754 	 * Legacy bindings do not use child nodes to exhibit NAND chip
2755 	 * properties and layout. Instead, NAND properties are mixed with the
2756 	 * controller ones, and partitions are defined as direct subnodes of the
2757 	 * NAND controller node.
2758 	 */
2759 	if (nfc->caps->legacy_of_bindings) {
2760 		ret = marvell_nand_chip_init(dev, nfc, np);
2761 		return ret;
2762 	}
2763 
2764 	for_each_child_of_node(np, nand_np) {
2765 		ret = marvell_nand_chip_init(dev, nfc, nand_np);
2766 		if (ret) {
2767 			of_node_put(nand_np);
2768 			goto cleanup_chips;
2769 		}
2770 	}
2771 
2772 	return 0;
2773 
2774 cleanup_chips:
2775 	marvell_nand_chips_cleanup(nfc);
2776 
2777 	return ret;
2778 }
2779 
2780 static int marvell_nfc_init_dma(struct marvell_nfc *nfc)
2781 {
2782 	struct platform_device *pdev = container_of(nfc->dev,
2783 						    struct platform_device,
2784 						    dev);
2785 	struct dma_slave_config config = {};
2786 	struct resource *r;
2787 	int ret;
2788 
2789 	if (!IS_ENABLED(CONFIG_PXA_DMA)) {
2790 		dev_warn(nfc->dev,
2791 			 "DMA not enabled in configuration\n");
2792 		return -ENOTSUPP;
2793 	}
2794 
2795 	ret = dma_set_mask_and_coherent(nfc->dev, DMA_BIT_MASK(32));
2796 	if (ret)
2797 		return ret;
2798 
2799 	nfc->dma_chan =	dma_request_chan(nfc->dev, "data");
2800 	if (IS_ERR(nfc->dma_chan)) {
2801 		ret = PTR_ERR(nfc->dma_chan);
2802 		nfc->dma_chan = NULL;
2803 		return dev_err_probe(nfc->dev, ret, "DMA channel request failed\n");
2804 	}
2805 
2806 	r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2807 	if (!r) {
2808 		ret = -ENXIO;
2809 		goto release_channel;
2810 	}
2811 
2812 	config.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
2813 	config.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
2814 	config.src_addr = r->start + NDDB;
2815 	config.dst_addr = r->start + NDDB;
2816 	config.src_maxburst = 32;
2817 	config.dst_maxburst = 32;
2818 	ret = dmaengine_slave_config(nfc->dma_chan, &config);
2819 	if (ret < 0) {
2820 		dev_err(nfc->dev, "Failed to configure DMA channel\n");
2821 		goto release_channel;
2822 	}
2823 
2824 	/*
2825 	 * DMA must act on length multiple of 32 and this length may be
2826 	 * bigger than the destination buffer. Use this buffer instead
2827 	 * for DMA transfers and then copy the desired amount of data to
2828 	 * the provided buffer.
2829 	 */
2830 	nfc->dma_buf = kmalloc(MAX_CHUNK_SIZE, GFP_KERNEL | GFP_DMA);
2831 	if (!nfc->dma_buf) {
2832 		ret = -ENOMEM;
2833 		goto release_channel;
2834 	}
2835 
2836 	nfc->use_dma = true;
2837 
2838 	return 0;
2839 
2840 release_channel:
2841 	dma_release_channel(nfc->dma_chan);
2842 	nfc->dma_chan = NULL;
2843 
2844 	return ret;
2845 }
2846 
2847 static void marvell_nfc_reset(struct marvell_nfc *nfc)
2848 {
2849 	/*
2850 	 * ECC operations and interruptions are only enabled when specifically
2851 	 * needed. ECC shall not be activated in the early stages (fails probe).
2852 	 * Arbiter flag, even if marked as "reserved", must be set (empirical).
2853 	 * SPARE_EN bit must always be set or ECC bytes will not be at the same
2854 	 * offset in the read page and this will fail the protection.
2855 	 */
2856 	writel_relaxed(NDCR_ALL_INT | NDCR_ND_ARB_EN | NDCR_SPARE_EN |
2857 		       NDCR_RD_ID_CNT(NFCV1_READID_LEN), nfc->regs + NDCR);
2858 	writel_relaxed(0xFFFFFFFF, nfc->regs + NDSR);
2859 	writel_relaxed(0, nfc->regs + NDECCCTRL);
2860 }
2861 
2862 static int marvell_nfc_init(struct marvell_nfc *nfc)
2863 {
2864 	struct device_node *np = nfc->dev->of_node;
2865 
2866 	/*
2867 	 * Some SoCs like A7k/A8k need to enable manually the NAND
2868 	 * controller, gated clocks and reset bits to avoid being bootloader
2869 	 * dependent. This is done through the use of the System Functions
2870 	 * registers.
2871 	 */
2872 	if (nfc->caps->need_system_controller) {
2873 		struct regmap *sysctrl_base =
2874 			syscon_regmap_lookup_by_phandle(np,
2875 							"marvell,system-controller");
2876 
2877 		if (IS_ERR(sysctrl_base))
2878 			return PTR_ERR(sysctrl_base);
2879 
2880 		regmap_write(sysctrl_base, GENCONF_SOC_DEVICE_MUX,
2881 			     GENCONF_SOC_DEVICE_MUX_NFC_EN |
2882 			     GENCONF_SOC_DEVICE_MUX_ECC_CLK_RST |
2883 			     GENCONF_SOC_DEVICE_MUX_ECC_CORE_RST |
2884 			     GENCONF_SOC_DEVICE_MUX_NFC_INT_EN |
2885 			     GENCONF_SOC_DEVICE_MUX_NFC_DEVBUS_ARB_EN);
2886 
2887 		regmap_update_bits(sysctrl_base, GENCONF_CLK_GATING_CTRL,
2888 				   GENCONF_CLK_GATING_CTRL_ND_GATE,
2889 				   GENCONF_CLK_GATING_CTRL_ND_GATE);
2890 
2891 		regmap_update_bits(sysctrl_base, GENCONF_ND_CLK_CTRL,
2892 				   GENCONF_ND_CLK_CTRL_EN,
2893 				   GENCONF_ND_CLK_CTRL_EN);
2894 	}
2895 
2896 	/* Configure the DMA if appropriate */
2897 	if (!nfc->caps->is_nfcv2)
2898 		marvell_nfc_init_dma(nfc);
2899 
2900 	marvell_nfc_reset(nfc);
2901 
2902 	return 0;
2903 }
2904 
2905 static int marvell_nfc_probe(struct platform_device *pdev)
2906 {
2907 	struct device *dev = &pdev->dev;
2908 	struct marvell_nfc *nfc;
2909 	int ret;
2910 	int irq;
2911 
2912 	nfc = devm_kzalloc(&pdev->dev, sizeof(struct marvell_nfc),
2913 			   GFP_KERNEL);
2914 	if (!nfc)
2915 		return -ENOMEM;
2916 
2917 	nfc->dev = dev;
2918 	nand_controller_init(&nfc->controller);
2919 	nfc->controller.ops = &marvell_nand_controller_ops;
2920 	INIT_LIST_HEAD(&nfc->chips);
2921 
2922 	nfc->regs = devm_platform_ioremap_resource(pdev, 0);
2923 	if (IS_ERR(nfc->regs))
2924 		return PTR_ERR(nfc->regs);
2925 
2926 	irq = platform_get_irq(pdev, 0);
2927 	if (irq < 0)
2928 		return irq;
2929 
2930 	nfc->core_clk = devm_clk_get(&pdev->dev, "core");
2931 
2932 	/* Managed the legacy case (when the first clock was not named) */
2933 	if (nfc->core_clk == ERR_PTR(-ENOENT))
2934 		nfc->core_clk = devm_clk_get(&pdev->dev, NULL);
2935 
2936 	if (IS_ERR(nfc->core_clk))
2937 		return PTR_ERR(nfc->core_clk);
2938 
2939 	ret = clk_prepare_enable(nfc->core_clk);
2940 	if (ret)
2941 		return ret;
2942 
2943 	nfc->reg_clk = devm_clk_get(&pdev->dev, "reg");
2944 	if (IS_ERR(nfc->reg_clk)) {
2945 		if (PTR_ERR(nfc->reg_clk) != -ENOENT) {
2946 			ret = PTR_ERR(nfc->reg_clk);
2947 			goto unprepare_core_clk;
2948 		}
2949 
2950 		nfc->reg_clk = NULL;
2951 	}
2952 
2953 	ret = clk_prepare_enable(nfc->reg_clk);
2954 	if (ret)
2955 		goto unprepare_core_clk;
2956 
2957 	marvell_nfc_disable_int(nfc, NDCR_ALL_INT);
2958 	marvell_nfc_clear_int(nfc, NDCR_ALL_INT);
2959 	ret = devm_request_irq(dev, irq, marvell_nfc_isr,
2960 			       0, "marvell-nfc", nfc);
2961 	if (ret)
2962 		goto unprepare_reg_clk;
2963 
2964 	/* Get NAND controller capabilities */
2965 	if (pdev->id_entry)
2966 		nfc->caps = (void *)pdev->id_entry->driver_data;
2967 	else
2968 		nfc->caps = of_device_get_match_data(&pdev->dev);
2969 
2970 	if (!nfc->caps) {
2971 		dev_err(dev, "Could not retrieve NFC caps\n");
2972 		ret = -EINVAL;
2973 		goto unprepare_reg_clk;
2974 	}
2975 
2976 	/* Init the controller and then probe the chips */
2977 	ret = marvell_nfc_init(nfc);
2978 	if (ret)
2979 		goto unprepare_reg_clk;
2980 
2981 	platform_set_drvdata(pdev, nfc);
2982 
2983 	ret = marvell_nand_chips_init(dev, nfc);
2984 	if (ret)
2985 		goto release_dma;
2986 
2987 	return 0;
2988 
2989 release_dma:
2990 	if (nfc->use_dma)
2991 		dma_release_channel(nfc->dma_chan);
2992 unprepare_reg_clk:
2993 	clk_disable_unprepare(nfc->reg_clk);
2994 unprepare_core_clk:
2995 	clk_disable_unprepare(nfc->core_clk);
2996 
2997 	return ret;
2998 }
2999 
3000 static int marvell_nfc_remove(struct platform_device *pdev)
3001 {
3002 	struct marvell_nfc *nfc = platform_get_drvdata(pdev);
3003 
3004 	marvell_nand_chips_cleanup(nfc);
3005 
3006 	if (nfc->use_dma) {
3007 		dmaengine_terminate_all(nfc->dma_chan);
3008 		dma_release_channel(nfc->dma_chan);
3009 	}
3010 
3011 	clk_disable_unprepare(nfc->reg_clk);
3012 	clk_disable_unprepare(nfc->core_clk);
3013 
3014 	return 0;
3015 }
3016 
3017 static int __maybe_unused marvell_nfc_suspend(struct device *dev)
3018 {
3019 	struct marvell_nfc *nfc = dev_get_drvdata(dev);
3020 	struct marvell_nand_chip *chip;
3021 
3022 	list_for_each_entry(chip, &nfc->chips, node)
3023 		marvell_nfc_wait_ndrun(&chip->chip);
3024 
3025 	clk_disable_unprepare(nfc->reg_clk);
3026 	clk_disable_unprepare(nfc->core_clk);
3027 
3028 	return 0;
3029 }
3030 
3031 static int __maybe_unused marvell_nfc_resume(struct device *dev)
3032 {
3033 	struct marvell_nfc *nfc = dev_get_drvdata(dev);
3034 	int ret;
3035 
3036 	ret = clk_prepare_enable(nfc->core_clk);
3037 	if (ret < 0)
3038 		return ret;
3039 
3040 	ret = clk_prepare_enable(nfc->reg_clk);
3041 	if (ret < 0) {
3042 		clk_disable_unprepare(nfc->core_clk);
3043 		return ret;
3044 	}
3045 
3046 	/*
3047 	 * Reset nfc->selected_chip so the next command will cause the timing
3048 	 * registers to be restored in marvell_nfc_select_target().
3049 	 */
3050 	nfc->selected_chip = NULL;
3051 
3052 	/* Reset registers that have lost their contents */
3053 	marvell_nfc_reset(nfc);
3054 
3055 	return 0;
3056 }
3057 
3058 static const struct dev_pm_ops marvell_nfc_pm_ops = {
3059 	SET_SYSTEM_SLEEP_PM_OPS(marvell_nfc_suspend, marvell_nfc_resume)
3060 };
3061 
3062 static const struct marvell_nfc_caps marvell_armada_8k_nfc_caps = {
3063 	.max_cs_nb = 4,
3064 	.max_rb_nb = 2,
3065 	.need_system_controller = true,
3066 	.is_nfcv2 = true,
3067 };
3068 
3069 static const struct marvell_nfc_caps marvell_armada370_nfc_caps = {
3070 	.max_cs_nb = 4,
3071 	.max_rb_nb = 2,
3072 	.is_nfcv2 = true,
3073 };
3074 
3075 static const struct marvell_nfc_caps marvell_pxa3xx_nfc_caps = {
3076 	.max_cs_nb = 2,
3077 	.max_rb_nb = 1,
3078 	.use_dma = true,
3079 };
3080 
3081 static const struct marvell_nfc_caps marvell_armada_8k_nfc_legacy_caps = {
3082 	.max_cs_nb = 4,
3083 	.max_rb_nb = 2,
3084 	.need_system_controller = true,
3085 	.legacy_of_bindings = true,
3086 	.is_nfcv2 = true,
3087 };
3088 
3089 static const struct marvell_nfc_caps marvell_armada370_nfc_legacy_caps = {
3090 	.max_cs_nb = 4,
3091 	.max_rb_nb = 2,
3092 	.legacy_of_bindings = true,
3093 	.is_nfcv2 = true,
3094 };
3095 
3096 static const struct marvell_nfc_caps marvell_pxa3xx_nfc_legacy_caps = {
3097 	.max_cs_nb = 2,
3098 	.max_rb_nb = 1,
3099 	.legacy_of_bindings = true,
3100 	.use_dma = true,
3101 };
3102 
3103 static const struct platform_device_id marvell_nfc_platform_ids[] = {
3104 	{
3105 		.name = "pxa3xx-nand",
3106 		.driver_data = (kernel_ulong_t)&marvell_pxa3xx_nfc_legacy_caps,
3107 	},
3108 	{ /* sentinel */ },
3109 };
3110 MODULE_DEVICE_TABLE(platform, marvell_nfc_platform_ids);
3111 
3112 static const struct of_device_id marvell_nfc_of_ids[] = {
3113 	{
3114 		.compatible = "marvell,armada-8k-nand-controller",
3115 		.data = &marvell_armada_8k_nfc_caps,
3116 	},
3117 	{
3118 		.compatible = "marvell,armada370-nand-controller",
3119 		.data = &marvell_armada370_nfc_caps,
3120 	},
3121 	{
3122 		.compatible = "marvell,pxa3xx-nand-controller",
3123 		.data = &marvell_pxa3xx_nfc_caps,
3124 	},
3125 	/* Support for old/deprecated bindings: */
3126 	{
3127 		.compatible = "marvell,armada-8k-nand",
3128 		.data = &marvell_armada_8k_nfc_legacy_caps,
3129 	},
3130 	{
3131 		.compatible = "marvell,armada370-nand",
3132 		.data = &marvell_armada370_nfc_legacy_caps,
3133 	},
3134 	{
3135 		.compatible = "marvell,pxa3xx-nand",
3136 		.data = &marvell_pxa3xx_nfc_legacy_caps,
3137 	},
3138 	{ /* sentinel */ },
3139 };
3140 MODULE_DEVICE_TABLE(of, marvell_nfc_of_ids);
3141 
3142 static struct platform_driver marvell_nfc_driver = {
3143 	.driver	= {
3144 		.name		= "marvell-nfc",
3145 		.of_match_table = marvell_nfc_of_ids,
3146 		.pm		= &marvell_nfc_pm_ops,
3147 	},
3148 	.id_table = marvell_nfc_platform_ids,
3149 	.probe = marvell_nfc_probe,
3150 	.remove	= marvell_nfc_remove,
3151 };
3152 module_platform_driver(marvell_nfc_driver);
3153 
3154 MODULE_LICENSE("GPL");
3155 MODULE_DESCRIPTION("Marvell NAND controller driver");
3156