1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) STMicroelectronics 2018
4  * Author: Christophe Kerello <christophe.kerello@st.com>
5  */
6 
7 #include <linux/bitfield.h>
8 #include <linux/clk.h>
9 #include <linux/dmaengine.h>
10 #include <linux/dma-mapping.h>
11 #include <linux/errno.h>
12 #include <linux/gpio/consumer.h>
13 #include <linux/interrupt.h>
14 #include <linux/iopoll.h>
15 #include <linux/mfd/syscon.h>
16 #include <linux/module.h>
17 #include <linux/mtd/rawnand.h>
18 #include <linux/of_address.h>
19 #include <linux/pinctrl/consumer.h>
20 #include <linux/platform_device.h>
21 #include <linux/regmap.h>
22 #include <linux/reset.h>
23 
24 /* Bad block marker length */
25 #define FMC2_BBM_LEN			2
26 
27 /* ECC step size */
28 #define FMC2_ECC_STEP_SIZE		512
29 
30 /* BCHDSRx registers length */
31 #define FMC2_BCHDSRS_LEN		20
32 
33 /* HECCR length */
34 #define FMC2_HECCR_LEN			4
35 
36 /* Max requests done for a 8k nand page size */
37 #define FMC2_MAX_SG			16
38 
39 /* Max chip enable */
40 #define FMC2_MAX_CE			2
41 
42 /* Max ECC buffer length */
43 #define FMC2_MAX_ECC_BUF_LEN		(FMC2_BCHDSRS_LEN * FMC2_MAX_SG)
44 
45 #define FMC2_TIMEOUT_MS			5000
46 
47 /* Timings */
48 #define FMC2_THIZ			1
49 #define FMC2_TIO			8000
50 #define FMC2_TSYNC			3000
51 #define FMC2_PCR_TIMING_MASK		0xf
52 #define FMC2_PMEM_PATT_TIMING_MASK	0xff
53 
54 /* FMC2 Controller Registers */
55 #define FMC2_BCR1			0x0
56 #define FMC2_PCR			0x80
57 #define FMC2_SR				0x84
58 #define FMC2_PMEM			0x88
59 #define FMC2_PATT			0x8c
60 #define FMC2_HECCR			0x94
61 #define FMC2_ISR			0x184
62 #define FMC2_ICR			0x188
63 #define FMC2_CSQCR			0x200
64 #define FMC2_CSQCFGR1			0x204
65 #define FMC2_CSQCFGR2			0x208
66 #define FMC2_CSQCFGR3			0x20c
67 #define FMC2_CSQAR1			0x210
68 #define FMC2_CSQAR2			0x214
69 #define FMC2_CSQIER			0x220
70 #define FMC2_CSQISR			0x224
71 #define FMC2_CSQICR			0x228
72 #define FMC2_CSQEMSR			0x230
73 #define FMC2_BCHIER			0x250
74 #define FMC2_BCHISR			0x254
75 #define FMC2_BCHICR			0x258
76 #define FMC2_BCHPBR1			0x260
77 #define FMC2_BCHPBR2			0x264
78 #define FMC2_BCHPBR3			0x268
79 #define FMC2_BCHPBR4			0x26c
80 #define FMC2_BCHDSR0			0x27c
81 #define FMC2_BCHDSR1			0x280
82 #define FMC2_BCHDSR2			0x284
83 #define FMC2_BCHDSR3			0x288
84 #define FMC2_BCHDSR4			0x28c
85 
86 /* Register: FMC2_BCR1 */
87 #define FMC2_BCR1_FMC2EN		BIT(31)
88 
89 /* Register: FMC2_PCR */
90 #define FMC2_PCR_PWAITEN		BIT(1)
91 #define FMC2_PCR_PBKEN			BIT(2)
92 #define FMC2_PCR_PWID			GENMASK(5, 4)
93 #define FMC2_PCR_PWID_BUSWIDTH_8	0
94 #define FMC2_PCR_PWID_BUSWIDTH_16	1
95 #define FMC2_PCR_ECCEN			BIT(6)
96 #define FMC2_PCR_ECCALG			BIT(8)
97 #define FMC2_PCR_TCLR			GENMASK(12, 9)
98 #define FMC2_PCR_TCLR_DEFAULT		0xf
99 #define FMC2_PCR_TAR			GENMASK(16, 13)
100 #define FMC2_PCR_TAR_DEFAULT		0xf
101 #define FMC2_PCR_ECCSS			GENMASK(19, 17)
102 #define FMC2_PCR_ECCSS_512		1
103 #define FMC2_PCR_ECCSS_2048		3
104 #define FMC2_PCR_BCHECC			BIT(24)
105 #define FMC2_PCR_WEN			BIT(25)
106 
107 /* Register: FMC2_SR */
108 #define FMC2_SR_NWRF			BIT(6)
109 
110 /* Register: FMC2_PMEM */
111 #define FMC2_PMEM_MEMSET		GENMASK(7, 0)
112 #define FMC2_PMEM_MEMWAIT		GENMASK(15, 8)
113 #define FMC2_PMEM_MEMHOLD		GENMASK(23, 16)
114 #define FMC2_PMEM_MEMHIZ		GENMASK(31, 24)
115 #define FMC2_PMEM_DEFAULT		0x0a0a0a0a
116 
117 /* Register: FMC2_PATT */
118 #define FMC2_PATT_ATTSET		GENMASK(7, 0)
119 #define FMC2_PATT_ATTWAIT		GENMASK(15, 8)
120 #define FMC2_PATT_ATTHOLD		GENMASK(23, 16)
121 #define FMC2_PATT_ATTHIZ		GENMASK(31, 24)
122 #define FMC2_PATT_DEFAULT		0x0a0a0a0a
123 
124 /* Register: FMC2_ISR */
125 #define FMC2_ISR_IHLF			BIT(1)
126 
127 /* Register: FMC2_ICR */
128 #define FMC2_ICR_CIHLF			BIT(1)
129 
130 /* Register: FMC2_CSQCR */
131 #define FMC2_CSQCR_CSQSTART		BIT(0)
132 
133 /* Register: FMC2_CSQCFGR1 */
134 #define FMC2_CSQCFGR1_CMD2EN		BIT(1)
135 #define FMC2_CSQCFGR1_DMADEN		BIT(2)
136 #define FMC2_CSQCFGR1_ACYNBR		GENMASK(6, 4)
137 #define FMC2_CSQCFGR1_CMD1		GENMASK(15, 8)
138 #define FMC2_CSQCFGR1_CMD2		GENMASK(23, 16)
139 #define FMC2_CSQCFGR1_CMD1T		BIT(24)
140 #define FMC2_CSQCFGR1_CMD2T		BIT(25)
141 
142 /* Register: FMC2_CSQCFGR2 */
143 #define FMC2_CSQCFGR2_SQSDTEN		BIT(0)
144 #define FMC2_CSQCFGR2_RCMD2EN		BIT(1)
145 #define FMC2_CSQCFGR2_DMASEN		BIT(2)
146 #define FMC2_CSQCFGR2_RCMD1		GENMASK(15, 8)
147 #define FMC2_CSQCFGR2_RCMD2		GENMASK(23, 16)
148 #define FMC2_CSQCFGR2_RCMD1T		BIT(24)
149 #define FMC2_CSQCFGR2_RCMD2T		BIT(25)
150 
151 /* Register: FMC2_CSQCFGR3 */
152 #define FMC2_CSQCFGR3_SNBR		GENMASK(13, 8)
153 #define FMC2_CSQCFGR3_AC1T		BIT(16)
154 #define FMC2_CSQCFGR3_AC2T		BIT(17)
155 #define FMC2_CSQCFGR3_AC3T		BIT(18)
156 #define FMC2_CSQCFGR3_AC4T		BIT(19)
157 #define FMC2_CSQCFGR3_AC5T		BIT(20)
158 #define FMC2_CSQCFGR3_SDT		BIT(21)
159 #define FMC2_CSQCFGR3_RAC1T		BIT(22)
160 #define FMC2_CSQCFGR3_RAC2T		BIT(23)
161 
162 /* Register: FMC2_CSQCAR1 */
163 #define FMC2_CSQCAR1_ADDC1		GENMASK(7, 0)
164 #define FMC2_CSQCAR1_ADDC2		GENMASK(15, 8)
165 #define FMC2_CSQCAR1_ADDC3		GENMASK(23, 16)
166 #define FMC2_CSQCAR1_ADDC4		GENMASK(31, 24)
167 
168 /* Register: FMC2_CSQCAR2 */
169 #define FMC2_CSQCAR2_ADDC5		GENMASK(7, 0)
170 #define FMC2_CSQCAR2_NANDCEN		GENMASK(11, 10)
171 #define FMC2_CSQCAR2_SAO		GENMASK(31, 16)
172 
173 /* Register: FMC2_CSQIER */
174 #define FMC2_CSQIER_TCIE		BIT(0)
175 
176 /* Register: FMC2_CSQICR */
177 #define FMC2_CSQICR_CLEAR_IRQ		GENMASK(4, 0)
178 
179 /* Register: FMC2_CSQEMSR */
180 #define FMC2_CSQEMSR_SEM		GENMASK(15, 0)
181 
182 /* Register: FMC2_BCHIER */
183 #define FMC2_BCHIER_DERIE		BIT(1)
184 #define FMC2_BCHIER_EPBRIE		BIT(4)
185 
186 /* Register: FMC2_BCHICR */
187 #define FMC2_BCHICR_CLEAR_IRQ		GENMASK(4, 0)
188 
189 /* Register: FMC2_BCHDSR0 */
190 #define FMC2_BCHDSR0_DUE		BIT(0)
191 #define FMC2_BCHDSR0_DEF		BIT(1)
192 #define FMC2_BCHDSR0_DEN		GENMASK(7, 4)
193 
194 /* Register: FMC2_BCHDSR1 */
195 #define FMC2_BCHDSR1_EBP1		GENMASK(12, 0)
196 #define FMC2_BCHDSR1_EBP2		GENMASK(28, 16)
197 
198 /* Register: FMC2_BCHDSR2 */
199 #define FMC2_BCHDSR2_EBP3		GENMASK(12, 0)
200 #define FMC2_BCHDSR2_EBP4		GENMASK(28, 16)
201 
202 /* Register: FMC2_BCHDSR3 */
203 #define FMC2_BCHDSR3_EBP5		GENMASK(12, 0)
204 #define FMC2_BCHDSR3_EBP6		GENMASK(28, 16)
205 
206 /* Register: FMC2_BCHDSR4 */
207 #define FMC2_BCHDSR4_EBP7		GENMASK(12, 0)
208 #define FMC2_BCHDSR4_EBP8		GENMASK(28, 16)
209 
210 enum stm32_fmc2_ecc {
211 	FMC2_ECC_HAM = 1,
212 	FMC2_ECC_BCH4 = 4,
213 	FMC2_ECC_BCH8 = 8
214 };
215 
216 enum stm32_fmc2_irq_state {
217 	FMC2_IRQ_UNKNOWN = 0,
218 	FMC2_IRQ_BCH,
219 	FMC2_IRQ_SEQ
220 };
221 
222 struct stm32_fmc2_timings {
223 	u8 tclr;
224 	u8 tar;
225 	u8 thiz;
226 	u8 twait;
227 	u8 thold_mem;
228 	u8 tset_mem;
229 	u8 thold_att;
230 	u8 tset_att;
231 };
232 
233 struct stm32_fmc2_nand {
234 	struct nand_chip chip;
235 	struct gpio_desc *wp_gpio;
236 	struct stm32_fmc2_timings timings;
237 	int ncs;
238 	int cs_used[FMC2_MAX_CE];
239 };
240 
241 static inline struct stm32_fmc2_nand *to_fmc2_nand(struct nand_chip *chip)
242 {
243 	return container_of(chip, struct stm32_fmc2_nand, chip);
244 }
245 
246 struct stm32_fmc2_nfc {
247 	struct nand_controller base;
248 	struct stm32_fmc2_nand nand;
249 	struct device *dev;
250 	struct device *cdev;
251 	struct regmap *regmap;
252 	void __iomem *data_base[FMC2_MAX_CE];
253 	void __iomem *cmd_base[FMC2_MAX_CE];
254 	void __iomem *addr_base[FMC2_MAX_CE];
255 	phys_addr_t io_phys_addr;
256 	phys_addr_t data_phys_addr[FMC2_MAX_CE];
257 	struct clk *clk;
258 	u8 irq_state;
259 
260 	struct dma_chan *dma_tx_ch;
261 	struct dma_chan *dma_rx_ch;
262 	struct dma_chan *dma_ecc_ch;
263 	struct sg_table dma_data_sg;
264 	struct sg_table dma_ecc_sg;
265 	u8 *ecc_buf;
266 	int dma_ecc_len;
267 
268 	struct completion complete;
269 	struct completion dma_data_complete;
270 	struct completion dma_ecc_complete;
271 
272 	u8 cs_assigned;
273 	int cs_sel;
274 };
275 
276 static inline struct stm32_fmc2_nfc *to_stm32_nfc(struct nand_controller *base)
277 {
278 	return container_of(base, struct stm32_fmc2_nfc, base);
279 }
280 
281 static void stm32_fmc2_nfc_timings_init(struct nand_chip *chip)
282 {
283 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
284 	struct stm32_fmc2_nand *nand = to_fmc2_nand(chip);
285 	struct stm32_fmc2_timings *timings = &nand->timings;
286 	u32 pmem, patt;
287 
288 	/* Set tclr/tar timings */
289 	regmap_update_bits(nfc->regmap, FMC2_PCR,
290 			   FMC2_PCR_TCLR | FMC2_PCR_TAR,
291 			   FIELD_PREP(FMC2_PCR_TCLR, timings->tclr) |
292 			   FIELD_PREP(FMC2_PCR_TAR, timings->tar));
293 
294 	/* Set tset/twait/thold/thiz timings in common bank */
295 	pmem = FIELD_PREP(FMC2_PMEM_MEMSET, timings->tset_mem);
296 	pmem |= FIELD_PREP(FMC2_PMEM_MEMWAIT, timings->twait);
297 	pmem |= FIELD_PREP(FMC2_PMEM_MEMHOLD, timings->thold_mem);
298 	pmem |= FIELD_PREP(FMC2_PMEM_MEMHIZ, timings->thiz);
299 	regmap_write(nfc->regmap, FMC2_PMEM, pmem);
300 
301 	/* Set tset/twait/thold/thiz timings in attribut bank */
302 	patt = FIELD_PREP(FMC2_PATT_ATTSET, timings->tset_att);
303 	patt |= FIELD_PREP(FMC2_PATT_ATTWAIT, timings->twait);
304 	patt |= FIELD_PREP(FMC2_PATT_ATTHOLD, timings->thold_att);
305 	patt |= FIELD_PREP(FMC2_PATT_ATTHIZ, timings->thiz);
306 	regmap_write(nfc->regmap, FMC2_PATT, patt);
307 }
308 
309 static void stm32_fmc2_nfc_setup(struct nand_chip *chip)
310 {
311 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
312 	u32 pcr = 0, pcr_mask;
313 
314 	/* Configure ECC algorithm (default configuration is Hamming) */
315 	pcr_mask = FMC2_PCR_ECCALG;
316 	pcr_mask |= FMC2_PCR_BCHECC;
317 	if (chip->ecc.strength == FMC2_ECC_BCH8) {
318 		pcr |= FMC2_PCR_ECCALG;
319 		pcr |= FMC2_PCR_BCHECC;
320 	} else if (chip->ecc.strength == FMC2_ECC_BCH4) {
321 		pcr |= FMC2_PCR_ECCALG;
322 	}
323 
324 	/* Set buswidth */
325 	pcr_mask |= FMC2_PCR_PWID;
326 	if (chip->options & NAND_BUSWIDTH_16)
327 		pcr |= FIELD_PREP(FMC2_PCR_PWID, FMC2_PCR_PWID_BUSWIDTH_16);
328 
329 	/* Set ECC sector size */
330 	pcr_mask |= FMC2_PCR_ECCSS;
331 	pcr |= FIELD_PREP(FMC2_PCR_ECCSS, FMC2_PCR_ECCSS_512);
332 
333 	regmap_update_bits(nfc->regmap, FMC2_PCR, pcr_mask, pcr);
334 }
335 
336 static int stm32_fmc2_nfc_select_chip(struct nand_chip *chip, int chipnr)
337 {
338 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
339 	struct stm32_fmc2_nand *nand = to_fmc2_nand(chip);
340 	struct dma_slave_config dma_cfg;
341 	int ret;
342 
343 	if (nand->cs_used[chipnr] == nfc->cs_sel)
344 		return 0;
345 
346 	nfc->cs_sel = nand->cs_used[chipnr];
347 	stm32_fmc2_nfc_setup(chip);
348 	stm32_fmc2_nfc_timings_init(chip);
349 
350 	if (nfc->dma_tx_ch && nfc->dma_rx_ch) {
351 		memset(&dma_cfg, 0, sizeof(dma_cfg));
352 		dma_cfg.src_addr = nfc->data_phys_addr[nfc->cs_sel];
353 		dma_cfg.dst_addr = nfc->data_phys_addr[nfc->cs_sel];
354 		dma_cfg.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
355 		dma_cfg.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
356 		dma_cfg.src_maxburst = 32;
357 		dma_cfg.dst_maxburst = 32;
358 
359 		ret = dmaengine_slave_config(nfc->dma_tx_ch, &dma_cfg);
360 		if (ret) {
361 			dev_err(nfc->dev, "tx DMA engine slave config failed\n");
362 			return ret;
363 		}
364 
365 		ret = dmaengine_slave_config(nfc->dma_rx_ch, &dma_cfg);
366 		if (ret) {
367 			dev_err(nfc->dev, "rx DMA engine slave config failed\n");
368 			return ret;
369 		}
370 	}
371 
372 	if (nfc->dma_ecc_ch) {
373 		/*
374 		 * Hamming: we read HECCR register
375 		 * BCH4/BCH8: we read BCHDSRSx registers
376 		 */
377 		memset(&dma_cfg, 0, sizeof(dma_cfg));
378 		dma_cfg.src_addr = nfc->io_phys_addr;
379 		dma_cfg.src_addr += chip->ecc.strength == FMC2_ECC_HAM ?
380 				    FMC2_HECCR : FMC2_BCHDSR0;
381 		dma_cfg.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
382 
383 		ret = dmaengine_slave_config(nfc->dma_ecc_ch, &dma_cfg);
384 		if (ret) {
385 			dev_err(nfc->dev, "ECC DMA engine slave config failed\n");
386 			return ret;
387 		}
388 
389 		/* Calculate ECC length needed for one sector */
390 		nfc->dma_ecc_len = chip->ecc.strength == FMC2_ECC_HAM ?
391 				   FMC2_HECCR_LEN : FMC2_BCHDSRS_LEN;
392 	}
393 
394 	return 0;
395 }
396 
397 static void stm32_fmc2_nfc_set_buswidth_16(struct stm32_fmc2_nfc *nfc, bool set)
398 {
399 	u32 pcr;
400 
401 	pcr = set ? FIELD_PREP(FMC2_PCR_PWID, FMC2_PCR_PWID_BUSWIDTH_16) :
402 		    FIELD_PREP(FMC2_PCR_PWID, FMC2_PCR_PWID_BUSWIDTH_8);
403 
404 	regmap_update_bits(nfc->regmap, FMC2_PCR, FMC2_PCR_PWID, pcr);
405 }
406 
407 static void stm32_fmc2_nfc_set_ecc(struct stm32_fmc2_nfc *nfc, bool enable)
408 {
409 	regmap_update_bits(nfc->regmap, FMC2_PCR, FMC2_PCR_ECCEN,
410 			   enable ? FMC2_PCR_ECCEN : 0);
411 }
412 
413 static void stm32_fmc2_nfc_enable_seq_irq(struct stm32_fmc2_nfc *nfc)
414 {
415 	nfc->irq_state = FMC2_IRQ_SEQ;
416 
417 	regmap_update_bits(nfc->regmap, FMC2_CSQIER,
418 			   FMC2_CSQIER_TCIE, FMC2_CSQIER_TCIE);
419 }
420 
421 static void stm32_fmc2_nfc_disable_seq_irq(struct stm32_fmc2_nfc *nfc)
422 {
423 	regmap_update_bits(nfc->regmap, FMC2_CSQIER, FMC2_CSQIER_TCIE, 0);
424 
425 	nfc->irq_state = FMC2_IRQ_UNKNOWN;
426 }
427 
428 static void stm32_fmc2_nfc_clear_seq_irq(struct stm32_fmc2_nfc *nfc)
429 {
430 	regmap_write(nfc->regmap, FMC2_CSQICR, FMC2_CSQICR_CLEAR_IRQ);
431 }
432 
433 static void stm32_fmc2_nfc_enable_bch_irq(struct stm32_fmc2_nfc *nfc, int mode)
434 {
435 	nfc->irq_state = FMC2_IRQ_BCH;
436 
437 	if (mode == NAND_ECC_WRITE)
438 		regmap_update_bits(nfc->regmap, FMC2_BCHIER,
439 				   FMC2_BCHIER_EPBRIE, FMC2_BCHIER_EPBRIE);
440 	else
441 		regmap_update_bits(nfc->regmap, FMC2_BCHIER,
442 				   FMC2_BCHIER_DERIE, FMC2_BCHIER_DERIE);
443 }
444 
445 static void stm32_fmc2_nfc_disable_bch_irq(struct stm32_fmc2_nfc *nfc)
446 {
447 	regmap_update_bits(nfc->regmap, FMC2_BCHIER,
448 			   FMC2_BCHIER_DERIE | FMC2_BCHIER_EPBRIE, 0);
449 
450 	nfc->irq_state = FMC2_IRQ_UNKNOWN;
451 }
452 
453 static void stm32_fmc2_nfc_clear_bch_irq(struct stm32_fmc2_nfc *nfc)
454 {
455 	regmap_write(nfc->regmap, FMC2_BCHICR, FMC2_BCHICR_CLEAR_IRQ);
456 }
457 
458 /*
459  * Enable ECC logic and reset syndrome/parity bits previously calculated
460  * Syndrome/parity bits is cleared by setting the ECCEN bit to 0
461  */
462 static void stm32_fmc2_nfc_hwctl(struct nand_chip *chip, int mode)
463 {
464 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
465 
466 	stm32_fmc2_nfc_set_ecc(nfc, false);
467 
468 	if (chip->ecc.strength != FMC2_ECC_HAM) {
469 		regmap_update_bits(nfc->regmap, FMC2_PCR, FMC2_PCR_WEN,
470 				   mode == NAND_ECC_WRITE ? FMC2_PCR_WEN : 0);
471 
472 		reinit_completion(&nfc->complete);
473 		stm32_fmc2_nfc_clear_bch_irq(nfc);
474 		stm32_fmc2_nfc_enable_bch_irq(nfc, mode);
475 	}
476 
477 	stm32_fmc2_nfc_set_ecc(nfc, true);
478 }
479 
480 /*
481  * ECC Hamming calculation
482  * ECC is 3 bytes for 512 bytes of data (supports error correction up to
483  * max of 1-bit)
484  */
485 static void stm32_fmc2_nfc_ham_set_ecc(const u32 ecc_sta, u8 *ecc)
486 {
487 	ecc[0] = ecc_sta;
488 	ecc[1] = ecc_sta >> 8;
489 	ecc[2] = ecc_sta >> 16;
490 }
491 
492 static int stm32_fmc2_nfc_ham_calculate(struct nand_chip *chip, const u8 *data,
493 					u8 *ecc)
494 {
495 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
496 	u32 sr, heccr;
497 	int ret;
498 
499 	ret = regmap_read_poll_timeout(nfc->regmap, FMC2_SR, sr,
500 				       sr & FMC2_SR_NWRF, 1,
501 				       1000 * FMC2_TIMEOUT_MS);
502 	if (ret) {
503 		dev_err(nfc->dev, "ham timeout\n");
504 		return ret;
505 	}
506 
507 	regmap_read(nfc->regmap, FMC2_HECCR, &heccr);
508 	stm32_fmc2_nfc_ham_set_ecc(heccr, ecc);
509 	stm32_fmc2_nfc_set_ecc(nfc, false);
510 
511 	return 0;
512 }
513 
514 static int stm32_fmc2_nfc_ham_correct(struct nand_chip *chip, u8 *dat,
515 				      u8 *read_ecc, u8 *calc_ecc)
516 {
517 	u8 bit_position = 0, b0, b1, b2;
518 	u32 byte_addr = 0, b;
519 	u32 i, shifting = 1;
520 
521 	/* Indicate which bit and byte is faulty (if any) */
522 	b0 = read_ecc[0] ^ calc_ecc[0];
523 	b1 = read_ecc[1] ^ calc_ecc[1];
524 	b2 = read_ecc[2] ^ calc_ecc[2];
525 	b = b0 | (b1 << 8) | (b2 << 16);
526 
527 	/* No errors */
528 	if (likely(!b))
529 		return 0;
530 
531 	/* Calculate bit position */
532 	for (i = 0; i < 3; i++) {
533 		switch (b % 4) {
534 		case 2:
535 			bit_position += shifting;
536 			break;
537 		case 1:
538 			break;
539 		default:
540 			return -EBADMSG;
541 		}
542 		shifting <<= 1;
543 		b >>= 2;
544 	}
545 
546 	/* Calculate byte position */
547 	shifting = 1;
548 	for (i = 0; i < 9; i++) {
549 		switch (b % 4) {
550 		case 2:
551 			byte_addr += shifting;
552 			break;
553 		case 1:
554 			break;
555 		default:
556 			return -EBADMSG;
557 		}
558 		shifting <<= 1;
559 		b >>= 2;
560 	}
561 
562 	/* Flip the bit */
563 	dat[byte_addr] ^= (1 << bit_position);
564 
565 	return 1;
566 }
567 
568 /*
569  * ECC BCH calculation and correction
570  * ECC is 7/13 bytes for 512 bytes of data (supports error correction up to
571  * max of 4-bit/8-bit)
572  */
573 static int stm32_fmc2_nfc_bch_calculate(struct nand_chip *chip, const u8 *data,
574 					u8 *ecc)
575 {
576 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
577 	u32 bchpbr;
578 
579 	/* Wait until the BCH code is ready */
580 	if (!wait_for_completion_timeout(&nfc->complete,
581 					 msecs_to_jiffies(FMC2_TIMEOUT_MS))) {
582 		dev_err(nfc->dev, "bch timeout\n");
583 		stm32_fmc2_nfc_disable_bch_irq(nfc);
584 		return -ETIMEDOUT;
585 	}
586 
587 	/* Read parity bits */
588 	regmap_read(nfc->regmap, FMC2_BCHPBR1, &bchpbr);
589 	ecc[0] = bchpbr;
590 	ecc[1] = bchpbr >> 8;
591 	ecc[2] = bchpbr >> 16;
592 	ecc[3] = bchpbr >> 24;
593 
594 	regmap_read(nfc->regmap, FMC2_BCHPBR2, &bchpbr);
595 	ecc[4] = bchpbr;
596 	ecc[5] = bchpbr >> 8;
597 	ecc[6] = bchpbr >> 16;
598 
599 	if (chip->ecc.strength == FMC2_ECC_BCH8) {
600 		ecc[7] = bchpbr >> 24;
601 
602 		regmap_read(nfc->regmap, FMC2_BCHPBR3, &bchpbr);
603 		ecc[8] = bchpbr;
604 		ecc[9] = bchpbr >> 8;
605 		ecc[10] = bchpbr >> 16;
606 		ecc[11] = bchpbr >> 24;
607 
608 		regmap_read(nfc->regmap, FMC2_BCHPBR4, &bchpbr);
609 		ecc[12] = bchpbr;
610 	}
611 
612 	stm32_fmc2_nfc_set_ecc(nfc, false);
613 
614 	return 0;
615 }
616 
617 static int stm32_fmc2_nfc_bch_decode(int eccsize, u8 *dat, u32 *ecc_sta)
618 {
619 	u32 bchdsr0 = ecc_sta[0];
620 	u32 bchdsr1 = ecc_sta[1];
621 	u32 bchdsr2 = ecc_sta[2];
622 	u32 bchdsr3 = ecc_sta[3];
623 	u32 bchdsr4 = ecc_sta[4];
624 	u16 pos[8];
625 	int i, den;
626 	unsigned int nb_errs = 0;
627 
628 	/* No errors found */
629 	if (likely(!(bchdsr0 & FMC2_BCHDSR0_DEF)))
630 		return 0;
631 
632 	/* Too many errors detected */
633 	if (unlikely(bchdsr0 & FMC2_BCHDSR0_DUE))
634 		return -EBADMSG;
635 
636 	pos[0] = FIELD_GET(FMC2_BCHDSR1_EBP1, bchdsr1);
637 	pos[1] = FIELD_GET(FMC2_BCHDSR1_EBP2, bchdsr1);
638 	pos[2] = FIELD_GET(FMC2_BCHDSR2_EBP3, bchdsr2);
639 	pos[3] = FIELD_GET(FMC2_BCHDSR2_EBP4, bchdsr2);
640 	pos[4] = FIELD_GET(FMC2_BCHDSR3_EBP5, bchdsr3);
641 	pos[5] = FIELD_GET(FMC2_BCHDSR3_EBP6, bchdsr3);
642 	pos[6] = FIELD_GET(FMC2_BCHDSR4_EBP7, bchdsr4);
643 	pos[7] = FIELD_GET(FMC2_BCHDSR4_EBP8, bchdsr4);
644 
645 	den = FIELD_GET(FMC2_BCHDSR0_DEN, bchdsr0);
646 	for (i = 0; i < den; i++) {
647 		if (pos[i] < eccsize * 8) {
648 			change_bit(pos[i], (unsigned long *)dat);
649 			nb_errs++;
650 		}
651 	}
652 
653 	return nb_errs;
654 }
655 
656 static int stm32_fmc2_nfc_bch_correct(struct nand_chip *chip, u8 *dat,
657 				      u8 *read_ecc, u8 *calc_ecc)
658 {
659 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
660 	u32 ecc_sta[5];
661 
662 	/* Wait until the decoding error is ready */
663 	if (!wait_for_completion_timeout(&nfc->complete,
664 					 msecs_to_jiffies(FMC2_TIMEOUT_MS))) {
665 		dev_err(nfc->dev, "bch timeout\n");
666 		stm32_fmc2_nfc_disable_bch_irq(nfc);
667 		return -ETIMEDOUT;
668 	}
669 
670 	regmap_bulk_read(nfc->regmap, FMC2_BCHDSR0, ecc_sta, 5);
671 
672 	stm32_fmc2_nfc_set_ecc(nfc, false);
673 
674 	return stm32_fmc2_nfc_bch_decode(chip->ecc.size, dat, ecc_sta);
675 }
676 
677 static int stm32_fmc2_nfc_read_page(struct nand_chip *chip, u8 *buf,
678 				    int oob_required, int page)
679 {
680 	struct mtd_info *mtd = nand_to_mtd(chip);
681 	int ret, i, s, stat, eccsize = chip->ecc.size;
682 	int eccbytes = chip->ecc.bytes;
683 	int eccsteps = chip->ecc.steps;
684 	int eccstrength = chip->ecc.strength;
685 	u8 *p = buf;
686 	u8 *ecc_calc = chip->ecc.calc_buf;
687 	u8 *ecc_code = chip->ecc.code_buf;
688 	unsigned int max_bitflips = 0;
689 
690 	ret = nand_read_page_op(chip, page, 0, NULL, 0);
691 	if (ret)
692 		return ret;
693 
694 	for (i = mtd->writesize + FMC2_BBM_LEN, s = 0; s < eccsteps;
695 	     s++, i += eccbytes, p += eccsize) {
696 		chip->ecc.hwctl(chip, NAND_ECC_READ);
697 
698 		/* Read the nand page sector (512 bytes) */
699 		ret = nand_change_read_column_op(chip, s * eccsize, p,
700 						 eccsize, false);
701 		if (ret)
702 			return ret;
703 
704 		/* Read the corresponding ECC bytes */
705 		ret = nand_change_read_column_op(chip, i, ecc_code,
706 						 eccbytes, false);
707 		if (ret)
708 			return ret;
709 
710 		/* Correct the data */
711 		stat = chip->ecc.correct(chip, p, ecc_code, ecc_calc);
712 		if (stat == -EBADMSG)
713 			/* Check for empty pages with bitflips */
714 			stat = nand_check_erased_ecc_chunk(p, eccsize,
715 							   ecc_code, eccbytes,
716 							   NULL, 0,
717 							   eccstrength);
718 
719 		if (stat < 0) {
720 			mtd->ecc_stats.failed++;
721 		} else {
722 			mtd->ecc_stats.corrected += stat;
723 			max_bitflips = max_t(unsigned int, max_bitflips, stat);
724 		}
725 	}
726 
727 	/* Read oob */
728 	if (oob_required) {
729 		ret = nand_change_read_column_op(chip, mtd->writesize,
730 						 chip->oob_poi, mtd->oobsize,
731 						 false);
732 		if (ret)
733 			return ret;
734 	}
735 
736 	return max_bitflips;
737 }
738 
739 /* Sequencer read/write configuration */
740 static void stm32_fmc2_nfc_rw_page_init(struct nand_chip *chip, int page,
741 					int raw, bool write_data)
742 {
743 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
744 	struct mtd_info *mtd = nand_to_mtd(chip);
745 	u32 ecc_offset = mtd->writesize + FMC2_BBM_LEN;
746 	/*
747 	 * cfg[0] => csqcfgr1, cfg[1] => csqcfgr2, cfg[2] => csqcfgr3
748 	 * cfg[3] => csqar1, cfg[4] => csqar2
749 	 */
750 	u32 cfg[5];
751 
752 	regmap_update_bits(nfc->regmap, FMC2_PCR, FMC2_PCR_WEN,
753 			   write_data ? FMC2_PCR_WEN : 0);
754 
755 	/*
756 	 * - Set Program Page/Page Read command
757 	 * - Enable DMA request data
758 	 * - Set timings
759 	 */
760 	cfg[0] = FMC2_CSQCFGR1_DMADEN | FMC2_CSQCFGR1_CMD1T;
761 	if (write_data)
762 		cfg[0] |= FIELD_PREP(FMC2_CSQCFGR1_CMD1, NAND_CMD_SEQIN);
763 	else
764 		cfg[0] |= FIELD_PREP(FMC2_CSQCFGR1_CMD1, NAND_CMD_READ0) |
765 			  FMC2_CSQCFGR1_CMD2EN |
766 			  FIELD_PREP(FMC2_CSQCFGR1_CMD2, NAND_CMD_READSTART) |
767 			  FMC2_CSQCFGR1_CMD2T;
768 
769 	/*
770 	 * - Set Random Data Input/Random Data Read command
771 	 * - Enable the sequencer to access the Spare data area
772 	 * - Enable  DMA request status decoding for read
773 	 * - Set timings
774 	 */
775 	if (write_data)
776 		cfg[1] = FIELD_PREP(FMC2_CSQCFGR2_RCMD1, NAND_CMD_RNDIN);
777 	else
778 		cfg[1] = FIELD_PREP(FMC2_CSQCFGR2_RCMD1, NAND_CMD_RNDOUT) |
779 			 FMC2_CSQCFGR2_RCMD2EN |
780 			 FIELD_PREP(FMC2_CSQCFGR2_RCMD2, NAND_CMD_RNDOUTSTART) |
781 			 FMC2_CSQCFGR2_RCMD1T |
782 			 FMC2_CSQCFGR2_RCMD2T;
783 	if (!raw) {
784 		cfg[1] |= write_data ? 0 : FMC2_CSQCFGR2_DMASEN;
785 		cfg[1] |= FMC2_CSQCFGR2_SQSDTEN;
786 	}
787 
788 	/*
789 	 * - Set the number of sectors to be written
790 	 * - Set timings
791 	 */
792 	cfg[2] = FIELD_PREP(FMC2_CSQCFGR3_SNBR, chip->ecc.steps - 1);
793 	if (write_data) {
794 		cfg[2] |= FMC2_CSQCFGR3_RAC2T;
795 		if (chip->options & NAND_ROW_ADDR_3)
796 			cfg[2] |= FMC2_CSQCFGR3_AC5T;
797 		else
798 			cfg[2] |= FMC2_CSQCFGR3_AC4T;
799 	}
800 
801 	/*
802 	 * Set the fourth first address cycles
803 	 * Byte 1 and byte 2 => column, we start at 0x0
804 	 * Byte 3 and byte 4 => page
805 	 */
806 	cfg[3] = FIELD_PREP(FMC2_CSQCAR1_ADDC3, page);
807 	cfg[3] |= FIELD_PREP(FMC2_CSQCAR1_ADDC4, page >> 8);
808 
809 	/*
810 	 * - Set chip enable number
811 	 * - Set ECC byte offset in the spare area
812 	 * - Calculate the number of address cycles to be issued
813 	 * - Set byte 5 of address cycle if needed
814 	 */
815 	cfg[4] = FIELD_PREP(FMC2_CSQCAR2_NANDCEN, nfc->cs_sel);
816 	if (chip->options & NAND_BUSWIDTH_16)
817 		cfg[4] |= FIELD_PREP(FMC2_CSQCAR2_SAO, ecc_offset >> 1);
818 	else
819 		cfg[4] |= FIELD_PREP(FMC2_CSQCAR2_SAO, ecc_offset);
820 	if (chip->options & NAND_ROW_ADDR_3) {
821 		cfg[0] |= FIELD_PREP(FMC2_CSQCFGR1_ACYNBR, 5);
822 		cfg[4] |= FIELD_PREP(FMC2_CSQCAR2_ADDC5, page >> 16);
823 	} else {
824 		cfg[0] |= FIELD_PREP(FMC2_CSQCFGR1_ACYNBR, 4);
825 	}
826 
827 	regmap_bulk_write(nfc->regmap, FMC2_CSQCFGR1, cfg, 5);
828 }
829 
830 static void stm32_fmc2_nfc_dma_callback(void *arg)
831 {
832 	complete((struct completion *)arg);
833 }
834 
835 /* Read/write data from/to a page */
836 static int stm32_fmc2_nfc_xfer(struct nand_chip *chip, const u8 *buf,
837 			       int raw, bool write_data)
838 {
839 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
840 	struct dma_async_tx_descriptor *desc_data, *desc_ecc;
841 	struct scatterlist *sg;
842 	struct dma_chan *dma_ch = nfc->dma_rx_ch;
843 	enum dma_data_direction dma_data_dir = DMA_FROM_DEVICE;
844 	enum dma_transfer_direction dma_transfer_dir = DMA_DEV_TO_MEM;
845 	int eccsteps = chip->ecc.steps;
846 	int eccsize = chip->ecc.size;
847 	unsigned long timeout = msecs_to_jiffies(FMC2_TIMEOUT_MS);
848 	const u8 *p = buf;
849 	int s, ret;
850 
851 	/* Configure DMA data */
852 	if (write_data) {
853 		dma_data_dir = DMA_TO_DEVICE;
854 		dma_transfer_dir = DMA_MEM_TO_DEV;
855 		dma_ch = nfc->dma_tx_ch;
856 	}
857 
858 	for_each_sg(nfc->dma_data_sg.sgl, sg, eccsteps, s) {
859 		sg_set_buf(sg, p, eccsize);
860 		p += eccsize;
861 	}
862 
863 	ret = dma_map_sg(nfc->dev, nfc->dma_data_sg.sgl,
864 			 eccsteps, dma_data_dir);
865 	if (!ret)
866 		return -EIO;
867 
868 	desc_data = dmaengine_prep_slave_sg(dma_ch, nfc->dma_data_sg.sgl,
869 					    eccsteps, dma_transfer_dir,
870 					    DMA_PREP_INTERRUPT);
871 	if (!desc_data) {
872 		ret = -ENOMEM;
873 		goto err_unmap_data;
874 	}
875 
876 	reinit_completion(&nfc->dma_data_complete);
877 	reinit_completion(&nfc->complete);
878 	desc_data->callback = stm32_fmc2_nfc_dma_callback;
879 	desc_data->callback_param = &nfc->dma_data_complete;
880 	ret = dma_submit_error(dmaengine_submit(desc_data));
881 	if (ret)
882 		goto err_unmap_data;
883 
884 	dma_async_issue_pending(dma_ch);
885 
886 	if (!write_data && !raw) {
887 		/* Configure DMA ECC status */
888 		p = nfc->ecc_buf;
889 		for_each_sg(nfc->dma_ecc_sg.sgl, sg, eccsteps, s) {
890 			sg_set_buf(sg, p, nfc->dma_ecc_len);
891 			p += nfc->dma_ecc_len;
892 		}
893 
894 		ret = dma_map_sg(nfc->dev, nfc->dma_ecc_sg.sgl,
895 				 eccsteps, dma_data_dir);
896 		if (!ret) {
897 			ret = -EIO;
898 			goto err_unmap_data;
899 		}
900 
901 		desc_ecc = dmaengine_prep_slave_sg(nfc->dma_ecc_ch,
902 						   nfc->dma_ecc_sg.sgl,
903 						   eccsteps, dma_transfer_dir,
904 						   DMA_PREP_INTERRUPT);
905 		if (!desc_ecc) {
906 			ret = -ENOMEM;
907 			goto err_unmap_ecc;
908 		}
909 
910 		reinit_completion(&nfc->dma_ecc_complete);
911 		desc_ecc->callback = stm32_fmc2_nfc_dma_callback;
912 		desc_ecc->callback_param = &nfc->dma_ecc_complete;
913 		ret = dma_submit_error(dmaengine_submit(desc_ecc));
914 		if (ret)
915 			goto err_unmap_ecc;
916 
917 		dma_async_issue_pending(nfc->dma_ecc_ch);
918 	}
919 
920 	stm32_fmc2_nfc_clear_seq_irq(nfc);
921 	stm32_fmc2_nfc_enable_seq_irq(nfc);
922 
923 	/* Start the transfer */
924 	regmap_update_bits(nfc->regmap, FMC2_CSQCR,
925 			   FMC2_CSQCR_CSQSTART, FMC2_CSQCR_CSQSTART);
926 
927 	/* Wait end of sequencer transfer */
928 	if (!wait_for_completion_timeout(&nfc->complete, timeout)) {
929 		dev_err(nfc->dev, "seq timeout\n");
930 		stm32_fmc2_nfc_disable_seq_irq(nfc);
931 		dmaengine_terminate_all(dma_ch);
932 		if (!write_data && !raw)
933 			dmaengine_terminate_all(nfc->dma_ecc_ch);
934 		ret = -ETIMEDOUT;
935 		goto err_unmap_ecc;
936 	}
937 
938 	/* Wait DMA data transfer completion */
939 	if (!wait_for_completion_timeout(&nfc->dma_data_complete, timeout)) {
940 		dev_err(nfc->dev, "data DMA timeout\n");
941 		dmaengine_terminate_all(dma_ch);
942 		ret = -ETIMEDOUT;
943 	}
944 
945 	/* Wait DMA ECC transfer completion */
946 	if (!write_data && !raw) {
947 		if (!wait_for_completion_timeout(&nfc->dma_ecc_complete,
948 						 timeout)) {
949 			dev_err(nfc->dev, "ECC DMA timeout\n");
950 			dmaengine_terminate_all(nfc->dma_ecc_ch);
951 			ret = -ETIMEDOUT;
952 		}
953 	}
954 
955 err_unmap_ecc:
956 	if (!write_data && !raw)
957 		dma_unmap_sg(nfc->dev, nfc->dma_ecc_sg.sgl,
958 			     eccsteps, dma_data_dir);
959 
960 err_unmap_data:
961 	dma_unmap_sg(nfc->dev, nfc->dma_data_sg.sgl, eccsteps, dma_data_dir);
962 
963 	return ret;
964 }
965 
966 static int stm32_fmc2_nfc_seq_write(struct nand_chip *chip, const u8 *buf,
967 				    int oob_required, int page, int raw)
968 {
969 	struct mtd_info *mtd = nand_to_mtd(chip);
970 	int ret;
971 
972 	/* Configure the sequencer */
973 	stm32_fmc2_nfc_rw_page_init(chip, page, raw, true);
974 
975 	/* Write the page */
976 	ret = stm32_fmc2_nfc_xfer(chip, buf, raw, true);
977 	if (ret)
978 		return ret;
979 
980 	/* Write oob */
981 	if (oob_required) {
982 		ret = nand_change_write_column_op(chip, mtd->writesize,
983 						  chip->oob_poi, mtd->oobsize,
984 						  false);
985 		if (ret)
986 			return ret;
987 	}
988 
989 	return nand_prog_page_end_op(chip);
990 }
991 
992 static int stm32_fmc2_nfc_seq_write_page(struct nand_chip *chip, const u8 *buf,
993 					 int oob_required, int page)
994 {
995 	int ret;
996 
997 	ret = stm32_fmc2_nfc_select_chip(chip, chip->cur_cs);
998 	if (ret)
999 		return ret;
1000 
1001 	return stm32_fmc2_nfc_seq_write(chip, buf, oob_required, page, false);
1002 }
1003 
1004 static int stm32_fmc2_nfc_seq_write_page_raw(struct nand_chip *chip,
1005 					     const u8 *buf, int oob_required,
1006 					     int page)
1007 {
1008 	int ret;
1009 
1010 	ret = stm32_fmc2_nfc_select_chip(chip, chip->cur_cs);
1011 	if (ret)
1012 		return ret;
1013 
1014 	return stm32_fmc2_nfc_seq_write(chip, buf, oob_required, page, true);
1015 }
1016 
1017 /* Get a status indicating which sectors have errors */
1018 static u16 stm32_fmc2_nfc_get_mapping_status(struct stm32_fmc2_nfc *nfc)
1019 {
1020 	u32 csqemsr;
1021 
1022 	regmap_read(nfc->regmap, FMC2_CSQEMSR, &csqemsr);
1023 
1024 	return FIELD_GET(FMC2_CSQEMSR_SEM, csqemsr);
1025 }
1026 
1027 static int stm32_fmc2_nfc_seq_correct(struct nand_chip *chip, u8 *dat,
1028 				      u8 *read_ecc, u8 *calc_ecc)
1029 {
1030 	struct mtd_info *mtd = nand_to_mtd(chip);
1031 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1032 	int eccbytes = chip->ecc.bytes;
1033 	int eccsteps = chip->ecc.steps;
1034 	int eccstrength = chip->ecc.strength;
1035 	int i, s, eccsize = chip->ecc.size;
1036 	u32 *ecc_sta = (u32 *)nfc->ecc_buf;
1037 	u16 sta_map = stm32_fmc2_nfc_get_mapping_status(nfc);
1038 	unsigned int max_bitflips = 0;
1039 
1040 	for (i = 0, s = 0; s < eccsteps; s++, i += eccbytes, dat += eccsize) {
1041 		int stat = 0;
1042 
1043 		if (eccstrength == FMC2_ECC_HAM) {
1044 			/* Ecc_sta = FMC2_HECCR */
1045 			if (sta_map & BIT(s)) {
1046 				stm32_fmc2_nfc_ham_set_ecc(*ecc_sta,
1047 							   &calc_ecc[i]);
1048 				stat = stm32_fmc2_nfc_ham_correct(chip, dat,
1049 								  &read_ecc[i],
1050 								  &calc_ecc[i]);
1051 			}
1052 			ecc_sta++;
1053 		} else {
1054 			/*
1055 			 * Ecc_sta[0] = FMC2_BCHDSR0
1056 			 * Ecc_sta[1] = FMC2_BCHDSR1
1057 			 * Ecc_sta[2] = FMC2_BCHDSR2
1058 			 * Ecc_sta[3] = FMC2_BCHDSR3
1059 			 * Ecc_sta[4] = FMC2_BCHDSR4
1060 			 */
1061 			if (sta_map & BIT(s))
1062 				stat = stm32_fmc2_nfc_bch_decode(eccsize, dat,
1063 								 ecc_sta);
1064 			ecc_sta += 5;
1065 		}
1066 
1067 		if (stat == -EBADMSG)
1068 			/* Check for empty pages with bitflips */
1069 			stat = nand_check_erased_ecc_chunk(dat, eccsize,
1070 							   &read_ecc[i],
1071 							   eccbytes,
1072 							   NULL, 0,
1073 							   eccstrength);
1074 
1075 		if (stat < 0) {
1076 			mtd->ecc_stats.failed++;
1077 		} else {
1078 			mtd->ecc_stats.corrected += stat;
1079 			max_bitflips = max_t(unsigned int, max_bitflips, stat);
1080 		}
1081 	}
1082 
1083 	return max_bitflips;
1084 }
1085 
1086 static int stm32_fmc2_nfc_seq_read_page(struct nand_chip *chip, u8 *buf,
1087 					int oob_required, int page)
1088 {
1089 	struct mtd_info *mtd = nand_to_mtd(chip);
1090 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1091 	u8 *ecc_calc = chip->ecc.calc_buf;
1092 	u8 *ecc_code = chip->ecc.code_buf;
1093 	u16 sta_map;
1094 	int ret;
1095 
1096 	ret = stm32_fmc2_nfc_select_chip(chip, chip->cur_cs);
1097 	if (ret)
1098 		return ret;
1099 
1100 	/* Configure the sequencer */
1101 	stm32_fmc2_nfc_rw_page_init(chip, page, 0, false);
1102 
1103 	/* Read the page */
1104 	ret = stm32_fmc2_nfc_xfer(chip, buf, 0, false);
1105 	if (ret)
1106 		return ret;
1107 
1108 	sta_map = stm32_fmc2_nfc_get_mapping_status(nfc);
1109 
1110 	/* Check if errors happen */
1111 	if (likely(!sta_map)) {
1112 		if (oob_required)
1113 			return nand_change_read_column_op(chip, mtd->writesize,
1114 							  chip->oob_poi,
1115 							  mtd->oobsize, false);
1116 
1117 		return 0;
1118 	}
1119 
1120 	/* Read oob */
1121 	ret = nand_change_read_column_op(chip, mtd->writesize,
1122 					 chip->oob_poi, mtd->oobsize, false);
1123 	if (ret)
1124 		return ret;
1125 
1126 	ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1127 					 chip->ecc.total);
1128 	if (ret)
1129 		return ret;
1130 
1131 	/* Correct data */
1132 	return chip->ecc.correct(chip, buf, ecc_code, ecc_calc);
1133 }
1134 
1135 static int stm32_fmc2_nfc_seq_read_page_raw(struct nand_chip *chip, u8 *buf,
1136 					    int oob_required, int page)
1137 {
1138 	struct mtd_info *mtd = nand_to_mtd(chip);
1139 	int ret;
1140 
1141 	ret = stm32_fmc2_nfc_select_chip(chip, chip->cur_cs);
1142 	if (ret)
1143 		return ret;
1144 
1145 	/* Configure the sequencer */
1146 	stm32_fmc2_nfc_rw_page_init(chip, page, 1, false);
1147 
1148 	/* Read the page */
1149 	ret = stm32_fmc2_nfc_xfer(chip, buf, 1, false);
1150 	if (ret)
1151 		return ret;
1152 
1153 	/* Read oob */
1154 	if (oob_required)
1155 		return nand_change_read_column_op(chip, mtd->writesize,
1156 						  chip->oob_poi, mtd->oobsize,
1157 						  false);
1158 
1159 	return 0;
1160 }
1161 
1162 static irqreturn_t stm32_fmc2_nfc_irq(int irq, void *dev_id)
1163 {
1164 	struct stm32_fmc2_nfc *nfc = (struct stm32_fmc2_nfc *)dev_id;
1165 
1166 	if (nfc->irq_state == FMC2_IRQ_SEQ)
1167 		/* Sequencer is used */
1168 		stm32_fmc2_nfc_disable_seq_irq(nfc);
1169 	else if (nfc->irq_state == FMC2_IRQ_BCH)
1170 		/* BCH is used */
1171 		stm32_fmc2_nfc_disable_bch_irq(nfc);
1172 
1173 	complete(&nfc->complete);
1174 
1175 	return IRQ_HANDLED;
1176 }
1177 
1178 static void stm32_fmc2_nfc_read_data(struct nand_chip *chip, void *buf,
1179 				     unsigned int len, bool force_8bit)
1180 {
1181 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1182 	void __iomem *io_addr_r = nfc->data_base[nfc->cs_sel];
1183 
1184 	if (force_8bit && chip->options & NAND_BUSWIDTH_16)
1185 		/* Reconfigure bus width to 8-bit */
1186 		stm32_fmc2_nfc_set_buswidth_16(nfc, false);
1187 
1188 	if (!IS_ALIGNED((uintptr_t)buf, sizeof(u32))) {
1189 		if (!IS_ALIGNED((uintptr_t)buf, sizeof(u16)) && len) {
1190 			*(u8 *)buf = readb_relaxed(io_addr_r);
1191 			buf += sizeof(u8);
1192 			len -= sizeof(u8);
1193 		}
1194 
1195 		if (!IS_ALIGNED((uintptr_t)buf, sizeof(u32)) &&
1196 		    len >= sizeof(u16)) {
1197 			*(u16 *)buf = readw_relaxed(io_addr_r);
1198 			buf += sizeof(u16);
1199 			len -= sizeof(u16);
1200 		}
1201 	}
1202 
1203 	/* Buf is aligned */
1204 	while (len >= sizeof(u32)) {
1205 		*(u32 *)buf = readl_relaxed(io_addr_r);
1206 		buf += sizeof(u32);
1207 		len -= sizeof(u32);
1208 	}
1209 
1210 	/* Read remaining bytes */
1211 	if (len >= sizeof(u16)) {
1212 		*(u16 *)buf = readw_relaxed(io_addr_r);
1213 		buf += sizeof(u16);
1214 		len -= sizeof(u16);
1215 	}
1216 
1217 	if (len)
1218 		*(u8 *)buf = readb_relaxed(io_addr_r);
1219 
1220 	if (force_8bit && chip->options & NAND_BUSWIDTH_16)
1221 		/* Reconfigure bus width to 16-bit */
1222 		stm32_fmc2_nfc_set_buswidth_16(nfc, true);
1223 }
1224 
1225 static void stm32_fmc2_nfc_write_data(struct nand_chip *chip, const void *buf,
1226 				      unsigned int len, bool force_8bit)
1227 {
1228 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1229 	void __iomem *io_addr_w = nfc->data_base[nfc->cs_sel];
1230 
1231 	if (force_8bit && chip->options & NAND_BUSWIDTH_16)
1232 		/* Reconfigure bus width to 8-bit */
1233 		stm32_fmc2_nfc_set_buswidth_16(nfc, false);
1234 
1235 	if (!IS_ALIGNED((uintptr_t)buf, sizeof(u32))) {
1236 		if (!IS_ALIGNED((uintptr_t)buf, sizeof(u16)) && len) {
1237 			writeb_relaxed(*(u8 *)buf, io_addr_w);
1238 			buf += sizeof(u8);
1239 			len -= sizeof(u8);
1240 		}
1241 
1242 		if (!IS_ALIGNED((uintptr_t)buf, sizeof(u32)) &&
1243 		    len >= sizeof(u16)) {
1244 			writew_relaxed(*(u16 *)buf, io_addr_w);
1245 			buf += sizeof(u16);
1246 			len -= sizeof(u16);
1247 		}
1248 	}
1249 
1250 	/* Buf is aligned */
1251 	while (len >= sizeof(u32)) {
1252 		writel_relaxed(*(u32 *)buf, io_addr_w);
1253 		buf += sizeof(u32);
1254 		len -= sizeof(u32);
1255 	}
1256 
1257 	/* Write remaining bytes */
1258 	if (len >= sizeof(u16)) {
1259 		writew_relaxed(*(u16 *)buf, io_addr_w);
1260 		buf += sizeof(u16);
1261 		len -= sizeof(u16);
1262 	}
1263 
1264 	if (len)
1265 		writeb_relaxed(*(u8 *)buf, io_addr_w);
1266 
1267 	if (force_8bit && chip->options & NAND_BUSWIDTH_16)
1268 		/* Reconfigure bus width to 16-bit */
1269 		stm32_fmc2_nfc_set_buswidth_16(nfc, true);
1270 }
1271 
1272 static int stm32_fmc2_nfc_waitrdy(struct nand_chip *chip,
1273 				  unsigned long timeout_ms)
1274 {
1275 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1276 	const struct nand_sdr_timings *timings;
1277 	u32 isr, sr;
1278 
1279 	/* Check if there is no pending requests to the NAND flash */
1280 	if (regmap_read_poll_timeout(nfc->regmap, FMC2_SR, sr,
1281 				     sr & FMC2_SR_NWRF, 1,
1282 				     1000 * FMC2_TIMEOUT_MS))
1283 		dev_warn(nfc->dev, "Waitrdy timeout\n");
1284 
1285 	/* Wait tWB before R/B# signal is low */
1286 	timings = nand_get_sdr_timings(nand_get_interface_config(chip));
1287 	ndelay(PSEC_TO_NSEC(timings->tWB_max));
1288 
1289 	/* R/B# signal is low, clear high level flag */
1290 	regmap_write(nfc->regmap, FMC2_ICR, FMC2_ICR_CIHLF);
1291 
1292 	/* Wait R/B# signal is high */
1293 	return regmap_read_poll_timeout(nfc->regmap, FMC2_ISR, isr,
1294 					isr & FMC2_ISR_IHLF, 5,
1295 					1000 * FMC2_TIMEOUT_MS);
1296 }
1297 
1298 static int stm32_fmc2_nfc_exec_op(struct nand_chip *chip,
1299 				  const struct nand_operation *op,
1300 				  bool check_only)
1301 {
1302 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1303 	const struct nand_op_instr *instr = NULL;
1304 	unsigned int op_id, i, timeout;
1305 	int ret;
1306 
1307 	if (check_only)
1308 		return 0;
1309 
1310 	ret = stm32_fmc2_nfc_select_chip(chip, op->cs);
1311 	if (ret)
1312 		return ret;
1313 
1314 	for (op_id = 0; op_id < op->ninstrs; op_id++) {
1315 		instr = &op->instrs[op_id];
1316 
1317 		switch (instr->type) {
1318 		case NAND_OP_CMD_INSTR:
1319 			writeb_relaxed(instr->ctx.cmd.opcode,
1320 				       nfc->cmd_base[nfc->cs_sel]);
1321 			break;
1322 
1323 		case NAND_OP_ADDR_INSTR:
1324 			for (i = 0; i < instr->ctx.addr.naddrs; i++)
1325 				writeb_relaxed(instr->ctx.addr.addrs[i],
1326 					       nfc->addr_base[nfc->cs_sel]);
1327 			break;
1328 
1329 		case NAND_OP_DATA_IN_INSTR:
1330 			stm32_fmc2_nfc_read_data(chip, instr->ctx.data.buf.in,
1331 						 instr->ctx.data.len,
1332 						 instr->ctx.data.force_8bit);
1333 			break;
1334 
1335 		case NAND_OP_DATA_OUT_INSTR:
1336 			stm32_fmc2_nfc_write_data(chip, instr->ctx.data.buf.out,
1337 						  instr->ctx.data.len,
1338 						  instr->ctx.data.force_8bit);
1339 			break;
1340 
1341 		case NAND_OP_WAITRDY_INSTR:
1342 			timeout = instr->ctx.waitrdy.timeout_ms;
1343 			ret = stm32_fmc2_nfc_waitrdy(chip, timeout);
1344 			break;
1345 		}
1346 	}
1347 
1348 	return ret;
1349 }
1350 
1351 static void stm32_fmc2_nfc_init(struct stm32_fmc2_nfc *nfc)
1352 {
1353 	u32 pcr;
1354 
1355 	regmap_read(nfc->regmap, FMC2_PCR, &pcr);
1356 
1357 	/* Set CS used to undefined */
1358 	nfc->cs_sel = -1;
1359 
1360 	/* Enable wait feature and nand flash memory bank */
1361 	pcr |= FMC2_PCR_PWAITEN;
1362 	pcr |= FMC2_PCR_PBKEN;
1363 
1364 	/* Set buswidth to 8 bits mode for identification */
1365 	pcr &= ~FMC2_PCR_PWID;
1366 
1367 	/* ECC logic is disabled */
1368 	pcr &= ~FMC2_PCR_ECCEN;
1369 
1370 	/* Default mode */
1371 	pcr &= ~FMC2_PCR_ECCALG;
1372 	pcr &= ~FMC2_PCR_BCHECC;
1373 	pcr &= ~FMC2_PCR_WEN;
1374 
1375 	/* Set default ECC sector size */
1376 	pcr &= ~FMC2_PCR_ECCSS;
1377 	pcr |= FIELD_PREP(FMC2_PCR_ECCSS, FMC2_PCR_ECCSS_2048);
1378 
1379 	/* Set default tclr/tar timings */
1380 	pcr &= ~FMC2_PCR_TCLR;
1381 	pcr |= FIELD_PREP(FMC2_PCR_TCLR, FMC2_PCR_TCLR_DEFAULT);
1382 	pcr &= ~FMC2_PCR_TAR;
1383 	pcr |= FIELD_PREP(FMC2_PCR_TAR, FMC2_PCR_TAR_DEFAULT);
1384 
1385 	/* Enable FMC2 controller */
1386 	if (nfc->dev == nfc->cdev)
1387 		regmap_update_bits(nfc->regmap, FMC2_BCR1,
1388 				   FMC2_BCR1_FMC2EN, FMC2_BCR1_FMC2EN);
1389 
1390 	regmap_write(nfc->regmap, FMC2_PCR, pcr);
1391 	regmap_write(nfc->regmap, FMC2_PMEM, FMC2_PMEM_DEFAULT);
1392 	regmap_write(nfc->regmap, FMC2_PATT, FMC2_PATT_DEFAULT);
1393 }
1394 
1395 static void stm32_fmc2_nfc_calc_timings(struct nand_chip *chip,
1396 					const struct nand_sdr_timings *sdrt)
1397 {
1398 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1399 	struct stm32_fmc2_nand *nand = to_fmc2_nand(chip);
1400 	struct stm32_fmc2_timings *tims = &nand->timings;
1401 	unsigned long hclk = clk_get_rate(nfc->clk);
1402 	unsigned long hclkp = NSEC_PER_SEC / (hclk / 1000);
1403 	unsigned long timing, tar, tclr, thiz, twait;
1404 	unsigned long tset_mem, tset_att, thold_mem, thold_att;
1405 
1406 	tar = max_t(unsigned long, hclkp, sdrt->tAR_min);
1407 	timing = DIV_ROUND_UP(tar, hclkp) - 1;
1408 	tims->tar = min_t(unsigned long, timing, FMC2_PCR_TIMING_MASK);
1409 
1410 	tclr = max_t(unsigned long, hclkp, sdrt->tCLR_min);
1411 	timing = DIV_ROUND_UP(tclr, hclkp) - 1;
1412 	tims->tclr = min_t(unsigned long, timing, FMC2_PCR_TIMING_MASK);
1413 
1414 	tims->thiz = FMC2_THIZ;
1415 	thiz = (tims->thiz + 1) * hclkp;
1416 
1417 	/*
1418 	 * tWAIT > tRP
1419 	 * tWAIT > tWP
1420 	 * tWAIT > tREA + tIO
1421 	 */
1422 	twait = max_t(unsigned long, hclkp, sdrt->tRP_min);
1423 	twait = max_t(unsigned long, twait, sdrt->tWP_min);
1424 	twait = max_t(unsigned long, twait, sdrt->tREA_max + FMC2_TIO);
1425 	timing = DIV_ROUND_UP(twait, hclkp);
1426 	tims->twait = clamp_val(timing, 1, FMC2_PMEM_PATT_TIMING_MASK);
1427 
1428 	/*
1429 	 * tSETUP_MEM > tCS - tWAIT
1430 	 * tSETUP_MEM > tALS - tWAIT
1431 	 * tSETUP_MEM > tDS - (tWAIT - tHIZ)
1432 	 */
1433 	tset_mem = hclkp;
1434 	if (sdrt->tCS_min > twait && (tset_mem < sdrt->tCS_min - twait))
1435 		tset_mem = sdrt->tCS_min - twait;
1436 	if (sdrt->tALS_min > twait && (tset_mem < sdrt->tALS_min - twait))
1437 		tset_mem = sdrt->tALS_min - twait;
1438 	if (twait > thiz && (sdrt->tDS_min > twait - thiz) &&
1439 	    (tset_mem < sdrt->tDS_min - (twait - thiz)))
1440 		tset_mem = sdrt->tDS_min - (twait - thiz);
1441 	timing = DIV_ROUND_UP(tset_mem, hclkp);
1442 	tims->tset_mem = clamp_val(timing, 1, FMC2_PMEM_PATT_TIMING_MASK);
1443 
1444 	/*
1445 	 * tHOLD_MEM > tCH
1446 	 * tHOLD_MEM > tREH - tSETUP_MEM
1447 	 * tHOLD_MEM > max(tRC, tWC) - (tSETUP_MEM + tWAIT)
1448 	 */
1449 	thold_mem = max_t(unsigned long, hclkp, sdrt->tCH_min);
1450 	if (sdrt->tREH_min > tset_mem &&
1451 	    (thold_mem < sdrt->tREH_min - tset_mem))
1452 		thold_mem = sdrt->tREH_min - tset_mem;
1453 	if ((sdrt->tRC_min > tset_mem + twait) &&
1454 	    (thold_mem < sdrt->tRC_min - (tset_mem + twait)))
1455 		thold_mem = sdrt->tRC_min - (tset_mem + twait);
1456 	if ((sdrt->tWC_min > tset_mem + twait) &&
1457 	    (thold_mem < sdrt->tWC_min - (tset_mem + twait)))
1458 		thold_mem = sdrt->tWC_min - (tset_mem + twait);
1459 	timing = DIV_ROUND_UP(thold_mem, hclkp);
1460 	tims->thold_mem = clamp_val(timing, 1, FMC2_PMEM_PATT_TIMING_MASK);
1461 
1462 	/*
1463 	 * tSETUP_ATT > tCS - tWAIT
1464 	 * tSETUP_ATT > tCLS - tWAIT
1465 	 * tSETUP_ATT > tALS - tWAIT
1466 	 * tSETUP_ATT > tRHW - tHOLD_MEM
1467 	 * tSETUP_ATT > tDS - (tWAIT - tHIZ)
1468 	 */
1469 	tset_att = hclkp;
1470 	if (sdrt->tCS_min > twait && (tset_att < sdrt->tCS_min - twait))
1471 		tset_att = sdrt->tCS_min - twait;
1472 	if (sdrt->tCLS_min > twait && (tset_att < sdrt->tCLS_min - twait))
1473 		tset_att = sdrt->tCLS_min - twait;
1474 	if (sdrt->tALS_min > twait && (tset_att < sdrt->tALS_min - twait))
1475 		tset_att = sdrt->tALS_min - twait;
1476 	if (sdrt->tRHW_min > thold_mem &&
1477 	    (tset_att < sdrt->tRHW_min - thold_mem))
1478 		tset_att = sdrt->tRHW_min - thold_mem;
1479 	if (twait > thiz && (sdrt->tDS_min > twait - thiz) &&
1480 	    (tset_att < sdrt->tDS_min - (twait - thiz)))
1481 		tset_att = sdrt->tDS_min - (twait - thiz);
1482 	timing = DIV_ROUND_UP(tset_att, hclkp);
1483 	tims->tset_att = clamp_val(timing, 1, FMC2_PMEM_PATT_TIMING_MASK);
1484 
1485 	/*
1486 	 * tHOLD_ATT > tALH
1487 	 * tHOLD_ATT > tCH
1488 	 * tHOLD_ATT > tCLH
1489 	 * tHOLD_ATT > tCOH
1490 	 * tHOLD_ATT > tDH
1491 	 * tHOLD_ATT > tWB + tIO + tSYNC - tSETUP_MEM
1492 	 * tHOLD_ATT > tADL - tSETUP_MEM
1493 	 * tHOLD_ATT > tWH - tSETUP_MEM
1494 	 * tHOLD_ATT > tWHR - tSETUP_MEM
1495 	 * tHOLD_ATT > tRC - (tSETUP_ATT + tWAIT)
1496 	 * tHOLD_ATT > tWC - (tSETUP_ATT + tWAIT)
1497 	 */
1498 	thold_att = max_t(unsigned long, hclkp, sdrt->tALH_min);
1499 	thold_att = max_t(unsigned long, thold_att, sdrt->tCH_min);
1500 	thold_att = max_t(unsigned long, thold_att, sdrt->tCLH_min);
1501 	thold_att = max_t(unsigned long, thold_att, sdrt->tCOH_min);
1502 	thold_att = max_t(unsigned long, thold_att, sdrt->tDH_min);
1503 	if ((sdrt->tWB_max + FMC2_TIO + FMC2_TSYNC > tset_mem) &&
1504 	    (thold_att < sdrt->tWB_max + FMC2_TIO + FMC2_TSYNC - tset_mem))
1505 		thold_att = sdrt->tWB_max + FMC2_TIO + FMC2_TSYNC - tset_mem;
1506 	if (sdrt->tADL_min > tset_mem &&
1507 	    (thold_att < sdrt->tADL_min - tset_mem))
1508 		thold_att = sdrt->tADL_min - tset_mem;
1509 	if (sdrt->tWH_min > tset_mem &&
1510 	    (thold_att < sdrt->tWH_min - tset_mem))
1511 		thold_att = sdrt->tWH_min - tset_mem;
1512 	if (sdrt->tWHR_min > tset_mem &&
1513 	    (thold_att < sdrt->tWHR_min - tset_mem))
1514 		thold_att = sdrt->tWHR_min - tset_mem;
1515 	if ((sdrt->tRC_min > tset_att + twait) &&
1516 	    (thold_att < sdrt->tRC_min - (tset_att + twait)))
1517 		thold_att = sdrt->tRC_min - (tset_att + twait);
1518 	if ((sdrt->tWC_min > tset_att + twait) &&
1519 	    (thold_att < sdrt->tWC_min - (tset_att + twait)))
1520 		thold_att = sdrt->tWC_min - (tset_att + twait);
1521 	timing = DIV_ROUND_UP(thold_att, hclkp);
1522 	tims->thold_att = clamp_val(timing, 1, FMC2_PMEM_PATT_TIMING_MASK);
1523 }
1524 
1525 static int stm32_fmc2_nfc_setup_interface(struct nand_chip *chip, int chipnr,
1526 					  const struct nand_interface_config *conf)
1527 {
1528 	const struct nand_sdr_timings *sdrt;
1529 
1530 	sdrt = nand_get_sdr_timings(conf);
1531 	if (IS_ERR(sdrt))
1532 		return PTR_ERR(sdrt);
1533 
1534 	if (chipnr == NAND_DATA_IFACE_CHECK_ONLY)
1535 		return 0;
1536 
1537 	stm32_fmc2_nfc_calc_timings(chip, sdrt);
1538 	stm32_fmc2_nfc_timings_init(chip);
1539 
1540 	return 0;
1541 }
1542 
1543 static int stm32_fmc2_nfc_dma_setup(struct stm32_fmc2_nfc *nfc)
1544 {
1545 	int ret = 0;
1546 
1547 	nfc->dma_tx_ch = dma_request_chan(nfc->dev, "tx");
1548 	if (IS_ERR(nfc->dma_tx_ch)) {
1549 		ret = PTR_ERR(nfc->dma_tx_ch);
1550 		if (ret != -ENODEV && ret != -EPROBE_DEFER)
1551 			dev_err(nfc->dev,
1552 				"failed to request tx DMA channel: %d\n", ret);
1553 		nfc->dma_tx_ch = NULL;
1554 		goto err_dma;
1555 	}
1556 
1557 	nfc->dma_rx_ch = dma_request_chan(nfc->dev, "rx");
1558 	if (IS_ERR(nfc->dma_rx_ch)) {
1559 		ret = PTR_ERR(nfc->dma_rx_ch);
1560 		if (ret != -ENODEV && ret != -EPROBE_DEFER)
1561 			dev_err(nfc->dev,
1562 				"failed to request rx DMA channel: %d\n", ret);
1563 		nfc->dma_rx_ch = NULL;
1564 		goto err_dma;
1565 	}
1566 
1567 	nfc->dma_ecc_ch = dma_request_chan(nfc->dev, "ecc");
1568 	if (IS_ERR(nfc->dma_ecc_ch)) {
1569 		ret = PTR_ERR(nfc->dma_ecc_ch);
1570 		if (ret != -ENODEV && ret != -EPROBE_DEFER)
1571 			dev_err(nfc->dev,
1572 				"failed to request ecc DMA channel: %d\n", ret);
1573 		nfc->dma_ecc_ch = NULL;
1574 		goto err_dma;
1575 	}
1576 
1577 	ret = sg_alloc_table(&nfc->dma_ecc_sg, FMC2_MAX_SG, GFP_KERNEL);
1578 	if (ret)
1579 		return ret;
1580 
1581 	/* Allocate a buffer to store ECC status registers */
1582 	nfc->ecc_buf = devm_kzalloc(nfc->dev, FMC2_MAX_ECC_BUF_LEN, GFP_KERNEL);
1583 	if (!nfc->ecc_buf)
1584 		return -ENOMEM;
1585 
1586 	ret = sg_alloc_table(&nfc->dma_data_sg, FMC2_MAX_SG, GFP_KERNEL);
1587 	if (ret)
1588 		return ret;
1589 
1590 	init_completion(&nfc->dma_data_complete);
1591 	init_completion(&nfc->dma_ecc_complete);
1592 
1593 	return 0;
1594 
1595 err_dma:
1596 	if (ret == -ENODEV) {
1597 		dev_warn(nfc->dev,
1598 			 "DMAs not defined in the DT, polling mode is used\n");
1599 		ret = 0;
1600 	}
1601 
1602 	return ret;
1603 }
1604 
1605 static void stm32_fmc2_nfc_nand_callbacks_setup(struct nand_chip *chip)
1606 {
1607 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1608 
1609 	/*
1610 	 * Specific callbacks to read/write a page depending on
1611 	 * the mode (polling/sequencer) and the algo used (Hamming, BCH).
1612 	 */
1613 	if (nfc->dma_tx_ch && nfc->dma_rx_ch && nfc->dma_ecc_ch) {
1614 		/* DMA => use sequencer mode callbacks */
1615 		chip->ecc.correct = stm32_fmc2_nfc_seq_correct;
1616 		chip->ecc.write_page = stm32_fmc2_nfc_seq_write_page;
1617 		chip->ecc.read_page = stm32_fmc2_nfc_seq_read_page;
1618 		chip->ecc.write_page_raw = stm32_fmc2_nfc_seq_write_page_raw;
1619 		chip->ecc.read_page_raw = stm32_fmc2_nfc_seq_read_page_raw;
1620 	} else {
1621 		/* No DMA => use polling mode callbacks */
1622 		chip->ecc.hwctl = stm32_fmc2_nfc_hwctl;
1623 		if (chip->ecc.strength == FMC2_ECC_HAM) {
1624 			/* Hamming is used */
1625 			chip->ecc.calculate = stm32_fmc2_nfc_ham_calculate;
1626 			chip->ecc.correct = stm32_fmc2_nfc_ham_correct;
1627 			chip->ecc.options |= NAND_ECC_GENERIC_ERASED_CHECK;
1628 		} else {
1629 			/* BCH is used */
1630 			chip->ecc.calculate = stm32_fmc2_nfc_bch_calculate;
1631 			chip->ecc.correct = stm32_fmc2_nfc_bch_correct;
1632 			chip->ecc.read_page = stm32_fmc2_nfc_read_page;
1633 		}
1634 	}
1635 
1636 	/* Specific configurations depending on the algo used */
1637 	if (chip->ecc.strength == FMC2_ECC_HAM)
1638 		chip->ecc.bytes = chip->options & NAND_BUSWIDTH_16 ? 4 : 3;
1639 	else if (chip->ecc.strength == FMC2_ECC_BCH8)
1640 		chip->ecc.bytes = chip->options & NAND_BUSWIDTH_16 ? 14 : 13;
1641 	else
1642 		chip->ecc.bytes = chip->options & NAND_BUSWIDTH_16 ? 8 : 7;
1643 }
1644 
1645 static int stm32_fmc2_nfc_ooblayout_ecc(struct mtd_info *mtd, int section,
1646 					struct mtd_oob_region *oobregion)
1647 {
1648 	struct nand_chip *chip = mtd_to_nand(mtd);
1649 	struct nand_ecc_ctrl *ecc = &chip->ecc;
1650 
1651 	if (section)
1652 		return -ERANGE;
1653 
1654 	oobregion->length = ecc->total;
1655 	oobregion->offset = FMC2_BBM_LEN;
1656 
1657 	return 0;
1658 }
1659 
1660 static int stm32_fmc2_nfc_ooblayout_free(struct mtd_info *mtd, int section,
1661 					 struct mtd_oob_region *oobregion)
1662 {
1663 	struct nand_chip *chip = mtd_to_nand(mtd);
1664 	struct nand_ecc_ctrl *ecc = &chip->ecc;
1665 
1666 	if (section)
1667 		return -ERANGE;
1668 
1669 	oobregion->length = mtd->oobsize - ecc->total - FMC2_BBM_LEN;
1670 	oobregion->offset = ecc->total + FMC2_BBM_LEN;
1671 
1672 	return 0;
1673 }
1674 
1675 static const struct mtd_ooblayout_ops stm32_fmc2_nfc_ooblayout_ops = {
1676 	.ecc = stm32_fmc2_nfc_ooblayout_ecc,
1677 	.free = stm32_fmc2_nfc_ooblayout_free,
1678 };
1679 
1680 static int stm32_fmc2_nfc_calc_ecc_bytes(int step_size, int strength)
1681 {
1682 	/* Hamming */
1683 	if (strength == FMC2_ECC_HAM)
1684 		return 4;
1685 
1686 	/* BCH8 */
1687 	if (strength == FMC2_ECC_BCH8)
1688 		return 14;
1689 
1690 	/* BCH4 */
1691 	return 8;
1692 }
1693 
1694 NAND_ECC_CAPS_SINGLE(stm32_fmc2_nfc_ecc_caps, stm32_fmc2_nfc_calc_ecc_bytes,
1695 		     FMC2_ECC_STEP_SIZE,
1696 		     FMC2_ECC_HAM, FMC2_ECC_BCH4, FMC2_ECC_BCH8);
1697 
1698 static int stm32_fmc2_nfc_attach_chip(struct nand_chip *chip)
1699 {
1700 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1701 	struct mtd_info *mtd = nand_to_mtd(chip);
1702 	int ret;
1703 
1704 	/*
1705 	 * Only NAND_ECC_ENGINE_TYPE_ON_HOST mode is actually supported
1706 	 * Hamming => ecc.strength = 1
1707 	 * BCH4 => ecc.strength = 4
1708 	 * BCH8 => ecc.strength = 8
1709 	 * ECC sector size = 512
1710 	 */
1711 	if (chip->ecc.engine_type != NAND_ECC_ENGINE_TYPE_ON_HOST) {
1712 		dev_err(nfc->dev,
1713 			"nand_ecc_engine_type is not well defined in the DT\n");
1714 		return -EINVAL;
1715 	}
1716 
1717 	/* Default ECC settings in case they are not set in the device tree */
1718 	if (!chip->ecc.size)
1719 		chip->ecc.size = FMC2_ECC_STEP_SIZE;
1720 
1721 	if (!chip->ecc.strength)
1722 		chip->ecc.strength = FMC2_ECC_BCH8;
1723 
1724 	ret = nand_ecc_choose_conf(chip, &stm32_fmc2_nfc_ecc_caps,
1725 				   mtd->oobsize - FMC2_BBM_LEN);
1726 	if (ret) {
1727 		dev_err(nfc->dev, "no valid ECC settings set\n");
1728 		return ret;
1729 	}
1730 
1731 	if (mtd->writesize / chip->ecc.size > FMC2_MAX_SG) {
1732 		dev_err(nfc->dev, "nand page size is not supported\n");
1733 		return -EINVAL;
1734 	}
1735 
1736 	if (chip->bbt_options & NAND_BBT_USE_FLASH)
1737 		chip->bbt_options |= NAND_BBT_NO_OOB;
1738 
1739 	stm32_fmc2_nfc_nand_callbacks_setup(chip);
1740 
1741 	mtd_set_ooblayout(mtd, &stm32_fmc2_nfc_ooblayout_ops);
1742 
1743 	stm32_fmc2_nfc_setup(chip);
1744 
1745 	return 0;
1746 }
1747 
1748 static const struct nand_controller_ops stm32_fmc2_nfc_controller_ops = {
1749 	.attach_chip = stm32_fmc2_nfc_attach_chip,
1750 	.exec_op = stm32_fmc2_nfc_exec_op,
1751 	.setup_interface = stm32_fmc2_nfc_setup_interface,
1752 };
1753 
1754 static void stm32_fmc2_nfc_wp_enable(struct stm32_fmc2_nand *nand)
1755 {
1756 	if (nand->wp_gpio)
1757 		gpiod_set_value(nand->wp_gpio, 1);
1758 }
1759 
1760 static void stm32_fmc2_nfc_wp_disable(struct stm32_fmc2_nand *nand)
1761 {
1762 	if (nand->wp_gpio)
1763 		gpiod_set_value(nand->wp_gpio, 0);
1764 }
1765 
1766 static int stm32_fmc2_nfc_parse_child(struct stm32_fmc2_nfc *nfc,
1767 				      struct device_node *dn)
1768 {
1769 	struct stm32_fmc2_nand *nand = &nfc->nand;
1770 	u32 cs;
1771 	int ret, i;
1772 
1773 	if (!of_get_property(dn, "reg", &nand->ncs))
1774 		return -EINVAL;
1775 
1776 	nand->ncs /= sizeof(u32);
1777 	if (!nand->ncs) {
1778 		dev_err(nfc->dev, "invalid reg property size\n");
1779 		return -EINVAL;
1780 	}
1781 
1782 	for (i = 0; i < nand->ncs; i++) {
1783 		ret = of_property_read_u32_index(dn, "reg", i, &cs);
1784 		if (ret) {
1785 			dev_err(nfc->dev, "could not retrieve reg property: %d\n",
1786 				ret);
1787 			return ret;
1788 		}
1789 
1790 		if (cs >= FMC2_MAX_CE) {
1791 			dev_err(nfc->dev, "invalid reg value: %d\n", cs);
1792 			return -EINVAL;
1793 		}
1794 
1795 		if (nfc->cs_assigned & BIT(cs)) {
1796 			dev_err(nfc->dev, "cs already assigned: %d\n", cs);
1797 			return -EINVAL;
1798 		}
1799 
1800 		nfc->cs_assigned |= BIT(cs);
1801 		nand->cs_used[i] = cs;
1802 	}
1803 
1804 	nand->wp_gpio = devm_fwnode_gpiod_get(nfc->dev, of_fwnode_handle(dn),
1805 					      "wp", GPIOD_OUT_HIGH, "wp");
1806 	if (IS_ERR(nand->wp_gpio)) {
1807 		ret = PTR_ERR(nand->wp_gpio);
1808 		if (ret != -ENOENT)
1809 			return dev_err_probe(nfc->dev, ret,
1810 					     "failed to request WP GPIO\n");
1811 
1812 		nand->wp_gpio = NULL;
1813 	}
1814 
1815 	nand_set_flash_node(&nand->chip, dn);
1816 
1817 	return 0;
1818 }
1819 
1820 static int stm32_fmc2_nfc_parse_dt(struct stm32_fmc2_nfc *nfc)
1821 {
1822 	struct device_node *dn = nfc->dev->of_node;
1823 	struct device_node *child;
1824 	int nchips = of_get_child_count(dn);
1825 	int ret = 0;
1826 
1827 	if (!nchips) {
1828 		dev_err(nfc->dev, "NAND chip not defined\n");
1829 		return -EINVAL;
1830 	}
1831 
1832 	if (nchips > 1) {
1833 		dev_err(nfc->dev, "too many NAND chips defined\n");
1834 		return -EINVAL;
1835 	}
1836 
1837 	for_each_child_of_node(dn, child) {
1838 		ret = stm32_fmc2_nfc_parse_child(nfc, child);
1839 		if (ret < 0) {
1840 			of_node_put(child);
1841 			return ret;
1842 		}
1843 	}
1844 
1845 	return ret;
1846 }
1847 
1848 static int stm32_fmc2_nfc_set_cdev(struct stm32_fmc2_nfc *nfc)
1849 {
1850 	struct device *dev = nfc->dev;
1851 	bool ebi_found = false;
1852 
1853 	if (dev->parent && of_device_is_compatible(dev->parent->of_node,
1854 						   "st,stm32mp1-fmc2-ebi"))
1855 		ebi_found = true;
1856 
1857 	if (of_device_is_compatible(dev->of_node, "st,stm32mp1-fmc2-nfc")) {
1858 		if (ebi_found) {
1859 			nfc->cdev = dev->parent;
1860 
1861 			return 0;
1862 		}
1863 
1864 		return -EINVAL;
1865 	}
1866 
1867 	if (ebi_found)
1868 		return -EINVAL;
1869 
1870 	nfc->cdev = dev;
1871 
1872 	return 0;
1873 }
1874 
1875 static int stm32_fmc2_nfc_probe(struct platform_device *pdev)
1876 {
1877 	struct device *dev = &pdev->dev;
1878 	struct reset_control *rstc;
1879 	struct stm32_fmc2_nfc *nfc;
1880 	struct stm32_fmc2_nand *nand;
1881 	struct resource *res;
1882 	struct mtd_info *mtd;
1883 	struct nand_chip *chip;
1884 	struct resource cres;
1885 	int chip_cs, mem_region, ret, irq;
1886 	int start_region = 0;
1887 
1888 	nfc = devm_kzalloc(dev, sizeof(*nfc), GFP_KERNEL);
1889 	if (!nfc)
1890 		return -ENOMEM;
1891 
1892 	nfc->dev = dev;
1893 	nand_controller_init(&nfc->base);
1894 	nfc->base.ops = &stm32_fmc2_nfc_controller_ops;
1895 
1896 	ret = stm32_fmc2_nfc_set_cdev(nfc);
1897 	if (ret)
1898 		return ret;
1899 
1900 	ret = stm32_fmc2_nfc_parse_dt(nfc);
1901 	if (ret)
1902 		return ret;
1903 
1904 	ret = of_address_to_resource(nfc->cdev->of_node, 0, &cres);
1905 	if (ret)
1906 		return ret;
1907 
1908 	nfc->io_phys_addr = cres.start;
1909 
1910 	nfc->regmap = device_node_to_regmap(nfc->cdev->of_node);
1911 	if (IS_ERR(nfc->regmap))
1912 		return PTR_ERR(nfc->regmap);
1913 
1914 	if (nfc->dev == nfc->cdev)
1915 		start_region = 1;
1916 
1917 	for (chip_cs = 0, mem_region = start_region; chip_cs < FMC2_MAX_CE;
1918 	     chip_cs++, mem_region += 3) {
1919 		if (!(nfc->cs_assigned & BIT(chip_cs)))
1920 			continue;
1921 
1922 		res = platform_get_resource(pdev, IORESOURCE_MEM, mem_region);
1923 		nfc->data_base[chip_cs] = devm_ioremap_resource(dev, res);
1924 		if (IS_ERR(nfc->data_base[chip_cs]))
1925 			return PTR_ERR(nfc->data_base[chip_cs]);
1926 
1927 		nfc->data_phys_addr[chip_cs] = res->start;
1928 
1929 		nfc->cmd_base[chip_cs] = devm_platform_ioremap_resource(pdev, mem_region + 1);
1930 		if (IS_ERR(nfc->cmd_base[chip_cs]))
1931 			return PTR_ERR(nfc->cmd_base[chip_cs]);
1932 
1933 		nfc->addr_base[chip_cs] = devm_platform_ioremap_resource(pdev, mem_region + 2);
1934 		if (IS_ERR(nfc->addr_base[chip_cs]))
1935 			return PTR_ERR(nfc->addr_base[chip_cs]);
1936 	}
1937 
1938 	irq = platform_get_irq(pdev, 0);
1939 	if (irq < 0)
1940 		return irq;
1941 
1942 	ret = devm_request_irq(dev, irq, stm32_fmc2_nfc_irq, 0,
1943 			       dev_name(dev), nfc);
1944 	if (ret) {
1945 		dev_err(dev, "failed to request irq\n");
1946 		return ret;
1947 	}
1948 
1949 	init_completion(&nfc->complete);
1950 
1951 	nfc->clk = devm_clk_get(nfc->cdev, NULL);
1952 	if (IS_ERR(nfc->clk))
1953 		return PTR_ERR(nfc->clk);
1954 
1955 	ret = clk_prepare_enable(nfc->clk);
1956 	if (ret) {
1957 		dev_err(dev, "can not enable the clock\n");
1958 		return ret;
1959 	}
1960 
1961 	rstc = devm_reset_control_get(dev, NULL);
1962 	if (IS_ERR(rstc)) {
1963 		ret = PTR_ERR(rstc);
1964 		if (ret == -EPROBE_DEFER)
1965 			goto err_clk_disable;
1966 	} else {
1967 		reset_control_assert(rstc);
1968 		reset_control_deassert(rstc);
1969 	}
1970 
1971 	ret = stm32_fmc2_nfc_dma_setup(nfc);
1972 	if (ret)
1973 		goto err_release_dma;
1974 
1975 	stm32_fmc2_nfc_init(nfc);
1976 
1977 	nand = &nfc->nand;
1978 	chip = &nand->chip;
1979 	mtd = nand_to_mtd(chip);
1980 	mtd->dev.parent = dev;
1981 
1982 	chip->controller = &nfc->base;
1983 	chip->options |= NAND_BUSWIDTH_AUTO | NAND_NO_SUBPAGE_WRITE |
1984 			 NAND_USES_DMA;
1985 
1986 	stm32_fmc2_nfc_wp_disable(nand);
1987 
1988 	/* Scan to find existence of the device */
1989 	ret = nand_scan(chip, nand->ncs);
1990 	if (ret)
1991 		goto err_wp_enable;
1992 
1993 	ret = mtd_device_register(mtd, NULL, 0);
1994 	if (ret)
1995 		goto err_nand_cleanup;
1996 
1997 	platform_set_drvdata(pdev, nfc);
1998 
1999 	return 0;
2000 
2001 err_nand_cleanup:
2002 	nand_cleanup(chip);
2003 
2004 err_wp_enable:
2005 	stm32_fmc2_nfc_wp_enable(nand);
2006 
2007 err_release_dma:
2008 	if (nfc->dma_ecc_ch)
2009 		dma_release_channel(nfc->dma_ecc_ch);
2010 	if (nfc->dma_tx_ch)
2011 		dma_release_channel(nfc->dma_tx_ch);
2012 	if (nfc->dma_rx_ch)
2013 		dma_release_channel(nfc->dma_rx_ch);
2014 
2015 	sg_free_table(&nfc->dma_data_sg);
2016 	sg_free_table(&nfc->dma_ecc_sg);
2017 
2018 err_clk_disable:
2019 	clk_disable_unprepare(nfc->clk);
2020 
2021 	return ret;
2022 }
2023 
2024 static int stm32_fmc2_nfc_remove(struct platform_device *pdev)
2025 {
2026 	struct stm32_fmc2_nfc *nfc = platform_get_drvdata(pdev);
2027 	struct stm32_fmc2_nand *nand = &nfc->nand;
2028 	struct nand_chip *chip = &nand->chip;
2029 	int ret;
2030 
2031 	ret = mtd_device_unregister(nand_to_mtd(chip));
2032 	WARN_ON(ret);
2033 	nand_cleanup(chip);
2034 
2035 	if (nfc->dma_ecc_ch)
2036 		dma_release_channel(nfc->dma_ecc_ch);
2037 	if (nfc->dma_tx_ch)
2038 		dma_release_channel(nfc->dma_tx_ch);
2039 	if (nfc->dma_rx_ch)
2040 		dma_release_channel(nfc->dma_rx_ch);
2041 
2042 	sg_free_table(&nfc->dma_data_sg);
2043 	sg_free_table(&nfc->dma_ecc_sg);
2044 
2045 	clk_disable_unprepare(nfc->clk);
2046 
2047 	stm32_fmc2_nfc_wp_enable(nand);
2048 
2049 	return 0;
2050 }
2051 
2052 static int __maybe_unused stm32_fmc2_nfc_suspend(struct device *dev)
2053 {
2054 	struct stm32_fmc2_nfc *nfc = dev_get_drvdata(dev);
2055 	struct stm32_fmc2_nand *nand = &nfc->nand;
2056 
2057 	clk_disable_unprepare(nfc->clk);
2058 
2059 	stm32_fmc2_nfc_wp_enable(nand);
2060 
2061 	pinctrl_pm_select_sleep_state(dev);
2062 
2063 	return 0;
2064 }
2065 
2066 static int __maybe_unused stm32_fmc2_nfc_resume(struct device *dev)
2067 {
2068 	struct stm32_fmc2_nfc *nfc = dev_get_drvdata(dev);
2069 	struct stm32_fmc2_nand *nand = &nfc->nand;
2070 	int chip_cs, ret;
2071 
2072 	pinctrl_pm_select_default_state(dev);
2073 
2074 	ret = clk_prepare_enable(nfc->clk);
2075 	if (ret) {
2076 		dev_err(dev, "can not enable the clock\n");
2077 		return ret;
2078 	}
2079 
2080 	stm32_fmc2_nfc_init(nfc);
2081 
2082 	stm32_fmc2_nfc_wp_disable(nand);
2083 
2084 	for (chip_cs = 0; chip_cs < FMC2_MAX_CE; chip_cs++) {
2085 		if (!(nfc->cs_assigned & BIT(chip_cs)))
2086 			continue;
2087 
2088 		nand_reset(&nand->chip, chip_cs);
2089 	}
2090 
2091 	return 0;
2092 }
2093 
2094 static SIMPLE_DEV_PM_OPS(stm32_fmc2_nfc_pm_ops, stm32_fmc2_nfc_suspend,
2095 			 stm32_fmc2_nfc_resume);
2096 
2097 static const struct of_device_id stm32_fmc2_nfc_match[] = {
2098 	{.compatible = "st,stm32mp15-fmc2"},
2099 	{.compatible = "st,stm32mp1-fmc2-nfc"},
2100 	{}
2101 };
2102 MODULE_DEVICE_TABLE(of, stm32_fmc2_nfc_match);
2103 
2104 static struct platform_driver stm32_fmc2_nfc_driver = {
2105 	.probe	= stm32_fmc2_nfc_probe,
2106 	.remove	= stm32_fmc2_nfc_remove,
2107 	.driver	= {
2108 		.name = "stm32_fmc2_nfc",
2109 		.of_match_table = stm32_fmc2_nfc_match,
2110 		.pm = &stm32_fmc2_nfc_pm_ops,
2111 	},
2112 };
2113 module_platform_driver(stm32_fmc2_nfc_driver);
2114 
2115 MODULE_ALIAS("platform:stm32_fmc2_nfc");
2116 MODULE_AUTHOR("Christophe Kerello <christophe.kerello@st.com>");
2117 MODULE_DESCRIPTION("STMicroelectronics STM32 FMC2 NFC driver");
2118 MODULE_LICENSE("GPL v2");
2119