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 < 0)
866 		return ret;
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 < 0)
897 			goto err_unmap_data;
898 
899 		desc_ecc = dmaengine_prep_slave_sg(nfc->dma_ecc_ch,
900 						   nfc->dma_ecc_sg.sgl,
901 						   eccsteps, dma_transfer_dir,
902 						   DMA_PREP_INTERRUPT);
903 		if (!desc_ecc) {
904 			ret = -ENOMEM;
905 			goto err_unmap_ecc;
906 		}
907 
908 		reinit_completion(&nfc->dma_ecc_complete);
909 		desc_ecc->callback = stm32_fmc2_nfc_dma_callback;
910 		desc_ecc->callback_param = &nfc->dma_ecc_complete;
911 		ret = dma_submit_error(dmaengine_submit(desc_ecc));
912 		if (ret)
913 			goto err_unmap_ecc;
914 
915 		dma_async_issue_pending(nfc->dma_ecc_ch);
916 	}
917 
918 	stm32_fmc2_nfc_clear_seq_irq(nfc);
919 	stm32_fmc2_nfc_enable_seq_irq(nfc);
920 
921 	/* Start the transfer */
922 	regmap_update_bits(nfc->regmap, FMC2_CSQCR,
923 			   FMC2_CSQCR_CSQSTART, FMC2_CSQCR_CSQSTART);
924 
925 	/* Wait end of sequencer transfer */
926 	if (!wait_for_completion_timeout(&nfc->complete, timeout)) {
927 		dev_err(nfc->dev, "seq timeout\n");
928 		stm32_fmc2_nfc_disable_seq_irq(nfc);
929 		dmaengine_terminate_all(dma_ch);
930 		if (!write_data && !raw)
931 			dmaengine_terminate_all(nfc->dma_ecc_ch);
932 		ret = -ETIMEDOUT;
933 		goto err_unmap_ecc;
934 	}
935 
936 	/* Wait DMA data transfer completion */
937 	if (!wait_for_completion_timeout(&nfc->dma_data_complete, timeout)) {
938 		dev_err(nfc->dev, "data DMA timeout\n");
939 		dmaengine_terminate_all(dma_ch);
940 		ret = -ETIMEDOUT;
941 	}
942 
943 	/* Wait DMA ECC transfer completion */
944 	if (!write_data && !raw) {
945 		if (!wait_for_completion_timeout(&nfc->dma_ecc_complete,
946 						 timeout)) {
947 			dev_err(nfc->dev, "ECC DMA timeout\n");
948 			dmaengine_terminate_all(nfc->dma_ecc_ch);
949 			ret = -ETIMEDOUT;
950 		}
951 	}
952 
953 err_unmap_ecc:
954 	if (!write_data && !raw)
955 		dma_unmap_sg(nfc->dev, nfc->dma_ecc_sg.sgl,
956 			     eccsteps, dma_data_dir);
957 
958 err_unmap_data:
959 	dma_unmap_sg(nfc->dev, nfc->dma_data_sg.sgl, eccsteps, dma_data_dir);
960 
961 	return ret;
962 }
963 
964 static int stm32_fmc2_nfc_seq_write(struct nand_chip *chip, const u8 *buf,
965 				    int oob_required, int page, int raw)
966 {
967 	struct mtd_info *mtd = nand_to_mtd(chip);
968 	int ret;
969 
970 	/* Configure the sequencer */
971 	stm32_fmc2_nfc_rw_page_init(chip, page, raw, true);
972 
973 	/* Write the page */
974 	ret = stm32_fmc2_nfc_xfer(chip, buf, raw, true);
975 	if (ret)
976 		return ret;
977 
978 	/* Write oob */
979 	if (oob_required) {
980 		ret = nand_change_write_column_op(chip, mtd->writesize,
981 						  chip->oob_poi, mtd->oobsize,
982 						  false);
983 		if (ret)
984 			return ret;
985 	}
986 
987 	return nand_prog_page_end_op(chip);
988 }
989 
990 static int stm32_fmc2_nfc_seq_write_page(struct nand_chip *chip, const u8 *buf,
991 					 int oob_required, int page)
992 {
993 	int ret;
994 
995 	ret = stm32_fmc2_nfc_select_chip(chip, chip->cur_cs);
996 	if (ret)
997 		return ret;
998 
999 	return stm32_fmc2_nfc_seq_write(chip, buf, oob_required, page, false);
1000 }
1001 
1002 static int stm32_fmc2_nfc_seq_write_page_raw(struct nand_chip *chip,
1003 					     const u8 *buf, int oob_required,
1004 					     int page)
1005 {
1006 	int ret;
1007 
1008 	ret = stm32_fmc2_nfc_select_chip(chip, chip->cur_cs);
1009 	if (ret)
1010 		return ret;
1011 
1012 	return stm32_fmc2_nfc_seq_write(chip, buf, oob_required, page, true);
1013 }
1014 
1015 /* Get a status indicating which sectors have errors */
1016 static u16 stm32_fmc2_nfc_get_mapping_status(struct stm32_fmc2_nfc *nfc)
1017 {
1018 	u32 csqemsr;
1019 
1020 	regmap_read(nfc->regmap, FMC2_CSQEMSR, &csqemsr);
1021 
1022 	return FIELD_GET(FMC2_CSQEMSR_SEM, csqemsr);
1023 }
1024 
1025 static int stm32_fmc2_nfc_seq_correct(struct nand_chip *chip, u8 *dat,
1026 				      u8 *read_ecc, u8 *calc_ecc)
1027 {
1028 	struct mtd_info *mtd = nand_to_mtd(chip);
1029 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1030 	int eccbytes = chip->ecc.bytes;
1031 	int eccsteps = chip->ecc.steps;
1032 	int eccstrength = chip->ecc.strength;
1033 	int i, s, eccsize = chip->ecc.size;
1034 	u32 *ecc_sta = (u32 *)nfc->ecc_buf;
1035 	u16 sta_map = stm32_fmc2_nfc_get_mapping_status(nfc);
1036 	unsigned int max_bitflips = 0;
1037 
1038 	for (i = 0, s = 0; s < eccsteps; s++, i += eccbytes, dat += eccsize) {
1039 		int stat = 0;
1040 
1041 		if (eccstrength == FMC2_ECC_HAM) {
1042 			/* Ecc_sta = FMC2_HECCR */
1043 			if (sta_map & BIT(s)) {
1044 				stm32_fmc2_nfc_ham_set_ecc(*ecc_sta,
1045 							   &calc_ecc[i]);
1046 				stat = stm32_fmc2_nfc_ham_correct(chip, dat,
1047 								  &read_ecc[i],
1048 								  &calc_ecc[i]);
1049 			}
1050 			ecc_sta++;
1051 		} else {
1052 			/*
1053 			 * Ecc_sta[0] = FMC2_BCHDSR0
1054 			 * Ecc_sta[1] = FMC2_BCHDSR1
1055 			 * Ecc_sta[2] = FMC2_BCHDSR2
1056 			 * Ecc_sta[3] = FMC2_BCHDSR3
1057 			 * Ecc_sta[4] = FMC2_BCHDSR4
1058 			 */
1059 			if (sta_map & BIT(s))
1060 				stat = stm32_fmc2_nfc_bch_decode(eccsize, dat,
1061 								 ecc_sta);
1062 			ecc_sta += 5;
1063 		}
1064 
1065 		if (stat == -EBADMSG)
1066 			/* Check for empty pages with bitflips */
1067 			stat = nand_check_erased_ecc_chunk(dat, eccsize,
1068 							   &read_ecc[i],
1069 							   eccbytes,
1070 							   NULL, 0,
1071 							   eccstrength);
1072 
1073 		if (stat < 0) {
1074 			mtd->ecc_stats.failed++;
1075 		} else {
1076 			mtd->ecc_stats.corrected += stat;
1077 			max_bitflips = max_t(unsigned int, max_bitflips, stat);
1078 		}
1079 	}
1080 
1081 	return max_bitflips;
1082 }
1083 
1084 static int stm32_fmc2_nfc_seq_read_page(struct nand_chip *chip, u8 *buf,
1085 					int oob_required, int page)
1086 {
1087 	struct mtd_info *mtd = nand_to_mtd(chip);
1088 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1089 	u8 *ecc_calc = chip->ecc.calc_buf;
1090 	u8 *ecc_code = chip->ecc.code_buf;
1091 	u16 sta_map;
1092 	int ret;
1093 
1094 	ret = stm32_fmc2_nfc_select_chip(chip, chip->cur_cs);
1095 	if (ret)
1096 		return ret;
1097 
1098 	/* Configure the sequencer */
1099 	stm32_fmc2_nfc_rw_page_init(chip, page, 0, false);
1100 
1101 	/* Read the page */
1102 	ret = stm32_fmc2_nfc_xfer(chip, buf, 0, false);
1103 	if (ret)
1104 		return ret;
1105 
1106 	sta_map = stm32_fmc2_nfc_get_mapping_status(nfc);
1107 
1108 	/* Check if errors happen */
1109 	if (likely(!sta_map)) {
1110 		if (oob_required)
1111 			return nand_change_read_column_op(chip, mtd->writesize,
1112 							  chip->oob_poi,
1113 							  mtd->oobsize, false);
1114 
1115 		return 0;
1116 	}
1117 
1118 	/* Read oob */
1119 	ret = nand_change_read_column_op(chip, mtd->writesize,
1120 					 chip->oob_poi, mtd->oobsize, false);
1121 	if (ret)
1122 		return ret;
1123 
1124 	ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1125 					 chip->ecc.total);
1126 	if (ret)
1127 		return ret;
1128 
1129 	/* Correct data */
1130 	return chip->ecc.correct(chip, buf, ecc_code, ecc_calc);
1131 }
1132 
1133 static int stm32_fmc2_nfc_seq_read_page_raw(struct nand_chip *chip, u8 *buf,
1134 					    int oob_required, int page)
1135 {
1136 	struct mtd_info *mtd = nand_to_mtd(chip);
1137 	int ret;
1138 
1139 	ret = stm32_fmc2_nfc_select_chip(chip, chip->cur_cs);
1140 	if (ret)
1141 		return ret;
1142 
1143 	/* Configure the sequencer */
1144 	stm32_fmc2_nfc_rw_page_init(chip, page, 1, false);
1145 
1146 	/* Read the page */
1147 	ret = stm32_fmc2_nfc_xfer(chip, buf, 1, false);
1148 	if (ret)
1149 		return ret;
1150 
1151 	/* Read oob */
1152 	if (oob_required)
1153 		return nand_change_read_column_op(chip, mtd->writesize,
1154 						  chip->oob_poi, mtd->oobsize,
1155 						  false);
1156 
1157 	return 0;
1158 }
1159 
1160 static irqreturn_t stm32_fmc2_nfc_irq(int irq, void *dev_id)
1161 {
1162 	struct stm32_fmc2_nfc *nfc = (struct stm32_fmc2_nfc *)dev_id;
1163 
1164 	if (nfc->irq_state == FMC2_IRQ_SEQ)
1165 		/* Sequencer is used */
1166 		stm32_fmc2_nfc_disable_seq_irq(nfc);
1167 	else if (nfc->irq_state == FMC2_IRQ_BCH)
1168 		/* BCH is used */
1169 		stm32_fmc2_nfc_disable_bch_irq(nfc);
1170 
1171 	complete(&nfc->complete);
1172 
1173 	return IRQ_HANDLED;
1174 }
1175 
1176 static void stm32_fmc2_nfc_read_data(struct nand_chip *chip, void *buf,
1177 				     unsigned int len, bool force_8bit)
1178 {
1179 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1180 	void __iomem *io_addr_r = nfc->data_base[nfc->cs_sel];
1181 
1182 	if (force_8bit && chip->options & NAND_BUSWIDTH_16)
1183 		/* Reconfigure bus width to 8-bit */
1184 		stm32_fmc2_nfc_set_buswidth_16(nfc, false);
1185 
1186 	if (!IS_ALIGNED((uintptr_t)buf, sizeof(u32))) {
1187 		if (!IS_ALIGNED((uintptr_t)buf, sizeof(u16)) && len) {
1188 			*(u8 *)buf = readb_relaxed(io_addr_r);
1189 			buf += sizeof(u8);
1190 			len -= sizeof(u8);
1191 		}
1192 
1193 		if (!IS_ALIGNED((uintptr_t)buf, sizeof(u32)) &&
1194 		    len >= sizeof(u16)) {
1195 			*(u16 *)buf = readw_relaxed(io_addr_r);
1196 			buf += sizeof(u16);
1197 			len -= sizeof(u16);
1198 		}
1199 	}
1200 
1201 	/* Buf is aligned */
1202 	while (len >= sizeof(u32)) {
1203 		*(u32 *)buf = readl_relaxed(io_addr_r);
1204 		buf += sizeof(u32);
1205 		len -= sizeof(u32);
1206 	}
1207 
1208 	/* Read remaining bytes */
1209 	if (len >= sizeof(u16)) {
1210 		*(u16 *)buf = readw_relaxed(io_addr_r);
1211 		buf += sizeof(u16);
1212 		len -= sizeof(u16);
1213 	}
1214 
1215 	if (len)
1216 		*(u8 *)buf = readb_relaxed(io_addr_r);
1217 
1218 	if (force_8bit && chip->options & NAND_BUSWIDTH_16)
1219 		/* Reconfigure bus width to 16-bit */
1220 		stm32_fmc2_nfc_set_buswidth_16(nfc, true);
1221 }
1222 
1223 static void stm32_fmc2_nfc_write_data(struct nand_chip *chip, const void *buf,
1224 				      unsigned int len, bool force_8bit)
1225 {
1226 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1227 	void __iomem *io_addr_w = nfc->data_base[nfc->cs_sel];
1228 
1229 	if (force_8bit && chip->options & NAND_BUSWIDTH_16)
1230 		/* Reconfigure bus width to 8-bit */
1231 		stm32_fmc2_nfc_set_buswidth_16(nfc, false);
1232 
1233 	if (!IS_ALIGNED((uintptr_t)buf, sizeof(u32))) {
1234 		if (!IS_ALIGNED((uintptr_t)buf, sizeof(u16)) && len) {
1235 			writeb_relaxed(*(u8 *)buf, io_addr_w);
1236 			buf += sizeof(u8);
1237 			len -= sizeof(u8);
1238 		}
1239 
1240 		if (!IS_ALIGNED((uintptr_t)buf, sizeof(u32)) &&
1241 		    len >= sizeof(u16)) {
1242 			writew_relaxed(*(u16 *)buf, io_addr_w);
1243 			buf += sizeof(u16);
1244 			len -= sizeof(u16);
1245 		}
1246 	}
1247 
1248 	/* Buf is aligned */
1249 	while (len >= sizeof(u32)) {
1250 		writel_relaxed(*(u32 *)buf, io_addr_w);
1251 		buf += sizeof(u32);
1252 		len -= sizeof(u32);
1253 	}
1254 
1255 	/* Write remaining bytes */
1256 	if (len >= sizeof(u16)) {
1257 		writew_relaxed(*(u16 *)buf, io_addr_w);
1258 		buf += sizeof(u16);
1259 		len -= sizeof(u16);
1260 	}
1261 
1262 	if (len)
1263 		writeb_relaxed(*(u8 *)buf, io_addr_w);
1264 
1265 	if (force_8bit && chip->options & NAND_BUSWIDTH_16)
1266 		/* Reconfigure bus width to 16-bit */
1267 		stm32_fmc2_nfc_set_buswidth_16(nfc, true);
1268 }
1269 
1270 static int stm32_fmc2_nfc_waitrdy(struct nand_chip *chip,
1271 				  unsigned long timeout_ms)
1272 {
1273 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1274 	const struct nand_sdr_timings *timings;
1275 	u32 isr, sr;
1276 
1277 	/* Check if there is no pending requests to the NAND flash */
1278 	if (regmap_read_poll_timeout(nfc->regmap, FMC2_SR, sr,
1279 				     sr & FMC2_SR_NWRF, 1,
1280 				     1000 * FMC2_TIMEOUT_MS))
1281 		dev_warn(nfc->dev, "Waitrdy timeout\n");
1282 
1283 	/* Wait tWB before R/B# signal is low */
1284 	timings = nand_get_sdr_timings(nand_get_interface_config(chip));
1285 	ndelay(PSEC_TO_NSEC(timings->tWB_max));
1286 
1287 	/* R/B# signal is low, clear high level flag */
1288 	regmap_write(nfc->regmap, FMC2_ICR, FMC2_ICR_CIHLF);
1289 
1290 	/* Wait R/B# signal is high */
1291 	return regmap_read_poll_timeout(nfc->regmap, FMC2_ISR, isr,
1292 					isr & FMC2_ISR_IHLF, 5,
1293 					1000 * FMC2_TIMEOUT_MS);
1294 }
1295 
1296 static int stm32_fmc2_nfc_exec_op(struct nand_chip *chip,
1297 				  const struct nand_operation *op,
1298 				  bool check_only)
1299 {
1300 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1301 	const struct nand_op_instr *instr = NULL;
1302 	unsigned int op_id, i, timeout;
1303 	int ret;
1304 
1305 	if (check_only)
1306 		return 0;
1307 
1308 	ret = stm32_fmc2_nfc_select_chip(chip, op->cs);
1309 	if (ret)
1310 		return ret;
1311 
1312 	for (op_id = 0; op_id < op->ninstrs; op_id++) {
1313 		instr = &op->instrs[op_id];
1314 
1315 		switch (instr->type) {
1316 		case NAND_OP_CMD_INSTR:
1317 			writeb_relaxed(instr->ctx.cmd.opcode,
1318 				       nfc->cmd_base[nfc->cs_sel]);
1319 			break;
1320 
1321 		case NAND_OP_ADDR_INSTR:
1322 			for (i = 0; i < instr->ctx.addr.naddrs; i++)
1323 				writeb_relaxed(instr->ctx.addr.addrs[i],
1324 					       nfc->addr_base[nfc->cs_sel]);
1325 			break;
1326 
1327 		case NAND_OP_DATA_IN_INSTR:
1328 			stm32_fmc2_nfc_read_data(chip, instr->ctx.data.buf.in,
1329 						 instr->ctx.data.len,
1330 						 instr->ctx.data.force_8bit);
1331 			break;
1332 
1333 		case NAND_OP_DATA_OUT_INSTR:
1334 			stm32_fmc2_nfc_write_data(chip, instr->ctx.data.buf.out,
1335 						  instr->ctx.data.len,
1336 						  instr->ctx.data.force_8bit);
1337 			break;
1338 
1339 		case NAND_OP_WAITRDY_INSTR:
1340 			timeout = instr->ctx.waitrdy.timeout_ms;
1341 			ret = stm32_fmc2_nfc_waitrdy(chip, timeout);
1342 			break;
1343 		}
1344 	}
1345 
1346 	return ret;
1347 }
1348 
1349 static void stm32_fmc2_nfc_init(struct stm32_fmc2_nfc *nfc)
1350 {
1351 	u32 pcr;
1352 
1353 	regmap_read(nfc->regmap, FMC2_PCR, &pcr);
1354 
1355 	/* Set CS used to undefined */
1356 	nfc->cs_sel = -1;
1357 
1358 	/* Enable wait feature and nand flash memory bank */
1359 	pcr |= FMC2_PCR_PWAITEN;
1360 	pcr |= FMC2_PCR_PBKEN;
1361 
1362 	/* Set buswidth to 8 bits mode for identification */
1363 	pcr &= ~FMC2_PCR_PWID;
1364 
1365 	/* ECC logic is disabled */
1366 	pcr &= ~FMC2_PCR_ECCEN;
1367 
1368 	/* Default mode */
1369 	pcr &= ~FMC2_PCR_ECCALG;
1370 	pcr &= ~FMC2_PCR_BCHECC;
1371 	pcr &= ~FMC2_PCR_WEN;
1372 
1373 	/* Set default ECC sector size */
1374 	pcr &= ~FMC2_PCR_ECCSS;
1375 	pcr |= FIELD_PREP(FMC2_PCR_ECCSS, FMC2_PCR_ECCSS_2048);
1376 
1377 	/* Set default tclr/tar timings */
1378 	pcr &= ~FMC2_PCR_TCLR;
1379 	pcr |= FIELD_PREP(FMC2_PCR_TCLR, FMC2_PCR_TCLR_DEFAULT);
1380 	pcr &= ~FMC2_PCR_TAR;
1381 	pcr |= FIELD_PREP(FMC2_PCR_TAR, FMC2_PCR_TAR_DEFAULT);
1382 
1383 	/* Enable FMC2 controller */
1384 	if (nfc->dev == nfc->cdev)
1385 		regmap_update_bits(nfc->regmap, FMC2_BCR1,
1386 				   FMC2_BCR1_FMC2EN, FMC2_BCR1_FMC2EN);
1387 
1388 	regmap_write(nfc->regmap, FMC2_PCR, pcr);
1389 	regmap_write(nfc->regmap, FMC2_PMEM, FMC2_PMEM_DEFAULT);
1390 	regmap_write(nfc->regmap, FMC2_PATT, FMC2_PATT_DEFAULT);
1391 }
1392 
1393 static void stm32_fmc2_nfc_calc_timings(struct nand_chip *chip,
1394 					const struct nand_sdr_timings *sdrt)
1395 {
1396 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1397 	struct stm32_fmc2_nand *nand = to_fmc2_nand(chip);
1398 	struct stm32_fmc2_timings *tims = &nand->timings;
1399 	unsigned long hclk = clk_get_rate(nfc->clk);
1400 	unsigned long hclkp = NSEC_PER_SEC / (hclk / 1000);
1401 	unsigned long timing, tar, tclr, thiz, twait;
1402 	unsigned long tset_mem, tset_att, thold_mem, thold_att;
1403 
1404 	tar = max_t(unsigned long, hclkp, sdrt->tAR_min);
1405 	timing = DIV_ROUND_UP(tar, hclkp) - 1;
1406 	tims->tar = min_t(unsigned long, timing, FMC2_PCR_TIMING_MASK);
1407 
1408 	tclr = max_t(unsigned long, hclkp, sdrt->tCLR_min);
1409 	timing = DIV_ROUND_UP(tclr, hclkp) - 1;
1410 	tims->tclr = min_t(unsigned long, timing, FMC2_PCR_TIMING_MASK);
1411 
1412 	tims->thiz = FMC2_THIZ;
1413 	thiz = (tims->thiz + 1) * hclkp;
1414 
1415 	/*
1416 	 * tWAIT > tRP
1417 	 * tWAIT > tWP
1418 	 * tWAIT > tREA + tIO
1419 	 */
1420 	twait = max_t(unsigned long, hclkp, sdrt->tRP_min);
1421 	twait = max_t(unsigned long, twait, sdrt->tWP_min);
1422 	twait = max_t(unsigned long, twait, sdrt->tREA_max + FMC2_TIO);
1423 	timing = DIV_ROUND_UP(twait, hclkp);
1424 	tims->twait = clamp_val(timing, 1, FMC2_PMEM_PATT_TIMING_MASK);
1425 
1426 	/*
1427 	 * tSETUP_MEM > tCS - tWAIT
1428 	 * tSETUP_MEM > tALS - tWAIT
1429 	 * tSETUP_MEM > tDS - (tWAIT - tHIZ)
1430 	 */
1431 	tset_mem = hclkp;
1432 	if (sdrt->tCS_min > twait && (tset_mem < sdrt->tCS_min - twait))
1433 		tset_mem = sdrt->tCS_min - twait;
1434 	if (sdrt->tALS_min > twait && (tset_mem < sdrt->tALS_min - twait))
1435 		tset_mem = sdrt->tALS_min - twait;
1436 	if (twait > thiz && (sdrt->tDS_min > twait - thiz) &&
1437 	    (tset_mem < sdrt->tDS_min - (twait - thiz)))
1438 		tset_mem = sdrt->tDS_min - (twait - thiz);
1439 	timing = DIV_ROUND_UP(tset_mem, hclkp);
1440 	tims->tset_mem = clamp_val(timing, 1, FMC2_PMEM_PATT_TIMING_MASK);
1441 
1442 	/*
1443 	 * tHOLD_MEM > tCH
1444 	 * tHOLD_MEM > tREH - tSETUP_MEM
1445 	 * tHOLD_MEM > max(tRC, tWC) - (tSETUP_MEM + tWAIT)
1446 	 */
1447 	thold_mem = max_t(unsigned long, hclkp, sdrt->tCH_min);
1448 	if (sdrt->tREH_min > tset_mem &&
1449 	    (thold_mem < sdrt->tREH_min - tset_mem))
1450 		thold_mem = sdrt->tREH_min - tset_mem;
1451 	if ((sdrt->tRC_min > tset_mem + twait) &&
1452 	    (thold_mem < sdrt->tRC_min - (tset_mem + twait)))
1453 		thold_mem = sdrt->tRC_min - (tset_mem + twait);
1454 	if ((sdrt->tWC_min > tset_mem + twait) &&
1455 	    (thold_mem < sdrt->tWC_min - (tset_mem + twait)))
1456 		thold_mem = sdrt->tWC_min - (tset_mem + twait);
1457 	timing = DIV_ROUND_UP(thold_mem, hclkp);
1458 	tims->thold_mem = clamp_val(timing, 1, FMC2_PMEM_PATT_TIMING_MASK);
1459 
1460 	/*
1461 	 * tSETUP_ATT > tCS - tWAIT
1462 	 * tSETUP_ATT > tCLS - tWAIT
1463 	 * tSETUP_ATT > tALS - tWAIT
1464 	 * tSETUP_ATT > tRHW - tHOLD_MEM
1465 	 * tSETUP_ATT > tDS - (tWAIT - tHIZ)
1466 	 */
1467 	tset_att = hclkp;
1468 	if (sdrt->tCS_min > twait && (tset_att < sdrt->tCS_min - twait))
1469 		tset_att = sdrt->tCS_min - twait;
1470 	if (sdrt->tCLS_min > twait && (tset_att < sdrt->tCLS_min - twait))
1471 		tset_att = sdrt->tCLS_min - twait;
1472 	if (sdrt->tALS_min > twait && (tset_att < sdrt->tALS_min - twait))
1473 		tset_att = sdrt->tALS_min - twait;
1474 	if (sdrt->tRHW_min > thold_mem &&
1475 	    (tset_att < sdrt->tRHW_min - thold_mem))
1476 		tset_att = sdrt->tRHW_min - thold_mem;
1477 	if (twait > thiz && (sdrt->tDS_min > twait - thiz) &&
1478 	    (tset_att < sdrt->tDS_min - (twait - thiz)))
1479 		tset_att = sdrt->tDS_min - (twait - thiz);
1480 	timing = DIV_ROUND_UP(tset_att, hclkp);
1481 	tims->tset_att = clamp_val(timing, 1, FMC2_PMEM_PATT_TIMING_MASK);
1482 
1483 	/*
1484 	 * tHOLD_ATT > tALH
1485 	 * tHOLD_ATT > tCH
1486 	 * tHOLD_ATT > tCLH
1487 	 * tHOLD_ATT > tCOH
1488 	 * tHOLD_ATT > tDH
1489 	 * tHOLD_ATT > tWB + tIO + tSYNC - tSETUP_MEM
1490 	 * tHOLD_ATT > tADL - tSETUP_MEM
1491 	 * tHOLD_ATT > tWH - tSETUP_MEM
1492 	 * tHOLD_ATT > tWHR - tSETUP_MEM
1493 	 * tHOLD_ATT > tRC - (tSETUP_ATT + tWAIT)
1494 	 * tHOLD_ATT > tWC - (tSETUP_ATT + tWAIT)
1495 	 */
1496 	thold_att = max_t(unsigned long, hclkp, sdrt->tALH_min);
1497 	thold_att = max_t(unsigned long, thold_att, sdrt->tCH_min);
1498 	thold_att = max_t(unsigned long, thold_att, sdrt->tCLH_min);
1499 	thold_att = max_t(unsigned long, thold_att, sdrt->tCOH_min);
1500 	thold_att = max_t(unsigned long, thold_att, sdrt->tDH_min);
1501 	if ((sdrt->tWB_max + FMC2_TIO + FMC2_TSYNC > tset_mem) &&
1502 	    (thold_att < sdrt->tWB_max + FMC2_TIO + FMC2_TSYNC - tset_mem))
1503 		thold_att = sdrt->tWB_max + FMC2_TIO + FMC2_TSYNC - tset_mem;
1504 	if (sdrt->tADL_min > tset_mem &&
1505 	    (thold_att < sdrt->tADL_min - tset_mem))
1506 		thold_att = sdrt->tADL_min - tset_mem;
1507 	if (sdrt->tWH_min > tset_mem &&
1508 	    (thold_att < sdrt->tWH_min - tset_mem))
1509 		thold_att = sdrt->tWH_min - tset_mem;
1510 	if (sdrt->tWHR_min > tset_mem &&
1511 	    (thold_att < sdrt->tWHR_min - tset_mem))
1512 		thold_att = sdrt->tWHR_min - tset_mem;
1513 	if ((sdrt->tRC_min > tset_att + twait) &&
1514 	    (thold_att < sdrt->tRC_min - (tset_att + twait)))
1515 		thold_att = sdrt->tRC_min - (tset_att + twait);
1516 	if ((sdrt->tWC_min > tset_att + twait) &&
1517 	    (thold_att < sdrt->tWC_min - (tset_att + twait)))
1518 		thold_att = sdrt->tWC_min - (tset_att + twait);
1519 	timing = DIV_ROUND_UP(thold_att, hclkp);
1520 	tims->thold_att = clamp_val(timing, 1, FMC2_PMEM_PATT_TIMING_MASK);
1521 }
1522 
1523 static int stm32_fmc2_nfc_setup_interface(struct nand_chip *chip, int chipnr,
1524 					  const struct nand_interface_config *conf)
1525 {
1526 	const struct nand_sdr_timings *sdrt;
1527 
1528 	sdrt = nand_get_sdr_timings(conf);
1529 	if (IS_ERR(sdrt))
1530 		return PTR_ERR(sdrt);
1531 
1532 	if (chipnr == NAND_DATA_IFACE_CHECK_ONLY)
1533 		return 0;
1534 
1535 	stm32_fmc2_nfc_calc_timings(chip, sdrt);
1536 	stm32_fmc2_nfc_timings_init(chip);
1537 
1538 	return 0;
1539 }
1540 
1541 static int stm32_fmc2_nfc_dma_setup(struct stm32_fmc2_nfc *nfc)
1542 {
1543 	int ret = 0;
1544 
1545 	nfc->dma_tx_ch = dma_request_chan(nfc->dev, "tx");
1546 	if (IS_ERR(nfc->dma_tx_ch)) {
1547 		ret = PTR_ERR(nfc->dma_tx_ch);
1548 		if (ret != -ENODEV && ret != -EPROBE_DEFER)
1549 			dev_err(nfc->dev,
1550 				"failed to request tx DMA channel: %d\n", ret);
1551 		nfc->dma_tx_ch = NULL;
1552 		goto err_dma;
1553 	}
1554 
1555 	nfc->dma_rx_ch = dma_request_chan(nfc->dev, "rx");
1556 	if (IS_ERR(nfc->dma_rx_ch)) {
1557 		ret = PTR_ERR(nfc->dma_rx_ch);
1558 		if (ret != -ENODEV && ret != -EPROBE_DEFER)
1559 			dev_err(nfc->dev,
1560 				"failed to request rx DMA channel: %d\n", ret);
1561 		nfc->dma_rx_ch = NULL;
1562 		goto err_dma;
1563 	}
1564 
1565 	nfc->dma_ecc_ch = dma_request_chan(nfc->dev, "ecc");
1566 	if (IS_ERR(nfc->dma_ecc_ch)) {
1567 		ret = PTR_ERR(nfc->dma_ecc_ch);
1568 		if (ret != -ENODEV && ret != -EPROBE_DEFER)
1569 			dev_err(nfc->dev,
1570 				"failed to request ecc DMA channel: %d\n", ret);
1571 		nfc->dma_ecc_ch = NULL;
1572 		goto err_dma;
1573 	}
1574 
1575 	ret = sg_alloc_table(&nfc->dma_ecc_sg, FMC2_MAX_SG, GFP_KERNEL);
1576 	if (ret)
1577 		return ret;
1578 
1579 	/* Allocate a buffer to store ECC status registers */
1580 	nfc->ecc_buf = devm_kzalloc(nfc->dev, FMC2_MAX_ECC_BUF_LEN, GFP_KERNEL);
1581 	if (!nfc->ecc_buf)
1582 		return -ENOMEM;
1583 
1584 	ret = sg_alloc_table(&nfc->dma_data_sg, FMC2_MAX_SG, GFP_KERNEL);
1585 	if (ret)
1586 		return ret;
1587 
1588 	init_completion(&nfc->dma_data_complete);
1589 	init_completion(&nfc->dma_ecc_complete);
1590 
1591 	return 0;
1592 
1593 err_dma:
1594 	if (ret == -ENODEV) {
1595 		dev_warn(nfc->dev,
1596 			 "DMAs not defined in the DT, polling mode is used\n");
1597 		ret = 0;
1598 	}
1599 
1600 	return ret;
1601 }
1602 
1603 static void stm32_fmc2_nfc_nand_callbacks_setup(struct nand_chip *chip)
1604 {
1605 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1606 
1607 	/*
1608 	 * Specific callbacks to read/write a page depending on
1609 	 * the mode (polling/sequencer) and the algo used (Hamming, BCH).
1610 	 */
1611 	if (nfc->dma_tx_ch && nfc->dma_rx_ch && nfc->dma_ecc_ch) {
1612 		/* DMA => use sequencer mode callbacks */
1613 		chip->ecc.correct = stm32_fmc2_nfc_seq_correct;
1614 		chip->ecc.write_page = stm32_fmc2_nfc_seq_write_page;
1615 		chip->ecc.read_page = stm32_fmc2_nfc_seq_read_page;
1616 		chip->ecc.write_page_raw = stm32_fmc2_nfc_seq_write_page_raw;
1617 		chip->ecc.read_page_raw = stm32_fmc2_nfc_seq_read_page_raw;
1618 	} else {
1619 		/* No DMA => use polling mode callbacks */
1620 		chip->ecc.hwctl = stm32_fmc2_nfc_hwctl;
1621 		if (chip->ecc.strength == FMC2_ECC_HAM) {
1622 			/* Hamming is used */
1623 			chip->ecc.calculate = stm32_fmc2_nfc_ham_calculate;
1624 			chip->ecc.correct = stm32_fmc2_nfc_ham_correct;
1625 			chip->ecc.options |= NAND_ECC_GENERIC_ERASED_CHECK;
1626 		} else {
1627 			/* BCH is used */
1628 			chip->ecc.calculate = stm32_fmc2_nfc_bch_calculate;
1629 			chip->ecc.correct = stm32_fmc2_nfc_bch_correct;
1630 			chip->ecc.read_page = stm32_fmc2_nfc_read_page;
1631 		}
1632 	}
1633 
1634 	/* Specific configurations depending on the algo used */
1635 	if (chip->ecc.strength == FMC2_ECC_HAM)
1636 		chip->ecc.bytes = chip->options & NAND_BUSWIDTH_16 ? 4 : 3;
1637 	else if (chip->ecc.strength == FMC2_ECC_BCH8)
1638 		chip->ecc.bytes = chip->options & NAND_BUSWIDTH_16 ? 14 : 13;
1639 	else
1640 		chip->ecc.bytes = chip->options & NAND_BUSWIDTH_16 ? 8 : 7;
1641 }
1642 
1643 static int stm32_fmc2_nfc_ooblayout_ecc(struct mtd_info *mtd, int section,
1644 					struct mtd_oob_region *oobregion)
1645 {
1646 	struct nand_chip *chip = mtd_to_nand(mtd);
1647 	struct nand_ecc_ctrl *ecc = &chip->ecc;
1648 
1649 	if (section)
1650 		return -ERANGE;
1651 
1652 	oobregion->length = ecc->total;
1653 	oobregion->offset = FMC2_BBM_LEN;
1654 
1655 	return 0;
1656 }
1657 
1658 static int stm32_fmc2_nfc_ooblayout_free(struct mtd_info *mtd, int section,
1659 					 struct mtd_oob_region *oobregion)
1660 {
1661 	struct nand_chip *chip = mtd_to_nand(mtd);
1662 	struct nand_ecc_ctrl *ecc = &chip->ecc;
1663 
1664 	if (section)
1665 		return -ERANGE;
1666 
1667 	oobregion->length = mtd->oobsize - ecc->total - FMC2_BBM_LEN;
1668 	oobregion->offset = ecc->total + FMC2_BBM_LEN;
1669 
1670 	return 0;
1671 }
1672 
1673 static const struct mtd_ooblayout_ops stm32_fmc2_nfc_ooblayout_ops = {
1674 	.ecc = stm32_fmc2_nfc_ooblayout_ecc,
1675 	.free = stm32_fmc2_nfc_ooblayout_free,
1676 };
1677 
1678 static int stm32_fmc2_nfc_calc_ecc_bytes(int step_size, int strength)
1679 {
1680 	/* Hamming */
1681 	if (strength == FMC2_ECC_HAM)
1682 		return 4;
1683 
1684 	/* BCH8 */
1685 	if (strength == FMC2_ECC_BCH8)
1686 		return 14;
1687 
1688 	/* BCH4 */
1689 	return 8;
1690 }
1691 
1692 NAND_ECC_CAPS_SINGLE(stm32_fmc2_nfc_ecc_caps, stm32_fmc2_nfc_calc_ecc_bytes,
1693 		     FMC2_ECC_STEP_SIZE,
1694 		     FMC2_ECC_HAM, FMC2_ECC_BCH4, FMC2_ECC_BCH8);
1695 
1696 static int stm32_fmc2_nfc_attach_chip(struct nand_chip *chip)
1697 {
1698 	struct stm32_fmc2_nfc *nfc = to_stm32_nfc(chip->controller);
1699 	struct mtd_info *mtd = nand_to_mtd(chip);
1700 	int ret;
1701 
1702 	/*
1703 	 * Only NAND_ECC_ENGINE_TYPE_ON_HOST mode is actually supported
1704 	 * Hamming => ecc.strength = 1
1705 	 * BCH4 => ecc.strength = 4
1706 	 * BCH8 => ecc.strength = 8
1707 	 * ECC sector size = 512
1708 	 */
1709 	if (chip->ecc.engine_type != NAND_ECC_ENGINE_TYPE_ON_HOST) {
1710 		dev_err(nfc->dev,
1711 			"nand_ecc_engine_type is not well defined in the DT\n");
1712 		return -EINVAL;
1713 	}
1714 
1715 	/* Default ECC settings in case they are not set in the device tree */
1716 	if (!chip->ecc.size)
1717 		chip->ecc.size = FMC2_ECC_STEP_SIZE;
1718 
1719 	if (!chip->ecc.strength)
1720 		chip->ecc.strength = FMC2_ECC_BCH8;
1721 
1722 	ret = nand_ecc_choose_conf(chip, &stm32_fmc2_nfc_ecc_caps,
1723 				   mtd->oobsize - FMC2_BBM_LEN);
1724 	if (ret) {
1725 		dev_err(nfc->dev, "no valid ECC settings set\n");
1726 		return ret;
1727 	}
1728 
1729 	if (mtd->writesize / chip->ecc.size > FMC2_MAX_SG) {
1730 		dev_err(nfc->dev, "nand page size is not supported\n");
1731 		return -EINVAL;
1732 	}
1733 
1734 	if (chip->bbt_options & NAND_BBT_USE_FLASH)
1735 		chip->bbt_options |= NAND_BBT_NO_OOB;
1736 
1737 	stm32_fmc2_nfc_nand_callbacks_setup(chip);
1738 
1739 	mtd_set_ooblayout(mtd, &stm32_fmc2_nfc_ooblayout_ops);
1740 
1741 	stm32_fmc2_nfc_setup(chip);
1742 
1743 	return 0;
1744 }
1745 
1746 static const struct nand_controller_ops stm32_fmc2_nfc_controller_ops = {
1747 	.attach_chip = stm32_fmc2_nfc_attach_chip,
1748 	.exec_op = stm32_fmc2_nfc_exec_op,
1749 	.setup_interface = stm32_fmc2_nfc_setup_interface,
1750 };
1751 
1752 static void stm32_fmc2_nfc_wp_enable(struct stm32_fmc2_nand *nand)
1753 {
1754 	if (nand->wp_gpio)
1755 		gpiod_set_value(nand->wp_gpio, 1);
1756 }
1757 
1758 static void stm32_fmc2_nfc_wp_disable(struct stm32_fmc2_nand *nand)
1759 {
1760 	if (nand->wp_gpio)
1761 		gpiod_set_value(nand->wp_gpio, 0);
1762 }
1763 
1764 static int stm32_fmc2_nfc_parse_child(struct stm32_fmc2_nfc *nfc,
1765 				      struct device_node *dn)
1766 {
1767 	struct stm32_fmc2_nand *nand = &nfc->nand;
1768 	u32 cs;
1769 	int ret, i;
1770 
1771 	if (!of_get_property(dn, "reg", &nand->ncs))
1772 		return -EINVAL;
1773 
1774 	nand->ncs /= sizeof(u32);
1775 	if (!nand->ncs) {
1776 		dev_err(nfc->dev, "invalid reg property size\n");
1777 		return -EINVAL;
1778 	}
1779 
1780 	for (i = 0; i < nand->ncs; i++) {
1781 		ret = of_property_read_u32_index(dn, "reg", i, &cs);
1782 		if (ret) {
1783 			dev_err(nfc->dev, "could not retrieve reg property: %d\n",
1784 				ret);
1785 			return ret;
1786 		}
1787 
1788 		if (cs >= FMC2_MAX_CE) {
1789 			dev_err(nfc->dev, "invalid reg value: %d\n", cs);
1790 			return -EINVAL;
1791 		}
1792 
1793 		if (nfc->cs_assigned & BIT(cs)) {
1794 			dev_err(nfc->dev, "cs already assigned: %d\n", cs);
1795 			return -EINVAL;
1796 		}
1797 
1798 		nfc->cs_assigned |= BIT(cs);
1799 		nand->cs_used[i] = cs;
1800 	}
1801 
1802 	nand->wp_gpio = devm_gpiod_get_from_of_node(nfc->dev, dn,
1803 						    "wp-gpios", 0,
1804 						    GPIOD_OUT_HIGH, "wp");
1805 	if (IS_ERR(nand->wp_gpio)) {
1806 		ret = PTR_ERR(nand->wp_gpio);
1807 		if (ret != -ENOENT)
1808 			return dev_err_probe(nfc->dev, ret,
1809 					     "failed to request WP GPIO\n");
1810 
1811 		nand->wp_gpio = NULL;
1812 	}
1813 
1814 	nand_set_flash_node(&nand->chip, dn);
1815 
1816 	return 0;
1817 }
1818 
1819 static int stm32_fmc2_nfc_parse_dt(struct stm32_fmc2_nfc *nfc)
1820 {
1821 	struct device_node *dn = nfc->dev->of_node;
1822 	struct device_node *child;
1823 	int nchips = of_get_child_count(dn);
1824 	int ret = 0;
1825 
1826 	if (!nchips) {
1827 		dev_err(nfc->dev, "NAND chip not defined\n");
1828 		return -EINVAL;
1829 	}
1830 
1831 	if (nchips > 1) {
1832 		dev_err(nfc->dev, "too many NAND chips defined\n");
1833 		return -EINVAL;
1834 	}
1835 
1836 	for_each_child_of_node(dn, child) {
1837 		ret = stm32_fmc2_nfc_parse_child(nfc, child);
1838 		if (ret < 0) {
1839 			of_node_put(child);
1840 			return ret;
1841 		}
1842 	}
1843 
1844 	return ret;
1845 }
1846 
1847 static int stm32_fmc2_nfc_set_cdev(struct stm32_fmc2_nfc *nfc)
1848 {
1849 	struct device *dev = nfc->dev;
1850 	bool ebi_found = false;
1851 
1852 	if (dev->parent && of_device_is_compatible(dev->parent->of_node,
1853 						   "st,stm32mp1-fmc2-ebi"))
1854 		ebi_found = true;
1855 
1856 	if (of_device_is_compatible(dev->of_node, "st,stm32mp1-fmc2-nfc")) {
1857 		if (ebi_found) {
1858 			nfc->cdev = dev->parent;
1859 
1860 			return 0;
1861 		}
1862 
1863 		return -EINVAL;
1864 	}
1865 
1866 	if (ebi_found)
1867 		return -EINVAL;
1868 
1869 	nfc->cdev = dev;
1870 
1871 	return 0;
1872 }
1873 
1874 static int stm32_fmc2_nfc_probe(struct platform_device *pdev)
1875 {
1876 	struct device *dev = &pdev->dev;
1877 	struct reset_control *rstc;
1878 	struct stm32_fmc2_nfc *nfc;
1879 	struct stm32_fmc2_nand *nand;
1880 	struct resource *res;
1881 	struct mtd_info *mtd;
1882 	struct nand_chip *chip;
1883 	struct resource cres;
1884 	int chip_cs, mem_region, ret, irq;
1885 	int start_region = 0;
1886 
1887 	nfc = devm_kzalloc(dev, sizeof(*nfc), GFP_KERNEL);
1888 	if (!nfc)
1889 		return -ENOMEM;
1890 
1891 	nfc->dev = dev;
1892 	nand_controller_init(&nfc->base);
1893 	nfc->base.ops = &stm32_fmc2_nfc_controller_ops;
1894 
1895 	ret = stm32_fmc2_nfc_set_cdev(nfc);
1896 	if (ret)
1897 		return ret;
1898 
1899 	ret = stm32_fmc2_nfc_parse_dt(nfc);
1900 	if (ret)
1901 		return ret;
1902 
1903 	ret = of_address_to_resource(nfc->cdev->of_node, 0, &cres);
1904 	if (ret)
1905 		return ret;
1906 
1907 	nfc->io_phys_addr = cres.start;
1908 
1909 	nfc->regmap = device_node_to_regmap(nfc->cdev->of_node);
1910 	if (IS_ERR(nfc->regmap))
1911 		return PTR_ERR(nfc->regmap);
1912 
1913 	if (nfc->dev == nfc->cdev)
1914 		start_region = 1;
1915 
1916 	for (chip_cs = 0, mem_region = start_region; chip_cs < FMC2_MAX_CE;
1917 	     chip_cs++, mem_region += 3) {
1918 		if (!(nfc->cs_assigned & BIT(chip_cs)))
1919 			continue;
1920 
1921 		res = platform_get_resource(pdev, IORESOURCE_MEM, mem_region);
1922 		nfc->data_base[chip_cs] = devm_ioremap_resource(dev, res);
1923 		if (IS_ERR(nfc->data_base[chip_cs]))
1924 			return PTR_ERR(nfc->data_base[chip_cs]);
1925 
1926 		nfc->data_phys_addr[chip_cs] = res->start;
1927 
1928 		nfc->cmd_base[chip_cs] = devm_platform_ioremap_resource(pdev, mem_region + 1);
1929 		if (IS_ERR(nfc->cmd_base[chip_cs]))
1930 			return PTR_ERR(nfc->cmd_base[chip_cs]);
1931 
1932 		nfc->addr_base[chip_cs] = devm_platform_ioremap_resource(pdev, mem_region + 2);
1933 		if (IS_ERR(nfc->addr_base[chip_cs]))
1934 			return PTR_ERR(nfc->addr_base[chip_cs]);
1935 	}
1936 
1937 	irq = platform_get_irq(pdev, 0);
1938 	if (irq < 0)
1939 		return irq;
1940 
1941 	ret = devm_request_irq(dev, irq, stm32_fmc2_nfc_irq, 0,
1942 			       dev_name(dev), nfc);
1943 	if (ret) {
1944 		dev_err(dev, "failed to request irq\n");
1945 		return ret;
1946 	}
1947 
1948 	init_completion(&nfc->complete);
1949 
1950 	nfc->clk = devm_clk_get(nfc->cdev, NULL);
1951 	if (IS_ERR(nfc->clk))
1952 		return PTR_ERR(nfc->clk);
1953 
1954 	ret = clk_prepare_enable(nfc->clk);
1955 	if (ret) {
1956 		dev_err(dev, "can not enable the clock\n");
1957 		return ret;
1958 	}
1959 
1960 	rstc = devm_reset_control_get(dev, NULL);
1961 	if (IS_ERR(rstc)) {
1962 		ret = PTR_ERR(rstc);
1963 		if (ret == -EPROBE_DEFER)
1964 			goto err_clk_disable;
1965 	} else {
1966 		reset_control_assert(rstc);
1967 		reset_control_deassert(rstc);
1968 	}
1969 
1970 	ret = stm32_fmc2_nfc_dma_setup(nfc);
1971 	if (ret)
1972 		goto err_release_dma;
1973 
1974 	stm32_fmc2_nfc_init(nfc);
1975 
1976 	nand = &nfc->nand;
1977 	chip = &nand->chip;
1978 	mtd = nand_to_mtd(chip);
1979 	mtd->dev.parent = dev;
1980 
1981 	chip->controller = &nfc->base;
1982 	chip->options |= NAND_BUSWIDTH_AUTO | NAND_NO_SUBPAGE_WRITE |
1983 			 NAND_USES_DMA;
1984 
1985 	stm32_fmc2_nfc_wp_disable(nand);
1986 
1987 	/* Scan to find existence of the device */
1988 	ret = nand_scan(chip, nand->ncs);
1989 	if (ret)
1990 		goto err_wp_enable;
1991 
1992 	ret = mtd_device_register(mtd, NULL, 0);
1993 	if (ret)
1994 		goto err_nand_cleanup;
1995 
1996 	platform_set_drvdata(pdev, nfc);
1997 
1998 	return 0;
1999 
2000 err_nand_cleanup:
2001 	nand_cleanup(chip);
2002 
2003 err_wp_enable:
2004 	stm32_fmc2_nfc_wp_enable(nand);
2005 
2006 err_release_dma:
2007 	if (nfc->dma_ecc_ch)
2008 		dma_release_channel(nfc->dma_ecc_ch);
2009 	if (nfc->dma_tx_ch)
2010 		dma_release_channel(nfc->dma_tx_ch);
2011 	if (nfc->dma_rx_ch)
2012 		dma_release_channel(nfc->dma_rx_ch);
2013 
2014 	sg_free_table(&nfc->dma_data_sg);
2015 	sg_free_table(&nfc->dma_ecc_sg);
2016 
2017 err_clk_disable:
2018 	clk_disable_unprepare(nfc->clk);
2019 
2020 	return ret;
2021 }
2022 
2023 static int stm32_fmc2_nfc_remove(struct platform_device *pdev)
2024 {
2025 	struct stm32_fmc2_nfc *nfc = platform_get_drvdata(pdev);
2026 	struct stm32_fmc2_nand *nand = &nfc->nand;
2027 	struct nand_chip *chip = &nand->chip;
2028 	int ret;
2029 
2030 	ret = mtd_device_unregister(nand_to_mtd(chip));
2031 	WARN_ON(ret);
2032 	nand_cleanup(chip);
2033 
2034 	if (nfc->dma_ecc_ch)
2035 		dma_release_channel(nfc->dma_ecc_ch);
2036 	if (nfc->dma_tx_ch)
2037 		dma_release_channel(nfc->dma_tx_ch);
2038 	if (nfc->dma_rx_ch)
2039 		dma_release_channel(nfc->dma_rx_ch);
2040 
2041 	sg_free_table(&nfc->dma_data_sg);
2042 	sg_free_table(&nfc->dma_ecc_sg);
2043 
2044 	clk_disable_unprepare(nfc->clk);
2045 
2046 	stm32_fmc2_nfc_wp_enable(nand);
2047 
2048 	return 0;
2049 }
2050 
2051 static int __maybe_unused stm32_fmc2_nfc_suspend(struct device *dev)
2052 {
2053 	struct stm32_fmc2_nfc *nfc = dev_get_drvdata(dev);
2054 	struct stm32_fmc2_nand *nand = &nfc->nand;
2055 
2056 	clk_disable_unprepare(nfc->clk);
2057 
2058 	stm32_fmc2_nfc_wp_enable(nand);
2059 
2060 	pinctrl_pm_select_sleep_state(dev);
2061 
2062 	return 0;
2063 }
2064 
2065 static int __maybe_unused stm32_fmc2_nfc_resume(struct device *dev)
2066 {
2067 	struct stm32_fmc2_nfc *nfc = dev_get_drvdata(dev);
2068 	struct stm32_fmc2_nand *nand = &nfc->nand;
2069 	int chip_cs, ret;
2070 
2071 	pinctrl_pm_select_default_state(dev);
2072 
2073 	ret = clk_prepare_enable(nfc->clk);
2074 	if (ret) {
2075 		dev_err(dev, "can not enable the clock\n");
2076 		return ret;
2077 	}
2078 
2079 	stm32_fmc2_nfc_init(nfc);
2080 
2081 	stm32_fmc2_nfc_wp_disable(nand);
2082 
2083 	for (chip_cs = 0; chip_cs < FMC2_MAX_CE; chip_cs++) {
2084 		if (!(nfc->cs_assigned & BIT(chip_cs)))
2085 			continue;
2086 
2087 		nand_reset(&nand->chip, chip_cs);
2088 	}
2089 
2090 	return 0;
2091 }
2092 
2093 static SIMPLE_DEV_PM_OPS(stm32_fmc2_nfc_pm_ops, stm32_fmc2_nfc_suspend,
2094 			 stm32_fmc2_nfc_resume);
2095 
2096 static const struct of_device_id stm32_fmc2_nfc_match[] = {
2097 	{.compatible = "st,stm32mp15-fmc2"},
2098 	{.compatible = "st,stm32mp1-fmc2-nfc"},
2099 	{}
2100 };
2101 MODULE_DEVICE_TABLE(of, stm32_fmc2_nfc_match);
2102 
2103 static struct platform_driver stm32_fmc2_nfc_driver = {
2104 	.probe	= stm32_fmc2_nfc_probe,
2105 	.remove	= stm32_fmc2_nfc_remove,
2106 	.driver	= {
2107 		.name = "stm32_fmc2_nfc",
2108 		.of_match_table = stm32_fmc2_nfc_match,
2109 		.pm = &stm32_fmc2_nfc_pm_ops,
2110 	},
2111 };
2112 module_platform_driver(stm32_fmc2_nfc_driver);
2113 
2114 MODULE_ALIAS("platform:stm32_fmc2_nfc");
2115 MODULE_AUTHOR("Christophe Kerello <christophe.kerello@st.com>");
2116 MODULE_DESCRIPTION("STMicroelectronics STM32 FMC2 NFC driver");
2117 MODULE_LICENSE("GPL v2");
2118