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