1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright 2017 ATMEL
4  * Copyright 2017 Free Electrons
5  *
6  * Author: Boris Brezillon <boris.brezillon@free-electrons.com>
7  *
8  * Derived from the atmel_nand.c driver which contained the following
9  * copyrights:
10  *
11  *   Copyright 2003 Rick Bronson
12  *
13  *   Derived from drivers/mtd/nand/autcpu12.c (removed in v3.8)
14  *	Copyright 2001 Thomas Gleixner (gleixner@autronix.de)
15  *
16  *   Derived from drivers/mtd/spia.c (removed in v3.8)
17  *	Copyright 2000 Steven J. Hill (sjhill@cotw.com)
18  *
19  *
20  *   Add Hardware ECC support for AT91SAM9260 / AT91SAM9263
21  *	Richard Genoud (richard.genoud@gmail.com), Adeneo Copyright 2007
22  *
23  *   Derived from Das U-Boot source code
24  *	(u-boot-1.1.5/board/atmel/at91sam9263ek/nand.c)
25  *	Copyright 2006 ATMEL Rousset, Lacressonniere Nicolas
26  *
27  *   Add Programmable Multibit ECC support for various AT91 SoC
28  *	Copyright 2012 ATMEL, Hong Xu
29  *
30  *   Add Nand Flash Controller support for SAMA5 SoC
31  *	Copyright 2013 ATMEL, Josh Wu (josh.wu@atmel.com)
32  *
33  * A few words about the naming convention in this file. This convention
34  * applies to structure and function names.
35  *
36  * Prefixes:
37  *
38  * - atmel_nand_: all generic structures/functions
39  * - atmel_smc_nand_: all structures/functions specific to the SMC interface
40  *		      (at91sam9 and avr32 SoCs)
41  * - atmel_hsmc_nand_: all structures/functions specific to the HSMC interface
42  *		       (sama5 SoCs and later)
43  * - atmel_nfc_: all structures/functions used to manipulate the NFC sub-block
44  *		 that is available in the HSMC block
45  * - <soc>_nand_: all SoC specific structures/functions
46  */
47 
48 #include <linux/clk.h>
49 #include <linux/dma-mapping.h>
50 #include <linux/dmaengine.h>
51 #include <linux/genalloc.h>
52 #include <linux/gpio/consumer.h>
53 #include <linux/interrupt.h>
54 #include <linux/mfd/syscon.h>
55 #include <linux/mfd/syscon/atmel-matrix.h>
56 #include <linux/mfd/syscon/atmel-smc.h>
57 #include <linux/module.h>
58 #include <linux/mtd/rawnand.h>
59 #include <linux/of_address.h>
60 #include <linux/of_irq.h>
61 #include <linux/of_platform.h>
62 #include <linux/iopoll.h>
63 #include <linux/platform_device.h>
64 #include <linux/regmap.h>
65 #include <soc/at91/atmel-sfr.h>
66 
67 #include "pmecc.h"
68 
69 #define ATMEL_HSMC_NFC_CFG			0x0
70 #define ATMEL_HSMC_NFC_CFG_SPARESIZE(x)		(((x) / 4) << 24)
71 #define ATMEL_HSMC_NFC_CFG_SPARESIZE_MASK	GENMASK(30, 24)
72 #define ATMEL_HSMC_NFC_CFG_DTO(cyc, mul)	(((cyc) << 16) | ((mul) << 20))
73 #define ATMEL_HSMC_NFC_CFG_DTO_MAX		GENMASK(22, 16)
74 #define ATMEL_HSMC_NFC_CFG_RBEDGE		BIT(13)
75 #define ATMEL_HSMC_NFC_CFG_FALLING_EDGE		BIT(12)
76 #define ATMEL_HSMC_NFC_CFG_RSPARE		BIT(9)
77 #define ATMEL_HSMC_NFC_CFG_WSPARE		BIT(8)
78 #define ATMEL_HSMC_NFC_CFG_PAGESIZE_MASK	GENMASK(2, 0)
79 #define ATMEL_HSMC_NFC_CFG_PAGESIZE(x)		(fls((x) / 512) - 1)
80 
81 #define ATMEL_HSMC_NFC_CTRL			0x4
82 #define ATMEL_HSMC_NFC_CTRL_EN			BIT(0)
83 #define ATMEL_HSMC_NFC_CTRL_DIS			BIT(1)
84 
85 #define ATMEL_HSMC_NFC_SR			0x8
86 #define ATMEL_HSMC_NFC_IER			0xc
87 #define ATMEL_HSMC_NFC_IDR			0x10
88 #define ATMEL_HSMC_NFC_IMR			0x14
89 #define ATMEL_HSMC_NFC_SR_ENABLED		BIT(1)
90 #define ATMEL_HSMC_NFC_SR_RB_RISE		BIT(4)
91 #define ATMEL_HSMC_NFC_SR_RB_FALL		BIT(5)
92 #define ATMEL_HSMC_NFC_SR_BUSY			BIT(8)
93 #define ATMEL_HSMC_NFC_SR_WR			BIT(11)
94 #define ATMEL_HSMC_NFC_SR_CSID			GENMASK(14, 12)
95 #define ATMEL_HSMC_NFC_SR_XFRDONE		BIT(16)
96 #define ATMEL_HSMC_NFC_SR_CMDDONE		BIT(17)
97 #define ATMEL_HSMC_NFC_SR_DTOE			BIT(20)
98 #define ATMEL_HSMC_NFC_SR_UNDEF			BIT(21)
99 #define ATMEL_HSMC_NFC_SR_AWB			BIT(22)
100 #define ATMEL_HSMC_NFC_SR_NFCASE		BIT(23)
101 #define ATMEL_HSMC_NFC_SR_ERRORS		(ATMEL_HSMC_NFC_SR_DTOE | \
102 						 ATMEL_HSMC_NFC_SR_UNDEF | \
103 						 ATMEL_HSMC_NFC_SR_AWB | \
104 						 ATMEL_HSMC_NFC_SR_NFCASE)
105 #define ATMEL_HSMC_NFC_SR_RBEDGE(x)		BIT((x) + 24)
106 
107 #define ATMEL_HSMC_NFC_ADDR			0x18
108 #define ATMEL_HSMC_NFC_BANK			0x1c
109 
110 #define ATMEL_NFC_MAX_RB_ID			7
111 
112 #define ATMEL_NFC_SRAM_SIZE			0x2400
113 
114 #define ATMEL_NFC_CMD(pos, cmd)			((cmd) << (((pos) * 8) + 2))
115 #define ATMEL_NFC_VCMD2				BIT(18)
116 #define ATMEL_NFC_ACYCLE(naddrs)		((naddrs) << 19)
117 #define ATMEL_NFC_CSID(cs)			((cs) << 22)
118 #define ATMEL_NFC_DATAEN			BIT(25)
119 #define ATMEL_NFC_NFCWR				BIT(26)
120 
121 #define ATMEL_NFC_MAX_ADDR_CYCLES		5
122 
123 #define ATMEL_NAND_ALE_OFFSET			BIT(21)
124 #define ATMEL_NAND_CLE_OFFSET			BIT(22)
125 
126 #define DEFAULT_TIMEOUT_MS			1000
127 #define MIN_DMA_LEN				128
128 
129 static bool atmel_nand_avoid_dma __read_mostly;
130 
131 MODULE_PARM_DESC(avoiddma, "Avoid using DMA");
132 module_param_named(avoiddma, atmel_nand_avoid_dma, bool, 0400);
133 
134 enum atmel_nand_rb_type {
135 	ATMEL_NAND_NO_RB,
136 	ATMEL_NAND_NATIVE_RB,
137 	ATMEL_NAND_GPIO_RB,
138 };
139 
140 struct atmel_nand_rb {
141 	enum atmel_nand_rb_type type;
142 	union {
143 		struct gpio_desc *gpio;
144 		int id;
145 	};
146 };
147 
148 struct atmel_nand_cs {
149 	int id;
150 	struct atmel_nand_rb rb;
151 	struct gpio_desc *csgpio;
152 	struct {
153 		void __iomem *virt;
154 		dma_addr_t dma;
155 	} io;
156 
157 	struct atmel_smc_cs_conf smcconf;
158 };
159 
160 struct atmel_nand {
161 	struct list_head node;
162 	struct device *dev;
163 	struct nand_chip base;
164 	struct atmel_nand_cs *activecs;
165 	struct atmel_pmecc_user *pmecc;
166 	struct gpio_desc *cdgpio;
167 	int numcs;
168 	struct atmel_nand_cs cs[];
169 };
170 
171 static inline struct atmel_nand *to_atmel_nand(struct nand_chip *chip)
172 {
173 	return container_of(chip, struct atmel_nand, base);
174 }
175 
176 enum atmel_nfc_data_xfer {
177 	ATMEL_NFC_NO_DATA,
178 	ATMEL_NFC_READ_DATA,
179 	ATMEL_NFC_WRITE_DATA,
180 };
181 
182 struct atmel_nfc_op {
183 	u8 cs;
184 	u8 ncmds;
185 	u8 cmds[2];
186 	u8 naddrs;
187 	u8 addrs[5];
188 	enum atmel_nfc_data_xfer data;
189 	u32 wait;
190 	u32 errors;
191 };
192 
193 struct atmel_nand_controller;
194 struct atmel_nand_controller_caps;
195 
196 struct atmel_nand_controller_ops {
197 	int (*probe)(struct platform_device *pdev,
198 		     const struct atmel_nand_controller_caps *caps);
199 	int (*remove)(struct atmel_nand_controller *nc);
200 	void (*nand_init)(struct atmel_nand_controller *nc,
201 			  struct atmel_nand *nand);
202 	int (*ecc_init)(struct nand_chip *chip);
203 	int (*setup_interface)(struct atmel_nand *nand, int csline,
204 			       const struct nand_interface_config *conf);
205 	int (*exec_op)(struct atmel_nand *nand,
206 		       const struct nand_operation *op, bool check_only);
207 };
208 
209 struct atmel_nand_controller_caps {
210 	bool has_dma;
211 	bool legacy_of_bindings;
212 	u32 ale_offs;
213 	u32 cle_offs;
214 	const char *ebi_csa_regmap_name;
215 	const struct atmel_nand_controller_ops *ops;
216 };
217 
218 struct atmel_nand_controller {
219 	struct nand_controller base;
220 	const struct atmel_nand_controller_caps *caps;
221 	struct device *dev;
222 	struct regmap *smc;
223 	struct dma_chan *dmac;
224 	struct atmel_pmecc *pmecc;
225 	struct list_head chips;
226 	struct clk *mck;
227 };
228 
229 static inline struct atmel_nand_controller *
230 to_nand_controller(struct nand_controller *ctl)
231 {
232 	return container_of(ctl, struct atmel_nand_controller, base);
233 }
234 
235 struct atmel_smc_nand_ebi_csa_cfg {
236 	u32 offs;
237 	u32 nfd0_on_d16;
238 };
239 
240 struct atmel_smc_nand_controller {
241 	struct atmel_nand_controller base;
242 	struct regmap *ebi_csa_regmap;
243 	struct atmel_smc_nand_ebi_csa_cfg *ebi_csa;
244 };
245 
246 static inline struct atmel_smc_nand_controller *
247 to_smc_nand_controller(struct nand_controller *ctl)
248 {
249 	return container_of(to_nand_controller(ctl),
250 			    struct atmel_smc_nand_controller, base);
251 }
252 
253 struct atmel_hsmc_nand_controller {
254 	struct atmel_nand_controller base;
255 	struct {
256 		struct gen_pool *pool;
257 		void __iomem *virt;
258 		dma_addr_t dma;
259 	} sram;
260 	const struct atmel_hsmc_reg_layout *hsmc_layout;
261 	struct regmap *io;
262 	struct atmel_nfc_op op;
263 	struct completion complete;
264 	u32 cfg;
265 	int irq;
266 
267 	/* Only used when instantiating from legacy DT bindings. */
268 	struct clk *clk;
269 };
270 
271 static inline struct atmel_hsmc_nand_controller *
272 to_hsmc_nand_controller(struct nand_controller *ctl)
273 {
274 	return container_of(to_nand_controller(ctl),
275 			    struct atmel_hsmc_nand_controller, base);
276 }
277 
278 static bool atmel_nfc_op_done(struct atmel_nfc_op *op, u32 status)
279 {
280 	op->errors |= status & ATMEL_HSMC_NFC_SR_ERRORS;
281 	op->wait ^= status & op->wait;
282 
283 	return !op->wait || op->errors;
284 }
285 
286 static irqreturn_t atmel_nfc_interrupt(int irq, void *data)
287 {
288 	struct atmel_hsmc_nand_controller *nc = data;
289 	u32 sr, rcvd;
290 	bool done;
291 
292 	regmap_read(nc->base.smc, ATMEL_HSMC_NFC_SR, &sr);
293 
294 	rcvd = sr & (nc->op.wait | ATMEL_HSMC_NFC_SR_ERRORS);
295 	done = atmel_nfc_op_done(&nc->op, sr);
296 
297 	if (rcvd)
298 		regmap_write(nc->base.smc, ATMEL_HSMC_NFC_IDR, rcvd);
299 
300 	if (done)
301 		complete(&nc->complete);
302 
303 	return rcvd ? IRQ_HANDLED : IRQ_NONE;
304 }
305 
306 static int atmel_nfc_wait(struct atmel_hsmc_nand_controller *nc, bool poll,
307 			  unsigned int timeout_ms)
308 {
309 	int ret;
310 
311 	if (!timeout_ms)
312 		timeout_ms = DEFAULT_TIMEOUT_MS;
313 
314 	if (poll) {
315 		u32 status;
316 
317 		ret = regmap_read_poll_timeout(nc->base.smc,
318 					       ATMEL_HSMC_NFC_SR, status,
319 					       atmel_nfc_op_done(&nc->op,
320 								 status),
321 					       0, timeout_ms * 1000);
322 	} else {
323 		init_completion(&nc->complete);
324 		regmap_write(nc->base.smc, ATMEL_HSMC_NFC_IER,
325 			     nc->op.wait | ATMEL_HSMC_NFC_SR_ERRORS);
326 		ret = wait_for_completion_timeout(&nc->complete,
327 						msecs_to_jiffies(timeout_ms));
328 		if (!ret)
329 			ret = -ETIMEDOUT;
330 		else
331 			ret = 0;
332 
333 		regmap_write(nc->base.smc, ATMEL_HSMC_NFC_IDR, 0xffffffff);
334 	}
335 
336 	if (nc->op.errors & ATMEL_HSMC_NFC_SR_DTOE) {
337 		dev_err(nc->base.dev, "Waiting NAND R/B Timeout\n");
338 		ret = -ETIMEDOUT;
339 	}
340 
341 	if (nc->op.errors & ATMEL_HSMC_NFC_SR_UNDEF) {
342 		dev_err(nc->base.dev, "Access to an undefined area\n");
343 		ret = -EIO;
344 	}
345 
346 	if (nc->op.errors & ATMEL_HSMC_NFC_SR_AWB) {
347 		dev_err(nc->base.dev, "Access while busy\n");
348 		ret = -EIO;
349 	}
350 
351 	if (nc->op.errors & ATMEL_HSMC_NFC_SR_NFCASE) {
352 		dev_err(nc->base.dev, "Wrong access size\n");
353 		ret = -EIO;
354 	}
355 
356 	return ret;
357 }
358 
359 static void atmel_nand_dma_transfer_finished(void *data)
360 {
361 	struct completion *finished = data;
362 
363 	complete(finished);
364 }
365 
366 static int atmel_nand_dma_transfer(struct atmel_nand_controller *nc,
367 				   void *buf, dma_addr_t dev_dma, size_t len,
368 				   enum dma_data_direction dir)
369 {
370 	DECLARE_COMPLETION_ONSTACK(finished);
371 	dma_addr_t src_dma, dst_dma, buf_dma;
372 	struct dma_async_tx_descriptor *tx;
373 	dma_cookie_t cookie;
374 
375 	buf_dma = dma_map_single(nc->dev, buf, len, dir);
376 	if (dma_mapping_error(nc->dev, dev_dma)) {
377 		dev_err(nc->dev,
378 			"Failed to prepare a buffer for DMA access\n");
379 		goto err;
380 	}
381 
382 	if (dir == DMA_FROM_DEVICE) {
383 		src_dma = dev_dma;
384 		dst_dma = buf_dma;
385 	} else {
386 		src_dma = buf_dma;
387 		dst_dma = dev_dma;
388 	}
389 
390 	tx = dmaengine_prep_dma_memcpy(nc->dmac, dst_dma, src_dma, len,
391 				       DMA_CTRL_ACK | DMA_PREP_INTERRUPT);
392 	if (!tx) {
393 		dev_err(nc->dev, "Failed to prepare DMA memcpy\n");
394 		goto err_unmap;
395 	}
396 
397 	tx->callback = atmel_nand_dma_transfer_finished;
398 	tx->callback_param = &finished;
399 
400 	cookie = dmaengine_submit(tx);
401 	if (dma_submit_error(cookie)) {
402 		dev_err(nc->dev, "Failed to do DMA tx_submit\n");
403 		goto err_unmap;
404 	}
405 
406 	dma_async_issue_pending(nc->dmac);
407 	wait_for_completion(&finished);
408 
409 	return 0;
410 
411 err_unmap:
412 	dma_unmap_single(nc->dev, buf_dma, len, dir);
413 
414 err:
415 	dev_dbg(nc->dev, "Fall back to CPU I/O\n");
416 
417 	return -EIO;
418 }
419 
420 static int atmel_nfc_exec_op(struct atmel_hsmc_nand_controller *nc, bool poll)
421 {
422 	u8 *addrs = nc->op.addrs;
423 	unsigned int op = 0;
424 	u32 addr, val;
425 	int i, ret;
426 
427 	nc->op.wait = ATMEL_HSMC_NFC_SR_CMDDONE;
428 
429 	for (i = 0; i < nc->op.ncmds; i++)
430 		op |= ATMEL_NFC_CMD(i, nc->op.cmds[i]);
431 
432 	if (nc->op.naddrs == ATMEL_NFC_MAX_ADDR_CYCLES)
433 		regmap_write(nc->base.smc, ATMEL_HSMC_NFC_ADDR, *addrs++);
434 
435 	op |= ATMEL_NFC_CSID(nc->op.cs) |
436 	      ATMEL_NFC_ACYCLE(nc->op.naddrs);
437 
438 	if (nc->op.ncmds > 1)
439 		op |= ATMEL_NFC_VCMD2;
440 
441 	addr = addrs[0] | (addrs[1] << 8) | (addrs[2] << 16) |
442 	       (addrs[3] << 24);
443 
444 	if (nc->op.data != ATMEL_NFC_NO_DATA) {
445 		op |= ATMEL_NFC_DATAEN;
446 		nc->op.wait |= ATMEL_HSMC_NFC_SR_XFRDONE;
447 
448 		if (nc->op.data == ATMEL_NFC_WRITE_DATA)
449 			op |= ATMEL_NFC_NFCWR;
450 	}
451 
452 	/* Clear all flags. */
453 	regmap_read(nc->base.smc, ATMEL_HSMC_NFC_SR, &val);
454 
455 	/* Send the command. */
456 	regmap_write(nc->io, op, addr);
457 
458 	ret = atmel_nfc_wait(nc, poll, 0);
459 	if (ret)
460 		dev_err(nc->base.dev,
461 			"Failed to send NAND command (err = %d)!",
462 			ret);
463 
464 	/* Reset the op state. */
465 	memset(&nc->op, 0, sizeof(nc->op));
466 
467 	return ret;
468 }
469 
470 static void atmel_nand_data_in(struct atmel_nand *nand, void *buf,
471 			       unsigned int len, bool force_8bit)
472 {
473 	struct atmel_nand_controller *nc;
474 
475 	nc = to_nand_controller(nand->base.controller);
476 
477 	/*
478 	 * If the controller supports DMA, the buffer address is DMA-able and
479 	 * len is long enough to make DMA transfers profitable, let's trigger
480 	 * a DMA transfer. If it fails, fallback to PIO mode.
481 	 */
482 	if (nc->dmac && virt_addr_valid(buf) &&
483 	    len >= MIN_DMA_LEN && !force_8bit &&
484 	    !atmel_nand_dma_transfer(nc, buf, nand->activecs->io.dma, len,
485 				     DMA_FROM_DEVICE))
486 		return;
487 
488 	if ((nand->base.options & NAND_BUSWIDTH_16) && !force_8bit)
489 		ioread16_rep(nand->activecs->io.virt, buf, len / 2);
490 	else
491 		ioread8_rep(nand->activecs->io.virt, buf, len);
492 }
493 
494 static void atmel_nand_data_out(struct atmel_nand *nand, const void *buf,
495 				unsigned int len, bool force_8bit)
496 {
497 	struct atmel_nand_controller *nc;
498 
499 	nc = to_nand_controller(nand->base.controller);
500 
501 	/*
502 	 * If the controller supports DMA, the buffer address is DMA-able and
503 	 * len is long enough to make DMA transfers profitable, let's trigger
504 	 * a DMA transfer. If it fails, fallback to PIO mode.
505 	 */
506 	if (nc->dmac && virt_addr_valid(buf) &&
507 	    len >= MIN_DMA_LEN && !force_8bit &&
508 	    !atmel_nand_dma_transfer(nc, (void *)buf, nand->activecs->io.dma,
509 				     len, DMA_TO_DEVICE))
510 		return;
511 
512 	if ((nand->base.options & NAND_BUSWIDTH_16) && !force_8bit)
513 		iowrite16_rep(nand->activecs->io.virt, buf, len / 2);
514 	else
515 		iowrite8_rep(nand->activecs->io.virt, buf, len);
516 }
517 
518 static int atmel_nand_waitrdy(struct atmel_nand *nand, unsigned int timeout_ms)
519 {
520 	if (nand->activecs->rb.type == ATMEL_NAND_NO_RB)
521 		return nand_soft_waitrdy(&nand->base, timeout_ms);
522 
523 	return nand_gpio_waitrdy(&nand->base, nand->activecs->rb.gpio,
524 				 timeout_ms);
525 }
526 
527 static int atmel_hsmc_nand_waitrdy(struct atmel_nand *nand,
528 				   unsigned int timeout_ms)
529 {
530 	struct atmel_hsmc_nand_controller *nc;
531 	u32 status, mask;
532 
533 	if (nand->activecs->rb.type != ATMEL_NAND_NATIVE_RB)
534 		return atmel_nand_waitrdy(nand, timeout_ms);
535 
536 	nc = to_hsmc_nand_controller(nand->base.controller);
537 	mask = ATMEL_HSMC_NFC_SR_RBEDGE(nand->activecs->rb.id);
538 	return regmap_read_poll_timeout_atomic(nc->base.smc, ATMEL_HSMC_NFC_SR,
539 					       status, status & mask,
540 					       10, timeout_ms * 1000);
541 }
542 
543 static void atmel_nand_select_target(struct atmel_nand *nand,
544 				     unsigned int cs)
545 {
546 	nand->activecs = &nand->cs[cs];
547 }
548 
549 static void atmel_hsmc_nand_select_target(struct atmel_nand *nand,
550 					  unsigned int cs)
551 {
552 	struct mtd_info *mtd = nand_to_mtd(&nand->base);
553 	struct atmel_hsmc_nand_controller *nc;
554 	u32 cfg = ATMEL_HSMC_NFC_CFG_PAGESIZE(mtd->writesize) |
555 		  ATMEL_HSMC_NFC_CFG_SPARESIZE(mtd->oobsize) |
556 		  ATMEL_HSMC_NFC_CFG_RSPARE;
557 
558 	nand->activecs = &nand->cs[cs];
559 	nc = to_hsmc_nand_controller(nand->base.controller);
560 	if (nc->cfg == cfg)
561 		return;
562 
563 	regmap_update_bits(nc->base.smc, ATMEL_HSMC_NFC_CFG,
564 			   ATMEL_HSMC_NFC_CFG_PAGESIZE_MASK |
565 			   ATMEL_HSMC_NFC_CFG_SPARESIZE_MASK |
566 			   ATMEL_HSMC_NFC_CFG_RSPARE |
567 			   ATMEL_HSMC_NFC_CFG_WSPARE,
568 			   cfg);
569 	nc->cfg = cfg;
570 }
571 
572 static int atmel_smc_nand_exec_instr(struct atmel_nand *nand,
573 				     const struct nand_op_instr *instr)
574 {
575 	struct atmel_nand_controller *nc;
576 	unsigned int i;
577 
578 	nc = to_nand_controller(nand->base.controller);
579 	switch (instr->type) {
580 	case NAND_OP_CMD_INSTR:
581 		writeb(instr->ctx.cmd.opcode,
582 		       nand->activecs->io.virt + nc->caps->cle_offs);
583 		return 0;
584 	case NAND_OP_ADDR_INSTR:
585 		for (i = 0; i < instr->ctx.addr.naddrs; i++)
586 			writeb(instr->ctx.addr.addrs[i],
587 			       nand->activecs->io.virt + nc->caps->ale_offs);
588 		return 0;
589 	case NAND_OP_DATA_IN_INSTR:
590 		atmel_nand_data_in(nand, instr->ctx.data.buf.in,
591 				   instr->ctx.data.len,
592 				   instr->ctx.data.force_8bit);
593 		return 0;
594 	case NAND_OP_DATA_OUT_INSTR:
595 		atmel_nand_data_out(nand, instr->ctx.data.buf.out,
596 				    instr->ctx.data.len,
597 				    instr->ctx.data.force_8bit);
598 		return 0;
599 	case NAND_OP_WAITRDY_INSTR:
600 		return atmel_nand_waitrdy(nand,
601 					  instr->ctx.waitrdy.timeout_ms);
602 	default:
603 		break;
604 	}
605 
606 	return -EINVAL;
607 }
608 
609 static int atmel_smc_nand_exec_op(struct atmel_nand *nand,
610 				  const struct nand_operation *op,
611 				  bool check_only)
612 {
613 	unsigned int i;
614 	int ret = 0;
615 
616 	if (check_only)
617 		return 0;
618 
619 	atmel_nand_select_target(nand, op->cs);
620 	gpiod_set_value(nand->activecs->csgpio, 0);
621 	for (i = 0; i < op->ninstrs; i++) {
622 		ret = atmel_smc_nand_exec_instr(nand, &op->instrs[i]);
623 		if (ret)
624 			break;
625 	}
626 	gpiod_set_value(nand->activecs->csgpio, 1);
627 
628 	return ret;
629 }
630 
631 static int atmel_hsmc_exec_cmd_addr(struct nand_chip *chip,
632 				    const struct nand_subop *subop)
633 {
634 	struct atmel_nand *nand = to_atmel_nand(chip);
635 	struct atmel_hsmc_nand_controller *nc;
636 	unsigned int i, j;
637 
638 	nc = to_hsmc_nand_controller(chip->controller);
639 
640 	nc->op.cs = nand->activecs->id;
641 	for (i = 0; i < subop->ninstrs; i++) {
642 		const struct nand_op_instr *instr = &subop->instrs[i];
643 
644 		if (instr->type == NAND_OP_CMD_INSTR) {
645 			nc->op.cmds[nc->op.ncmds++] = instr->ctx.cmd.opcode;
646 			continue;
647 		}
648 
649 		for (j = nand_subop_get_addr_start_off(subop, i);
650 		     j < nand_subop_get_num_addr_cyc(subop, i); j++) {
651 			nc->op.addrs[nc->op.naddrs] = instr->ctx.addr.addrs[j];
652 			nc->op.naddrs++;
653 		}
654 	}
655 
656 	return atmel_nfc_exec_op(nc, true);
657 }
658 
659 static int atmel_hsmc_exec_rw(struct nand_chip *chip,
660 			      const struct nand_subop *subop)
661 {
662 	const struct nand_op_instr *instr = subop->instrs;
663 	struct atmel_nand *nand = to_atmel_nand(chip);
664 
665 	if (instr->type == NAND_OP_DATA_IN_INSTR)
666 		atmel_nand_data_in(nand, instr->ctx.data.buf.in,
667 				   instr->ctx.data.len,
668 				   instr->ctx.data.force_8bit);
669 	else
670 		atmel_nand_data_out(nand, instr->ctx.data.buf.out,
671 				    instr->ctx.data.len,
672 				    instr->ctx.data.force_8bit);
673 
674 	return 0;
675 }
676 
677 static int atmel_hsmc_exec_waitrdy(struct nand_chip *chip,
678 				   const struct nand_subop *subop)
679 {
680 	const struct nand_op_instr *instr = subop->instrs;
681 	struct atmel_nand *nand = to_atmel_nand(chip);
682 
683 	return atmel_hsmc_nand_waitrdy(nand, instr->ctx.waitrdy.timeout_ms);
684 }
685 
686 static const struct nand_op_parser atmel_hsmc_op_parser = NAND_OP_PARSER(
687 	NAND_OP_PARSER_PATTERN(atmel_hsmc_exec_cmd_addr,
688 		NAND_OP_PARSER_PAT_CMD_ELEM(true),
689 		NAND_OP_PARSER_PAT_ADDR_ELEM(true, 5),
690 		NAND_OP_PARSER_PAT_CMD_ELEM(true)),
691 	NAND_OP_PARSER_PATTERN(atmel_hsmc_exec_rw,
692 		NAND_OP_PARSER_PAT_DATA_IN_ELEM(false, 0)),
693 	NAND_OP_PARSER_PATTERN(atmel_hsmc_exec_rw,
694 		NAND_OP_PARSER_PAT_DATA_OUT_ELEM(false, 0)),
695 	NAND_OP_PARSER_PATTERN(atmel_hsmc_exec_waitrdy,
696 		NAND_OP_PARSER_PAT_WAITRDY_ELEM(false)),
697 );
698 
699 static int atmel_hsmc_nand_exec_op(struct atmel_nand *nand,
700 				   const struct nand_operation *op,
701 				   bool check_only)
702 {
703 	int ret;
704 
705 	if (check_only)
706 		return nand_op_parser_exec_op(&nand->base,
707 					      &atmel_hsmc_op_parser, op, true);
708 
709 	atmel_hsmc_nand_select_target(nand, op->cs);
710 	ret = nand_op_parser_exec_op(&nand->base, &atmel_hsmc_op_parser, op,
711 				     false);
712 
713 	return ret;
714 }
715 
716 static void atmel_nfc_copy_to_sram(struct nand_chip *chip, const u8 *buf,
717 				   bool oob_required)
718 {
719 	struct mtd_info *mtd = nand_to_mtd(chip);
720 	struct atmel_hsmc_nand_controller *nc;
721 	int ret = -EIO;
722 
723 	nc = to_hsmc_nand_controller(chip->controller);
724 
725 	if (nc->base.dmac)
726 		ret = atmel_nand_dma_transfer(&nc->base, (void *)buf,
727 					      nc->sram.dma, mtd->writesize,
728 					      DMA_TO_DEVICE);
729 
730 	/* Falling back to CPU copy. */
731 	if (ret)
732 		memcpy_toio(nc->sram.virt, buf, mtd->writesize);
733 
734 	if (oob_required)
735 		memcpy_toio(nc->sram.virt + mtd->writesize, chip->oob_poi,
736 			    mtd->oobsize);
737 }
738 
739 static void atmel_nfc_copy_from_sram(struct nand_chip *chip, u8 *buf,
740 				     bool oob_required)
741 {
742 	struct mtd_info *mtd = nand_to_mtd(chip);
743 	struct atmel_hsmc_nand_controller *nc;
744 	int ret = -EIO;
745 
746 	nc = to_hsmc_nand_controller(chip->controller);
747 
748 	if (nc->base.dmac)
749 		ret = atmel_nand_dma_transfer(&nc->base, buf, nc->sram.dma,
750 					      mtd->writesize, DMA_FROM_DEVICE);
751 
752 	/* Falling back to CPU copy. */
753 	if (ret)
754 		memcpy_fromio(buf, nc->sram.virt, mtd->writesize);
755 
756 	if (oob_required)
757 		memcpy_fromio(chip->oob_poi, nc->sram.virt + mtd->writesize,
758 			      mtd->oobsize);
759 }
760 
761 static void atmel_nfc_set_op_addr(struct nand_chip *chip, int page, int column)
762 {
763 	struct mtd_info *mtd = nand_to_mtd(chip);
764 	struct atmel_hsmc_nand_controller *nc;
765 
766 	nc = to_hsmc_nand_controller(chip->controller);
767 
768 	if (column >= 0) {
769 		nc->op.addrs[nc->op.naddrs++] = column;
770 
771 		/*
772 		 * 2 address cycles for the column offset on large page NANDs.
773 		 */
774 		if (mtd->writesize > 512)
775 			nc->op.addrs[nc->op.naddrs++] = column >> 8;
776 	}
777 
778 	if (page >= 0) {
779 		nc->op.addrs[nc->op.naddrs++] = page;
780 		nc->op.addrs[nc->op.naddrs++] = page >> 8;
781 
782 		if (chip->options & NAND_ROW_ADDR_3)
783 			nc->op.addrs[nc->op.naddrs++] = page >> 16;
784 	}
785 }
786 
787 static int atmel_nand_pmecc_enable(struct nand_chip *chip, int op, bool raw)
788 {
789 	struct atmel_nand *nand = to_atmel_nand(chip);
790 	struct atmel_nand_controller *nc;
791 	int ret;
792 
793 	nc = to_nand_controller(chip->controller);
794 
795 	if (raw)
796 		return 0;
797 
798 	ret = atmel_pmecc_enable(nand->pmecc, op);
799 	if (ret)
800 		dev_err(nc->dev,
801 			"Failed to enable ECC engine (err = %d)\n", ret);
802 
803 	return ret;
804 }
805 
806 static void atmel_nand_pmecc_disable(struct nand_chip *chip, bool raw)
807 {
808 	struct atmel_nand *nand = to_atmel_nand(chip);
809 
810 	if (!raw)
811 		atmel_pmecc_disable(nand->pmecc);
812 }
813 
814 static int atmel_nand_pmecc_generate_eccbytes(struct nand_chip *chip, bool raw)
815 {
816 	struct atmel_nand *nand = to_atmel_nand(chip);
817 	struct mtd_info *mtd = nand_to_mtd(chip);
818 	struct atmel_nand_controller *nc;
819 	struct mtd_oob_region oobregion;
820 	void *eccbuf;
821 	int ret, i;
822 
823 	nc = to_nand_controller(chip->controller);
824 
825 	if (raw)
826 		return 0;
827 
828 	ret = atmel_pmecc_wait_rdy(nand->pmecc);
829 	if (ret) {
830 		dev_err(nc->dev,
831 			"Failed to transfer NAND page data (err = %d)\n",
832 			ret);
833 		return ret;
834 	}
835 
836 	mtd_ooblayout_ecc(mtd, 0, &oobregion);
837 	eccbuf = chip->oob_poi + oobregion.offset;
838 
839 	for (i = 0; i < chip->ecc.steps; i++) {
840 		atmel_pmecc_get_generated_eccbytes(nand->pmecc, i,
841 						   eccbuf);
842 		eccbuf += chip->ecc.bytes;
843 	}
844 
845 	return 0;
846 }
847 
848 static int atmel_nand_pmecc_correct_data(struct nand_chip *chip, void *buf,
849 					 bool raw)
850 {
851 	struct atmel_nand *nand = to_atmel_nand(chip);
852 	struct mtd_info *mtd = nand_to_mtd(chip);
853 	struct atmel_nand_controller *nc;
854 	struct mtd_oob_region oobregion;
855 	int ret, i, max_bitflips = 0;
856 	void *databuf, *eccbuf;
857 
858 	nc = to_nand_controller(chip->controller);
859 
860 	if (raw)
861 		return 0;
862 
863 	ret = atmel_pmecc_wait_rdy(nand->pmecc);
864 	if (ret) {
865 		dev_err(nc->dev,
866 			"Failed to read NAND page data (err = %d)\n",
867 			ret);
868 		return ret;
869 	}
870 
871 	mtd_ooblayout_ecc(mtd, 0, &oobregion);
872 	eccbuf = chip->oob_poi + oobregion.offset;
873 	databuf = buf;
874 
875 	for (i = 0; i < chip->ecc.steps; i++) {
876 		ret = atmel_pmecc_correct_sector(nand->pmecc, i, databuf,
877 						 eccbuf);
878 		if (ret < 0 && !atmel_pmecc_correct_erased_chunks(nand->pmecc))
879 			ret = nand_check_erased_ecc_chunk(databuf,
880 							  chip->ecc.size,
881 							  eccbuf,
882 							  chip->ecc.bytes,
883 							  NULL, 0,
884 							  chip->ecc.strength);
885 
886 		if (ret >= 0) {
887 			mtd->ecc_stats.corrected += ret;
888 			max_bitflips = max(ret, max_bitflips);
889 		} else {
890 			mtd->ecc_stats.failed++;
891 		}
892 
893 		databuf += chip->ecc.size;
894 		eccbuf += chip->ecc.bytes;
895 	}
896 
897 	return max_bitflips;
898 }
899 
900 static int atmel_nand_pmecc_write_pg(struct nand_chip *chip, const u8 *buf,
901 				     bool oob_required, int page, bool raw)
902 {
903 	struct mtd_info *mtd = nand_to_mtd(chip);
904 	struct atmel_nand *nand = to_atmel_nand(chip);
905 	int ret;
906 
907 	nand_prog_page_begin_op(chip, page, 0, NULL, 0);
908 
909 	ret = atmel_nand_pmecc_enable(chip, NAND_ECC_WRITE, raw);
910 	if (ret)
911 		return ret;
912 
913 	nand_write_data_op(chip, buf, mtd->writesize, false);
914 
915 	ret = atmel_nand_pmecc_generate_eccbytes(chip, raw);
916 	if (ret) {
917 		atmel_pmecc_disable(nand->pmecc);
918 		return ret;
919 	}
920 
921 	atmel_nand_pmecc_disable(chip, raw);
922 
923 	nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
924 
925 	return nand_prog_page_end_op(chip);
926 }
927 
928 static int atmel_nand_pmecc_write_page(struct nand_chip *chip, const u8 *buf,
929 				       int oob_required, int page)
930 {
931 	return atmel_nand_pmecc_write_pg(chip, buf, oob_required, page, false);
932 }
933 
934 static int atmel_nand_pmecc_write_page_raw(struct nand_chip *chip,
935 					   const u8 *buf, int oob_required,
936 					   int page)
937 {
938 	return atmel_nand_pmecc_write_pg(chip, buf, oob_required, page, true);
939 }
940 
941 static int atmel_nand_pmecc_read_pg(struct nand_chip *chip, u8 *buf,
942 				    bool oob_required, int page, bool raw)
943 {
944 	struct mtd_info *mtd = nand_to_mtd(chip);
945 	int ret;
946 
947 	nand_read_page_op(chip, page, 0, NULL, 0);
948 
949 	ret = atmel_nand_pmecc_enable(chip, NAND_ECC_READ, raw);
950 	if (ret)
951 		return ret;
952 
953 	ret = nand_read_data_op(chip, buf, mtd->writesize, false, false);
954 	if (ret)
955 		goto out_disable;
956 
957 	ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false, false);
958 	if (ret)
959 		goto out_disable;
960 
961 	ret = atmel_nand_pmecc_correct_data(chip, buf, raw);
962 
963 out_disable:
964 	atmel_nand_pmecc_disable(chip, raw);
965 
966 	return ret;
967 }
968 
969 static int atmel_nand_pmecc_read_page(struct nand_chip *chip, u8 *buf,
970 				      int oob_required, int page)
971 {
972 	return atmel_nand_pmecc_read_pg(chip, buf, oob_required, page, false);
973 }
974 
975 static int atmel_nand_pmecc_read_page_raw(struct nand_chip *chip, u8 *buf,
976 					  int oob_required, int page)
977 {
978 	return atmel_nand_pmecc_read_pg(chip, buf, oob_required, page, true);
979 }
980 
981 static int atmel_hsmc_nand_pmecc_write_pg(struct nand_chip *chip,
982 					  const u8 *buf, bool oob_required,
983 					  int page, bool raw)
984 {
985 	struct mtd_info *mtd = nand_to_mtd(chip);
986 	struct atmel_nand *nand = to_atmel_nand(chip);
987 	struct atmel_hsmc_nand_controller *nc;
988 	int ret;
989 
990 	atmel_hsmc_nand_select_target(nand, chip->cur_cs);
991 	nc = to_hsmc_nand_controller(chip->controller);
992 
993 	atmel_nfc_copy_to_sram(chip, buf, false);
994 
995 	nc->op.cmds[0] = NAND_CMD_SEQIN;
996 	nc->op.ncmds = 1;
997 	atmel_nfc_set_op_addr(chip, page, 0x0);
998 	nc->op.cs = nand->activecs->id;
999 	nc->op.data = ATMEL_NFC_WRITE_DATA;
1000 
1001 	ret = atmel_nand_pmecc_enable(chip, NAND_ECC_WRITE, raw);
1002 	if (ret)
1003 		return ret;
1004 
1005 	ret = atmel_nfc_exec_op(nc, false);
1006 	if (ret) {
1007 		atmel_nand_pmecc_disable(chip, raw);
1008 		dev_err(nc->base.dev,
1009 			"Failed to transfer NAND page data (err = %d)\n",
1010 			ret);
1011 		return ret;
1012 	}
1013 
1014 	ret = atmel_nand_pmecc_generate_eccbytes(chip, raw);
1015 
1016 	atmel_nand_pmecc_disable(chip, raw);
1017 
1018 	if (ret)
1019 		return ret;
1020 
1021 	nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
1022 
1023 	return nand_prog_page_end_op(chip);
1024 }
1025 
1026 static int atmel_hsmc_nand_pmecc_write_page(struct nand_chip *chip,
1027 					    const u8 *buf, int oob_required,
1028 					    int page)
1029 {
1030 	return atmel_hsmc_nand_pmecc_write_pg(chip, buf, oob_required, page,
1031 					      false);
1032 }
1033 
1034 static int atmel_hsmc_nand_pmecc_write_page_raw(struct nand_chip *chip,
1035 						const u8 *buf,
1036 						int oob_required, int page)
1037 {
1038 	return atmel_hsmc_nand_pmecc_write_pg(chip, buf, oob_required, page,
1039 					      true);
1040 }
1041 
1042 static int atmel_hsmc_nand_pmecc_read_pg(struct nand_chip *chip, u8 *buf,
1043 					 bool oob_required, int page,
1044 					 bool raw)
1045 {
1046 	struct mtd_info *mtd = nand_to_mtd(chip);
1047 	struct atmel_nand *nand = to_atmel_nand(chip);
1048 	struct atmel_hsmc_nand_controller *nc;
1049 	int ret;
1050 
1051 	atmel_hsmc_nand_select_target(nand, chip->cur_cs);
1052 	nc = to_hsmc_nand_controller(chip->controller);
1053 
1054 	/*
1055 	 * Optimized read page accessors only work when the NAND R/B pin is
1056 	 * connected to a native SoC R/B pin. If that's not the case, fallback
1057 	 * to the non-optimized one.
1058 	 */
1059 	if (nand->activecs->rb.type != ATMEL_NAND_NATIVE_RB)
1060 		return atmel_nand_pmecc_read_pg(chip, buf, oob_required, page,
1061 						raw);
1062 
1063 	nc->op.cmds[nc->op.ncmds++] = NAND_CMD_READ0;
1064 
1065 	if (mtd->writesize > 512)
1066 		nc->op.cmds[nc->op.ncmds++] = NAND_CMD_READSTART;
1067 
1068 	atmel_nfc_set_op_addr(chip, page, 0x0);
1069 	nc->op.cs = nand->activecs->id;
1070 	nc->op.data = ATMEL_NFC_READ_DATA;
1071 
1072 	ret = atmel_nand_pmecc_enable(chip, NAND_ECC_READ, raw);
1073 	if (ret)
1074 		return ret;
1075 
1076 	ret = atmel_nfc_exec_op(nc, false);
1077 	if (ret) {
1078 		atmel_nand_pmecc_disable(chip, raw);
1079 		dev_err(nc->base.dev,
1080 			"Failed to load NAND page data (err = %d)\n",
1081 			ret);
1082 		return ret;
1083 	}
1084 
1085 	atmel_nfc_copy_from_sram(chip, buf, true);
1086 
1087 	ret = atmel_nand_pmecc_correct_data(chip, buf, raw);
1088 
1089 	atmel_nand_pmecc_disable(chip, raw);
1090 
1091 	return ret;
1092 }
1093 
1094 static int atmel_hsmc_nand_pmecc_read_page(struct nand_chip *chip, u8 *buf,
1095 					   int oob_required, int page)
1096 {
1097 	return atmel_hsmc_nand_pmecc_read_pg(chip, buf, oob_required, page,
1098 					     false);
1099 }
1100 
1101 static int atmel_hsmc_nand_pmecc_read_page_raw(struct nand_chip *chip,
1102 					       u8 *buf, int oob_required,
1103 					       int page)
1104 {
1105 	return atmel_hsmc_nand_pmecc_read_pg(chip, buf, oob_required, page,
1106 					     true);
1107 }
1108 
1109 static int atmel_nand_pmecc_init(struct nand_chip *chip)
1110 {
1111 	const struct nand_ecc_props *requirements =
1112 		nanddev_get_ecc_requirements(&chip->base);
1113 	struct mtd_info *mtd = nand_to_mtd(chip);
1114 	struct nand_device *nanddev = mtd_to_nanddev(mtd);
1115 	struct atmel_nand *nand = to_atmel_nand(chip);
1116 	struct atmel_nand_controller *nc;
1117 	struct atmel_pmecc_user_req req;
1118 
1119 	nc = to_nand_controller(chip->controller);
1120 
1121 	if (!nc->pmecc) {
1122 		dev_err(nc->dev, "HW ECC not supported\n");
1123 		return -ENOTSUPP;
1124 	}
1125 
1126 	if (nc->caps->legacy_of_bindings) {
1127 		u32 val;
1128 
1129 		if (!of_property_read_u32(nc->dev->of_node, "atmel,pmecc-cap",
1130 					  &val))
1131 			chip->ecc.strength = val;
1132 
1133 		if (!of_property_read_u32(nc->dev->of_node,
1134 					  "atmel,pmecc-sector-size",
1135 					  &val))
1136 			chip->ecc.size = val;
1137 	}
1138 
1139 	if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH)
1140 		req.ecc.strength = ATMEL_PMECC_MAXIMIZE_ECC_STRENGTH;
1141 	else if (chip->ecc.strength)
1142 		req.ecc.strength = chip->ecc.strength;
1143 	else if (requirements->strength)
1144 		req.ecc.strength = requirements->strength;
1145 	else
1146 		req.ecc.strength = ATMEL_PMECC_MAXIMIZE_ECC_STRENGTH;
1147 
1148 	if (chip->ecc.size)
1149 		req.ecc.sectorsize = chip->ecc.size;
1150 	else if (requirements->step_size)
1151 		req.ecc.sectorsize = requirements->step_size;
1152 	else
1153 		req.ecc.sectorsize = ATMEL_PMECC_SECTOR_SIZE_AUTO;
1154 
1155 	req.pagesize = mtd->writesize;
1156 	req.oobsize = mtd->oobsize;
1157 
1158 	if (mtd->writesize <= 512) {
1159 		req.ecc.bytes = 4;
1160 		req.ecc.ooboffset = 0;
1161 	} else {
1162 		req.ecc.bytes = mtd->oobsize - 2;
1163 		req.ecc.ooboffset = ATMEL_PMECC_OOBOFFSET_AUTO;
1164 	}
1165 
1166 	nand->pmecc = atmel_pmecc_create_user(nc->pmecc, &req);
1167 	if (IS_ERR(nand->pmecc))
1168 		return PTR_ERR(nand->pmecc);
1169 
1170 	chip->ecc.algo = NAND_ECC_ALGO_BCH;
1171 	chip->ecc.size = req.ecc.sectorsize;
1172 	chip->ecc.bytes = req.ecc.bytes / req.ecc.nsectors;
1173 	chip->ecc.strength = req.ecc.strength;
1174 
1175 	chip->options |= NAND_NO_SUBPAGE_WRITE;
1176 
1177 	mtd_set_ooblayout(mtd, nand_get_large_page_ooblayout());
1178 
1179 	return 0;
1180 }
1181 
1182 static int atmel_nand_ecc_init(struct nand_chip *chip)
1183 {
1184 	struct atmel_nand_controller *nc;
1185 	int ret;
1186 
1187 	nc = to_nand_controller(chip->controller);
1188 
1189 	switch (chip->ecc.engine_type) {
1190 	case NAND_ECC_ENGINE_TYPE_NONE:
1191 	case NAND_ECC_ENGINE_TYPE_SOFT:
1192 		/*
1193 		 * Nothing to do, the core will initialize everything for us.
1194 		 */
1195 		break;
1196 
1197 	case NAND_ECC_ENGINE_TYPE_ON_HOST:
1198 		ret = atmel_nand_pmecc_init(chip);
1199 		if (ret)
1200 			return ret;
1201 
1202 		chip->ecc.read_page = atmel_nand_pmecc_read_page;
1203 		chip->ecc.write_page = atmel_nand_pmecc_write_page;
1204 		chip->ecc.read_page_raw = atmel_nand_pmecc_read_page_raw;
1205 		chip->ecc.write_page_raw = atmel_nand_pmecc_write_page_raw;
1206 		break;
1207 
1208 	default:
1209 		/* Other modes are not supported. */
1210 		dev_err(nc->dev, "Unsupported ECC mode: %d\n",
1211 			chip->ecc.engine_type);
1212 		return -ENOTSUPP;
1213 	}
1214 
1215 	return 0;
1216 }
1217 
1218 static int atmel_hsmc_nand_ecc_init(struct nand_chip *chip)
1219 {
1220 	int ret;
1221 
1222 	ret = atmel_nand_ecc_init(chip);
1223 	if (ret)
1224 		return ret;
1225 
1226 	if (chip->ecc.engine_type != NAND_ECC_ENGINE_TYPE_ON_HOST)
1227 		return 0;
1228 
1229 	/* Adjust the ECC operations for the HSMC IP. */
1230 	chip->ecc.read_page = atmel_hsmc_nand_pmecc_read_page;
1231 	chip->ecc.write_page = atmel_hsmc_nand_pmecc_write_page;
1232 	chip->ecc.read_page_raw = atmel_hsmc_nand_pmecc_read_page_raw;
1233 	chip->ecc.write_page_raw = atmel_hsmc_nand_pmecc_write_page_raw;
1234 
1235 	return 0;
1236 }
1237 
1238 static int atmel_smc_nand_prepare_smcconf(struct atmel_nand *nand,
1239 					const struct nand_interface_config *conf,
1240 					struct atmel_smc_cs_conf *smcconf)
1241 {
1242 	u32 ncycles, totalcycles, timeps, mckperiodps;
1243 	struct atmel_nand_controller *nc;
1244 	int ret;
1245 
1246 	nc = to_nand_controller(nand->base.controller);
1247 
1248 	/* DDR interface not supported. */
1249 	if (conf->type != NAND_SDR_IFACE)
1250 		return -ENOTSUPP;
1251 
1252 	/*
1253 	 * tRC < 30ns implies EDO mode. This controller does not support this
1254 	 * mode.
1255 	 */
1256 	if (conf->timings.sdr.tRC_min < 30000)
1257 		return -ENOTSUPP;
1258 
1259 	atmel_smc_cs_conf_init(smcconf);
1260 
1261 	mckperiodps = NSEC_PER_SEC / clk_get_rate(nc->mck);
1262 	mckperiodps *= 1000;
1263 
1264 	/*
1265 	 * Set write pulse timing. This one is easy to extract:
1266 	 *
1267 	 * NWE_PULSE = tWP
1268 	 */
1269 	ncycles = DIV_ROUND_UP(conf->timings.sdr.tWP_min, mckperiodps);
1270 	totalcycles = ncycles;
1271 	ret = atmel_smc_cs_conf_set_pulse(smcconf, ATMEL_SMC_NWE_SHIFT,
1272 					  ncycles);
1273 	if (ret)
1274 		return ret;
1275 
1276 	/*
1277 	 * The write setup timing depends on the operation done on the NAND.
1278 	 * All operations goes through the same data bus, but the operation
1279 	 * type depends on the address we are writing to (ALE/CLE address
1280 	 * lines).
1281 	 * Since we have no way to differentiate the different operations at
1282 	 * the SMC level, we must consider the worst case (the biggest setup
1283 	 * time among all operation types):
1284 	 *
1285 	 * NWE_SETUP = max(tCLS, tCS, tALS, tDS) - NWE_PULSE
1286 	 */
1287 	timeps = max3(conf->timings.sdr.tCLS_min, conf->timings.sdr.tCS_min,
1288 		      conf->timings.sdr.tALS_min);
1289 	timeps = max(timeps, conf->timings.sdr.tDS_min);
1290 	ncycles = DIV_ROUND_UP(timeps, mckperiodps);
1291 	ncycles = ncycles > totalcycles ? ncycles - totalcycles : 0;
1292 	totalcycles += ncycles;
1293 	ret = atmel_smc_cs_conf_set_setup(smcconf, ATMEL_SMC_NWE_SHIFT,
1294 					  ncycles);
1295 	if (ret)
1296 		return ret;
1297 
1298 	/*
1299 	 * As for the write setup timing, the write hold timing depends on the
1300 	 * operation done on the NAND:
1301 	 *
1302 	 * NWE_HOLD = max(tCLH, tCH, tALH, tDH, tWH)
1303 	 */
1304 	timeps = max3(conf->timings.sdr.tCLH_min, conf->timings.sdr.tCH_min,
1305 		      conf->timings.sdr.tALH_min);
1306 	timeps = max3(timeps, conf->timings.sdr.tDH_min,
1307 		      conf->timings.sdr.tWH_min);
1308 	ncycles = DIV_ROUND_UP(timeps, mckperiodps);
1309 	totalcycles += ncycles;
1310 
1311 	/*
1312 	 * The write cycle timing is directly matching tWC, but is also
1313 	 * dependent on the other timings on the setup and hold timings we
1314 	 * calculated earlier, which gives:
1315 	 *
1316 	 * NWE_CYCLE = max(tWC, NWE_SETUP + NWE_PULSE + NWE_HOLD)
1317 	 */
1318 	ncycles = DIV_ROUND_UP(conf->timings.sdr.tWC_min, mckperiodps);
1319 	ncycles = max(totalcycles, ncycles);
1320 	ret = atmel_smc_cs_conf_set_cycle(smcconf, ATMEL_SMC_NWE_SHIFT,
1321 					  ncycles);
1322 	if (ret)
1323 		return ret;
1324 
1325 	/*
1326 	 * We don't want the CS line to be toggled between each byte/word
1327 	 * transfer to the NAND. The only way to guarantee that is to have the
1328 	 * NCS_{WR,RD}_{SETUP,HOLD} timings set to 0, which in turn means:
1329 	 *
1330 	 * NCS_WR_PULSE = NWE_CYCLE
1331 	 */
1332 	ret = atmel_smc_cs_conf_set_pulse(smcconf, ATMEL_SMC_NCS_WR_SHIFT,
1333 					  ncycles);
1334 	if (ret)
1335 		return ret;
1336 
1337 	/*
1338 	 * As for the write setup timing, the read hold timing depends on the
1339 	 * operation done on the NAND:
1340 	 *
1341 	 * NRD_HOLD = max(tREH, tRHOH)
1342 	 */
1343 	timeps = max(conf->timings.sdr.tREH_min, conf->timings.sdr.tRHOH_min);
1344 	ncycles = DIV_ROUND_UP(timeps, mckperiodps);
1345 	totalcycles = ncycles;
1346 
1347 	/*
1348 	 * TDF = tRHZ - NRD_HOLD
1349 	 */
1350 	ncycles = DIV_ROUND_UP(conf->timings.sdr.tRHZ_max, mckperiodps);
1351 	ncycles -= totalcycles;
1352 
1353 	/*
1354 	 * In ONFI 4.0 specs, tRHZ has been increased to support EDO NANDs and
1355 	 * we might end up with a config that does not fit in the TDF field.
1356 	 * Just take the max value in this case and hope that the NAND is more
1357 	 * tolerant than advertised.
1358 	 */
1359 	if (ncycles > ATMEL_SMC_MODE_TDF_MAX)
1360 		ncycles = ATMEL_SMC_MODE_TDF_MAX;
1361 	else if (ncycles < ATMEL_SMC_MODE_TDF_MIN)
1362 		ncycles = ATMEL_SMC_MODE_TDF_MIN;
1363 
1364 	smcconf->mode |= ATMEL_SMC_MODE_TDF(ncycles) |
1365 			 ATMEL_SMC_MODE_TDFMODE_OPTIMIZED;
1366 
1367 	/*
1368 	 * Read pulse timing directly matches tRP:
1369 	 *
1370 	 * NRD_PULSE = tRP
1371 	 */
1372 	ncycles = DIV_ROUND_UP(conf->timings.sdr.tRP_min, mckperiodps);
1373 	totalcycles += ncycles;
1374 	ret = atmel_smc_cs_conf_set_pulse(smcconf, ATMEL_SMC_NRD_SHIFT,
1375 					  ncycles);
1376 	if (ret)
1377 		return ret;
1378 
1379 	/*
1380 	 * The write cycle timing is directly matching tWC, but is also
1381 	 * dependent on the setup and hold timings we calculated earlier,
1382 	 * which gives:
1383 	 *
1384 	 * NRD_CYCLE = max(tRC, NRD_PULSE + NRD_HOLD)
1385 	 *
1386 	 * NRD_SETUP is always 0.
1387 	 */
1388 	ncycles = DIV_ROUND_UP(conf->timings.sdr.tRC_min, mckperiodps);
1389 	ncycles = max(totalcycles, ncycles);
1390 	ret = atmel_smc_cs_conf_set_cycle(smcconf, ATMEL_SMC_NRD_SHIFT,
1391 					  ncycles);
1392 	if (ret)
1393 		return ret;
1394 
1395 	/*
1396 	 * We don't want the CS line to be toggled between each byte/word
1397 	 * transfer from the NAND. The only way to guarantee that is to have
1398 	 * the NCS_{WR,RD}_{SETUP,HOLD} timings set to 0, which in turn means:
1399 	 *
1400 	 * NCS_RD_PULSE = NRD_CYCLE
1401 	 */
1402 	ret = atmel_smc_cs_conf_set_pulse(smcconf, ATMEL_SMC_NCS_RD_SHIFT,
1403 					  ncycles);
1404 	if (ret)
1405 		return ret;
1406 
1407 	/* Txxx timings are directly matching tXXX ones. */
1408 	ncycles = DIV_ROUND_UP(conf->timings.sdr.tCLR_min, mckperiodps);
1409 	ret = atmel_smc_cs_conf_set_timing(smcconf,
1410 					   ATMEL_HSMC_TIMINGS_TCLR_SHIFT,
1411 					   ncycles);
1412 	if (ret)
1413 		return ret;
1414 
1415 	ncycles = DIV_ROUND_UP(conf->timings.sdr.tADL_min, mckperiodps);
1416 	ret = atmel_smc_cs_conf_set_timing(smcconf,
1417 					   ATMEL_HSMC_TIMINGS_TADL_SHIFT,
1418 					   ncycles);
1419 	/*
1420 	 * Version 4 of the ONFI spec mandates that tADL be at least 400
1421 	 * nanoseconds, but, depending on the master clock rate, 400 ns may not
1422 	 * fit in the tADL field of the SMC reg. We need to relax the check and
1423 	 * accept the -ERANGE return code.
1424 	 *
1425 	 * Note that previous versions of the ONFI spec had a lower tADL_min
1426 	 * (100 or 200 ns). It's not clear why this timing constraint got
1427 	 * increased but it seems most NANDs are fine with values lower than
1428 	 * 400ns, so we should be safe.
1429 	 */
1430 	if (ret && ret != -ERANGE)
1431 		return ret;
1432 
1433 	ncycles = DIV_ROUND_UP(conf->timings.sdr.tAR_min, mckperiodps);
1434 	ret = atmel_smc_cs_conf_set_timing(smcconf,
1435 					   ATMEL_HSMC_TIMINGS_TAR_SHIFT,
1436 					   ncycles);
1437 	if (ret)
1438 		return ret;
1439 
1440 	ncycles = DIV_ROUND_UP(conf->timings.sdr.tRR_min, mckperiodps);
1441 	ret = atmel_smc_cs_conf_set_timing(smcconf,
1442 					   ATMEL_HSMC_TIMINGS_TRR_SHIFT,
1443 					   ncycles);
1444 	if (ret)
1445 		return ret;
1446 
1447 	ncycles = DIV_ROUND_UP(conf->timings.sdr.tWB_max, mckperiodps);
1448 	ret = atmel_smc_cs_conf_set_timing(smcconf,
1449 					   ATMEL_HSMC_TIMINGS_TWB_SHIFT,
1450 					   ncycles);
1451 	if (ret)
1452 		return ret;
1453 
1454 	/* Attach the CS line to the NFC logic. */
1455 	smcconf->timings |= ATMEL_HSMC_TIMINGS_NFSEL;
1456 
1457 	/* Set the appropriate data bus width. */
1458 	if (nand->base.options & NAND_BUSWIDTH_16)
1459 		smcconf->mode |= ATMEL_SMC_MODE_DBW_16;
1460 
1461 	/* Operate in NRD/NWE READ/WRITEMODE. */
1462 	smcconf->mode |= ATMEL_SMC_MODE_READMODE_NRD |
1463 			 ATMEL_SMC_MODE_WRITEMODE_NWE;
1464 
1465 	return 0;
1466 }
1467 
1468 static int atmel_smc_nand_setup_interface(struct atmel_nand *nand,
1469 					int csline,
1470 					const struct nand_interface_config *conf)
1471 {
1472 	struct atmel_nand_controller *nc;
1473 	struct atmel_smc_cs_conf smcconf;
1474 	struct atmel_nand_cs *cs;
1475 	int ret;
1476 
1477 	nc = to_nand_controller(nand->base.controller);
1478 
1479 	ret = atmel_smc_nand_prepare_smcconf(nand, conf, &smcconf);
1480 	if (ret)
1481 		return ret;
1482 
1483 	if (csline == NAND_DATA_IFACE_CHECK_ONLY)
1484 		return 0;
1485 
1486 	cs = &nand->cs[csline];
1487 	cs->smcconf = smcconf;
1488 	atmel_smc_cs_conf_apply(nc->smc, cs->id, &cs->smcconf);
1489 
1490 	return 0;
1491 }
1492 
1493 static int atmel_hsmc_nand_setup_interface(struct atmel_nand *nand,
1494 					int csline,
1495 					const struct nand_interface_config *conf)
1496 {
1497 	struct atmel_hsmc_nand_controller *nc;
1498 	struct atmel_smc_cs_conf smcconf;
1499 	struct atmel_nand_cs *cs;
1500 	int ret;
1501 
1502 	nc = to_hsmc_nand_controller(nand->base.controller);
1503 
1504 	ret = atmel_smc_nand_prepare_smcconf(nand, conf, &smcconf);
1505 	if (ret)
1506 		return ret;
1507 
1508 	if (csline == NAND_DATA_IFACE_CHECK_ONLY)
1509 		return 0;
1510 
1511 	cs = &nand->cs[csline];
1512 	cs->smcconf = smcconf;
1513 
1514 	if (cs->rb.type == ATMEL_NAND_NATIVE_RB)
1515 		cs->smcconf.timings |= ATMEL_HSMC_TIMINGS_RBNSEL(cs->rb.id);
1516 
1517 	atmel_hsmc_cs_conf_apply(nc->base.smc, nc->hsmc_layout, cs->id,
1518 				 &cs->smcconf);
1519 
1520 	return 0;
1521 }
1522 
1523 static int atmel_nand_setup_interface(struct nand_chip *chip, int csline,
1524 				      const struct nand_interface_config *conf)
1525 {
1526 	struct atmel_nand *nand = to_atmel_nand(chip);
1527 	struct atmel_nand_controller *nc;
1528 
1529 	nc = to_nand_controller(nand->base.controller);
1530 
1531 	if (csline >= nand->numcs ||
1532 	    (csline < 0 && csline != NAND_DATA_IFACE_CHECK_ONLY))
1533 		return -EINVAL;
1534 
1535 	return nc->caps->ops->setup_interface(nand, csline, conf);
1536 }
1537 
1538 static int atmel_nand_exec_op(struct nand_chip *chip,
1539 			      const struct nand_operation *op,
1540 			      bool check_only)
1541 {
1542 	struct atmel_nand *nand = to_atmel_nand(chip);
1543 	struct atmel_nand_controller *nc;
1544 
1545 	nc = to_nand_controller(nand->base.controller);
1546 
1547 	return nc->caps->ops->exec_op(nand, op, check_only);
1548 }
1549 
1550 static void atmel_nand_init(struct atmel_nand_controller *nc,
1551 			    struct atmel_nand *nand)
1552 {
1553 	struct nand_chip *chip = &nand->base;
1554 	struct mtd_info *mtd = nand_to_mtd(chip);
1555 
1556 	mtd->dev.parent = nc->dev;
1557 	nand->base.controller = &nc->base;
1558 
1559 	if (!nc->mck || !nc->caps->ops->setup_interface)
1560 		chip->options |= NAND_KEEP_TIMINGS;
1561 
1562 	/*
1563 	 * Use a bounce buffer when the buffer passed by the MTD user is not
1564 	 * suitable for DMA.
1565 	 */
1566 	if (nc->dmac)
1567 		chip->options |= NAND_USES_DMA;
1568 
1569 	/* Default to HW ECC if pmecc is available. */
1570 	if (nc->pmecc)
1571 		chip->ecc.engine_type = NAND_ECC_ENGINE_TYPE_ON_HOST;
1572 }
1573 
1574 static void atmel_smc_nand_init(struct atmel_nand_controller *nc,
1575 				struct atmel_nand *nand)
1576 {
1577 	struct nand_chip *chip = &nand->base;
1578 	struct atmel_smc_nand_controller *smc_nc;
1579 	int i;
1580 
1581 	atmel_nand_init(nc, nand);
1582 
1583 	smc_nc = to_smc_nand_controller(chip->controller);
1584 	if (!smc_nc->ebi_csa_regmap)
1585 		return;
1586 
1587 	/* Attach the CS to the NAND Flash logic. */
1588 	for (i = 0; i < nand->numcs; i++)
1589 		regmap_update_bits(smc_nc->ebi_csa_regmap,
1590 				   smc_nc->ebi_csa->offs,
1591 				   BIT(nand->cs[i].id), BIT(nand->cs[i].id));
1592 
1593 	if (smc_nc->ebi_csa->nfd0_on_d16)
1594 		regmap_update_bits(smc_nc->ebi_csa_regmap,
1595 				   smc_nc->ebi_csa->offs,
1596 				   smc_nc->ebi_csa->nfd0_on_d16,
1597 				   smc_nc->ebi_csa->nfd0_on_d16);
1598 }
1599 
1600 static int atmel_nand_controller_remove_nand(struct atmel_nand *nand)
1601 {
1602 	struct nand_chip *chip = &nand->base;
1603 	struct mtd_info *mtd = nand_to_mtd(chip);
1604 	int ret;
1605 
1606 	ret = mtd_device_unregister(mtd);
1607 	if (ret)
1608 		return ret;
1609 
1610 	nand_cleanup(chip);
1611 	list_del(&nand->node);
1612 
1613 	return 0;
1614 }
1615 
1616 static struct atmel_nand *atmel_nand_create(struct atmel_nand_controller *nc,
1617 					    struct device_node *np,
1618 					    int reg_cells)
1619 {
1620 	struct atmel_nand *nand;
1621 	struct gpio_desc *gpio;
1622 	int numcs, ret, i;
1623 
1624 	numcs = of_property_count_elems_of_size(np, "reg",
1625 						reg_cells * sizeof(u32));
1626 	if (numcs < 1) {
1627 		dev_err(nc->dev, "Missing or invalid reg property\n");
1628 		return ERR_PTR(-EINVAL);
1629 	}
1630 
1631 	nand = devm_kzalloc(nc->dev, struct_size(nand, cs, numcs), GFP_KERNEL);
1632 	if (!nand) {
1633 		dev_err(nc->dev, "Failed to allocate NAND object\n");
1634 		return ERR_PTR(-ENOMEM);
1635 	}
1636 
1637 	nand->numcs = numcs;
1638 
1639 	gpio = devm_fwnode_gpiod_get(nc->dev, of_fwnode_handle(np),
1640 				     "det", GPIOD_IN, "nand-det");
1641 	if (IS_ERR(gpio) && PTR_ERR(gpio) != -ENOENT) {
1642 		dev_err(nc->dev,
1643 			"Failed to get detect gpio (err = %ld)\n",
1644 			PTR_ERR(gpio));
1645 		return ERR_CAST(gpio);
1646 	}
1647 
1648 	if (!IS_ERR(gpio))
1649 		nand->cdgpio = gpio;
1650 
1651 	for (i = 0; i < numcs; i++) {
1652 		struct resource res;
1653 		u32 val;
1654 
1655 		ret = of_address_to_resource(np, 0, &res);
1656 		if (ret) {
1657 			dev_err(nc->dev, "Invalid reg property (err = %d)\n",
1658 				ret);
1659 			return ERR_PTR(ret);
1660 		}
1661 
1662 		ret = of_property_read_u32_index(np, "reg", i * reg_cells,
1663 						 &val);
1664 		if (ret) {
1665 			dev_err(nc->dev, "Invalid reg property (err = %d)\n",
1666 				ret);
1667 			return ERR_PTR(ret);
1668 		}
1669 
1670 		nand->cs[i].id = val;
1671 
1672 		nand->cs[i].io.dma = res.start;
1673 		nand->cs[i].io.virt = devm_ioremap_resource(nc->dev, &res);
1674 		if (IS_ERR(nand->cs[i].io.virt))
1675 			return ERR_CAST(nand->cs[i].io.virt);
1676 
1677 		if (!of_property_read_u32(np, "atmel,rb", &val)) {
1678 			if (val > ATMEL_NFC_MAX_RB_ID)
1679 				return ERR_PTR(-EINVAL);
1680 
1681 			nand->cs[i].rb.type = ATMEL_NAND_NATIVE_RB;
1682 			nand->cs[i].rb.id = val;
1683 		} else {
1684 			gpio = devm_fwnode_gpiod_get_index(nc->dev,
1685 							   of_fwnode_handle(np),
1686 							   "rb", i, GPIOD_IN,
1687 							   "nand-rb");
1688 			if (IS_ERR(gpio) && PTR_ERR(gpio) != -ENOENT) {
1689 				dev_err(nc->dev,
1690 					"Failed to get R/B gpio (err = %ld)\n",
1691 					PTR_ERR(gpio));
1692 				return ERR_CAST(gpio);
1693 			}
1694 
1695 			if (!IS_ERR(gpio)) {
1696 				nand->cs[i].rb.type = ATMEL_NAND_GPIO_RB;
1697 				nand->cs[i].rb.gpio = gpio;
1698 			}
1699 		}
1700 
1701 		gpio = devm_fwnode_gpiod_get_index(nc->dev,
1702 						   of_fwnode_handle(np),
1703 						   "cs", i, GPIOD_OUT_HIGH,
1704 						   "nand-cs");
1705 		if (IS_ERR(gpio) && PTR_ERR(gpio) != -ENOENT) {
1706 			dev_err(nc->dev,
1707 				"Failed to get CS gpio (err = %ld)\n",
1708 				PTR_ERR(gpio));
1709 			return ERR_CAST(gpio);
1710 		}
1711 
1712 		if (!IS_ERR(gpio))
1713 			nand->cs[i].csgpio = gpio;
1714 	}
1715 
1716 	nand_set_flash_node(&nand->base, np);
1717 
1718 	return nand;
1719 }
1720 
1721 static int
1722 atmel_nand_controller_add_nand(struct atmel_nand_controller *nc,
1723 			       struct atmel_nand *nand)
1724 {
1725 	struct nand_chip *chip = &nand->base;
1726 	struct mtd_info *mtd = nand_to_mtd(chip);
1727 	int ret;
1728 
1729 	/* No card inserted, skip this NAND. */
1730 	if (nand->cdgpio && gpiod_get_value(nand->cdgpio)) {
1731 		dev_info(nc->dev, "No SmartMedia card inserted.\n");
1732 		return 0;
1733 	}
1734 
1735 	nc->caps->ops->nand_init(nc, nand);
1736 
1737 	ret = nand_scan(chip, nand->numcs);
1738 	if (ret) {
1739 		dev_err(nc->dev, "NAND scan failed: %d\n", ret);
1740 		return ret;
1741 	}
1742 
1743 	ret = mtd_device_register(mtd, NULL, 0);
1744 	if (ret) {
1745 		dev_err(nc->dev, "Failed to register mtd device: %d\n", ret);
1746 		nand_cleanup(chip);
1747 		return ret;
1748 	}
1749 
1750 	list_add_tail(&nand->node, &nc->chips);
1751 
1752 	return 0;
1753 }
1754 
1755 static int
1756 atmel_nand_controller_remove_nands(struct atmel_nand_controller *nc)
1757 {
1758 	struct atmel_nand *nand, *tmp;
1759 	int ret;
1760 
1761 	list_for_each_entry_safe(nand, tmp, &nc->chips, node) {
1762 		ret = atmel_nand_controller_remove_nand(nand);
1763 		if (ret)
1764 			return ret;
1765 	}
1766 
1767 	return 0;
1768 }
1769 
1770 static int
1771 atmel_nand_controller_legacy_add_nands(struct atmel_nand_controller *nc)
1772 {
1773 	struct device *dev = nc->dev;
1774 	struct platform_device *pdev = to_platform_device(dev);
1775 	struct atmel_nand *nand;
1776 	struct gpio_desc *gpio;
1777 	struct resource *res;
1778 
1779 	/*
1780 	 * Legacy bindings only allow connecting a single NAND with a unique CS
1781 	 * line to the controller.
1782 	 */
1783 	nand = devm_kzalloc(nc->dev, sizeof(*nand) + sizeof(*nand->cs),
1784 			    GFP_KERNEL);
1785 	if (!nand)
1786 		return -ENOMEM;
1787 
1788 	nand->numcs = 1;
1789 
1790 	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1791 	nand->cs[0].io.virt = devm_ioremap_resource(dev, res);
1792 	if (IS_ERR(nand->cs[0].io.virt))
1793 		return PTR_ERR(nand->cs[0].io.virt);
1794 
1795 	nand->cs[0].io.dma = res->start;
1796 
1797 	/*
1798 	 * The old driver was hardcoding the CS id to 3 for all sama5
1799 	 * controllers. Since this id is only meaningful for the sama5
1800 	 * controller we can safely assign this id to 3 no matter the
1801 	 * controller.
1802 	 * If one wants to connect a NAND to a different CS line, he will
1803 	 * have to use the new bindings.
1804 	 */
1805 	nand->cs[0].id = 3;
1806 
1807 	/* R/B GPIO. */
1808 	gpio = devm_gpiod_get_index_optional(dev, NULL, 0,  GPIOD_IN);
1809 	if (IS_ERR(gpio)) {
1810 		dev_err(dev, "Failed to get R/B gpio (err = %ld)\n",
1811 			PTR_ERR(gpio));
1812 		return PTR_ERR(gpio);
1813 	}
1814 
1815 	if (gpio) {
1816 		nand->cs[0].rb.type = ATMEL_NAND_GPIO_RB;
1817 		nand->cs[0].rb.gpio = gpio;
1818 	}
1819 
1820 	/* CS GPIO. */
1821 	gpio = devm_gpiod_get_index_optional(dev, NULL, 1, GPIOD_OUT_HIGH);
1822 	if (IS_ERR(gpio)) {
1823 		dev_err(dev, "Failed to get CS gpio (err = %ld)\n",
1824 			PTR_ERR(gpio));
1825 		return PTR_ERR(gpio);
1826 	}
1827 
1828 	nand->cs[0].csgpio = gpio;
1829 
1830 	/* Card detect GPIO. */
1831 	gpio = devm_gpiod_get_index_optional(nc->dev, NULL, 2, GPIOD_IN);
1832 	if (IS_ERR(gpio)) {
1833 		dev_err(dev,
1834 			"Failed to get detect gpio (err = %ld)\n",
1835 			PTR_ERR(gpio));
1836 		return PTR_ERR(gpio);
1837 	}
1838 
1839 	nand->cdgpio = gpio;
1840 
1841 	nand_set_flash_node(&nand->base, nc->dev->of_node);
1842 
1843 	return atmel_nand_controller_add_nand(nc, nand);
1844 }
1845 
1846 static int atmel_nand_controller_add_nands(struct atmel_nand_controller *nc)
1847 {
1848 	struct device_node *np, *nand_np;
1849 	struct device *dev = nc->dev;
1850 	int ret, reg_cells;
1851 	u32 val;
1852 
1853 	/* We do not retrieve the SMC syscon when parsing old DTs. */
1854 	if (nc->caps->legacy_of_bindings)
1855 		return atmel_nand_controller_legacy_add_nands(nc);
1856 
1857 	np = dev->of_node;
1858 
1859 	ret = of_property_read_u32(np, "#address-cells", &val);
1860 	if (ret) {
1861 		dev_err(dev, "missing #address-cells property\n");
1862 		return ret;
1863 	}
1864 
1865 	reg_cells = val;
1866 
1867 	ret = of_property_read_u32(np, "#size-cells", &val);
1868 	if (ret) {
1869 		dev_err(dev, "missing #size-cells property\n");
1870 		return ret;
1871 	}
1872 
1873 	reg_cells += val;
1874 
1875 	for_each_child_of_node(np, nand_np) {
1876 		struct atmel_nand *nand;
1877 
1878 		nand = atmel_nand_create(nc, nand_np, reg_cells);
1879 		if (IS_ERR(nand)) {
1880 			ret = PTR_ERR(nand);
1881 			goto err;
1882 		}
1883 
1884 		ret = atmel_nand_controller_add_nand(nc, nand);
1885 		if (ret)
1886 			goto err;
1887 	}
1888 
1889 	return 0;
1890 
1891 err:
1892 	atmel_nand_controller_remove_nands(nc);
1893 
1894 	return ret;
1895 }
1896 
1897 static void atmel_nand_controller_cleanup(struct atmel_nand_controller *nc)
1898 {
1899 	if (nc->dmac)
1900 		dma_release_channel(nc->dmac);
1901 
1902 	clk_put(nc->mck);
1903 }
1904 
1905 static const struct atmel_smc_nand_ebi_csa_cfg at91sam9260_ebi_csa = {
1906 	.offs = AT91SAM9260_MATRIX_EBICSA,
1907 };
1908 
1909 static const struct atmel_smc_nand_ebi_csa_cfg at91sam9261_ebi_csa = {
1910 	.offs = AT91SAM9261_MATRIX_EBICSA,
1911 };
1912 
1913 static const struct atmel_smc_nand_ebi_csa_cfg at91sam9263_ebi_csa = {
1914 	.offs = AT91SAM9263_MATRIX_EBI0CSA,
1915 };
1916 
1917 static const struct atmel_smc_nand_ebi_csa_cfg at91sam9rl_ebi_csa = {
1918 	.offs = AT91SAM9RL_MATRIX_EBICSA,
1919 };
1920 
1921 static const struct atmel_smc_nand_ebi_csa_cfg at91sam9g45_ebi_csa = {
1922 	.offs = AT91SAM9G45_MATRIX_EBICSA,
1923 };
1924 
1925 static const struct atmel_smc_nand_ebi_csa_cfg at91sam9n12_ebi_csa = {
1926 	.offs = AT91SAM9N12_MATRIX_EBICSA,
1927 };
1928 
1929 static const struct atmel_smc_nand_ebi_csa_cfg at91sam9x5_ebi_csa = {
1930 	.offs = AT91SAM9X5_MATRIX_EBICSA,
1931 };
1932 
1933 static const struct atmel_smc_nand_ebi_csa_cfg sam9x60_ebi_csa = {
1934 	.offs = AT91_SFR_CCFG_EBICSA,
1935 	.nfd0_on_d16 = AT91_SFR_CCFG_NFD0_ON_D16,
1936 };
1937 
1938 static const struct of_device_id atmel_ebi_csa_regmap_of_ids[] = {
1939 	{
1940 		.compatible = "atmel,at91sam9260-matrix",
1941 		.data = &at91sam9260_ebi_csa,
1942 	},
1943 	{
1944 		.compatible = "atmel,at91sam9261-matrix",
1945 		.data = &at91sam9261_ebi_csa,
1946 	},
1947 	{
1948 		.compatible = "atmel,at91sam9263-matrix",
1949 		.data = &at91sam9263_ebi_csa,
1950 	},
1951 	{
1952 		.compatible = "atmel,at91sam9rl-matrix",
1953 		.data = &at91sam9rl_ebi_csa,
1954 	},
1955 	{
1956 		.compatible = "atmel,at91sam9g45-matrix",
1957 		.data = &at91sam9g45_ebi_csa,
1958 	},
1959 	{
1960 		.compatible = "atmel,at91sam9n12-matrix",
1961 		.data = &at91sam9n12_ebi_csa,
1962 	},
1963 	{
1964 		.compatible = "atmel,at91sam9x5-matrix",
1965 		.data = &at91sam9x5_ebi_csa,
1966 	},
1967 	{
1968 		.compatible = "microchip,sam9x60-sfr",
1969 		.data = &sam9x60_ebi_csa,
1970 	},
1971 	{ /* sentinel */ },
1972 };
1973 
1974 static int atmel_nand_attach_chip(struct nand_chip *chip)
1975 {
1976 	struct atmel_nand_controller *nc = to_nand_controller(chip->controller);
1977 	struct atmel_nand *nand = to_atmel_nand(chip);
1978 	struct mtd_info *mtd = nand_to_mtd(chip);
1979 	int ret;
1980 
1981 	ret = nc->caps->ops->ecc_init(chip);
1982 	if (ret)
1983 		return ret;
1984 
1985 	if (nc->caps->legacy_of_bindings || !nc->dev->of_node) {
1986 		/*
1987 		 * We keep the MTD name unchanged to avoid breaking platforms
1988 		 * where the MTD cmdline parser is used and the bootloader
1989 		 * has not been updated to use the new naming scheme.
1990 		 */
1991 		mtd->name = "atmel_nand";
1992 	} else if (!mtd->name) {
1993 		/*
1994 		 * If the new bindings are used and the bootloader has not been
1995 		 * updated to pass a new mtdparts parameter on the cmdline, you
1996 		 * should define the following property in your nand node:
1997 		 *
1998 		 *	label = "atmel_nand";
1999 		 *
2000 		 * This way, mtd->name will be set by the core when
2001 		 * nand_set_flash_node() is called.
2002 		 */
2003 		mtd->name = devm_kasprintf(nc->dev, GFP_KERNEL,
2004 					   "%s:nand.%d", dev_name(nc->dev),
2005 					   nand->cs[0].id);
2006 		if (!mtd->name) {
2007 			dev_err(nc->dev, "Failed to allocate mtd->name\n");
2008 			return -ENOMEM;
2009 		}
2010 	}
2011 
2012 	return 0;
2013 }
2014 
2015 static const struct nand_controller_ops atmel_nand_controller_ops = {
2016 	.attach_chip = atmel_nand_attach_chip,
2017 	.setup_interface = atmel_nand_setup_interface,
2018 	.exec_op = atmel_nand_exec_op,
2019 };
2020 
2021 static int atmel_nand_controller_init(struct atmel_nand_controller *nc,
2022 				struct platform_device *pdev,
2023 				const struct atmel_nand_controller_caps *caps)
2024 {
2025 	struct device *dev = &pdev->dev;
2026 	struct device_node *np = dev->of_node;
2027 	int ret;
2028 
2029 	nand_controller_init(&nc->base);
2030 	nc->base.ops = &atmel_nand_controller_ops;
2031 	INIT_LIST_HEAD(&nc->chips);
2032 	nc->dev = dev;
2033 	nc->caps = caps;
2034 
2035 	platform_set_drvdata(pdev, nc);
2036 
2037 	nc->pmecc = devm_atmel_pmecc_get(dev);
2038 	if (IS_ERR(nc->pmecc))
2039 		return dev_err_probe(dev, PTR_ERR(nc->pmecc),
2040 				     "Could not get PMECC object\n");
2041 
2042 	if (nc->caps->has_dma && !atmel_nand_avoid_dma) {
2043 		dma_cap_mask_t mask;
2044 
2045 		dma_cap_zero(mask);
2046 		dma_cap_set(DMA_MEMCPY, mask);
2047 
2048 		nc->dmac = dma_request_channel(mask, NULL, NULL);
2049 		if (!nc->dmac)
2050 			dev_err(nc->dev, "Failed to request DMA channel\n");
2051 	}
2052 
2053 	/* We do not retrieve the SMC syscon when parsing old DTs. */
2054 	if (nc->caps->legacy_of_bindings)
2055 		return 0;
2056 
2057 	nc->mck = of_clk_get(dev->parent->of_node, 0);
2058 	if (IS_ERR(nc->mck)) {
2059 		dev_err(dev, "Failed to retrieve MCK clk\n");
2060 		return PTR_ERR(nc->mck);
2061 	}
2062 
2063 	np = of_parse_phandle(dev->parent->of_node, "atmel,smc", 0);
2064 	if (!np) {
2065 		dev_err(dev, "Missing or invalid atmel,smc property\n");
2066 		return -EINVAL;
2067 	}
2068 
2069 	nc->smc = syscon_node_to_regmap(np);
2070 	of_node_put(np);
2071 	if (IS_ERR(nc->smc)) {
2072 		ret = PTR_ERR(nc->smc);
2073 		dev_err(dev, "Could not get SMC regmap (err = %d)\n", ret);
2074 		return ret;
2075 	}
2076 
2077 	return 0;
2078 }
2079 
2080 static int
2081 atmel_smc_nand_controller_init(struct atmel_smc_nand_controller *nc)
2082 {
2083 	struct device *dev = nc->base.dev;
2084 	const struct of_device_id *match;
2085 	struct device_node *np;
2086 	int ret;
2087 
2088 	/* We do not retrieve the EBICSA regmap when parsing old DTs. */
2089 	if (nc->base.caps->legacy_of_bindings)
2090 		return 0;
2091 
2092 	np = of_parse_phandle(dev->parent->of_node,
2093 			      nc->base.caps->ebi_csa_regmap_name, 0);
2094 	if (!np)
2095 		return 0;
2096 
2097 	match = of_match_node(atmel_ebi_csa_regmap_of_ids, np);
2098 	if (!match) {
2099 		of_node_put(np);
2100 		return 0;
2101 	}
2102 
2103 	nc->ebi_csa_regmap = syscon_node_to_regmap(np);
2104 	of_node_put(np);
2105 	if (IS_ERR(nc->ebi_csa_regmap)) {
2106 		ret = PTR_ERR(nc->ebi_csa_regmap);
2107 		dev_err(dev, "Could not get EBICSA regmap (err = %d)\n", ret);
2108 		return ret;
2109 	}
2110 
2111 	nc->ebi_csa = (struct atmel_smc_nand_ebi_csa_cfg *)match->data;
2112 
2113 	/*
2114 	 * The at91sam9263 has 2 EBIs, if the NAND controller is under EBI1
2115 	 * add 4 to ->ebi_csa->offs.
2116 	 */
2117 	if (of_device_is_compatible(dev->parent->of_node,
2118 				    "atmel,at91sam9263-ebi1"))
2119 		nc->ebi_csa->offs += 4;
2120 
2121 	return 0;
2122 }
2123 
2124 static int
2125 atmel_hsmc_nand_controller_legacy_init(struct atmel_hsmc_nand_controller *nc)
2126 {
2127 	struct regmap_config regmap_conf = {
2128 		.reg_bits = 32,
2129 		.val_bits = 32,
2130 		.reg_stride = 4,
2131 	};
2132 
2133 	struct device *dev = nc->base.dev;
2134 	struct device_node *nand_np, *nfc_np;
2135 	void __iomem *iomem;
2136 	struct resource res;
2137 	int ret;
2138 
2139 	nand_np = dev->of_node;
2140 	nfc_np = of_get_compatible_child(dev->of_node, "atmel,sama5d3-nfc");
2141 	if (!nfc_np) {
2142 		dev_err(dev, "Could not find device node for sama5d3-nfc\n");
2143 		return -ENODEV;
2144 	}
2145 
2146 	nc->clk = of_clk_get(nfc_np, 0);
2147 	if (IS_ERR(nc->clk)) {
2148 		ret = PTR_ERR(nc->clk);
2149 		dev_err(dev, "Failed to retrieve HSMC clock (err = %d)\n",
2150 			ret);
2151 		goto out;
2152 	}
2153 
2154 	ret = clk_prepare_enable(nc->clk);
2155 	if (ret) {
2156 		dev_err(dev, "Failed to enable the HSMC clock (err = %d)\n",
2157 			ret);
2158 		goto out;
2159 	}
2160 
2161 	nc->irq = of_irq_get(nand_np, 0);
2162 	if (nc->irq <= 0) {
2163 		ret = nc->irq ?: -ENXIO;
2164 		if (ret != -EPROBE_DEFER)
2165 			dev_err(dev, "Failed to get IRQ number (err = %d)\n",
2166 				ret);
2167 		goto out;
2168 	}
2169 
2170 	ret = of_address_to_resource(nfc_np, 0, &res);
2171 	if (ret) {
2172 		dev_err(dev, "Invalid or missing NFC IO resource (err = %d)\n",
2173 			ret);
2174 		goto out;
2175 	}
2176 
2177 	iomem = devm_ioremap_resource(dev, &res);
2178 	if (IS_ERR(iomem)) {
2179 		ret = PTR_ERR(iomem);
2180 		goto out;
2181 	}
2182 
2183 	regmap_conf.name = "nfc-io";
2184 	regmap_conf.max_register = resource_size(&res) - 4;
2185 	nc->io = devm_regmap_init_mmio(dev, iomem, &regmap_conf);
2186 	if (IS_ERR(nc->io)) {
2187 		ret = PTR_ERR(nc->io);
2188 		dev_err(dev, "Could not create NFC IO regmap (err = %d)\n",
2189 			ret);
2190 		goto out;
2191 	}
2192 
2193 	ret = of_address_to_resource(nfc_np, 1, &res);
2194 	if (ret) {
2195 		dev_err(dev, "Invalid or missing HSMC resource (err = %d)\n",
2196 			ret);
2197 		goto out;
2198 	}
2199 
2200 	iomem = devm_ioremap_resource(dev, &res);
2201 	if (IS_ERR(iomem)) {
2202 		ret = PTR_ERR(iomem);
2203 		goto out;
2204 	}
2205 
2206 	regmap_conf.name = "smc";
2207 	regmap_conf.max_register = resource_size(&res) - 4;
2208 	nc->base.smc = devm_regmap_init_mmio(dev, iomem, &regmap_conf);
2209 	if (IS_ERR(nc->base.smc)) {
2210 		ret = PTR_ERR(nc->base.smc);
2211 		dev_err(dev, "Could not create NFC IO regmap (err = %d)\n",
2212 			ret);
2213 		goto out;
2214 	}
2215 
2216 	ret = of_address_to_resource(nfc_np, 2, &res);
2217 	if (ret) {
2218 		dev_err(dev, "Invalid or missing SRAM resource (err = %d)\n",
2219 			ret);
2220 		goto out;
2221 	}
2222 
2223 	nc->sram.virt = devm_ioremap_resource(dev, &res);
2224 	if (IS_ERR(nc->sram.virt)) {
2225 		ret = PTR_ERR(nc->sram.virt);
2226 		goto out;
2227 	}
2228 
2229 	nc->sram.dma = res.start;
2230 
2231 out:
2232 	of_node_put(nfc_np);
2233 
2234 	return ret;
2235 }
2236 
2237 static int
2238 atmel_hsmc_nand_controller_init(struct atmel_hsmc_nand_controller *nc)
2239 {
2240 	struct device *dev = nc->base.dev;
2241 	struct device_node *np;
2242 	int ret;
2243 
2244 	np = of_parse_phandle(dev->parent->of_node, "atmel,smc", 0);
2245 	if (!np) {
2246 		dev_err(dev, "Missing or invalid atmel,smc property\n");
2247 		return -EINVAL;
2248 	}
2249 
2250 	nc->hsmc_layout = atmel_hsmc_get_reg_layout(np);
2251 
2252 	nc->irq = of_irq_get(np, 0);
2253 	of_node_put(np);
2254 	if (nc->irq <= 0) {
2255 		ret = nc->irq ?: -ENXIO;
2256 		if (ret != -EPROBE_DEFER)
2257 			dev_err(dev, "Failed to get IRQ number (err = %d)\n",
2258 				ret);
2259 		return ret;
2260 	}
2261 
2262 	np = of_parse_phandle(dev->of_node, "atmel,nfc-io", 0);
2263 	if (!np) {
2264 		dev_err(dev, "Missing or invalid atmel,nfc-io property\n");
2265 		return -EINVAL;
2266 	}
2267 
2268 	nc->io = syscon_node_to_regmap(np);
2269 	of_node_put(np);
2270 	if (IS_ERR(nc->io)) {
2271 		ret = PTR_ERR(nc->io);
2272 		dev_err(dev, "Could not get NFC IO regmap (err = %d)\n", ret);
2273 		return ret;
2274 	}
2275 
2276 	nc->sram.pool = of_gen_pool_get(nc->base.dev->of_node,
2277 					 "atmel,nfc-sram", 0);
2278 	if (!nc->sram.pool) {
2279 		dev_err(nc->base.dev, "Missing SRAM\n");
2280 		return -ENOMEM;
2281 	}
2282 
2283 	nc->sram.virt = (void __iomem *)gen_pool_dma_alloc(nc->sram.pool,
2284 							   ATMEL_NFC_SRAM_SIZE,
2285 							   &nc->sram.dma);
2286 	if (!nc->sram.virt) {
2287 		dev_err(nc->base.dev,
2288 			"Could not allocate memory from the NFC SRAM pool\n");
2289 		return -ENOMEM;
2290 	}
2291 
2292 	return 0;
2293 }
2294 
2295 static int
2296 atmel_hsmc_nand_controller_remove(struct atmel_nand_controller *nc)
2297 {
2298 	struct atmel_hsmc_nand_controller *hsmc_nc;
2299 	int ret;
2300 
2301 	ret = atmel_nand_controller_remove_nands(nc);
2302 	if (ret)
2303 		return ret;
2304 
2305 	hsmc_nc = container_of(nc, struct atmel_hsmc_nand_controller, base);
2306 	regmap_write(hsmc_nc->base.smc, ATMEL_HSMC_NFC_CTRL,
2307 		     ATMEL_HSMC_NFC_CTRL_DIS);
2308 
2309 	if (hsmc_nc->sram.pool)
2310 		gen_pool_free(hsmc_nc->sram.pool,
2311 			      (unsigned long)hsmc_nc->sram.virt,
2312 			      ATMEL_NFC_SRAM_SIZE);
2313 
2314 	if (hsmc_nc->clk) {
2315 		clk_disable_unprepare(hsmc_nc->clk);
2316 		clk_put(hsmc_nc->clk);
2317 	}
2318 
2319 	atmel_nand_controller_cleanup(nc);
2320 
2321 	return 0;
2322 }
2323 
2324 static int atmel_hsmc_nand_controller_probe(struct platform_device *pdev,
2325 				const struct atmel_nand_controller_caps *caps)
2326 {
2327 	struct device *dev = &pdev->dev;
2328 	struct atmel_hsmc_nand_controller *nc;
2329 	int ret;
2330 
2331 	nc = devm_kzalloc(dev, sizeof(*nc), GFP_KERNEL);
2332 	if (!nc)
2333 		return -ENOMEM;
2334 
2335 	ret = atmel_nand_controller_init(&nc->base, pdev, caps);
2336 	if (ret)
2337 		return ret;
2338 
2339 	if (caps->legacy_of_bindings)
2340 		ret = atmel_hsmc_nand_controller_legacy_init(nc);
2341 	else
2342 		ret = atmel_hsmc_nand_controller_init(nc);
2343 
2344 	if (ret)
2345 		return ret;
2346 
2347 	/* Make sure all irqs are masked before registering our IRQ handler. */
2348 	regmap_write(nc->base.smc, ATMEL_HSMC_NFC_IDR, 0xffffffff);
2349 	ret = devm_request_irq(dev, nc->irq, atmel_nfc_interrupt,
2350 			       IRQF_SHARED, "nfc", nc);
2351 	if (ret) {
2352 		dev_err(dev,
2353 			"Could not get register NFC interrupt handler (err = %d)\n",
2354 			ret);
2355 		goto err;
2356 	}
2357 
2358 	/* Initial NFC configuration. */
2359 	regmap_write(nc->base.smc, ATMEL_HSMC_NFC_CFG,
2360 		     ATMEL_HSMC_NFC_CFG_DTO_MAX);
2361 	regmap_write(nc->base.smc, ATMEL_HSMC_NFC_CTRL,
2362 		     ATMEL_HSMC_NFC_CTRL_EN);
2363 
2364 	ret = atmel_nand_controller_add_nands(&nc->base);
2365 	if (ret)
2366 		goto err;
2367 
2368 	return 0;
2369 
2370 err:
2371 	atmel_hsmc_nand_controller_remove(&nc->base);
2372 
2373 	return ret;
2374 }
2375 
2376 static const struct atmel_nand_controller_ops atmel_hsmc_nc_ops = {
2377 	.probe = atmel_hsmc_nand_controller_probe,
2378 	.remove = atmel_hsmc_nand_controller_remove,
2379 	.ecc_init = atmel_hsmc_nand_ecc_init,
2380 	.nand_init = atmel_nand_init,
2381 	.setup_interface = atmel_hsmc_nand_setup_interface,
2382 	.exec_op = atmel_hsmc_nand_exec_op,
2383 };
2384 
2385 static const struct atmel_nand_controller_caps atmel_sama5_nc_caps = {
2386 	.has_dma = true,
2387 	.ale_offs = BIT(21),
2388 	.cle_offs = BIT(22),
2389 	.ops = &atmel_hsmc_nc_ops,
2390 };
2391 
2392 /* Only used to parse old bindings. */
2393 static const struct atmel_nand_controller_caps atmel_sama5_nand_caps = {
2394 	.has_dma = true,
2395 	.ale_offs = BIT(21),
2396 	.cle_offs = BIT(22),
2397 	.ops = &atmel_hsmc_nc_ops,
2398 	.legacy_of_bindings = true,
2399 };
2400 
2401 static int atmel_smc_nand_controller_probe(struct platform_device *pdev,
2402 				const struct atmel_nand_controller_caps *caps)
2403 {
2404 	struct device *dev = &pdev->dev;
2405 	struct atmel_smc_nand_controller *nc;
2406 	int ret;
2407 
2408 	nc = devm_kzalloc(dev, sizeof(*nc), GFP_KERNEL);
2409 	if (!nc)
2410 		return -ENOMEM;
2411 
2412 	ret = atmel_nand_controller_init(&nc->base, pdev, caps);
2413 	if (ret)
2414 		return ret;
2415 
2416 	ret = atmel_smc_nand_controller_init(nc);
2417 	if (ret)
2418 		return ret;
2419 
2420 	return atmel_nand_controller_add_nands(&nc->base);
2421 }
2422 
2423 static int
2424 atmel_smc_nand_controller_remove(struct atmel_nand_controller *nc)
2425 {
2426 	int ret;
2427 
2428 	ret = atmel_nand_controller_remove_nands(nc);
2429 	if (ret)
2430 		return ret;
2431 
2432 	atmel_nand_controller_cleanup(nc);
2433 
2434 	return 0;
2435 }
2436 
2437 /*
2438  * The SMC reg layout of at91rm9200 is completely different which prevents us
2439  * from re-using atmel_smc_nand_setup_interface() for the
2440  * ->setup_interface() hook.
2441  * At this point, there's no support for the at91rm9200 SMC IP, so we leave
2442  * ->setup_interface() unassigned.
2443  */
2444 static const struct atmel_nand_controller_ops at91rm9200_nc_ops = {
2445 	.probe = atmel_smc_nand_controller_probe,
2446 	.remove = atmel_smc_nand_controller_remove,
2447 	.ecc_init = atmel_nand_ecc_init,
2448 	.nand_init = atmel_smc_nand_init,
2449 	.exec_op = atmel_smc_nand_exec_op,
2450 };
2451 
2452 static const struct atmel_nand_controller_caps atmel_rm9200_nc_caps = {
2453 	.ale_offs = BIT(21),
2454 	.cle_offs = BIT(22),
2455 	.ebi_csa_regmap_name = "atmel,matrix",
2456 	.ops = &at91rm9200_nc_ops,
2457 };
2458 
2459 static const struct atmel_nand_controller_ops atmel_smc_nc_ops = {
2460 	.probe = atmel_smc_nand_controller_probe,
2461 	.remove = atmel_smc_nand_controller_remove,
2462 	.ecc_init = atmel_nand_ecc_init,
2463 	.nand_init = atmel_smc_nand_init,
2464 	.setup_interface = atmel_smc_nand_setup_interface,
2465 	.exec_op = atmel_smc_nand_exec_op,
2466 };
2467 
2468 static const struct atmel_nand_controller_caps atmel_sam9260_nc_caps = {
2469 	.ale_offs = BIT(21),
2470 	.cle_offs = BIT(22),
2471 	.ebi_csa_regmap_name = "atmel,matrix",
2472 	.ops = &atmel_smc_nc_ops,
2473 };
2474 
2475 static const struct atmel_nand_controller_caps atmel_sam9261_nc_caps = {
2476 	.ale_offs = BIT(22),
2477 	.cle_offs = BIT(21),
2478 	.ebi_csa_regmap_name = "atmel,matrix",
2479 	.ops = &atmel_smc_nc_ops,
2480 };
2481 
2482 static const struct atmel_nand_controller_caps atmel_sam9g45_nc_caps = {
2483 	.has_dma = true,
2484 	.ale_offs = BIT(21),
2485 	.cle_offs = BIT(22),
2486 	.ebi_csa_regmap_name = "atmel,matrix",
2487 	.ops = &atmel_smc_nc_ops,
2488 };
2489 
2490 static const struct atmel_nand_controller_caps microchip_sam9x60_nc_caps = {
2491 	.has_dma = true,
2492 	.ale_offs = BIT(21),
2493 	.cle_offs = BIT(22),
2494 	.ebi_csa_regmap_name = "microchip,sfr",
2495 	.ops = &atmel_smc_nc_ops,
2496 };
2497 
2498 /* Only used to parse old bindings. */
2499 static const struct atmel_nand_controller_caps atmel_rm9200_nand_caps = {
2500 	.ale_offs = BIT(21),
2501 	.cle_offs = BIT(22),
2502 	.ops = &atmel_smc_nc_ops,
2503 	.legacy_of_bindings = true,
2504 };
2505 
2506 static const struct atmel_nand_controller_caps atmel_sam9261_nand_caps = {
2507 	.ale_offs = BIT(22),
2508 	.cle_offs = BIT(21),
2509 	.ops = &atmel_smc_nc_ops,
2510 	.legacy_of_bindings = true,
2511 };
2512 
2513 static const struct atmel_nand_controller_caps atmel_sam9g45_nand_caps = {
2514 	.has_dma = true,
2515 	.ale_offs = BIT(21),
2516 	.cle_offs = BIT(22),
2517 	.ops = &atmel_smc_nc_ops,
2518 	.legacy_of_bindings = true,
2519 };
2520 
2521 static const struct of_device_id atmel_nand_controller_of_ids[] = {
2522 	{
2523 		.compatible = "atmel,at91rm9200-nand-controller",
2524 		.data = &atmel_rm9200_nc_caps,
2525 	},
2526 	{
2527 		.compatible = "atmel,at91sam9260-nand-controller",
2528 		.data = &atmel_sam9260_nc_caps,
2529 	},
2530 	{
2531 		.compatible = "atmel,at91sam9261-nand-controller",
2532 		.data = &atmel_sam9261_nc_caps,
2533 	},
2534 	{
2535 		.compatible = "atmel,at91sam9g45-nand-controller",
2536 		.data = &atmel_sam9g45_nc_caps,
2537 	},
2538 	{
2539 		.compatible = "atmel,sama5d3-nand-controller",
2540 		.data = &atmel_sama5_nc_caps,
2541 	},
2542 	{
2543 		.compatible = "microchip,sam9x60-nand-controller",
2544 		.data = &microchip_sam9x60_nc_caps,
2545 	},
2546 	/* Support for old/deprecated bindings: */
2547 	{
2548 		.compatible = "atmel,at91rm9200-nand",
2549 		.data = &atmel_rm9200_nand_caps,
2550 	},
2551 	{
2552 		.compatible = "atmel,sama5d4-nand",
2553 		.data = &atmel_rm9200_nand_caps,
2554 	},
2555 	{
2556 		.compatible = "atmel,sama5d2-nand",
2557 		.data = &atmel_rm9200_nand_caps,
2558 	},
2559 	{ /* sentinel */ },
2560 };
2561 MODULE_DEVICE_TABLE(of, atmel_nand_controller_of_ids);
2562 
2563 static int atmel_nand_controller_probe(struct platform_device *pdev)
2564 {
2565 	const struct atmel_nand_controller_caps *caps;
2566 
2567 	if (pdev->id_entry)
2568 		caps = (void *)pdev->id_entry->driver_data;
2569 	else
2570 		caps = of_device_get_match_data(&pdev->dev);
2571 
2572 	if (!caps) {
2573 		dev_err(&pdev->dev, "Could not retrieve NFC caps\n");
2574 		return -EINVAL;
2575 	}
2576 
2577 	if (caps->legacy_of_bindings) {
2578 		struct device_node *nfc_node;
2579 		u32 ale_offs = 21;
2580 
2581 		/*
2582 		 * If we are parsing legacy DT props and the DT contains a
2583 		 * valid NFC node, forward the request to the sama5 logic.
2584 		 */
2585 		nfc_node = of_get_compatible_child(pdev->dev.of_node,
2586 						   "atmel,sama5d3-nfc");
2587 		if (nfc_node) {
2588 			caps = &atmel_sama5_nand_caps;
2589 			of_node_put(nfc_node);
2590 		}
2591 
2592 		/*
2593 		 * Even if the compatible says we are dealing with an
2594 		 * at91rm9200 controller, the atmel,nand-has-dma specify that
2595 		 * this controller supports DMA, which means we are in fact
2596 		 * dealing with an at91sam9g45+ controller.
2597 		 */
2598 		if (!caps->has_dma &&
2599 		    of_property_read_bool(pdev->dev.of_node,
2600 					  "atmel,nand-has-dma"))
2601 			caps = &atmel_sam9g45_nand_caps;
2602 
2603 		/*
2604 		 * All SoCs except the at91sam9261 are assigning ALE to A21 and
2605 		 * CLE to A22. If atmel,nand-addr-offset != 21 this means we're
2606 		 * actually dealing with an at91sam9261 controller.
2607 		 */
2608 		of_property_read_u32(pdev->dev.of_node,
2609 				     "atmel,nand-addr-offset", &ale_offs);
2610 		if (ale_offs != 21)
2611 			caps = &atmel_sam9261_nand_caps;
2612 	}
2613 
2614 	return caps->ops->probe(pdev, caps);
2615 }
2616 
2617 static int atmel_nand_controller_remove(struct platform_device *pdev)
2618 {
2619 	struct atmel_nand_controller *nc = platform_get_drvdata(pdev);
2620 
2621 	return nc->caps->ops->remove(nc);
2622 }
2623 
2624 static __maybe_unused int atmel_nand_controller_resume(struct device *dev)
2625 {
2626 	struct atmel_nand_controller *nc = dev_get_drvdata(dev);
2627 	struct atmel_nand *nand;
2628 
2629 	if (nc->pmecc)
2630 		atmel_pmecc_reset(nc->pmecc);
2631 
2632 	list_for_each_entry(nand, &nc->chips, node) {
2633 		int i;
2634 
2635 		for (i = 0; i < nand->numcs; i++)
2636 			nand_reset(&nand->base, i);
2637 	}
2638 
2639 	return 0;
2640 }
2641 
2642 static SIMPLE_DEV_PM_OPS(atmel_nand_controller_pm_ops, NULL,
2643 			 atmel_nand_controller_resume);
2644 
2645 static struct platform_driver atmel_nand_controller_driver = {
2646 	.driver = {
2647 		.name = "atmel-nand-controller",
2648 		.of_match_table = of_match_ptr(atmel_nand_controller_of_ids),
2649 		.pm = &atmel_nand_controller_pm_ops,
2650 	},
2651 	.probe = atmel_nand_controller_probe,
2652 	.remove = atmel_nand_controller_remove,
2653 };
2654 module_platform_driver(atmel_nand_controller_driver);
2655 
2656 MODULE_LICENSE("GPL");
2657 MODULE_AUTHOR("Boris Brezillon <boris.brezillon@free-electrons.com>");
2658 MODULE_DESCRIPTION("NAND Flash Controller driver for Atmel SoCs");
2659 MODULE_ALIAS("platform:atmel-nand-controller");
2660