1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Cadence NAND flash controller driver
4  *
5  * Copyright (C) 2019 Cadence
6  *
7  * Author: Piotr Sroka <piotrs@cadence.com>
8  */
9 
10 #include <linux/bitfield.h>
11 #include <linux/clk.h>
12 #include <linux/dma-mapping.h>
13 #include <linux/dmaengine.h>
14 #include <linux/interrupt.h>
15 #include <linux/module.h>
16 #include <linux/mtd/mtd.h>
17 #include <linux/mtd/rawnand.h>
18 #include <linux/of_device.h>
19 #include <linux/iopoll.h>
20 
21 /*
22  * HPNFC can work in 3 modes:
23  * -  PIO - can work in master or slave DMA
24  * -  CDMA - needs Master DMA for accessing command descriptors.
25  * -  Generic mode - can use only slave DMA.
26  * CDMA and PIO modes can be used to execute only base commands.
27  * Generic mode can be used to execute any command
28  * on NAND flash memory. Driver uses CDMA mode for
29  * block erasing, page reading, page programing.
30  * Generic mode is used for executing rest of commands.
31  */
32 
33 #define MAX_ADDRESS_CYC		6
34 #define MAX_ERASE_ADDRESS_CYC	3
35 #define MAX_DATA_SIZE		0xFFFC
36 #define DMA_DATA_SIZE_ALIGN	8
37 
38 /* Register definition. */
39 /*
40  * Command register 0.
41  * Writing data to this register will initiate a new transaction
42  * of the NF controller.
43  */
44 #define CMD_REG0			0x0000
45 /* Command type field mask. */
46 #define		CMD_REG0_CT		GENMASK(31, 30)
47 /* Command type CDMA. */
48 #define		CMD_REG0_CT_CDMA	0uL
49 /* Command type generic. */
50 #define		CMD_REG0_CT_GEN		3uL
51 /* Command thread number field mask. */
52 #define		CMD_REG0_TN		GENMASK(27, 24)
53 
54 /* Command register 2. */
55 #define CMD_REG2			0x0008
56 /* Command register 3. */
57 #define CMD_REG3			0x000C
58 /* Pointer register to select which thread status will be selected. */
59 #define CMD_STATUS_PTR			0x0010
60 /* Command status register for selected thread. */
61 #define CMD_STATUS			0x0014
62 
63 /* Interrupt status register. */
64 #define INTR_STATUS			0x0110
65 #define		INTR_STATUS_SDMA_ERR	BIT(22)
66 #define		INTR_STATUS_SDMA_TRIGG	BIT(21)
67 #define		INTR_STATUS_UNSUPP_CMD	BIT(19)
68 #define		INTR_STATUS_DDMA_TERR	BIT(18)
69 #define		INTR_STATUS_CDMA_TERR	BIT(17)
70 #define		INTR_STATUS_CDMA_IDL	BIT(16)
71 
72 /* Interrupt enable register. */
73 #define INTR_ENABLE				0x0114
74 #define		INTR_ENABLE_INTR_EN		BIT(31)
75 #define		INTR_ENABLE_SDMA_ERR_EN		BIT(22)
76 #define		INTR_ENABLE_SDMA_TRIGG_EN	BIT(21)
77 #define		INTR_ENABLE_UNSUPP_CMD_EN	BIT(19)
78 #define		INTR_ENABLE_DDMA_TERR_EN	BIT(18)
79 #define		INTR_ENABLE_CDMA_TERR_EN	BIT(17)
80 #define		INTR_ENABLE_CDMA_IDLE_EN	BIT(16)
81 
82 /* Controller internal state. */
83 #define CTRL_STATUS				0x0118
84 #define		CTRL_STATUS_INIT_COMP		BIT(9)
85 #define		CTRL_STATUS_CTRL_BUSY		BIT(8)
86 
87 /* Command Engine threads state. */
88 #define TRD_STATUS				0x0120
89 
90 /* Command Engine interrupt thread error status. */
91 #define TRD_ERR_INT_STATUS			0x0128
92 /* Command Engine interrupt thread error enable. */
93 #define TRD_ERR_INT_STATUS_EN			0x0130
94 /* Command Engine interrupt thread complete status. */
95 #define TRD_COMP_INT_STATUS			0x0138
96 
97 /*
98  * Transfer config 0 register.
99  * Configures data transfer parameters.
100  */
101 #define TRAN_CFG_0				0x0400
102 /* Offset value from the beginning of the page. */
103 #define		TRAN_CFG_0_OFFSET		GENMASK(31, 16)
104 /* Numbers of sectors to transfer within singlNF device's page. */
105 #define		TRAN_CFG_0_SEC_CNT		GENMASK(7, 0)
106 
107 /*
108  * Transfer config 1 register.
109  * Configures data transfer parameters.
110  */
111 #define TRAN_CFG_1				0x0404
112 /* Size of last data sector. */
113 #define		TRAN_CFG_1_LAST_SEC_SIZE	GENMASK(31, 16)
114 /* Size of not-last data sector. */
115 #define		TRAN_CFG_1_SECTOR_SIZE		GENMASK(15, 0)
116 
117 /* ECC engine configuration register 0. */
118 #define ECC_CONFIG_0				0x0428
119 /* Correction strength. */
120 #define		ECC_CONFIG_0_CORR_STR		GENMASK(10, 8)
121 /* Enable erased pages detection mechanism. */
122 #define		ECC_CONFIG_0_ERASE_DET_EN	BIT(1)
123 /* Enable controller ECC check bits generation and correction. */
124 #define		ECC_CONFIG_0_ECC_EN		BIT(0)
125 
126 /* ECC engine configuration register 1. */
127 #define ECC_CONFIG_1				0x042C
128 
129 /* Multiplane settings register. */
130 #define MULTIPLANE_CFG				0x0434
131 /* Cache operation settings. */
132 #define CACHE_CFG				0x0438
133 
134 /* DMA settings register. */
135 #define DMA_SETINGS				0x043C
136 /* Enable SDMA error report on access unprepared slave DMA interface. */
137 #define		DMA_SETINGS_SDMA_ERR_RSP	BIT(17)
138 
139 /* Transferred data block size for the slave DMA module. */
140 #define SDMA_SIZE				0x0440
141 
142 /* Thread number associated with transferred data block
143  * for the slave DMA module.
144  */
145 #define SDMA_TRD_NUM				0x0444
146 /* Thread number mask. */
147 #define		SDMA_TRD_NUM_SDMA_TRD		GENMASK(2, 0)
148 
149 #define CONTROL_DATA_CTRL			0x0494
150 /* Thread number mask. */
151 #define		CONTROL_DATA_CTRL_SIZE		GENMASK(15, 0)
152 
153 #define CTRL_VERSION				0x800
154 #define		CTRL_VERSION_REV		GENMASK(7, 0)
155 
156 /* Available hardware features of the controller. */
157 #define CTRL_FEATURES				0x804
158 /* Support for NV-DDR2/3 work mode. */
159 #define		CTRL_FEATURES_NVDDR_2_3		BIT(28)
160 /* Support for NV-DDR work mode. */
161 #define		CTRL_FEATURES_NVDDR		BIT(27)
162 /* Support for asynchronous work mode. */
163 #define		CTRL_FEATURES_ASYNC		BIT(26)
164 /* Support for asynchronous work mode. */
165 #define		CTRL_FEATURES_N_BANKS		GENMASK(25, 24)
166 /* Slave and Master DMA data width. */
167 #define		CTRL_FEATURES_DMA_DWITH64	BIT(21)
168 /* Availability of Control Data feature.*/
169 #define		CTRL_FEATURES_CONTROL_DATA	BIT(10)
170 
171 /* BCH Engine identification register 0 - correction strengths. */
172 #define BCH_CFG_0				0x838
173 #define		BCH_CFG_0_CORR_CAP_0		GENMASK(7, 0)
174 #define		BCH_CFG_0_CORR_CAP_1		GENMASK(15, 8)
175 #define		BCH_CFG_0_CORR_CAP_2		GENMASK(23, 16)
176 #define		BCH_CFG_0_CORR_CAP_3		GENMASK(31, 24)
177 
178 /* BCH Engine identification register 1 - correction strengths. */
179 #define BCH_CFG_1				0x83C
180 #define		BCH_CFG_1_CORR_CAP_4		GENMASK(7, 0)
181 #define		BCH_CFG_1_CORR_CAP_5		GENMASK(15, 8)
182 #define		BCH_CFG_1_CORR_CAP_6		GENMASK(23, 16)
183 #define		BCH_CFG_1_CORR_CAP_7		GENMASK(31, 24)
184 
185 /* BCH Engine identification register 2 - sector sizes. */
186 #define BCH_CFG_2				0x840
187 #define		BCH_CFG_2_SECT_0		GENMASK(15, 0)
188 #define		BCH_CFG_2_SECT_1		GENMASK(31, 16)
189 
190 /* BCH Engine identification register 3. */
191 #define BCH_CFG_3				0x844
192 #define		BCH_CFG_3_METADATA_SIZE		GENMASK(23, 16)
193 
194 /* Ready/Busy# line status. */
195 #define RBN_SETINGS				0x1004
196 
197 /* Common settings. */
198 #define COMMON_SET				0x1008
199 /* 16 bit device connected to the NAND Flash interface. */
200 #define		COMMON_SET_DEVICE_16BIT		BIT(8)
201 
202 /* Skip_bytes registers. */
203 #define SKIP_BYTES_CONF				0x100C
204 #define		SKIP_BYTES_MARKER_VALUE		GENMASK(31, 16)
205 #define		SKIP_BYTES_NUM_OF_BYTES		GENMASK(7, 0)
206 
207 #define SKIP_BYTES_OFFSET			0x1010
208 #define		 SKIP_BYTES_OFFSET_VALUE	GENMASK(23, 0)
209 
210 /* Timings configuration. */
211 #define ASYNC_TOGGLE_TIMINGS			0x101c
212 #define		ASYNC_TOGGLE_TIMINGS_TRH	GENMASK(28, 24)
213 #define		ASYNC_TOGGLE_TIMINGS_TRP	GENMASK(20, 16)
214 #define		ASYNC_TOGGLE_TIMINGS_TWH	GENMASK(12, 8)
215 #define		ASYNC_TOGGLE_TIMINGS_TWP	GENMASK(4, 0)
216 
217 #define	TIMINGS0				0x1024
218 #define		TIMINGS0_TADL			GENMASK(31, 24)
219 #define		TIMINGS0_TCCS			GENMASK(23, 16)
220 #define		TIMINGS0_TWHR			GENMASK(15, 8)
221 #define		TIMINGS0_TRHW			GENMASK(7, 0)
222 
223 #define	TIMINGS1				0x1028
224 #define		TIMINGS1_TRHZ			GENMASK(31, 24)
225 #define		TIMINGS1_TWB			GENMASK(23, 16)
226 #define		TIMINGS1_TVDLY			GENMASK(7, 0)
227 
228 #define	TIMINGS2				0x102c
229 #define		TIMINGS2_TFEAT			GENMASK(25, 16)
230 #define		TIMINGS2_CS_HOLD_TIME		GENMASK(13, 8)
231 #define		TIMINGS2_CS_SETUP_TIME		GENMASK(5, 0)
232 
233 /* Configuration of the resynchronization of slave DLL of PHY. */
234 #define DLL_PHY_CTRL				0x1034
235 #define		DLL_PHY_CTRL_DLL_RST_N		BIT(24)
236 #define		DLL_PHY_CTRL_EXTENDED_WR_MODE	BIT(17)
237 #define		DLL_PHY_CTRL_EXTENDED_RD_MODE	BIT(16)
238 #define		DLL_PHY_CTRL_RS_HIGH_WAIT_CNT	GENMASK(11, 8)
239 #define		DLL_PHY_CTRL_RS_IDLE_CNT	GENMASK(7, 0)
240 
241 /* Register controlling DQ related timing. */
242 #define PHY_DQ_TIMING				0x2000
243 /* Register controlling DSQ related timing.  */
244 #define PHY_DQS_TIMING				0x2004
245 #define		PHY_DQS_TIMING_DQS_SEL_OE_END	GENMASK(3, 0)
246 #define		PHY_DQS_TIMING_PHONY_DQS_SEL	BIT(16)
247 #define		PHY_DQS_TIMING_USE_PHONY_DQS	BIT(20)
248 
249 /* Register controlling the gate and loopback control related timing. */
250 #define PHY_GATE_LPBK_CTRL			0x2008
251 #define		PHY_GATE_LPBK_CTRL_RDS		GENMASK(24, 19)
252 
253 /* Register holds the control for the master DLL logic. */
254 #define PHY_DLL_MASTER_CTRL			0x200C
255 #define		PHY_DLL_MASTER_CTRL_BYPASS_MODE	BIT(23)
256 
257 /* Register holds the control for the slave DLL logic. */
258 #define PHY_DLL_SLAVE_CTRL			0x2010
259 
260 /* This register handles the global control settings for the PHY. */
261 #define PHY_CTRL				0x2080
262 #define		PHY_CTRL_SDR_DQS		BIT(14)
263 #define		PHY_CTRL_PHONY_DQS		GENMASK(9, 4)
264 
265 /*
266  * This register handles the global control settings
267  * for the termination selects for reads.
268  */
269 #define PHY_TSEL				0x2084
270 
271 /* Generic command layout. */
272 #define GCMD_LAY_CS			GENMASK_ULL(11, 8)
273 /*
274  * This bit informs the minicotroller if it has to wait for tWB
275  * after sending the last CMD/ADDR/DATA in the sequence.
276  */
277 #define GCMD_LAY_TWB			BIT_ULL(6)
278 /* Type of generic instruction. */
279 #define GCMD_LAY_INSTR			GENMASK_ULL(5, 0)
280 
281 /* Generic CMD sequence type. */
282 #define		GCMD_LAY_INSTR_CMD	0
283 /* Generic ADDR sequence type. */
284 #define		GCMD_LAY_INSTR_ADDR	1
285 /* Generic data transfer sequence type. */
286 #define		GCMD_LAY_INSTR_DATA	2
287 
288 /* Input part of generic command type of input is command. */
289 #define GCMD_LAY_INPUT_CMD		GENMASK_ULL(23, 16)
290 
291 /* Generic command address sequence - address fields. */
292 #define GCMD_LAY_INPUT_ADDR		GENMASK_ULL(63, 16)
293 /* Generic command address sequence - address size. */
294 #define GCMD_LAY_INPUT_ADDR_SIZE	GENMASK_ULL(13, 11)
295 
296 /* Transfer direction field of generic command data sequence. */
297 #define GCMD_DIR			BIT_ULL(11)
298 /* Read transfer direction of generic command data sequence. */
299 #define		GCMD_DIR_READ		0
300 /* Write transfer direction of generic command data sequence. */
301 #define		GCMD_DIR_WRITE		1
302 
303 /* ECC enabled flag of generic command data sequence - ECC enabled. */
304 #define GCMD_ECC_EN			BIT_ULL(12)
305 /* Generic command data sequence - sector size. */
306 #define GCMD_SECT_SIZE			GENMASK_ULL(31, 16)
307 /* Generic command data sequence - sector count. */
308 #define GCMD_SECT_CNT			GENMASK_ULL(39, 32)
309 /* Generic command data sequence - last sector size. */
310 #define GCMD_LAST_SIZE			GENMASK_ULL(55, 40)
311 
312 /* CDMA descriptor fields. */
313 /* Erase command type of CDMA descriptor. */
314 #define CDMA_CT_ERASE		0x1000
315 /* Program page command type of CDMA descriptor. */
316 #define CDMA_CT_WR		0x2100
317 /* Read page command type of CDMA descriptor. */
318 #define CDMA_CT_RD		0x2200
319 
320 /* Flash pointer memory shift. */
321 #define CDMA_CFPTR_MEM_SHIFT	24
322 /* Flash pointer memory mask. */
323 #define CDMA_CFPTR_MEM		GENMASK(26, 24)
324 
325 /*
326  * Command DMA descriptor flags. If set causes issue interrupt after
327  * the completion of descriptor processing.
328  */
329 #define CDMA_CF_INT		BIT(8)
330 /*
331  * Command DMA descriptor flags - the next descriptor
332  * address field is valid and descriptor processing should continue.
333  */
334 #define CDMA_CF_CONT		BIT(9)
335 /* DMA master flag of command DMA descriptor. */
336 #define CDMA_CF_DMA_MASTER	BIT(10)
337 
338 /* Operation complete status of command descriptor. */
339 #define CDMA_CS_COMP		BIT(15)
340 /* Operation complete status of command descriptor. */
341 /* Command descriptor status - operation fail. */
342 #define CDMA_CS_FAIL		BIT(14)
343 /* Command descriptor status - page erased. */
344 #define CDMA_CS_ERP		BIT(11)
345 /* Command descriptor status - timeout occurred. */
346 #define CDMA_CS_TOUT		BIT(10)
347 /*
348  * Maximum amount of correction applied to one ECC sector.
349  * It is part of command descriptor status.
350  */
351 #define CDMA_CS_MAXERR		GENMASK(9, 2)
352 /* Command descriptor status - uncorrectable ECC error. */
353 #define CDMA_CS_UNCE		BIT(1)
354 /* Command descriptor status - descriptor error. */
355 #define CDMA_CS_ERR		BIT(0)
356 
357 /* Status of operation - OK. */
358 #define STAT_OK			0
359 /* Status of operation - FAIL. */
360 #define STAT_FAIL		2
361 /* Status of operation - uncorrectable ECC error. */
362 #define STAT_ECC_UNCORR		3
363 /* Status of operation - page erased. */
364 #define STAT_ERASED		5
365 /* Status of operation - correctable ECC error. */
366 #define STAT_ECC_CORR		6
367 /* Status of operation - unsuspected state. */
368 #define STAT_UNKNOWN		7
369 /* Status of operation - operation is not completed yet. */
370 #define STAT_BUSY		0xFF
371 
372 #define BCH_MAX_NUM_CORR_CAPS		8
373 #define BCH_MAX_NUM_SECTOR_SIZES	2
374 
375 struct cadence_nand_timings {
376 	u32 async_toggle_timings;
377 	u32 timings0;
378 	u32 timings1;
379 	u32 timings2;
380 	u32 dll_phy_ctrl;
381 	u32 phy_ctrl;
382 	u32 phy_dqs_timing;
383 	u32 phy_gate_lpbk_ctrl;
384 };
385 
386 /* Command DMA descriptor. */
387 struct cadence_nand_cdma_desc {
388 	/* Next descriptor address. */
389 	u64 next_pointer;
390 
391 	/* Flash address is a 32-bit address comprising of BANK and ROW ADDR. */
392 	u32 flash_pointer;
393 	/*field appears in HPNFC version 13*/
394 	u16 bank;
395 	u16 rsvd0;
396 
397 	/* Operation the controller needs to perform. */
398 	u16 command_type;
399 	u16 rsvd1;
400 	/* Flags for operation of this command. */
401 	u16 command_flags;
402 	u16 rsvd2;
403 
404 	/* System/host memory address required for data DMA commands. */
405 	u64 memory_pointer;
406 
407 	/* Status of operation. */
408 	u32 status;
409 	u32 rsvd3;
410 
411 	/* Address pointer to sync buffer location. */
412 	u64 sync_flag_pointer;
413 
414 	/* Controls the buffer sync mechanism. */
415 	u32 sync_arguments;
416 	u32 rsvd4;
417 
418 	/* Control data pointer. */
419 	u64 ctrl_data_ptr;
420 };
421 
422 /* Interrupt status. */
423 struct cadence_nand_irq_status {
424 	/* Thread operation complete status. */
425 	u32 trd_status;
426 	/* Thread operation error. */
427 	u32 trd_error;
428 	/* Controller status. */
429 	u32 status;
430 };
431 
432 /* Cadence NAND flash controller capabilities get from driver data. */
433 struct cadence_nand_dt_devdata {
434 	/* Skew value of the output signals of the NAND Flash interface. */
435 	u32 if_skew;
436 	/* It informs if slave DMA interface is connected to DMA engine. */
437 	unsigned int has_dma:1;
438 };
439 
440 /* Cadence NAND flash controller capabilities read from registers. */
441 struct cdns_nand_caps {
442 	/* Maximum number of banks supported by hardware. */
443 	u8 max_banks;
444 	/* Slave and Master DMA data width in bytes (4 or 8). */
445 	u8 data_dma_width;
446 	/* Control Data feature supported. */
447 	bool data_control_supp;
448 	/* Is PHY type DLL. */
449 	bool is_phy_type_dll;
450 };
451 
452 struct cdns_nand_ctrl {
453 	struct device *dev;
454 	struct nand_controller controller;
455 	struct cadence_nand_cdma_desc *cdma_desc;
456 	/* IP capability. */
457 	const struct cadence_nand_dt_devdata *caps1;
458 	struct cdns_nand_caps caps2;
459 	u8 ctrl_rev;
460 	dma_addr_t dma_cdma_desc;
461 	u8 *buf;
462 	u32 buf_size;
463 	u8 curr_corr_str_idx;
464 
465 	/* Register interface. */
466 	void __iomem *reg;
467 
468 	struct {
469 		void __iomem *virt;
470 		dma_addr_t dma;
471 	} io;
472 
473 	int irq;
474 	/* Interrupts that have happened. */
475 	struct cadence_nand_irq_status irq_status;
476 	/* Interrupts we are waiting for. */
477 	struct cadence_nand_irq_status irq_mask;
478 	struct completion complete;
479 	/* Protect irq_mask and irq_status. */
480 	spinlock_t irq_lock;
481 
482 	int ecc_strengths[BCH_MAX_NUM_CORR_CAPS];
483 	struct nand_ecc_step_info ecc_stepinfos[BCH_MAX_NUM_SECTOR_SIZES];
484 	struct nand_ecc_caps ecc_caps;
485 
486 	int curr_trans_type;
487 
488 	struct dma_chan *dmac;
489 
490 	u32 nf_clk_rate;
491 	/*
492 	 * Estimated Board delay. The value includes the total
493 	 * round trip delay for the signals and is used for deciding on values
494 	 * associated with data read capture.
495 	 */
496 	u32 board_delay;
497 
498 	struct nand_chip *selected_chip;
499 
500 	unsigned long assigned_cs;
501 	struct list_head chips;
502 	u8 bch_metadata_size;
503 };
504 
505 struct cdns_nand_chip {
506 	struct cadence_nand_timings timings;
507 	struct nand_chip chip;
508 	u8 nsels;
509 	struct list_head node;
510 
511 	/*
512 	 * part of oob area of NAND flash memory page.
513 	 * This part is available for user to read or write.
514 	 */
515 	u32 avail_oob_size;
516 
517 	/* Sector size. There are few sectors per mtd->writesize */
518 	u32 sector_size;
519 	u32 sector_count;
520 
521 	/* Offset of BBM. */
522 	u8 bbm_offs;
523 	/* Number of bytes reserved for BBM. */
524 	u8 bbm_len;
525 	/* ECC strength index. */
526 	u8 corr_str_idx;
527 
528 	u8 cs[];
529 };
530 
531 struct ecc_info {
532 	int (*calc_ecc_bytes)(int step_size, int strength);
533 	int max_step_size;
534 };
535 
536 static inline struct
537 cdns_nand_chip *to_cdns_nand_chip(struct nand_chip *chip)
538 {
539 	return container_of(chip, struct cdns_nand_chip, chip);
540 }
541 
542 static inline struct
543 cdns_nand_ctrl *to_cdns_nand_ctrl(struct nand_controller *controller)
544 {
545 	return container_of(controller, struct cdns_nand_ctrl, controller);
546 }
547 
548 static bool
549 cadence_nand_dma_buf_ok(struct cdns_nand_ctrl *cdns_ctrl, const void *buf,
550 			u32 buf_len)
551 {
552 	u8 data_dma_width = cdns_ctrl->caps2.data_dma_width;
553 
554 	return buf && virt_addr_valid(buf) &&
555 		likely(IS_ALIGNED((uintptr_t)buf, data_dma_width)) &&
556 		likely(IS_ALIGNED(buf_len, DMA_DATA_SIZE_ALIGN));
557 }
558 
559 static int cadence_nand_wait_for_value(struct cdns_nand_ctrl *cdns_ctrl,
560 				       u32 reg_offset, u32 timeout_us,
561 				       u32 mask, bool is_clear)
562 {
563 	u32 val;
564 	int ret;
565 
566 	ret = readl_relaxed_poll_timeout(cdns_ctrl->reg + reg_offset,
567 					 val, !(val & mask) == is_clear,
568 					 10, timeout_us);
569 
570 	if (ret < 0) {
571 		dev_err(cdns_ctrl->dev,
572 			"Timeout while waiting for reg %x with mask %x is clear %d\n",
573 			reg_offset, mask, is_clear);
574 	}
575 
576 	return ret;
577 }
578 
579 static int cadence_nand_set_ecc_enable(struct cdns_nand_ctrl *cdns_ctrl,
580 				       bool enable)
581 {
582 	u32 reg;
583 
584 	if (cadence_nand_wait_for_value(cdns_ctrl, CTRL_STATUS,
585 					1000000,
586 					CTRL_STATUS_CTRL_BUSY, true))
587 		return -ETIMEDOUT;
588 
589 	reg = readl_relaxed(cdns_ctrl->reg + ECC_CONFIG_0);
590 
591 	if (enable)
592 		reg |= ECC_CONFIG_0_ECC_EN;
593 	else
594 		reg &= ~ECC_CONFIG_0_ECC_EN;
595 
596 	writel_relaxed(reg, cdns_ctrl->reg + ECC_CONFIG_0);
597 
598 	return 0;
599 }
600 
601 static void cadence_nand_set_ecc_strength(struct cdns_nand_ctrl *cdns_ctrl,
602 					  u8 corr_str_idx)
603 {
604 	u32 reg;
605 
606 	if (cdns_ctrl->curr_corr_str_idx == corr_str_idx)
607 		return;
608 
609 	reg = readl_relaxed(cdns_ctrl->reg + ECC_CONFIG_0);
610 	reg &= ~ECC_CONFIG_0_CORR_STR;
611 	reg |= FIELD_PREP(ECC_CONFIG_0_CORR_STR, corr_str_idx);
612 	writel_relaxed(reg, cdns_ctrl->reg + ECC_CONFIG_0);
613 
614 	cdns_ctrl->curr_corr_str_idx = corr_str_idx;
615 }
616 
617 static int cadence_nand_get_ecc_strength_idx(struct cdns_nand_ctrl *cdns_ctrl,
618 					     u8 strength)
619 {
620 	int i, corr_str_idx = -1;
621 
622 	for (i = 0; i < BCH_MAX_NUM_CORR_CAPS; i++) {
623 		if (cdns_ctrl->ecc_strengths[i] == strength) {
624 			corr_str_idx = i;
625 			break;
626 		}
627 	}
628 
629 	return corr_str_idx;
630 }
631 
632 static int cadence_nand_set_skip_marker_val(struct cdns_nand_ctrl *cdns_ctrl,
633 					    u16 marker_value)
634 {
635 	u32 reg;
636 
637 	if (cadence_nand_wait_for_value(cdns_ctrl, CTRL_STATUS,
638 					1000000,
639 					CTRL_STATUS_CTRL_BUSY, true))
640 		return -ETIMEDOUT;
641 
642 	reg = readl_relaxed(cdns_ctrl->reg + SKIP_BYTES_CONF);
643 	reg &= ~SKIP_BYTES_MARKER_VALUE;
644 	reg |= FIELD_PREP(SKIP_BYTES_MARKER_VALUE,
645 			  marker_value);
646 
647 	writel_relaxed(reg, cdns_ctrl->reg + SKIP_BYTES_CONF);
648 
649 	return 0;
650 }
651 
652 static int cadence_nand_set_skip_bytes_conf(struct cdns_nand_ctrl *cdns_ctrl,
653 					    u8 num_of_bytes,
654 					    u32 offset_value,
655 					    int enable)
656 {
657 	u32 reg, skip_bytes_offset;
658 
659 	if (cadence_nand_wait_for_value(cdns_ctrl, CTRL_STATUS,
660 					1000000,
661 					CTRL_STATUS_CTRL_BUSY, true))
662 		return -ETIMEDOUT;
663 
664 	if (!enable) {
665 		num_of_bytes = 0;
666 		offset_value = 0;
667 	}
668 
669 	reg = readl_relaxed(cdns_ctrl->reg + SKIP_BYTES_CONF);
670 	reg &= ~SKIP_BYTES_NUM_OF_BYTES;
671 	reg |= FIELD_PREP(SKIP_BYTES_NUM_OF_BYTES,
672 			  num_of_bytes);
673 	skip_bytes_offset = FIELD_PREP(SKIP_BYTES_OFFSET_VALUE,
674 				       offset_value);
675 
676 	writel_relaxed(reg, cdns_ctrl->reg + SKIP_BYTES_CONF);
677 	writel_relaxed(skip_bytes_offset, cdns_ctrl->reg + SKIP_BYTES_OFFSET);
678 
679 	return 0;
680 }
681 
682 /* Functions enables/disables hardware detection of erased data */
683 static void cadence_nand_set_erase_detection(struct cdns_nand_ctrl *cdns_ctrl,
684 					     bool enable,
685 					     u8 bitflips_threshold)
686 {
687 	u32 reg;
688 
689 	reg = readl_relaxed(cdns_ctrl->reg + ECC_CONFIG_0);
690 
691 	if (enable)
692 		reg |= ECC_CONFIG_0_ERASE_DET_EN;
693 	else
694 		reg &= ~ECC_CONFIG_0_ERASE_DET_EN;
695 
696 	writel_relaxed(reg, cdns_ctrl->reg + ECC_CONFIG_0);
697 	writel_relaxed(bitflips_threshold, cdns_ctrl->reg + ECC_CONFIG_1);
698 }
699 
700 static int cadence_nand_set_access_width16(struct cdns_nand_ctrl *cdns_ctrl,
701 					   bool bit_bus16)
702 {
703 	u32 reg;
704 
705 	if (cadence_nand_wait_for_value(cdns_ctrl, CTRL_STATUS,
706 					1000000,
707 					CTRL_STATUS_CTRL_BUSY, true))
708 		return -ETIMEDOUT;
709 
710 	reg = readl_relaxed(cdns_ctrl->reg + COMMON_SET);
711 
712 	if (!bit_bus16)
713 		reg &= ~COMMON_SET_DEVICE_16BIT;
714 	else
715 		reg |= COMMON_SET_DEVICE_16BIT;
716 	writel_relaxed(reg, cdns_ctrl->reg + COMMON_SET);
717 
718 	return 0;
719 }
720 
721 static void
722 cadence_nand_clear_interrupt(struct cdns_nand_ctrl *cdns_ctrl,
723 			     struct cadence_nand_irq_status *irq_status)
724 {
725 	writel_relaxed(irq_status->status, cdns_ctrl->reg + INTR_STATUS);
726 	writel_relaxed(irq_status->trd_status,
727 		       cdns_ctrl->reg + TRD_COMP_INT_STATUS);
728 	writel_relaxed(irq_status->trd_error,
729 		       cdns_ctrl->reg + TRD_ERR_INT_STATUS);
730 }
731 
732 static void
733 cadence_nand_read_int_status(struct cdns_nand_ctrl *cdns_ctrl,
734 			     struct cadence_nand_irq_status *irq_status)
735 {
736 	irq_status->status = readl_relaxed(cdns_ctrl->reg + INTR_STATUS);
737 	irq_status->trd_status = readl_relaxed(cdns_ctrl->reg
738 					       + TRD_COMP_INT_STATUS);
739 	irq_status->trd_error = readl_relaxed(cdns_ctrl->reg
740 					      + TRD_ERR_INT_STATUS);
741 }
742 
743 static u32 irq_detected(struct cdns_nand_ctrl *cdns_ctrl,
744 			struct cadence_nand_irq_status *irq_status)
745 {
746 	cadence_nand_read_int_status(cdns_ctrl, irq_status);
747 
748 	return irq_status->status || irq_status->trd_status ||
749 		irq_status->trd_error;
750 }
751 
752 static void cadence_nand_reset_irq(struct cdns_nand_ctrl *cdns_ctrl)
753 {
754 	unsigned long flags;
755 
756 	spin_lock_irqsave(&cdns_ctrl->irq_lock, flags);
757 	memset(&cdns_ctrl->irq_status, 0, sizeof(cdns_ctrl->irq_status));
758 	memset(&cdns_ctrl->irq_mask, 0, sizeof(cdns_ctrl->irq_mask));
759 	spin_unlock_irqrestore(&cdns_ctrl->irq_lock, flags);
760 }
761 
762 /*
763  * This is the interrupt service routine. It handles all interrupts
764  * sent to this device.
765  */
766 static irqreturn_t cadence_nand_isr(int irq, void *dev_id)
767 {
768 	struct cdns_nand_ctrl *cdns_ctrl = dev_id;
769 	struct cadence_nand_irq_status irq_status;
770 	irqreturn_t result = IRQ_NONE;
771 
772 	spin_lock(&cdns_ctrl->irq_lock);
773 
774 	if (irq_detected(cdns_ctrl, &irq_status)) {
775 		/* Handle interrupt. */
776 		/* First acknowledge it. */
777 		cadence_nand_clear_interrupt(cdns_ctrl, &irq_status);
778 		/* Status in the device context for someone to read. */
779 		cdns_ctrl->irq_status.status |= irq_status.status;
780 		cdns_ctrl->irq_status.trd_status |= irq_status.trd_status;
781 		cdns_ctrl->irq_status.trd_error |= irq_status.trd_error;
782 		/* Notify anyone who cares that it happened. */
783 		complete(&cdns_ctrl->complete);
784 		/* Tell the OS that we've handled this. */
785 		result = IRQ_HANDLED;
786 	}
787 	spin_unlock(&cdns_ctrl->irq_lock);
788 
789 	return result;
790 }
791 
792 static void cadence_nand_set_irq_mask(struct cdns_nand_ctrl *cdns_ctrl,
793 				      struct cadence_nand_irq_status *irq_mask)
794 {
795 	writel_relaxed(INTR_ENABLE_INTR_EN | irq_mask->status,
796 		       cdns_ctrl->reg + INTR_ENABLE);
797 
798 	writel_relaxed(irq_mask->trd_error,
799 		       cdns_ctrl->reg + TRD_ERR_INT_STATUS_EN);
800 }
801 
802 static void
803 cadence_nand_wait_for_irq(struct cdns_nand_ctrl *cdns_ctrl,
804 			  struct cadence_nand_irq_status *irq_mask,
805 			  struct cadence_nand_irq_status *irq_status)
806 {
807 	unsigned long timeout = msecs_to_jiffies(10000);
808 	unsigned long time_left;
809 
810 	time_left = wait_for_completion_timeout(&cdns_ctrl->complete,
811 						timeout);
812 
813 	*irq_status = cdns_ctrl->irq_status;
814 	if (time_left == 0) {
815 		/* Timeout error. */
816 		dev_err(cdns_ctrl->dev, "timeout occurred:\n");
817 		dev_err(cdns_ctrl->dev, "\tstatus = 0x%x, mask = 0x%x\n",
818 			irq_status->status, irq_mask->status);
819 		dev_err(cdns_ctrl->dev,
820 			"\ttrd_status = 0x%x, trd_status mask = 0x%x\n",
821 			irq_status->trd_status, irq_mask->trd_status);
822 		dev_err(cdns_ctrl->dev,
823 			"\t trd_error = 0x%x, trd_error mask = 0x%x\n",
824 			irq_status->trd_error, irq_mask->trd_error);
825 	}
826 }
827 
828 /* Execute generic command on NAND controller. */
829 static int cadence_nand_generic_cmd_send(struct cdns_nand_ctrl *cdns_ctrl,
830 					 u8 chip_nr,
831 					 u64 mini_ctrl_cmd)
832 {
833 	u32 mini_ctrl_cmd_l, mini_ctrl_cmd_h, reg;
834 
835 	mini_ctrl_cmd |= FIELD_PREP(GCMD_LAY_CS, chip_nr);
836 	mini_ctrl_cmd_l = mini_ctrl_cmd & 0xFFFFFFFF;
837 	mini_ctrl_cmd_h = mini_ctrl_cmd >> 32;
838 
839 	if (cadence_nand_wait_for_value(cdns_ctrl, CTRL_STATUS,
840 					1000000,
841 					CTRL_STATUS_CTRL_BUSY, true))
842 		return -ETIMEDOUT;
843 
844 	cadence_nand_reset_irq(cdns_ctrl);
845 
846 	writel_relaxed(mini_ctrl_cmd_l, cdns_ctrl->reg + CMD_REG2);
847 	writel_relaxed(mini_ctrl_cmd_h, cdns_ctrl->reg + CMD_REG3);
848 
849 	/* Select generic command. */
850 	reg = FIELD_PREP(CMD_REG0_CT, CMD_REG0_CT_GEN);
851 	/* Thread number. */
852 	reg |= FIELD_PREP(CMD_REG0_TN, 0);
853 
854 	/* Issue command. */
855 	writel_relaxed(reg, cdns_ctrl->reg + CMD_REG0);
856 
857 	return 0;
858 }
859 
860 /* Wait for data on slave DMA interface. */
861 static int cadence_nand_wait_on_sdma(struct cdns_nand_ctrl *cdns_ctrl,
862 				     u8 *out_sdma_trd,
863 				     u32 *out_sdma_size)
864 {
865 	struct cadence_nand_irq_status irq_mask, irq_status;
866 
867 	irq_mask.trd_status = 0;
868 	irq_mask.trd_error = 0;
869 	irq_mask.status = INTR_STATUS_SDMA_TRIGG
870 		| INTR_STATUS_SDMA_ERR
871 		| INTR_STATUS_UNSUPP_CMD;
872 
873 	cadence_nand_set_irq_mask(cdns_ctrl, &irq_mask);
874 	cadence_nand_wait_for_irq(cdns_ctrl, &irq_mask, &irq_status);
875 	if (irq_status.status == 0) {
876 		dev_err(cdns_ctrl->dev, "Timeout while waiting for SDMA\n");
877 		return -ETIMEDOUT;
878 	}
879 
880 	if (irq_status.status & INTR_STATUS_SDMA_TRIGG) {
881 		*out_sdma_size = readl_relaxed(cdns_ctrl->reg + SDMA_SIZE);
882 		*out_sdma_trd  = readl_relaxed(cdns_ctrl->reg + SDMA_TRD_NUM);
883 		*out_sdma_trd =
884 			FIELD_GET(SDMA_TRD_NUM_SDMA_TRD, *out_sdma_trd);
885 	} else {
886 		dev_err(cdns_ctrl->dev, "SDMA error - irq_status %x\n",
887 			irq_status.status);
888 		return -EIO;
889 	}
890 
891 	return 0;
892 }
893 
894 static void cadence_nand_get_caps(struct cdns_nand_ctrl *cdns_ctrl)
895 {
896 	u32  reg;
897 
898 	reg = readl_relaxed(cdns_ctrl->reg + CTRL_FEATURES);
899 
900 	cdns_ctrl->caps2.max_banks = 1 << FIELD_GET(CTRL_FEATURES_N_BANKS, reg);
901 
902 	if (FIELD_GET(CTRL_FEATURES_DMA_DWITH64, reg))
903 		cdns_ctrl->caps2.data_dma_width = 8;
904 	else
905 		cdns_ctrl->caps2.data_dma_width = 4;
906 
907 	if (reg & CTRL_FEATURES_CONTROL_DATA)
908 		cdns_ctrl->caps2.data_control_supp = true;
909 
910 	if (reg & (CTRL_FEATURES_NVDDR_2_3
911 		   | CTRL_FEATURES_NVDDR))
912 		cdns_ctrl->caps2.is_phy_type_dll = true;
913 }
914 
915 /* Prepare CDMA descriptor. */
916 static void
917 cadence_nand_cdma_desc_prepare(struct cdns_nand_ctrl *cdns_ctrl,
918 			       char nf_mem, u32 flash_ptr, dma_addr_t mem_ptr,
919 				   dma_addr_t ctrl_data_ptr, u16 ctype)
920 {
921 	struct cadence_nand_cdma_desc *cdma_desc = cdns_ctrl->cdma_desc;
922 
923 	memset(cdma_desc, 0, sizeof(struct cadence_nand_cdma_desc));
924 
925 	/* Set fields for one descriptor. */
926 	cdma_desc->flash_pointer = flash_ptr;
927 	if (cdns_ctrl->ctrl_rev >= 13)
928 		cdma_desc->bank = nf_mem;
929 	else
930 		cdma_desc->flash_pointer |= (nf_mem << CDMA_CFPTR_MEM_SHIFT);
931 
932 	cdma_desc->command_flags |= CDMA_CF_DMA_MASTER;
933 	cdma_desc->command_flags  |= CDMA_CF_INT;
934 
935 	cdma_desc->memory_pointer = mem_ptr;
936 	cdma_desc->status = 0;
937 	cdma_desc->sync_flag_pointer = 0;
938 	cdma_desc->sync_arguments = 0;
939 
940 	cdma_desc->command_type = ctype;
941 	cdma_desc->ctrl_data_ptr = ctrl_data_ptr;
942 }
943 
944 static u8 cadence_nand_check_desc_error(struct cdns_nand_ctrl *cdns_ctrl,
945 					u32 desc_status)
946 {
947 	if (desc_status & CDMA_CS_ERP)
948 		return STAT_ERASED;
949 
950 	if (desc_status & CDMA_CS_UNCE)
951 		return STAT_ECC_UNCORR;
952 
953 	if (desc_status & CDMA_CS_ERR) {
954 		dev_err(cdns_ctrl->dev, ":CDMA desc error flag detected.\n");
955 		return STAT_FAIL;
956 	}
957 
958 	if (FIELD_GET(CDMA_CS_MAXERR, desc_status))
959 		return STAT_ECC_CORR;
960 
961 	return STAT_FAIL;
962 }
963 
964 static int cadence_nand_cdma_finish(struct cdns_nand_ctrl *cdns_ctrl)
965 {
966 	struct cadence_nand_cdma_desc *desc_ptr = cdns_ctrl->cdma_desc;
967 	u8 status = STAT_BUSY;
968 
969 	if (desc_ptr->status & CDMA_CS_FAIL) {
970 		status = cadence_nand_check_desc_error(cdns_ctrl,
971 						       desc_ptr->status);
972 		dev_err(cdns_ctrl->dev, ":CDMA error %x\n", desc_ptr->status);
973 	} else if (desc_ptr->status & CDMA_CS_COMP) {
974 		/* Descriptor finished with no errors. */
975 		if (desc_ptr->command_flags & CDMA_CF_CONT) {
976 			dev_info(cdns_ctrl->dev, "DMA unsupported flag is set");
977 			status = STAT_UNKNOWN;
978 		} else {
979 			/* Last descriptor.  */
980 			status = STAT_OK;
981 		}
982 	}
983 
984 	return status;
985 }
986 
987 static int cadence_nand_cdma_send(struct cdns_nand_ctrl *cdns_ctrl,
988 				  u8 thread)
989 {
990 	u32 reg;
991 	int status;
992 
993 	/* Wait for thread ready. */
994 	status = cadence_nand_wait_for_value(cdns_ctrl, TRD_STATUS,
995 					     1000000,
996 					     BIT(thread), true);
997 	if (status)
998 		return status;
999 
1000 	cadence_nand_reset_irq(cdns_ctrl);
1001 	reinit_completion(&cdns_ctrl->complete);
1002 
1003 	writel_relaxed((u32)cdns_ctrl->dma_cdma_desc,
1004 		       cdns_ctrl->reg + CMD_REG2);
1005 	writel_relaxed(0, cdns_ctrl->reg + CMD_REG3);
1006 
1007 	/* Select CDMA mode. */
1008 	reg = FIELD_PREP(CMD_REG0_CT, CMD_REG0_CT_CDMA);
1009 	/* Thread number. */
1010 	reg |= FIELD_PREP(CMD_REG0_TN, thread);
1011 	/* Issue command. */
1012 	writel_relaxed(reg, cdns_ctrl->reg + CMD_REG0);
1013 
1014 	return 0;
1015 }
1016 
1017 /* Send SDMA command and wait for finish. */
1018 static u32
1019 cadence_nand_cdma_send_and_wait(struct cdns_nand_ctrl *cdns_ctrl,
1020 				u8 thread)
1021 {
1022 	struct cadence_nand_irq_status irq_mask, irq_status = {0};
1023 	int status;
1024 
1025 	irq_mask.trd_status = BIT(thread);
1026 	irq_mask.trd_error = BIT(thread);
1027 	irq_mask.status = INTR_STATUS_CDMA_TERR;
1028 
1029 	cadence_nand_set_irq_mask(cdns_ctrl, &irq_mask);
1030 
1031 	status = cadence_nand_cdma_send(cdns_ctrl, thread);
1032 	if (status)
1033 		return status;
1034 
1035 	cadence_nand_wait_for_irq(cdns_ctrl, &irq_mask, &irq_status);
1036 
1037 	if (irq_status.status == 0 && irq_status.trd_status == 0 &&
1038 	    irq_status.trd_error == 0) {
1039 		dev_err(cdns_ctrl->dev, "CDMA command timeout\n");
1040 		return -ETIMEDOUT;
1041 	}
1042 	if (irq_status.status & irq_mask.status) {
1043 		dev_err(cdns_ctrl->dev, "CDMA command failed\n");
1044 		return -EIO;
1045 	}
1046 
1047 	return 0;
1048 }
1049 
1050 /*
1051  * ECC size depends on configured ECC strength and on maximum supported
1052  * ECC step size.
1053  */
1054 static int cadence_nand_calc_ecc_bytes(int max_step_size, int strength)
1055 {
1056 	int nbytes = DIV_ROUND_UP(fls(8 * max_step_size) * strength, 8);
1057 
1058 	return ALIGN(nbytes, 2);
1059 }
1060 
1061 #define CADENCE_NAND_CALC_ECC_BYTES(max_step_size) \
1062 	static int \
1063 	cadence_nand_calc_ecc_bytes_##max_step_size(int step_size, \
1064 						    int strength)\
1065 	{\
1066 		return cadence_nand_calc_ecc_bytes(max_step_size, strength);\
1067 	}
1068 
1069 CADENCE_NAND_CALC_ECC_BYTES(256)
1070 CADENCE_NAND_CALC_ECC_BYTES(512)
1071 CADENCE_NAND_CALC_ECC_BYTES(1024)
1072 CADENCE_NAND_CALC_ECC_BYTES(2048)
1073 CADENCE_NAND_CALC_ECC_BYTES(4096)
1074 
1075 /* Function reads BCH capabilities. */
1076 static int cadence_nand_read_bch_caps(struct cdns_nand_ctrl *cdns_ctrl)
1077 {
1078 	struct nand_ecc_caps *ecc_caps = &cdns_ctrl->ecc_caps;
1079 	int max_step_size = 0, nstrengths, i;
1080 	u32 reg;
1081 
1082 	reg = readl_relaxed(cdns_ctrl->reg + BCH_CFG_3);
1083 	cdns_ctrl->bch_metadata_size = FIELD_GET(BCH_CFG_3_METADATA_SIZE, reg);
1084 	if (cdns_ctrl->bch_metadata_size < 4) {
1085 		dev_err(cdns_ctrl->dev,
1086 			"Driver needs at least 4 bytes of BCH meta data\n");
1087 		return -EIO;
1088 	}
1089 
1090 	reg = readl_relaxed(cdns_ctrl->reg + BCH_CFG_0);
1091 	cdns_ctrl->ecc_strengths[0] = FIELD_GET(BCH_CFG_0_CORR_CAP_0, reg);
1092 	cdns_ctrl->ecc_strengths[1] = FIELD_GET(BCH_CFG_0_CORR_CAP_1, reg);
1093 	cdns_ctrl->ecc_strengths[2] = FIELD_GET(BCH_CFG_0_CORR_CAP_2, reg);
1094 	cdns_ctrl->ecc_strengths[3] = FIELD_GET(BCH_CFG_0_CORR_CAP_3, reg);
1095 
1096 	reg = readl_relaxed(cdns_ctrl->reg + BCH_CFG_1);
1097 	cdns_ctrl->ecc_strengths[4] = FIELD_GET(BCH_CFG_1_CORR_CAP_4, reg);
1098 	cdns_ctrl->ecc_strengths[5] = FIELD_GET(BCH_CFG_1_CORR_CAP_5, reg);
1099 	cdns_ctrl->ecc_strengths[6] = FIELD_GET(BCH_CFG_1_CORR_CAP_6, reg);
1100 	cdns_ctrl->ecc_strengths[7] = FIELD_GET(BCH_CFG_1_CORR_CAP_7, reg);
1101 
1102 	reg = readl_relaxed(cdns_ctrl->reg + BCH_CFG_2);
1103 	cdns_ctrl->ecc_stepinfos[0].stepsize =
1104 		FIELD_GET(BCH_CFG_2_SECT_0, reg);
1105 
1106 	cdns_ctrl->ecc_stepinfos[1].stepsize =
1107 		FIELD_GET(BCH_CFG_2_SECT_1, reg);
1108 
1109 	nstrengths = 0;
1110 	for (i = 0; i < BCH_MAX_NUM_CORR_CAPS; i++) {
1111 		if (cdns_ctrl->ecc_strengths[i] != 0)
1112 			nstrengths++;
1113 	}
1114 
1115 	ecc_caps->nstepinfos = 0;
1116 	for (i = 0; i < BCH_MAX_NUM_SECTOR_SIZES; i++) {
1117 		/* ECC strengths are common for all step infos. */
1118 		cdns_ctrl->ecc_stepinfos[i].nstrengths = nstrengths;
1119 		cdns_ctrl->ecc_stepinfos[i].strengths =
1120 			cdns_ctrl->ecc_strengths;
1121 
1122 		if (cdns_ctrl->ecc_stepinfos[i].stepsize != 0)
1123 			ecc_caps->nstepinfos++;
1124 
1125 		if (cdns_ctrl->ecc_stepinfos[i].stepsize > max_step_size)
1126 			max_step_size = cdns_ctrl->ecc_stepinfos[i].stepsize;
1127 	}
1128 	ecc_caps->stepinfos = &cdns_ctrl->ecc_stepinfos[0];
1129 
1130 	switch (max_step_size) {
1131 	case 256:
1132 		ecc_caps->calc_ecc_bytes = &cadence_nand_calc_ecc_bytes_256;
1133 		break;
1134 	case 512:
1135 		ecc_caps->calc_ecc_bytes = &cadence_nand_calc_ecc_bytes_512;
1136 		break;
1137 	case 1024:
1138 		ecc_caps->calc_ecc_bytes = &cadence_nand_calc_ecc_bytes_1024;
1139 		break;
1140 	case 2048:
1141 		ecc_caps->calc_ecc_bytes = &cadence_nand_calc_ecc_bytes_2048;
1142 		break;
1143 	case 4096:
1144 		ecc_caps->calc_ecc_bytes = &cadence_nand_calc_ecc_bytes_4096;
1145 		break;
1146 	default:
1147 		dev_err(cdns_ctrl->dev,
1148 			"Unsupported sector size(ecc step size) %d\n",
1149 			max_step_size);
1150 		return -EIO;
1151 	}
1152 
1153 	return 0;
1154 }
1155 
1156 /* Hardware initialization. */
1157 static int cadence_nand_hw_init(struct cdns_nand_ctrl *cdns_ctrl)
1158 {
1159 	int status;
1160 	u32 reg;
1161 
1162 	status = cadence_nand_wait_for_value(cdns_ctrl, CTRL_STATUS,
1163 					     1000000,
1164 					     CTRL_STATUS_INIT_COMP, false);
1165 	if (status)
1166 		return status;
1167 
1168 	reg = readl_relaxed(cdns_ctrl->reg + CTRL_VERSION);
1169 	cdns_ctrl->ctrl_rev = FIELD_GET(CTRL_VERSION_REV, reg);
1170 
1171 	dev_info(cdns_ctrl->dev,
1172 		 "%s: cadence nand controller version reg %x\n",
1173 		 __func__, reg);
1174 
1175 	/* Disable cache and multiplane. */
1176 	writel_relaxed(0, cdns_ctrl->reg + MULTIPLANE_CFG);
1177 	writel_relaxed(0, cdns_ctrl->reg + CACHE_CFG);
1178 
1179 	/* Clear all interrupts. */
1180 	writel_relaxed(0xFFFFFFFF, cdns_ctrl->reg + INTR_STATUS);
1181 
1182 	cadence_nand_get_caps(cdns_ctrl);
1183 	if (cadence_nand_read_bch_caps(cdns_ctrl))
1184 		return -EIO;
1185 
1186 	/*
1187 	 * Set IO width access to 8.
1188 	 * It is because during SW device discovering width access
1189 	 * is expected to be 8.
1190 	 */
1191 	status = cadence_nand_set_access_width16(cdns_ctrl, false);
1192 
1193 	return status;
1194 }
1195 
1196 #define TT_MAIN_OOB_AREAS	2
1197 #define TT_RAW_PAGE		3
1198 #define TT_BBM			4
1199 #define TT_MAIN_OOB_AREA_EXT	5
1200 
1201 /* Prepare size of data to transfer. */
1202 static void
1203 cadence_nand_prepare_data_size(struct nand_chip *chip,
1204 			       int transfer_type)
1205 {
1206 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
1207 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
1208 	struct mtd_info *mtd = nand_to_mtd(chip);
1209 	u32 sec_size = 0, offset = 0, sec_cnt = 1;
1210 	u32 last_sec_size = cdns_chip->sector_size;
1211 	u32 data_ctrl_size = 0;
1212 	u32 reg = 0;
1213 
1214 	if (cdns_ctrl->curr_trans_type == transfer_type)
1215 		return;
1216 
1217 	switch (transfer_type) {
1218 	case TT_MAIN_OOB_AREA_EXT:
1219 		sec_cnt = cdns_chip->sector_count;
1220 		sec_size = cdns_chip->sector_size;
1221 		data_ctrl_size = cdns_chip->avail_oob_size;
1222 		break;
1223 	case TT_MAIN_OOB_AREAS:
1224 		sec_cnt = cdns_chip->sector_count;
1225 		last_sec_size = cdns_chip->sector_size
1226 			+ cdns_chip->avail_oob_size;
1227 		sec_size = cdns_chip->sector_size;
1228 		break;
1229 	case TT_RAW_PAGE:
1230 		last_sec_size = mtd->writesize + mtd->oobsize;
1231 		break;
1232 	case TT_BBM:
1233 		offset = mtd->writesize + cdns_chip->bbm_offs;
1234 		last_sec_size = 8;
1235 		break;
1236 	}
1237 
1238 	reg = 0;
1239 	reg |= FIELD_PREP(TRAN_CFG_0_OFFSET, offset);
1240 	reg |= FIELD_PREP(TRAN_CFG_0_SEC_CNT, sec_cnt);
1241 	writel_relaxed(reg, cdns_ctrl->reg + TRAN_CFG_0);
1242 
1243 	reg = 0;
1244 	reg |= FIELD_PREP(TRAN_CFG_1_LAST_SEC_SIZE, last_sec_size);
1245 	reg |= FIELD_PREP(TRAN_CFG_1_SECTOR_SIZE, sec_size);
1246 	writel_relaxed(reg, cdns_ctrl->reg + TRAN_CFG_1);
1247 
1248 	if (cdns_ctrl->caps2.data_control_supp) {
1249 		reg = readl_relaxed(cdns_ctrl->reg + CONTROL_DATA_CTRL);
1250 		reg &= ~CONTROL_DATA_CTRL_SIZE;
1251 		reg |= FIELD_PREP(CONTROL_DATA_CTRL_SIZE, data_ctrl_size);
1252 		writel_relaxed(reg, cdns_ctrl->reg + CONTROL_DATA_CTRL);
1253 	}
1254 
1255 	cdns_ctrl->curr_trans_type = transfer_type;
1256 }
1257 
1258 static int
1259 cadence_nand_cdma_transfer(struct cdns_nand_ctrl *cdns_ctrl, u8 chip_nr,
1260 			   int page, void *buf, void *ctrl_dat, u32 buf_size,
1261 			   u32 ctrl_dat_size, enum dma_data_direction dir,
1262 			   bool with_ecc)
1263 {
1264 	dma_addr_t dma_buf, dma_ctrl_dat = 0;
1265 	u8 thread_nr = chip_nr;
1266 	int status;
1267 	u16 ctype;
1268 
1269 	if (dir == DMA_FROM_DEVICE)
1270 		ctype = CDMA_CT_RD;
1271 	else
1272 		ctype = CDMA_CT_WR;
1273 
1274 	cadence_nand_set_ecc_enable(cdns_ctrl, with_ecc);
1275 
1276 	dma_buf = dma_map_single(cdns_ctrl->dev, buf, buf_size, dir);
1277 	if (dma_mapping_error(cdns_ctrl->dev, dma_buf)) {
1278 		dev_err(cdns_ctrl->dev, "Failed to map DMA buffer\n");
1279 		return -EIO;
1280 	}
1281 
1282 	if (ctrl_dat && ctrl_dat_size) {
1283 		dma_ctrl_dat = dma_map_single(cdns_ctrl->dev, ctrl_dat,
1284 					      ctrl_dat_size, dir);
1285 		if (dma_mapping_error(cdns_ctrl->dev, dma_ctrl_dat)) {
1286 			dma_unmap_single(cdns_ctrl->dev, dma_buf,
1287 					 buf_size, dir);
1288 			dev_err(cdns_ctrl->dev, "Failed to map DMA buffer\n");
1289 			return -EIO;
1290 		}
1291 	}
1292 
1293 	cadence_nand_cdma_desc_prepare(cdns_ctrl, chip_nr, page,
1294 				       dma_buf, dma_ctrl_dat, ctype);
1295 
1296 	status = cadence_nand_cdma_send_and_wait(cdns_ctrl, thread_nr);
1297 
1298 	dma_unmap_single(cdns_ctrl->dev, dma_buf,
1299 			 buf_size, dir);
1300 
1301 	if (ctrl_dat && ctrl_dat_size)
1302 		dma_unmap_single(cdns_ctrl->dev, dma_ctrl_dat,
1303 				 ctrl_dat_size, dir);
1304 	if (status)
1305 		return status;
1306 
1307 	return cadence_nand_cdma_finish(cdns_ctrl);
1308 }
1309 
1310 static void cadence_nand_set_timings(struct cdns_nand_ctrl *cdns_ctrl,
1311 				     struct cadence_nand_timings *t)
1312 {
1313 	writel_relaxed(t->async_toggle_timings,
1314 		       cdns_ctrl->reg + ASYNC_TOGGLE_TIMINGS);
1315 	writel_relaxed(t->timings0, cdns_ctrl->reg + TIMINGS0);
1316 	writel_relaxed(t->timings1, cdns_ctrl->reg + TIMINGS1);
1317 	writel_relaxed(t->timings2, cdns_ctrl->reg + TIMINGS2);
1318 
1319 	if (cdns_ctrl->caps2.is_phy_type_dll)
1320 		writel_relaxed(t->dll_phy_ctrl, cdns_ctrl->reg + DLL_PHY_CTRL);
1321 
1322 	writel_relaxed(t->phy_ctrl, cdns_ctrl->reg + PHY_CTRL);
1323 
1324 	if (cdns_ctrl->caps2.is_phy_type_dll) {
1325 		writel_relaxed(0, cdns_ctrl->reg + PHY_TSEL);
1326 		writel_relaxed(2, cdns_ctrl->reg + PHY_DQ_TIMING);
1327 		writel_relaxed(t->phy_dqs_timing,
1328 			       cdns_ctrl->reg + PHY_DQS_TIMING);
1329 		writel_relaxed(t->phy_gate_lpbk_ctrl,
1330 			       cdns_ctrl->reg + PHY_GATE_LPBK_CTRL);
1331 		writel_relaxed(PHY_DLL_MASTER_CTRL_BYPASS_MODE,
1332 			       cdns_ctrl->reg + PHY_DLL_MASTER_CTRL);
1333 		writel_relaxed(0, cdns_ctrl->reg + PHY_DLL_SLAVE_CTRL);
1334 	}
1335 }
1336 
1337 static int cadence_nand_select_target(struct nand_chip *chip)
1338 {
1339 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
1340 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
1341 
1342 	if (chip == cdns_ctrl->selected_chip)
1343 		return 0;
1344 
1345 	if (cadence_nand_wait_for_value(cdns_ctrl, CTRL_STATUS,
1346 					1000000,
1347 					CTRL_STATUS_CTRL_BUSY, true))
1348 		return -ETIMEDOUT;
1349 
1350 	cadence_nand_set_timings(cdns_ctrl, &cdns_chip->timings);
1351 
1352 	cadence_nand_set_ecc_strength(cdns_ctrl,
1353 				      cdns_chip->corr_str_idx);
1354 
1355 	cadence_nand_set_erase_detection(cdns_ctrl, true,
1356 					 chip->ecc.strength);
1357 
1358 	cdns_ctrl->curr_trans_type = -1;
1359 	cdns_ctrl->selected_chip = chip;
1360 
1361 	return 0;
1362 }
1363 
1364 static int cadence_nand_erase(struct nand_chip *chip, u32 page)
1365 {
1366 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
1367 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
1368 	int status;
1369 	u8 thread_nr = cdns_chip->cs[chip->cur_cs];
1370 
1371 	cadence_nand_cdma_desc_prepare(cdns_ctrl,
1372 				       cdns_chip->cs[chip->cur_cs],
1373 				       page, 0, 0,
1374 				       CDMA_CT_ERASE);
1375 	status = cadence_nand_cdma_send_and_wait(cdns_ctrl, thread_nr);
1376 	if (status) {
1377 		dev_err(cdns_ctrl->dev, "erase operation failed\n");
1378 		return -EIO;
1379 	}
1380 
1381 	status = cadence_nand_cdma_finish(cdns_ctrl);
1382 	if (status)
1383 		return status;
1384 
1385 	return 0;
1386 }
1387 
1388 static int cadence_nand_read_bbm(struct nand_chip *chip, int page, u8 *buf)
1389 {
1390 	int status;
1391 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
1392 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
1393 	struct mtd_info *mtd = nand_to_mtd(chip);
1394 
1395 	cadence_nand_prepare_data_size(chip, TT_BBM);
1396 
1397 	cadence_nand_set_skip_bytes_conf(cdns_ctrl, 0, 0, 0);
1398 
1399 	/*
1400 	 * Read only bad block marker from offset
1401 	 * defined by a memory manufacturer.
1402 	 */
1403 	status = cadence_nand_cdma_transfer(cdns_ctrl,
1404 					    cdns_chip->cs[chip->cur_cs],
1405 					    page, cdns_ctrl->buf, NULL,
1406 					    mtd->oobsize,
1407 					    0, DMA_FROM_DEVICE, false);
1408 	if (status) {
1409 		dev_err(cdns_ctrl->dev, "read BBM failed\n");
1410 		return -EIO;
1411 	}
1412 
1413 	memcpy(buf + cdns_chip->bbm_offs, cdns_ctrl->buf, cdns_chip->bbm_len);
1414 
1415 	return 0;
1416 }
1417 
1418 static int cadence_nand_write_page(struct nand_chip *chip,
1419 				   const u8 *buf, int oob_required,
1420 				   int page)
1421 {
1422 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
1423 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
1424 	struct mtd_info *mtd = nand_to_mtd(chip);
1425 	int status;
1426 	u16 marker_val = 0xFFFF;
1427 
1428 	status = cadence_nand_select_target(chip);
1429 	if (status)
1430 		return status;
1431 
1432 	cadence_nand_set_skip_bytes_conf(cdns_ctrl, cdns_chip->bbm_len,
1433 					 mtd->writesize
1434 					 + cdns_chip->bbm_offs,
1435 					 1);
1436 
1437 	if (oob_required) {
1438 		marker_val = *(u16 *)(chip->oob_poi
1439 				      + cdns_chip->bbm_offs);
1440 	} else {
1441 		/* Set oob data to 0xFF. */
1442 		memset(cdns_ctrl->buf + mtd->writesize, 0xFF,
1443 		       cdns_chip->avail_oob_size);
1444 	}
1445 
1446 	cadence_nand_set_skip_marker_val(cdns_ctrl, marker_val);
1447 
1448 	cadence_nand_prepare_data_size(chip, TT_MAIN_OOB_AREA_EXT);
1449 
1450 	if (cadence_nand_dma_buf_ok(cdns_ctrl, buf, mtd->writesize) &&
1451 	    cdns_ctrl->caps2.data_control_supp) {
1452 		u8 *oob;
1453 
1454 		if (oob_required)
1455 			oob = chip->oob_poi;
1456 		else
1457 			oob = cdns_ctrl->buf + mtd->writesize;
1458 
1459 		status = cadence_nand_cdma_transfer(cdns_ctrl,
1460 						    cdns_chip->cs[chip->cur_cs],
1461 						    page, (void *)buf, oob,
1462 						    mtd->writesize,
1463 						    cdns_chip->avail_oob_size,
1464 						    DMA_TO_DEVICE, true);
1465 		if (status) {
1466 			dev_err(cdns_ctrl->dev, "write page failed\n");
1467 			return -EIO;
1468 		}
1469 
1470 		return 0;
1471 	}
1472 
1473 	if (oob_required) {
1474 		/* Transfer the data to the oob area. */
1475 		memcpy(cdns_ctrl->buf + mtd->writesize, chip->oob_poi,
1476 		       cdns_chip->avail_oob_size);
1477 	}
1478 
1479 	memcpy(cdns_ctrl->buf, buf, mtd->writesize);
1480 
1481 	cadence_nand_prepare_data_size(chip, TT_MAIN_OOB_AREAS);
1482 
1483 	return cadence_nand_cdma_transfer(cdns_ctrl,
1484 					  cdns_chip->cs[chip->cur_cs],
1485 					  page, cdns_ctrl->buf, NULL,
1486 					  mtd->writesize
1487 					  + cdns_chip->avail_oob_size,
1488 					  0, DMA_TO_DEVICE, true);
1489 }
1490 
1491 static int cadence_nand_write_oob(struct nand_chip *chip, int page)
1492 {
1493 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
1494 	struct mtd_info *mtd = nand_to_mtd(chip);
1495 
1496 	memset(cdns_ctrl->buf, 0xFF, mtd->writesize);
1497 
1498 	return cadence_nand_write_page(chip, cdns_ctrl->buf, 1, page);
1499 }
1500 
1501 static int cadence_nand_write_page_raw(struct nand_chip *chip,
1502 				       const u8 *buf, int oob_required,
1503 				       int page)
1504 {
1505 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
1506 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
1507 	struct mtd_info *mtd = nand_to_mtd(chip);
1508 	int writesize = mtd->writesize;
1509 	int oobsize = mtd->oobsize;
1510 	int ecc_steps = chip->ecc.steps;
1511 	int ecc_size = chip->ecc.size;
1512 	int ecc_bytes = chip->ecc.bytes;
1513 	void *tmp_buf = cdns_ctrl->buf;
1514 	int oob_skip = cdns_chip->bbm_len;
1515 	size_t size = writesize + oobsize;
1516 	int i, pos, len;
1517 	int status = 0;
1518 
1519 	status = cadence_nand_select_target(chip);
1520 	if (status)
1521 		return status;
1522 
1523 	/*
1524 	 * Fill the buffer with 0xff first except the full page transfer.
1525 	 * This simplifies the logic.
1526 	 */
1527 	if (!buf || !oob_required)
1528 		memset(tmp_buf, 0xff, size);
1529 
1530 	cadence_nand_set_skip_bytes_conf(cdns_ctrl, 0, 0, 0);
1531 
1532 	/* Arrange the buffer for syndrome payload/ecc layout. */
1533 	if (buf) {
1534 		for (i = 0; i < ecc_steps; i++) {
1535 			pos = i * (ecc_size + ecc_bytes);
1536 			len = ecc_size;
1537 
1538 			if (pos >= writesize)
1539 				pos += oob_skip;
1540 			else if (pos + len > writesize)
1541 				len = writesize - pos;
1542 
1543 			memcpy(tmp_buf + pos, buf, len);
1544 			buf += len;
1545 			if (len < ecc_size) {
1546 				len = ecc_size - len;
1547 				memcpy(tmp_buf + writesize + oob_skip, buf,
1548 				       len);
1549 				buf += len;
1550 			}
1551 		}
1552 	}
1553 
1554 	if (oob_required) {
1555 		const u8 *oob = chip->oob_poi;
1556 		u32 oob_data_offset = (cdns_chip->sector_count - 1) *
1557 			(cdns_chip->sector_size + chip->ecc.bytes)
1558 			+ cdns_chip->sector_size + oob_skip;
1559 
1560 		/* BBM at the beginning of the OOB area. */
1561 		memcpy(tmp_buf + writesize, oob, oob_skip);
1562 
1563 		/* OOB free. */
1564 		memcpy(tmp_buf + oob_data_offset, oob,
1565 		       cdns_chip->avail_oob_size);
1566 		oob += cdns_chip->avail_oob_size;
1567 
1568 		/* OOB ECC. */
1569 		for (i = 0; i < ecc_steps; i++) {
1570 			pos = ecc_size + i * (ecc_size + ecc_bytes);
1571 			if (i == (ecc_steps - 1))
1572 				pos += cdns_chip->avail_oob_size;
1573 
1574 			len = ecc_bytes;
1575 
1576 			if (pos >= writesize)
1577 				pos += oob_skip;
1578 			else if (pos + len > writesize)
1579 				len = writesize - pos;
1580 
1581 			memcpy(tmp_buf + pos, oob, len);
1582 			oob += len;
1583 			if (len < ecc_bytes) {
1584 				len = ecc_bytes - len;
1585 				memcpy(tmp_buf + writesize + oob_skip, oob,
1586 				       len);
1587 				oob += len;
1588 			}
1589 		}
1590 	}
1591 
1592 	cadence_nand_prepare_data_size(chip, TT_RAW_PAGE);
1593 
1594 	return cadence_nand_cdma_transfer(cdns_ctrl,
1595 					  cdns_chip->cs[chip->cur_cs],
1596 					  page, cdns_ctrl->buf, NULL,
1597 					  mtd->writesize +
1598 					  mtd->oobsize,
1599 					  0, DMA_TO_DEVICE, false);
1600 }
1601 
1602 static int cadence_nand_write_oob_raw(struct nand_chip *chip,
1603 				      int page)
1604 {
1605 	return cadence_nand_write_page_raw(chip, NULL, true, page);
1606 }
1607 
1608 static int cadence_nand_read_page(struct nand_chip *chip,
1609 				  u8 *buf, int oob_required, int page)
1610 {
1611 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
1612 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
1613 	struct mtd_info *mtd = nand_to_mtd(chip);
1614 	int status = 0;
1615 	int ecc_err_count = 0;
1616 
1617 	status = cadence_nand_select_target(chip);
1618 	if (status)
1619 		return status;
1620 
1621 	cadence_nand_set_skip_bytes_conf(cdns_ctrl, cdns_chip->bbm_len,
1622 					 mtd->writesize
1623 					 + cdns_chip->bbm_offs, 1);
1624 
1625 	/*
1626 	 * If data buffer can be accessed by DMA and data_control feature
1627 	 * is supported then transfer data and oob directly.
1628 	 */
1629 	if (cadence_nand_dma_buf_ok(cdns_ctrl, buf, mtd->writesize) &&
1630 	    cdns_ctrl->caps2.data_control_supp) {
1631 		u8 *oob;
1632 
1633 		if (oob_required)
1634 			oob = chip->oob_poi;
1635 		else
1636 			oob = cdns_ctrl->buf + mtd->writesize;
1637 
1638 		cadence_nand_prepare_data_size(chip, TT_MAIN_OOB_AREA_EXT);
1639 		status = cadence_nand_cdma_transfer(cdns_ctrl,
1640 						    cdns_chip->cs[chip->cur_cs],
1641 						    page, buf, oob,
1642 						    mtd->writesize,
1643 						    cdns_chip->avail_oob_size,
1644 						    DMA_FROM_DEVICE, true);
1645 	/* Otherwise use bounce buffer. */
1646 	} else {
1647 		cadence_nand_prepare_data_size(chip, TT_MAIN_OOB_AREAS);
1648 		status = cadence_nand_cdma_transfer(cdns_ctrl,
1649 						    cdns_chip->cs[chip->cur_cs],
1650 						    page, cdns_ctrl->buf,
1651 						    NULL, mtd->writesize
1652 						    + cdns_chip->avail_oob_size,
1653 						    0, DMA_FROM_DEVICE, true);
1654 
1655 		memcpy(buf, cdns_ctrl->buf, mtd->writesize);
1656 		if (oob_required)
1657 			memcpy(chip->oob_poi,
1658 			       cdns_ctrl->buf + mtd->writesize,
1659 			       mtd->oobsize);
1660 	}
1661 
1662 	switch (status) {
1663 	case STAT_ECC_UNCORR:
1664 		mtd->ecc_stats.failed++;
1665 		ecc_err_count++;
1666 		break;
1667 	case STAT_ECC_CORR:
1668 		ecc_err_count = FIELD_GET(CDMA_CS_MAXERR,
1669 					  cdns_ctrl->cdma_desc->status);
1670 		mtd->ecc_stats.corrected += ecc_err_count;
1671 		break;
1672 	case STAT_ERASED:
1673 	case STAT_OK:
1674 		break;
1675 	default:
1676 		dev_err(cdns_ctrl->dev, "read page failed\n");
1677 		return -EIO;
1678 	}
1679 
1680 	if (oob_required)
1681 		if (cadence_nand_read_bbm(chip, page, chip->oob_poi))
1682 			return -EIO;
1683 
1684 	return ecc_err_count;
1685 }
1686 
1687 /* Reads OOB data from the device. */
1688 static int cadence_nand_read_oob(struct nand_chip *chip, int page)
1689 {
1690 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
1691 
1692 	return cadence_nand_read_page(chip, cdns_ctrl->buf, 1, page);
1693 }
1694 
1695 static int cadence_nand_read_page_raw(struct nand_chip *chip,
1696 				      u8 *buf, int oob_required, int page)
1697 {
1698 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
1699 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
1700 	struct mtd_info *mtd = nand_to_mtd(chip);
1701 	int oob_skip = cdns_chip->bbm_len;
1702 	int writesize = mtd->writesize;
1703 	int ecc_steps = chip->ecc.steps;
1704 	int ecc_size = chip->ecc.size;
1705 	int ecc_bytes = chip->ecc.bytes;
1706 	void *tmp_buf = cdns_ctrl->buf;
1707 	int i, pos, len;
1708 	int status = 0;
1709 
1710 	status = cadence_nand_select_target(chip);
1711 	if (status)
1712 		return status;
1713 
1714 	cadence_nand_set_skip_bytes_conf(cdns_ctrl, 0, 0, 0);
1715 
1716 	cadence_nand_prepare_data_size(chip, TT_RAW_PAGE);
1717 	status = cadence_nand_cdma_transfer(cdns_ctrl,
1718 					    cdns_chip->cs[chip->cur_cs],
1719 					    page, cdns_ctrl->buf, NULL,
1720 					    mtd->writesize
1721 					    + mtd->oobsize,
1722 					    0, DMA_FROM_DEVICE, false);
1723 
1724 	switch (status) {
1725 	case STAT_ERASED:
1726 	case STAT_OK:
1727 		break;
1728 	default:
1729 		dev_err(cdns_ctrl->dev, "read raw page failed\n");
1730 		return -EIO;
1731 	}
1732 
1733 	/* Arrange the buffer for syndrome payload/ecc layout. */
1734 	if (buf) {
1735 		for (i = 0; i < ecc_steps; i++) {
1736 			pos = i * (ecc_size + ecc_bytes);
1737 			len = ecc_size;
1738 
1739 			if (pos >= writesize)
1740 				pos += oob_skip;
1741 			else if (pos + len > writesize)
1742 				len = writesize - pos;
1743 
1744 			memcpy(buf, tmp_buf + pos, len);
1745 			buf += len;
1746 			if (len < ecc_size) {
1747 				len = ecc_size - len;
1748 				memcpy(buf, tmp_buf + writesize + oob_skip,
1749 				       len);
1750 				buf += len;
1751 			}
1752 		}
1753 	}
1754 
1755 	if (oob_required) {
1756 		u8 *oob = chip->oob_poi;
1757 		u32 oob_data_offset = (cdns_chip->sector_count - 1) *
1758 			(cdns_chip->sector_size + chip->ecc.bytes)
1759 			+ cdns_chip->sector_size + oob_skip;
1760 
1761 		/* OOB free. */
1762 		memcpy(oob, tmp_buf + oob_data_offset,
1763 		       cdns_chip->avail_oob_size);
1764 
1765 		/* BBM at the beginning of the OOB area. */
1766 		memcpy(oob, tmp_buf + writesize, oob_skip);
1767 
1768 		oob += cdns_chip->avail_oob_size;
1769 
1770 		/* OOB ECC */
1771 		for (i = 0; i < ecc_steps; i++) {
1772 			pos = ecc_size + i * (ecc_size + ecc_bytes);
1773 			len = ecc_bytes;
1774 
1775 			if (i == (ecc_steps - 1))
1776 				pos += cdns_chip->avail_oob_size;
1777 
1778 			if (pos >= writesize)
1779 				pos += oob_skip;
1780 			else if (pos + len > writesize)
1781 				len = writesize - pos;
1782 
1783 			memcpy(oob, tmp_buf + pos, len);
1784 			oob += len;
1785 			if (len < ecc_bytes) {
1786 				len = ecc_bytes - len;
1787 				memcpy(oob, tmp_buf + writesize + oob_skip,
1788 				       len);
1789 				oob += len;
1790 			}
1791 		}
1792 	}
1793 
1794 	return 0;
1795 }
1796 
1797 static int cadence_nand_read_oob_raw(struct nand_chip *chip,
1798 				     int page)
1799 {
1800 	return cadence_nand_read_page_raw(chip, NULL, true, page);
1801 }
1802 
1803 static void cadence_nand_slave_dma_transfer_finished(void *data)
1804 {
1805 	struct completion *finished = data;
1806 
1807 	complete(finished);
1808 }
1809 
1810 static int cadence_nand_slave_dma_transfer(struct cdns_nand_ctrl *cdns_ctrl,
1811 					   void *buf,
1812 					   dma_addr_t dev_dma, size_t len,
1813 					   enum dma_data_direction dir)
1814 {
1815 	DECLARE_COMPLETION_ONSTACK(finished);
1816 	struct dma_chan *chan;
1817 	struct dma_device *dma_dev;
1818 	dma_addr_t src_dma, dst_dma, buf_dma;
1819 	struct dma_async_tx_descriptor *tx;
1820 	dma_cookie_t cookie;
1821 
1822 	chan = cdns_ctrl->dmac;
1823 	dma_dev = chan->device;
1824 
1825 	buf_dma = dma_map_single(dma_dev->dev, buf, len, dir);
1826 	if (dma_mapping_error(dma_dev->dev, buf_dma)) {
1827 		dev_err(cdns_ctrl->dev, "Failed to map DMA buffer\n");
1828 		goto err;
1829 	}
1830 
1831 	if (dir == DMA_FROM_DEVICE) {
1832 		src_dma = cdns_ctrl->io.dma;
1833 		dst_dma = buf_dma;
1834 	} else {
1835 		src_dma = buf_dma;
1836 		dst_dma = cdns_ctrl->io.dma;
1837 	}
1838 
1839 	tx = dmaengine_prep_dma_memcpy(cdns_ctrl->dmac, dst_dma, src_dma, len,
1840 				       DMA_CTRL_ACK | DMA_PREP_INTERRUPT);
1841 	if (!tx) {
1842 		dev_err(cdns_ctrl->dev, "Failed to prepare DMA memcpy\n");
1843 		goto err_unmap;
1844 	}
1845 
1846 	tx->callback = cadence_nand_slave_dma_transfer_finished;
1847 	tx->callback_param = &finished;
1848 
1849 	cookie = dmaengine_submit(tx);
1850 	if (dma_submit_error(cookie)) {
1851 		dev_err(cdns_ctrl->dev, "Failed to do DMA tx_submit\n");
1852 		goto err_unmap;
1853 	}
1854 
1855 	dma_async_issue_pending(cdns_ctrl->dmac);
1856 	wait_for_completion(&finished);
1857 
1858 	dma_unmap_single(cdns_ctrl->dev, buf_dma, len, dir);
1859 
1860 	return 0;
1861 
1862 err_unmap:
1863 	dma_unmap_single(cdns_ctrl->dev, buf_dma, len, dir);
1864 
1865 err:
1866 	dev_dbg(cdns_ctrl->dev, "Fall back to CPU I/O\n");
1867 
1868 	return -EIO;
1869 }
1870 
1871 static int cadence_nand_read_buf(struct cdns_nand_ctrl *cdns_ctrl,
1872 				 u8 *buf, int len)
1873 {
1874 	u8 thread_nr = 0;
1875 	u32 sdma_size;
1876 	int status;
1877 
1878 	/* Wait until slave DMA interface is ready to data transfer. */
1879 	status = cadence_nand_wait_on_sdma(cdns_ctrl, &thread_nr, &sdma_size);
1880 	if (status)
1881 		return status;
1882 
1883 	if (!cdns_ctrl->caps1->has_dma) {
1884 		int len_in_words = len >> 2;
1885 
1886 		/* read alingment data */
1887 		ioread32_rep(cdns_ctrl->io.virt, buf, len_in_words);
1888 		if (sdma_size > len) {
1889 			/* read rest data from slave DMA interface if any */
1890 			ioread32_rep(cdns_ctrl->io.virt, cdns_ctrl->buf,
1891 				     sdma_size / 4 - len_in_words);
1892 			/* copy rest of data */
1893 			memcpy(buf + (len_in_words << 2), cdns_ctrl->buf,
1894 			       len - (len_in_words << 2));
1895 		}
1896 		return 0;
1897 	}
1898 
1899 	if (cadence_nand_dma_buf_ok(cdns_ctrl, buf, len)) {
1900 		status = cadence_nand_slave_dma_transfer(cdns_ctrl, buf,
1901 							 cdns_ctrl->io.dma,
1902 							 len, DMA_FROM_DEVICE);
1903 		if (status == 0)
1904 			return 0;
1905 
1906 		dev_warn(cdns_ctrl->dev,
1907 			 "Slave DMA transfer failed. Try again using bounce buffer.");
1908 	}
1909 
1910 	/* If DMA transfer is not possible or failed then use bounce buffer. */
1911 	status = cadence_nand_slave_dma_transfer(cdns_ctrl, cdns_ctrl->buf,
1912 						 cdns_ctrl->io.dma,
1913 						 sdma_size, DMA_FROM_DEVICE);
1914 
1915 	if (status) {
1916 		dev_err(cdns_ctrl->dev, "Slave DMA transfer failed");
1917 		return status;
1918 	}
1919 
1920 	memcpy(buf, cdns_ctrl->buf, len);
1921 
1922 	return 0;
1923 }
1924 
1925 static int cadence_nand_write_buf(struct cdns_nand_ctrl *cdns_ctrl,
1926 				  const u8 *buf, int len)
1927 {
1928 	u8 thread_nr = 0;
1929 	u32 sdma_size;
1930 	int status;
1931 
1932 	/* Wait until slave DMA interface is ready to data transfer. */
1933 	status = cadence_nand_wait_on_sdma(cdns_ctrl, &thread_nr, &sdma_size);
1934 	if (status)
1935 		return status;
1936 
1937 	if (!cdns_ctrl->caps1->has_dma) {
1938 		int len_in_words = len >> 2;
1939 
1940 		iowrite32_rep(cdns_ctrl->io.virt, buf, len_in_words);
1941 		if (sdma_size > len) {
1942 			/* copy rest of data */
1943 			memcpy(cdns_ctrl->buf, buf + (len_in_words << 2),
1944 			       len - (len_in_words << 2));
1945 			/* write all expected by nand controller data */
1946 			iowrite32_rep(cdns_ctrl->io.virt, cdns_ctrl->buf,
1947 				      sdma_size / 4 - len_in_words);
1948 		}
1949 
1950 		return 0;
1951 	}
1952 
1953 	if (cadence_nand_dma_buf_ok(cdns_ctrl, buf, len)) {
1954 		status = cadence_nand_slave_dma_transfer(cdns_ctrl, (void *)buf,
1955 							 cdns_ctrl->io.dma,
1956 							 len, DMA_TO_DEVICE);
1957 		if (status == 0)
1958 			return 0;
1959 
1960 		dev_warn(cdns_ctrl->dev,
1961 			 "Slave DMA transfer failed. Try again using bounce buffer.");
1962 	}
1963 
1964 	/* If DMA transfer is not possible or failed then use bounce buffer. */
1965 	memcpy(cdns_ctrl->buf, buf, len);
1966 
1967 	status = cadence_nand_slave_dma_transfer(cdns_ctrl, cdns_ctrl->buf,
1968 						 cdns_ctrl->io.dma,
1969 						 sdma_size, DMA_TO_DEVICE);
1970 
1971 	if (status)
1972 		dev_err(cdns_ctrl->dev, "Slave DMA transfer failed");
1973 
1974 	return status;
1975 }
1976 
1977 static int cadence_nand_force_byte_access(struct nand_chip *chip,
1978 					  bool force_8bit)
1979 {
1980 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
1981 	int status;
1982 
1983 	/*
1984 	 * Callers of this function do not verify if the NAND is using a 16-bit
1985 	 * an 8-bit bus for normal operations, so we need to take care of that
1986 	 * here by leaving the configuration unchanged if the NAND does not have
1987 	 * the NAND_BUSWIDTH_16 flag set.
1988 	 */
1989 	if (!(chip->options & NAND_BUSWIDTH_16))
1990 		return 0;
1991 
1992 	status = cadence_nand_set_access_width16(cdns_ctrl, !force_8bit);
1993 
1994 	return status;
1995 }
1996 
1997 static int cadence_nand_cmd_opcode(struct nand_chip *chip,
1998 				   const struct nand_subop *subop)
1999 {
2000 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
2001 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
2002 	const struct nand_op_instr *instr;
2003 	unsigned int op_id = 0;
2004 	u64 mini_ctrl_cmd = 0;
2005 	int ret;
2006 
2007 	instr = &subop->instrs[op_id];
2008 
2009 	if (instr->delay_ns > 0)
2010 		mini_ctrl_cmd |= GCMD_LAY_TWB;
2011 
2012 	mini_ctrl_cmd |= FIELD_PREP(GCMD_LAY_INSTR,
2013 				    GCMD_LAY_INSTR_CMD);
2014 	mini_ctrl_cmd |= FIELD_PREP(GCMD_LAY_INPUT_CMD,
2015 				    instr->ctx.cmd.opcode);
2016 
2017 	ret = cadence_nand_generic_cmd_send(cdns_ctrl,
2018 					    cdns_chip->cs[chip->cur_cs],
2019 					    mini_ctrl_cmd);
2020 	if (ret)
2021 		dev_err(cdns_ctrl->dev, "send cmd %x failed\n",
2022 			instr->ctx.cmd.opcode);
2023 
2024 	return ret;
2025 }
2026 
2027 static int cadence_nand_cmd_address(struct nand_chip *chip,
2028 				    const struct nand_subop *subop)
2029 {
2030 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
2031 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
2032 	const struct nand_op_instr *instr;
2033 	unsigned int op_id = 0;
2034 	u64 mini_ctrl_cmd = 0;
2035 	unsigned int offset, naddrs;
2036 	u64 address = 0;
2037 	const u8 *addrs;
2038 	int ret;
2039 	int i;
2040 
2041 	instr = &subop->instrs[op_id];
2042 
2043 	if (instr->delay_ns > 0)
2044 		mini_ctrl_cmd |= GCMD_LAY_TWB;
2045 
2046 	mini_ctrl_cmd |= FIELD_PREP(GCMD_LAY_INSTR,
2047 				    GCMD_LAY_INSTR_ADDR);
2048 
2049 	offset = nand_subop_get_addr_start_off(subop, op_id);
2050 	naddrs = nand_subop_get_num_addr_cyc(subop, op_id);
2051 	addrs = &instr->ctx.addr.addrs[offset];
2052 
2053 	for (i = 0; i < naddrs; i++)
2054 		address |= (u64)addrs[i] << (8 * i);
2055 
2056 	mini_ctrl_cmd |= FIELD_PREP(GCMD_LAY_INPUT_ADDR,
2057 				    address);
2058 	mini_ctrl_cmd |= FIELD_PREP(GCMD_LAY_INPUT_ADDR_SIZE,
2059 				    naddrs - 1);
2060 
2061 	ret = cadence_nand_generic_cmd_send(cdns_ctrl,
2062 					    cdns_chip->cs[chip->cur_cs],
2063 					    mini_ctrl_cmd);
2064 	if (ret)
2065 		dev_err(cdns_ctrl->dev, "send address %llx failed\n", address);
2066 
2067 	return ret;
2068 }
2069 
2070 static int cadence_nand_cmd_erase(struct nand_chip *chip,
2071 				  const struct nand_subop *subop)
2072 {
2073 	unsigned int op_id;
2074 
2075 	if (subop->instrs[0].ctx.cmd.opcode == NAND_CMD_ERASE1) {
2076 		int i;
2077 		const struct nand_op_instr *instr = NULL;
2078 		unsigned int offset, naddrs;
2079 		const u8 *addrs;
2080 		u32 page = 0;
2081 
2082 		instr = &subop->instrs[1];
2083 		offset = nand_subop_get_addr_start_off(subop, 1);
2084 		naddrs = nand_subop_get_num_addr_cyc(subop, 1);
2085 		addrs = &instr->ctx.addr.addrs[offset];
2086 
2087 		for (i = 0; i < naddrs; i++)
2088 			page |= (u32)addrs[i] << (8 * i);
2089 
2090 		return cadence_nand_erase(chip, page);
2091 	}
2092 
2093 	/*
2094 	 * If it is not an erase operation then handle operation
2095 	 * by calling exec_op function.
2096 	 */
2097 	for (op_id = 0; op_id < subop->ninstrs; op_id++) {
2098 		int ret;
2099 		const struct nand_operation nand_op = {
2100 			.cs = chip->cur_cs,
2101 			.instrs =  &subop->instrs[op_id],
2102 			.ninstrs = 1};
2103 		ret = chip->controller->ops->exec_op(chip, &nand_op, false);
2104 		if (ret)
2105 			return ret;
2106 	}
2107 
2108 	return 0;
2109 }
2110 
2111 static int cadence_nand_cmd_data(struct nand_chip *chip,
2112 				 const struct nand_subop *subop)
2113 {
2114 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
2115 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
2116 	const struct nand_op_instr *instr;
2117 	unsigned int offset, op_id = 0;
2118 	u64 mini_ctrl_cmd = 0;
2119 	int len = 0;
2120 	int ret;
2121 
2122 	instr = &subop->instrs[op_id];
2123 
2124 	if (instr->delay_ns > 0)
2125 		mini_ctrl_cmd |= GCMD_LAY_TWB;
2126 
2127 	mini_ctrl_cmd |= FIELD_PREP(GCMD_LAY_INSTR,
2128 				    GCMD_LAY_INSTR_DATA);
2129 
2130 	if (instr->type == NAND_OP_DATA_OUT_INSTR)
2131 		mini_ctrl_cmd |= FIELD_PREP(GCMD_DIR,
2132 					    GCMD_DIR_WRITE);
2133 
2134 	len = nand_subop_get_data_len(subop, op_id);
2135 	offset = nand_subop_get_data_start_off(subop, op_id);
2136 	mini_ctrl_cmd |= FIELD_PREP(GCMD_SECT_CNT, 1);
2137 	mini_ctrl_cmd |= FIELD_PREP(GCMD_LAST_SIZE, len);
2138 	if (instr->ctx.data.force_8bit) {
2139 		ret = cadence_nand_force_byte_access(chip, true);
2140 		if (ret) {
2141 			dev_err(cdns_ctrl->dev,
2142 				"cannot change byte access generic data cmd failed\n");
2143 			return ret;
2144 		}
2145 	}
2146 
2147 	ret = cadence_nand_generic_cmd_send(cdns_ctrl,
2148 					    cdns_chip->cs[chip->cur_cs],
2149 					    mini_ctrl_cmd);
2150 	if (ret) {
2151 		dev_err(cdns_ctrl->dev, "send generic data cmd failed\n");
2152 		return ret;
2153 	}
2154 
2155 	if (instr->type == NAND_OP_DATA_IN_INSTR) {
2156 		void *buf = instr->ctx.data.buf.in + offset;
2157 
2158 		ret = cadence_nand_read_buf(cdns_ctrl, buf, len);
2159 	} else {
2160 		const void *buf = instr->ctx.data.buf.out + offset;
2161 
2162 		ret = cadence_nand_write_buf(cdns_ctrl, buf, len);
2163 	}
2164 
2165 	if (ret) {
2166 		dev_err(cdns_ctrl->dev, "data transfer failed for generic command\n");
2167 		return ret;
2168 	}
2169 
2170 	if (instr->ctx.data.force_8bit) {
2171 		ret = cadence_nand_force_byte_access(chip, false);
2172 		if (ret) {
2173 			dev_err(cdns_ctrl->dev,
2174 				"cannot change byte access generic data cmd failed\n");
2175 		}
2176 	}
2177 
2178 	return ret;
2179 }
2180 
2181 static int cadence_nand_cmd_waitrdy(struct nand_chip *chip,
2182 				    const struct nand_subop *subop)
2183 {
2184 	int status;
2185 	unsigned int op_id = 0;
2186 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
2187 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
2188 	const struct nand_op_instr *instr = &subop->instrs[op_id];
2189 	u32 timeout_us = instr->ctx.waitrdy.timeout_ms * 1000;
2190 
2191 	status = cadence_nand_wait_for_value(cdns_ctrl, RBN_SETINGS,
2192 					     timeout_us,
2193 					     BIT(cdns_chip->cs[chip->cur_cs]),
2194 					     false);
2195 	return status;
2196 }
2197 
2198 static const struct nand_op_parser cadence_nand_op_parser = NAND_OP_PARSER(
2199 	NAND_OP_PARSER_PATTERN(
2200 		cadence_nand_cmd_erase,
2201 		NAND_OP_PARSER_PAT_CMD_ELEM(false),
2202 		NAND_OP_PARSER_PAT_ADDR_ELEM(false, MAX_ERASE_ADDRESS_CYC),
2203 		NAND_OP_PARSER_PAT_CMD_ELEM(false),
2204 		NAND_OP_PARSER_PAT_WAITRDY_ELEM(false)),
2205 	NAND_OP_PARSER_PATTERN(
2206 		cadence_nand_cmd_opcode,
2207 		NAND_OP_PARSER_PAT_CMD_ELEM(false)),
2208 	NAND_OP_PARSER_PATTERN(
2209 		cadence_nand_cmd_address,
2210 		NAND_OP_PARSER_PAT_ADDR_ELEM(false, MAX_ADDRESS_CYC)),
2211 	NAND_OP_PARSER_PATTERN(
2212 		cadence_nand_cmd_data,
2213 		NAND_OP_PARSER_PAT_DATA_IN_ELEM(false, MAX_DATA_SIZE)),
2214 	NAND_OP_PARSER_PATTERN(
2215 		cadence_nand_cmd_data,
2216 		NAND_OP_PARSER_PAT_DATA_OUT_ELEM(false, MAX_DATA_SIZE)),
2217 	NAND_OP_PARSER_PATTERN(
2218 		cadence_nand_cmd_waitrdy,
2219 		NAND_OP_PARSER_PAT_WAITRDY_ELEM(false))
2220 	);
2221 
2222 static int cadence_nand_exec_op(struct nand_chip *chip,
2223 				const struct nand_operation *op,
2224 				bool check_only)
2225 {
2226 	int status = cadence_nand_select_target(chip);
2227 
2228 	if (status)
2229 		return status;
2230 
2231 	return nand_op_parser_exec_op(chip, &cadence_nand_op_parser, op,
2232 				      check_only);
2233 }
2234 
2235 static int cadence_nand_ooblayout_free(struct mtd_info *mtd, int section,
2236 				       struct mtd_oob_region *oobregion)
2237 {
2238 	struct nand_chip *chip = mtd_to_nand(mtd);
2239 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
2240 
2241 	if (section)
2242 		return -ERANGE;
2243 
2244 	oobregion->offset = cdns_chip->bbm_len;
2245 	oobregion->length = cdns_chip->avail_oob_size
2246 		- cdns_chip->bbm_len;
2247 
2248 	return 0;
2249 }
2250 
2251 static int cadence_nand_ooblayout_ecc(struct mtd_info *mtd, int section,
2252 				      struct mtd_oob_region *oobregion)
2253 {
2254 	struct nand_chip *chip = mtd_to_nand(mtd);
2255 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
2256 
2257 	if (section)
2258 		return -ERANGE;
2259 
2260 	oobregion->offset = cdns_chip->avail_oob_size;
2261 	oobregion->length = chip->ecc.total;
2262 
2263 	return 0;
2264 }
2265 
2266 static const struct mtd_ooblayout_ops cadence_nand_ooblayout_ops = {
2267 	.free = cadence_nand_ooblayout_free,
2268 	.ecc = cadence_nand_ooblayout_ecc,
2269 };
2270 
2271 static int calc_cycl(u32 timing, u32 clock)
2272 {
2273 	if (timing == 0 || clock == 0)
2274 		return 0;
2275 
2276 	if ((timing % clock) > 0)
2277 		return timing / clock;
2278 	else
2279 		return timing / clock - 1;
2280 }
2281 
2282 /* Calculate max data valid window. */
2283 static inline u32 calc_tdvw_max(u32 trp_cnt, u32 clk_period, u32 trhoh_min,
2284 				u32 board_delay_skew_min, u32 ext_mode)
2285 {
2286 	if (ext_mode == 0)
2287 		clk_period /= 2;
2288 
2289 	return (trp_cnt + 1) * clk_period + trhoh_min +
2290 		board_delay_skew_min;
2291 }
2292 
2293 /* Calculate data valid window. */
2294 static inline u32 calc_tdvw(u32 trp_cnt, u32 clk_period, u32 trhoh_min,
2295 			    u32 trea_max, u32 ext_mode)
2296 {
2297 	if (ext_mode == 0)
2298 		clk_period /= 2;
2299 
2300 	return (trp_cnt + 1) * clk_period + trhoh_min - trea_max;
2301 }
2302 
2303 static int
2304 cadence_nand_setup_data_interface(struct nand_chip *chip, int chipnr,
2305 				  const struct nand_data_interface *conf)
2306 {
2307 	const struct nand_sdr_timings *sdr;
2308 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
2309 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
2310 	struct cadence_nand_timings *t = &cdns_chip->timings;
2311 	u32 reg;
2312 	u32 board_delay = cdns_ctrl->board_delay;
2313 	u32 clk_period = DIV_ROUND_DOWN_ULL(1000000000000ULL,
2314 					    cdns_ctrl->nf_clk_rate);
2315 	u32 tceh_cnt, tcs_cnt, tadl_cnt, tccs_cnt;
2316 	u32 tfeat_cnt, trhz_cnt, tvdly_cnt;
2317 	u32 trhw_cnt, twb_cnt, twh_cnt = 0, twhr_cnt;
2318 	u32 twp_cnt = 0, trp_cnt = 0, trh_cnt = 0;
2319 	u32 if_skew = cdns_ctrl->caps1->if_skew;
2320 	u32 board_delay_skew_min = board_delay - if_skew;
2321 	u32 board_delay_skew_max = board_delay + if_skew;
2322 	u32 dqs_sampl_res, phony_dqs_mod;
2323 	u32 tdvw, tdvw_min, tdvw_max;
2324 	u32 ext_rd_mode, ext_wr_mode;
2325 	u32 dll_phy_dqs_timing = 0, phony_dqs_timing = 0, rd_del_sel = 0;
2326 	u32 sampling_point;
2327 
2328 	sdr = nand_get_sdr_timings(conf);
2329 	if (IS_ERR(sdr))
2330 		return PTR_ERR(sdr);
2331 
2332 	memset(t, 0, sizeof(*t));
2333 	/* Sampling point calculation. */
2334 
2335 	if (cdns_ctrl->caps2.is_phy_type_dll)
2336 		phony_dqs_mod = 2;
2337 	else
2338 		phony_dqs_mod = 1;
2339 
2340 	dqs_sampl_res = clk_period / phony_dqs_mod;
2341 
2342 	tdvw_min = sdr->tREA_max + board_delay_skew_max;
2343 	/*
2344 	 * The idea of those calculation is to get the optimum value
2345 	 * for tRP and tRH timings. If it is NOT possible to sample data
2346 	 * with optimal tRP/tRH settings, the parameters will be extended.
2347 	 * If clk_period is 50ns (the lowest value) this condition is met
2348 	 * for asynchronous timing modes 1, 2, 3, 4 and 5.
2349 	 * If clk_period is 20ns the condition is met only
2350 	 * for asynchronous timing mode 5.
2351 	 */
2352 	if (sdr->tRC_min <= clk_period &&
2353 	    sdr->tRP_min <= (clk_period / 2) &&
2354 	    sdr->tREH_min <= (clk_period / 2)) {
2355 		/* Performance mode. */
2356 		ext_rd_mode = 0;
2357 		tdvw = calc_tdvw(trp_cnt, clk_period, sdr->tRHOH_min,
2358 				 sdr->tREA_max, ext_rd_mode);
2359 		tdvw_max = calc_tdvw_max(trp_cnt, clk_period, sdr->tRHOH_min,
2360 					 board_delay_skew_min,
2361 					 ext_rd_mode);
2362 		/*
2363 		 * Check if data valid window and sampling point can be found
2364 		 * and is not on the edge (ie. we have hold margin).
2365 		 * If not extend the tRP timings.
2366 		 */
2367 		if (tdvw > 0) {
2368 			if (tdvw_max <= tdvw_min ||
2369 			    (tdvw_max % dqs_sampl_res) == 0) {
2370 				/*
2371 				 * No valid sampling point so the RE pulse need
2372 				 * to be widen widening by half clock cycle.
2373 				 */
2374 				ext_rd_mode = 1;
2375 			}
2376 		} else {
2377 			/*
2378 			 * There is no valid window
2379 			 * to be able to sample data the tRP need to be widen.
2380 			 * Very safe calculations are performed here.
2381 			 */
2382 			trp_cnt = (sdr->tREA_max + board_delay_skew_max
2383 				   + dqs_sampl_res) / clk_period;
2384 			ext_rd_mode = 1;
2385 		}
2386 
2387 	} else {
2388 		/* Extended read mode. */
2389 		u32 trh;
2390 
2391 		ext_rd_mode = 1;
2392 		trp_cnt = calc_cycl(sdr->tRP_min, clk_period);
2393 		trh = sdr->tRC_min - ((trp_cnt + 1) * clk_period);
2394 		if (sdr->tREH_min >= trh)
2395 			trh_cnt = calc_cycl(sdr->tREH_min, clk_period);
2396 		else
2397 			trh_cnt = calc_cycl(trh, clk_period);
2398 
2399 		tdvw = calc_tdvw(trp_cnt, clk_period, sdr->tRHOH_min,
2400 				 sdr->tREA_max, ext_rd_mode);
2401 		/*
2402 		 * Check if data valid window and sampling point can be found
2403 		 * or if it is at the edge check if previous is valid
2404 		 * - if not extend the tRP timings.
2405 		 */
2406 		if (tdvw > 0) {
2407 			tdvw_max = calc_tdvw_max(trp_cnt, clk_period,
2408 						 sdr->tRHOH_min,
2409 						 board_delay_skew_min,
2410 						 ext_rd_mode);
2411 
2412 			if ((((tdvw_max / dqs_sampl_res)
2413 			      * dqs_sampl_res) <= tdvw_min) ||
2414 			    (((tdvw_max % dqs_sampl_res) == 0) &&
2415 			     (((tdvw_max / dqs_sampl_res - 1)
2416 			       * dqs_sampl_res) <= tdvw_min))) {
2417 				/*
2418 				 * Data valid window width is lower than
2419 				 * sampling resolution and do not hit any
2420 				 * sampling point to be sure the sampling point
2421 				 * will be found the RE low pulse width will be
2422 				 *  extended by one clock cycle.
2423 				 */
2424 				trp_cnt = trp_cnt + 1;
2425 			}
2426 		} else {
2427 			/*
2428 			 * There is no valid window to be able to sample data.
2429 			 * The tRP need to be widen.
2430 			 * Very safe calculations are performed here.
2431 			 */
2432 			trp_cnt = (sdr->tREA_max + board_delay_skew_max
2433 				   + dqs_sampl_res) / clk_period;
2434 		}
2435 	}
2436 
2437 	tdvw_max = calc_tdvw_max(trp_cnt, clk_period,
2438 				 sdr->tRHOH_min,
2439 				 board_delay_skew_min, ext_rd_mode);
2440 
2441 	if (sdr->tWC_min <= clk_period &&
2442 	    (sdr->tWP_min + if_skew) <= (clk_period / 2) &&
2443 	    (sdr->tWH_min + if_skew) <= (clk_period / 2)) {
2444 		ext_wr_mode = 0;
2445 	} else {
2446 		u32 twh;
2447 
2448 		ext_wr_mode = 1;
2449 		twp_cnt = calc_cycl(sdr->tWP_min + if_skew, clk_period);
2450 		if ((twp_cnt + 1) * clk_period < (sdr->tALS_min + if_skew))
2451 			twp_cnt = calc_cycl(sdr->tALS_min + if_skew,
2452 					    clk_period);
2453 
2454 		twh = (sdr->tWC_min - (twp_cnt + 1) * clk_period);
2455 		if (sdr->tWH_min >= twh)
2456 			twh = sdr->tWH_min;
2457 
2458 		twh_cnt = calc_cycl(twh + if_skew, clk_period);
2459 	}
2460 
2461 	reg = FIELD_PREP(ASYNC_TOGGLE_TIMINGS_TRH, trh_cnt);
2462 	reg |= FIELD_PREP(ASYNC_TOGGLE_TIMINGS_TRP, trp_cnt);
2463 	reg |= FIELD_PREP(ASYNC_TOGGLE_TIMINGS_TWH, twh_cnt);
2464 	reg |= FIELD_PREP(ASYNC_TOGGLE_TIMINGS_TWP, twp_cnt);
2465 	t->async_toggle_timings = reg;
2466 	dev_dbg(cdns_ctrl->dev, "ASYNC_TOGGLE_TIMINGS_SDR\t%x\n", reg);
2467 
2468 	tadl_cnt = calc_cycl((sdr->tADL_min + if_skew), clk_period);
2469 	tccs_cnt = calc_cycl((sdr->tCCS_min + if_skew), clk_period);
2470 	twhr_cnt = calc_cycl((sdr->tWHR_min + if_skew), clk_period);
2471 	trhw_cnt = calc_cycl((sdr->tRHW_min + if_skew), clk_period);
2472 	reg = FIELD_PREP(TIMINGS0_TADL, tadl_cnt);
2473 
2474 	/*
2475 	 * If timing exceeds delay field in timing register
2476 	 * then use maximum value.
2477 	 */
2478 	if (FIELD_FIT(TIMINGS0_TCCS, tccs_cnt))
2479 		reg |= FIELD_PREP(TIMINGS0_TCCS, tccs_cnt);
2480 	else
2481 		reg |= TIMINGS0_TCCS;
2482 
2483 	reg |= FIELD_PREP(TIMINGS0_TWHR, twhr_cnt);
2484 	reg |= FIELD_PREP(TIMINGS0_TRHW, trhw_cnt);
2485 	t->timings0 = reg;
2486 	dev_dbg(cdns_ctrl->dev, "TIMINGS0_SDR\t%x\n", reg);
2487 
2488 	/* The following is related to single signal so skew is not needed. */
2489 	trhz_cnt = calc_cycl(sdr->tRHZ_max, clk_period);
2490 	trhz_cnt = trhz_cnt + 1;
2491 	twb_cnt = calc_cycl((sdr->tWB_max + board_delay), clk_period);
2492 	/*
2493 	 * Because of the two stage syncflop the value must be increased by 3
2494 	 * first value is related with sync, second value is related
2495 	 * with output if delay.
2496 	 */
2497 	twb_cnt = twb_cnt + 3 + 5;
2498 	/*
2499 	 * The following is related to the we edge of the random data input
2500 	 * sequence so skew is not needed.
2501 	 */
2502 	tvdly_cnt = calc_cycl(500000 + if_skew, clk_period);
2503 	reg = FIELD_PREP(TIMINGS1_TRHZ, trhz_cnt);
2504 	reg |= FIELD_PREP(TIMINGS1_TWB, twb_cnt);
2505 	reg |= FIELD_PREP(TIMINGS1_TVDLY, tvdly_cnt);
2506 	t->timings1 = reg;
2507 	dev_dbg(cdns_ctrl->dev, "TIMINGS1_SDR\t%x\n", reg);
2508 
2509 	tfeat_cnt = calc_cycl(sdr->tFEAT_max, clk_period);
2510 	if (tfeat_cnt < twb_cnt)
2511 		tfeat_cnt = twb_cnt;
2512 
2513 	tceh_cnt = calc_cycl(sdr->tCEH_min, clk_period);
2514 	tcs_cnt = calc_cycl((sdr->tCS_min + if_skew), clk_period);
2515 
2516 	reg = FIELD_PREP(TIMINGS2_TFEAT, tfeat_cnt);
2517 	reg |= FIELD_PREP(TIMINGS2_CS_HOLD_TIME, tceh_cnt);
2518 	reg |= FIELD_PREP(TIMINGS2_CS_SETUP_TIME, tcs_cnt);
2519 	t->timings2 = reg;
2520 	dev_dbg(cdns_ctrl->dev, "TIMINGS2_SDR\t%x\n", reg);
2521 
2522 	if (cdns_ctrl->caps2.is_phy_type_dll) {
2523 		reg = DLL_PHY_CTRL_DLL_RST_N;
2524 		if (ext_wr_mode)
2525 			reg |= DLL_PHY_CTRL_EXTENDED_WR_MODE;
2526 		if (ext_rd_mode)
2527 			reg |= DLL_PHY_CTRL_EXTENDED_RD_MODE;
2528 
2529 		reg |= FIELD_PREP(DLL_PHY_CTRL_RS_HIGH_WAIT_CNT, 7);
2530 		reg |= FIELD_PREP(DLL_PHY_CTRL_RS_IDLE_CNT, 7);
2531 		t->dll_phy_ctrl = reg;
2532 		dev_dbg(cdns_ctrl->dev, "DLL_PHY_CTRL_SDR\t%x\n", reg);
2533 	}
2534 
2535 	/* Sampling point calculation. */
2536 	if ((tdvw_max % dqs_sampl_res) > 0)
2537 		sampling_point = tdvw_max / dqs_sampl_res;
2538 	else
2539 		sampling_point = (tdvw_max / dqs_sampl_res - 1);
2540 
2541 	if (sampling_point * dqs_sampl_res > tdvw_min) {
2542 		dll_phy_dqs_timing =
2543 			FIELD_PREP(PHY_DQS_TIMING_DQS_SEL_OE_END, 4);
2544 		dll_phy_dqs_timing |= PHY_DQS_TIMING_USE_PHONY_DQS;
2545 		phony_dqs_timing = sampling_point / phony_dqs_mod;
2546 
2547 		if ((sampling_point % 2) > 0) {
2548 			dll_phy_dqs_timing |= PHY_DQS_TIMING_PHONY_DQS_SEL;
2549 			if ((tdvw_max % dqs_sampl_res) == 0)
2550 				/*
2551 				 * Calculation for sampling point at the edge
2552 				 * of data and being odd number.
2553 				 */
2554 				phony_dqs_timing = (tdvw_max / dqs_sampl_res)
2555 					/ phony_dqs_mod - 1;
2556 
2557 			if (!cdns_ctrl->caps2.is_phy_type_dll)
2558 				phony_dqs_timing--;
2559 
2560 		} else {
2561 			phony_dqs_timing--;
2562 		}
2563 		rd_del_sel = phony_dqs_timing + 3;
2564 	} else {
2565 		dev_warn(cdns_ctrl->dev,
2566 			 "ERROR : cannot find valid sampling point\n");
2567 	}
2568 
2569 	reg = FIELD_PREP(PHY_CTRL_PHONY_DQS, phony_dqs_timing);
2570 	if (cdns_ctrl->caps2.is_phy_type_dll)
2571 		reg  |= PHY_CTRL_SDR_DQS;
2572 	t->phy_ctrl = reg;
2573 	dev_dbg(cdns_ctrl->dev, "PHY_CTRL_REG_SDR\t%x\n", reg);
2574 
2575 	if (cdns_ctrl->caps2.is_phy_type_dll) {
2576 		dev_dbg(cdns_ctrl->dev, "PHY_TSEL_REG_SDR\t%x\n", 0);
2577 		dev_dbg(cdns_ctrl->dev, "PHY_DQ_TIMING_REG_SDR\t%x\n", 2);
2578 		dev_dbg(cdns_ctrl->dev, "PHY_DQS_TIMING_REG_SDR\t%x\n",
2579 			dll_phy_dqs_timing);
2580 		t->phy_dqs_timing = dll_phy_dqs_timing;
2581 
2582 		reg = FIELD_PREP(PHY_GATE_LPBK_CTRL_RDS, rd_del_sel);
2583 		dev_dbg(cdns_ctrl->dev, "PHY_GATE_LPBK_CTRL_REG_SDR\t%x\n",
2584 			reg);
2585 		t->phy_gate_lpbk_ctrl = reg;
2586 
2587 		dev_dbg(cdns_ctrl->dev, "PHY_DLL_MASTER_CTRL_REG_SDR\t%lx\n",
2588 			PHY_DLL_MASTER_CTRL_BYPASS_MODE);
2589 		dev_dbg(cdns_ctrl->dev, "PHY_DLL_SLAVE_CTRL_REG_SDR\t%x\n", 0);
2590 	}
2591 
2592 	return 0;
2593 }
2594 
2595 int cadence_nand_attach_chip(struct nand_chip *chip)
2596 {
2597 	struct cdns_nand_ctrl *cdns_ctrl = to_cdns_nand_ctrl(chip->controller);
2598 	struct cdns_nand_chip *cdns_chip = to_cdns_nand_chip(chip);
2599 	u32 ecc_size;
2600 	struct mtd_info *mtd = nand_to_mtd(chip);
2601 	int ret;
2602 
2603 	if (chip->options & NAND_BUSWIDTH_16) {
2604 		ret = cadence_nand_set_access_width16(cdns_ctrl, true);
2605 		if (ret)
2606 			return ret;
2607 	}
2608 
2609 	chip->bbt_options |= NAND_BBT_USE_FLASH;
2610 	chip->bbt_options |= NAND_BBT_NO_OOB;
2611 	chip->ecc.mode = NAND_ECC_HW;
2612 
2613 	chip->options |= NAND_NO_SUBPAGE_WRITE;
2614 
2615 	cdns_chip->bbm_offs = chip->badblockpos;
2616 	cdns_chip->bbm_offs &= ~0x01;
2617 	/* this value should be even number */
2618 	cdns_chip->bbm_len = 2;
2619 
2620 	ret = nand_ecc_choose_conf(chip,
2621 				   &cdns_ctrl->ecc_caps,
2622 				   mtd->oobsize - cdns_chip->bbm_len);
2623 	if (ret) {
2624 		dev_err(cdns_ctrl->dev, "ECC configuration failed\n");
2625 		return ret;
2626 	}
2627 
2628 	dev_dbg(cdns_ctrl->dev,
2629 		"chosen ECC settings: step=%d, strength=%d, bytes=%d\n",
2630 		chip->ecc.size, chip->ecc.strength, chip->ecc.bytes);
2631 
2632 	/* Error correction configuration. */
2633 	cdns_chip->sector_size = chip->ecc.size;
2634 	cdns_chip->sector_count = mtd->writesize / cdns_chip->sector_size;
2635 	ecc_size = cdns_chip->sector_count * chip->ecc.bytes;
2636 
2637 	cdns_chip->avail_oob_size = mtd->oobsize - ecc_size;
2638 
2639 	if (cdns_chip->avail_oob_size > cdns_ctrl->bch_metadata_size)
2640 		cdns_chip->avail_oob_size = cdns_ctrl->bch_metadata_size;
2641 
2642 	if ((cdns_chip->avail_oob_size + cdns_chip->bbm_len + ecc_size)
2643 	    > mtd->oobsize)
2644 		cdns_chip->avail_oob_size -= 4;
2645 
2646 	ret = cadence_nand_get_ecc_strength_idx(cdns_ctrl, chip->ecc.strength);
2647 	if (ret < 0)
2648 		return -EINVAL;
2649 
2650 	cdns_chip->corr_str_idx = (u8)ret;
2651 
2652 	if (cadence_nand_wait_for_value(cdns_ctrl, CTRL_STATUS,
2653 					1000000,
2654 					CTRL_STATUS_CTRL_BUSY, true))
2655 		return -ETIMEDOUT;
2656 
2657 	cadence_nand_set_ecc_strength(cdns_ctrl,
2658 				      cdns_chip->corr_str_idx);
2659 
2660 	cadence_nand_set_erase_detection(cdns_ctrl, true,
2661 					 chip->ecc.strength);
2662 
2663 	/* Override the default read operations. */
2664 	chip->ecc.read_page = cadence_nand_read_page;
2665 	chip->ecc.read_page_raw = cadence_nand_read_page_raw;
2666 	chip->ecc.write_page = cadence_nand_write_page;
2667 	chip->ecc.write_page_raw = cadence_nand_write_page_raw;
2668 	chip->ecc.read_oob = cadence_nand_read_oob;
2669 	chip->ecc.write_oob = cadence_nand_write_oob;
2670 	chip->ecc.read_oob_raw = cadence_nand_read_oob_raw;
2671 	chip->ecc.write_oob_raw = cadence_nand_write_oob_raw;
2672 
2673 	if ((mtd->writesize + mtd->oobsize) > cdns_ctrl->buf_size)
2674 		cdns_ctrl->buf_size = mtd->writesize + mtd->oobsize;
2675 
2676 	/* Is 32-bit DMA supported? */
2677 	ret = dma_set_mask(cdns_ctrl->dev, DMA_BIT_MASK(32));
2678 	if (ret) {
2679 		dev_err(cdns_ctrl->dev, "no usable DMA configuration\n");
2680 		return ret;
2681 	}
2682 
2683 	mtd_set_ooblayout(mtd, &cadence_nand_ooblayout_ops);
2684 
2685 	return 0;
2686 }
2687 
2688 static const struct nand_controller_ops cadence_nand_controller_ops = {
2689 	.attach_chip = cadence_nand_attach_chip,
2690 	.exec_op = cadence_nand_exec_op,
2691 	.setup_data_interface = cadence_nand_setup_data_interface,
2692 };
2693 
2694 static int cadence_nand_chip_init(struct cdns_nand_ctrl *cdns_ctrl,
2695 				  struct device_node *np)
2696 {
2697 	struct cdns_nand_chip *cdns_chip;
2698 	struct mtd_info *mtd;
2699 	struct nand_chip *chip;
2700 	int nsels, ret, i;
2701 	u32 cs;
2702 
2703 	nsels = of_property_count_elems_of_size(np, "reg", sizeof(u32));
2704 	if (nsels <= 0) {
2705 		dev_err(cdns_ctrl->dev, "missing/invalid reg property\n");
2706 		return -EINVAL;
2707 	}
2708 
2709 	/* Allocate the nand chip structure. */
2710 	cdns_chip = devm_kzalloc(cdns_ctrl->dev, sizeof(*cdns_chip) +
2711 				 (nsels * sizeof(u8)),
2712 				 GFP_KERNEL);
2713 	if (!cdns_chip) {
2714 		dev_err(cdns_ctrl->dev, "could not allocate chip structure\n");
2715 		return -ENOMEM;
2716 	}
2717 
2718 	cdns_chip->nsels = nsels;
2719 
2720 	for (i = 0; i < nsels; i++) {
2721 		/* Retrieve CS id. */
2722 		ret = of_property_read_u32_index(np, "reg", i, &cs);
2723 		if (ret) {
2724 			dev_err(cdns_ctrl->dev,
2725 				"could not retrieve reg property: %d\n",
2726 				ret);
2727 			return ret;
2728 		}
2729 
2730 		if (cs >= cdns_ctrl->caps2.max_banks) {
2731 			dev_err(cdns_ctrl->dev,
2732 				"invalid reg value: %u (max CS = %d)\n",
2733 				cs, cdns_ctrl->caps2.max_banks);
2734 			return -EINVAL;
2735 		}
2736 
2737 		if (test_and_set_bit(cs, &cdns_ctrl->assigned_cs)) {
2738 			dev_err(cdns_ctrl->dev,
2739 				"CS %d already assigned\n", cs);
2740 			return -EINVAL;
2741 		}
2742 
2743 		cdns_chip->cs[i] = cs;
2744 	}
2745 
2746 	chip = &cdns_chip->chip;
2747 	chip->controller = &cdns_ctrl->controller;
2748 	nand_set_flash_node(chip, np);
2749 
2750 	mtd = nand_to_mtd(chip);
2751 	mtd->dev.parent = cdns_ctrl->dev;
2752 
2753 	/*
2754 	 * Default to HW ECC engine mode. If the nand-ecc-mode property is given
2755 	 * in the DT node, this entry will be overwritten in nand_scan_ident().
2756 	 */
2757 	chip->ecc.mode = NAND_ECC_HW;
2758 
2759 	ret = nand_scan(chip, cdns_chip->nsels);
2760 	if (ret) {
2761 		dev_err(cdns_ctrl->dev, "could not scan the nand chip\n");
2762 		return ret;
2763 	}
2764 
2765 	ret = mtd_device_register(mtd, NULL, 0);
2766 	if (ret) {
2767 		dev_err(cdns_ctrl->dev,
2768 			"failed to register mtd device: %d\n", ret);
2769 		nand_cleanup(chip);
2770 		return ret;
2771 	}
2772 
2773 	list_add_tail(&cdns_chip->node, &cdns_ctrl->chips);
2774 
2775 	return 0;
2776 }
2777 
2778 static void cadence_nand_chips_cleanup(struct cdns_nand_ctrl *cdns_ctrl)
2779 {
2780 	struct cdns_nand_chip *entry, *temp;
2781 
2782 	list_for_each_entry_safe(entry, temp, &cdns_ctrl->chips, node) {
2783 		nand_release(&entry->chip);
2784 		list_del(&entry->node);
2785 	}
2786 }
2787 
2788 static int cadence_nand_chips_init(struct cdns_nand_ctrl *cdns_ctrl)
2789 {
2790 	struct device_node *np = cdns_ctrl->dev->of_node;
2791 	struct device_node *nand_np;
2792 	int max_cs = cdns_ctrl->caps2.max_banks;
2793 	int nchips, ret;
2794 
2795 	nchips = of_get_child_count(np);
2796 
2797 	if (nchips > max_cs) {
2798 		dev_err(cdns_ctrl->dev,
2799 			"too many NAND chips: %d (max = %d CS)\n",
2800 			nchips, max_cs);
2801 		return -EINVAL;
2802 	}
2803 
2804 	for_each_child_of_node(np, nand_np) {
2805 		ret = cadence_nand_chip_init(cdns_ctrl, nand_np);
2806 		if (ret) {
2807 			of_node_put(nand_np);
2808 			cadence_nand_chips_cleanup(cdns_ctrl);
2809 			return ret;
2810 		}
2811 	}
2812 
2813 	return 0;
2814 }
2815 
2816 static void
2817 cadence_nand_irq_cleanup(int irqnum, struct cdns_nand_ctrl *cdns_ctrl)
2818 {
2819 	/* Disable interrupts. */
2820 	writel_relaxed(INTR_ENABLE_INTR_EN, cdns_ctrl->reg + INTR_ENABLE);
2821 }
2822 
2823 static int cadence_nand_init(struct cdns_nand_ctrl *cdns_ctrl)
2824 {
2825 	dma_cap_mask_t mask;
2826 	int ret;
2827 
2828 	cdns_ctrl->cdma_desc = dma_alloc_coherent(cdns_ctrl->dev,
2829 						  sizeof(*cdns_ctrl->cdma_desc),
2830 						  &cdns_ctrl->dma_cdma_desc,
2831 						  GFP_KERNEL);
2832 	if (!cdns_ctrl->dma_cdma_desc)
2833 		return -ENOMEM;
2834 
2835 	cdns_ctrl->buf_size = SZ_16K;
2836 	cdns_ctrl->buf = kmalloc(cdns_ctrl->buf_size, GFP_KERNEL);
2837 	if (!cdns_ctrl->buf) {
2838 		ret = -ENOMEM;
2839 		goto free_buf_desc;
2840 	}
2841 
2842 	if (devm_request_irq(cdns_ctrl->dev, cdns_ctrl->irq, cadence_nand_isr,
2843 			     IRQF_SHARED, "cadence-nand-controller",
2844 			     cdns_ctrl)) {
2845 		dev_err(cdns_ctrl->dev, "Unable to allocate IRQ\n");
2846 		ret = -ENODEV;
2847 		goto free_buf;
2848 	}
2849 
2850 	spin_lock_init(&cdns_ctrl->irq_lock);
2851 	init_completion(&cdns_ctrl->complete);
2852 
2853 	ret = cadence_nand_hw_init(cdns_ctrl);
2854 	if (ret)
2855 		goto disable_irq;
2856 
2857 	dma_cap_zero(mask);
2858 	dma_cap_set(DMA_MEMCPY, mask);
2859 
2860 	if (cdns_ctrl->caps1->has_dma) {
2861 		cdns_ctrl->dmac = dma_request_channel(mask, NULL, NULL);
2862 		if (!cdns_ctrl->dmac) {
2863 			dev_err(cdns_ctrl->dev,
2864 				"Unable to get a DMA channel\n");
2865 			ret = -EBUSY;
2866 			goto disable_irq;
2867 		}
2868 	}
2869 
2870 	nand_controller_init(&cdns_ctrl->controller);
2871 	INIT_LIST_HEAD(&cdns_ctrl->chips);
2872 
2873 	cdns_ctrl->controller.ops = &cadence_nand_controller_ops;
2874 	cdns_ctrl->curr_corr_str_idx = 0xFF;
2875 
2876 	ret = cadence_nand_chips_init(cdns_ctrl);
2877 	if (ret) {
2878 		dev_err(cdns_ctrl->dev, "Failed to register MTD: %d\n",
2879 			ret);
2880 		goto dma_release_chnl;
2881 	}
2882 
2883 	kfree(cdns_ctrl->buf);
2884 	cdns_ctrl->buf = kzalloc(cdns_ctrl->buf_size, GFP_KERNEL);
2885 	if (!cdns_ctrl->buf) {
2886 		ret = -ENOMEM;
2887 		goto dma_release_chnl;
2888 	}
2889 
2890 	return 0;
2891 
2892 dma_release_chnl:
2893 	if (cdns_ctrl->dmac)
2894 		dma_release_channel(cdns_ctrl->dmac);
2895 
2896 disable_irq:
2897 	cadence_nand_irq_cleanup(cdns_ctrl->irq, cdns_ctrl);
2898 
2899 free_buf:
2900 	kfree(cdns_ctrl->buf);
2901 
2902 free_buf_desc:
2903 	dma_free_coherent(cdns_ctrl->dev, sizeof(struct cadence_nand_cdma_desc),
2904 			  cdns_ctrl->cdma_desc, cdns_ctrl->dma_cdma_desc);
2905 
2906 	return ret;
2907 }
2908 
2909 /* Driver exit point. */
2910 static void cadence_nand_remove(struct cdns_nand_ctrl *cdns_ctrl)
2911 {
2912 	cadence_nand_chips_cleanup(cdns_ctrl);
2913 	cadence_nand_irq_cleanup(cdns_ctrl->irq, cdns_ctrl);
2914 	kfree(cdns_ctrl->buf);
2915 	dma_free_coherent(cdns_ctrl->dev, sizeof(struct cadence_nand_cdma_desc),
2916 			  cdns_ctrl->cdma_desc, cdns_ctrl->dma_cdma_desc);
2917 
2918 	if (cdns_ctrl->dmac)
2919 		dma_release_channel(cdns_ctrl->dmac);
2920 }
2921 
2922 struct cadence_nand_dt {
2923 	struct cdns_nand_ctrl cdns_ctrl;
2924 	struct clk *clk;
2925 };
2926 
2927 static const struct cadence_nand_dt_devdata cadence_nand_default = {
2928 	.if_skew = 0,
2929 	.has_dma = 1,
2930 };
2931 
2932 static const struct of_device_id cadence_nand_dt_ids[] = {
2933 	{
2934 		.compatible = "cdns,hp-nfc",
2935 		.data = &cadence_nand_default
2936 	}, {}
2937 };
2938 
2939 MODULE_DEVICE_TABLE(of, cadence_nand_dt_ids);
2940 
2941 static int cadence_nand_dt_probe(struct platform_device *ofdev)
2942 {
2943 	struct resource *res;
2944 	struct cadence_nand_dt *dt;
2945 	struct cdns_nand_ctrl *cdns_ctrl;
2946 	int ret;
2947 	const struct of_device_id *of_id;
2948 	const struct cadence_nand_dt_devdata *devdata;
2949 	u32 val;
2950 
2951 	of_id = of_match_device(cadence_nand_dt_ids, &ofdev->dev);
2952 	if (of_id) {
2953 		ofdev->id_entry = of_id->data;
2954 		devdata = of_id->data;
2955 	} else {
2956 		pr_err("Failed to find the right device id.\n");
2957 		return -ENOMEM;
2958 	}
2959 
2960 	dt = devm_kzalloc(&ofdev->dev, sizeof(*dt), GFP_KERNEL);
2961 	if (!dt)
2962 		return -ENOMEM;
2963 
2964 	cdns_ctrl = &dt->cdns_ctrl;
2965 	cdns_ctrl->caps1 = devdata;
2966 
2967 	cdns_ctrl->dev = &ofdev->dev;
2968 	cdns_ctrl->irq = platform_get_irq(ofdev, 0);
2969 	if (cdns_ctrl->irq < 0)
2970 		return cdns_ctrl->irq;
2971 
2972 	dev_info(cdns_ctrl->dev, "IRQ: nr %d\n", cdns_ctrl->irq);
2973 
2974 	cdns_ctrl->reg = devm_platform_ioremap_resource(ofdev, 0);
2975 	if (IS_ERR(cdns_ctrl->reg)) {
2976 		dev_err(&ofdev->dev, "devm_ioremap_resource res 0 failed\n");
2977 		return PTR_ERR(cdns_ctrl->reg);
2978 	}
2979 
2980 	res = platform_get_resource(ofdev, IORESOURCE_MEM, 1);
2981 	cdns_ctrl->io.dma = res->start;
2982 	cdns_ctrl->io.virt = devm_ioremap_resource(&ofdev->dev, res);
2983 	if (IS_ERR(cdns_ctrl->io.virt)) {
2984 		dev_err(cdns_ctrl->dev, "devm_ioremap_resource res 1 failed\n");
2985 		return PTR_ERR(cdns_ctrl->io.virt);
2986 	}
2987 
2988 	dt->clk = devm_clk_get(cdns_ctrl->dev, "nf_clk");
2989 	if (IS_ERR(dt->clk))
2990 		return PTR_ERR(dt->clk);
2991 
2992 	cdns_ctrl->nf_clk_rate = clk_get_rate(dt->clk);
2993 
2994 	ret = of_property_read_u32(ofdev->dev.of_node,
2995 				   "cdns,board-delay-ps", &val);
2996 	if (ret) {
2997 		val = 4830;
2998 		dev_info(cdns_ctrl->dev,
2999 			 "missing cdns,board-delay-ps property, %d was set\n",
3000 			 val);
3001 	}
3002 	cdns_ctrl->board_delay = val;
3003 
3004 	ret = cadence_nand_init(cdns_ctrl);
3005 	if (ret)
3006 		return ret;
3007 
3008 	platform_set_drvdata(ofdev, dt);
3009 	return 0;
3010 }
3011 
3012 static int cadence_nand_dt_remove(struct platform_device *ofdev)
3013 {
3014 	struct cadence_nand_dt *dt = platform_get_drvdata(ofdev);
3015 
3016 	cadence_nand_remove(&dt->cdns_ctrl);
3017 
3018 	return 0;
3019 }
3020 
3021 static struct platform_driver cadence_nand_dt_driver = {
3022 	.probe		= cadence_nand_dt_probe,
3023 	.remove		= cadence_nand_dt_remove,
3024 	.driver		= {
3025 		.name	= "cadence-nand-controller",
3026 		.of_match_table = cadence_nand_dt_ids,
3027 	},
3028 };
3029 
3030 module_platform_driver(cadence_nand_dt_driver);
3031 
3032 MODULE_AUTHOR("Piotr Sroka <piotrs@cadence.com>");
3033 MODULE_LICENSE("GPL v2");
3034 MODULE_DESCRIPTION("Driver for Cadence NAND flash controller");
3035 
3036