1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Freescale GPMI NAND Flash Driver
4  *
5  * Copyright (C) 2010-2015 Freescale Semiconductor, Inc.
6  * Copyright (C) 2008 Embedded Alley Solutions, Inc.
7  */
8 #include <linux/clk.h>
9 #include <linux/delay.h>
10 #include <linux/slab.h>
11 #include <linux/sched/task_stack.h>
12 #include <linux/interrupt.h>
13 #include <linux/module.h>
14 #include <linux/mtd/partitions.h>
15 #include <linux/of.h>
16 #include <linux/of_device.h>
17 #include <linux/pm_runtime.h>
18 #include <linux/dma/mxs-dma.h>
19 #include "gpmi-nand.h"
20 #include "gpmi-regs.h"
21 #include "bch-regs.h"
22 
23 /* Resource names for the GPMI NAND driver. */
24 #define GPMI_NAND_GPMI_REGS_ADDR_RES_NAME  "gpmi-nand"
25 #define GPMI_NAND_BCH_REGS_ADDR_RES_NAME   "bch"
26 #define GPMI_NAND_BCH_INTERRUPT_RES_NAME   "bch"
27 
28 /* Converts time to clock cycles */
29 #define TO_CYCLES(duration, period) DIV_ROUND_UP_ULL(duration, period)
30 
31 #define MXS_SET_ADDR		0x4
32 #define MXS_CLR_ADDR		0x8
33 /*
34  * Clear the bit and poll it cleared.  This is usually called with
35  * a reset address and mask being either SFTRST(bit 31) or CLKGATE
36  * (bit 30).
37  */
38 static int clear_poll_bit(void __iomem *addr, u32 mask)
39 {
40 	int timeout = 0x400;
41 
42 	/* clear the bit */
43 	writel(mask, addr + MXS_CLR_ADDR);
44 
45 	/*
46 	 * SFTRST needs 3 GPMI clocks to settle, the reference manual
47 	 * recommends to wait 1us.
48 	 */
49 	udelay(1);
50 
51 	/* poll the bit becoming clear */
52 	while ((readl(addr) & mask) && --timeout)
53 		/* nothing */;
54 
55 	return !timeout;
56 }
57 
58 #define MODULE_CLKGATE		(1 << 30)
59 #define MODULE_SFTRST		(1 << 31)
60 /*
61  * The current mxs_reset_block() will do two things:
62  *  [1] enable the module.
63  *  [2] reset the module.
64  *
65  * In most of the cases, it's ok.
66  * But in MX23, there is a hardware bug in the BCH block (see erratum #2847).
67  * If you try to soft reset the BCH block, it becomes unusable until
68  * the next hard reset. This case occurs in the NAND boot mode. When the board
69  * boots by NAND, the ROM of the chip will initialize the BCH blocks itself.
70  * So If the driver tries to reset the BCH again, the BCH will not work anymore.
71  * You will see a DMA timeout in this case. The bug has been fixed
72  * in the following chips, such as MX28.
73  *
74  * To avoid this bug, just add a new parameter `just_enable` for
75  * the mxs_reset_block(), and rewrite it here.
76  */
77 static int gpmi_reset_block(void __iomem *reset_addr, bool just_enable)
78 {
79 	int ret;
80 	int timeout = 0x400;
81 
82 	/* clear and poll SFTRST */
83 	ret = clear_poll_bit(reset_addr, MODULE_SFTRST);
84 	if (unlikely(ret))
85 		goto error;
86 
87 	/* clear CLKGATE */
88 	writel(MODULE_CLKGATE, reset_addr + MXS_CLR_ADDR);
89 
90 	if (!just_enable) {
91 		/* set SFTRST to reset the block */
92 		writel(MODULE_SFTRST, reset_addr + MXS_SET_ADDR);
93 		udelay(1);
94 
95 		/* poll CLKGATE becoming set */
96 		while ((!(readl(reset_addr) & MODULE_CLKGATE)) && --timeout)
97 			/* nothing */;
98 		if (unlikely(!timeout))
99 			goto error;
100 	}
101 
102 	/* clear and poll SFTRST */
103 	ret = clear_poll_bit(reset_addr, MODULE_SFTRST);
104 	if (unlikely(ret))
105 		goto error;
106 
107 	/* clear and poll CLKGATE */
108 	ret = clear_poll_bit(reset_addr, MODULE_CLKGATE);
109 	if (unlikely(ret))
110 		goto error;
111 
112 	return 0;
113 
114 error:
115 	pr_err("%s(%p): module reset timeout\n", __func__, reset_addr);
116 	return -ETIMEDOUT;
117 }
118 
119 static int __gpmi_enable_clk(struct gpmi_nand_data *this, bool v)
120 {
121 	struct clk *clk;
122 	int ret;
123 	int i;
124 
125 	for (i = 0; i < GPMI_CLK_MAX; i++) {
126 		clk = this->resources.clock[i];
127 		if (!clk)
128 			break;
129 
130 		if (v) {
131 			ret = clk_prepare_enable(clk);
132 			if (ret)
133 				goto err_clk;
134 		} else {
135 			clk_disable_unprepare(clk);
136 		}
137 	}
138 	return 0;
139 
140 err_clk:
141 	for (; i > 0; i--)
142 		clk_disable_unprepare(this->resources.clock[i - 1]);
143 	return ret;
144 }
145 
146 static int gpmi_init(struct gpmi_nand_data *this)
147 {
148 	struct resources *r = &this->resources;
149 	int ret;
150 
151 	ret = pm_runtime_get_sync(this->dev);
152 	if (ret < 0) {
153 		pm_runtime_put_noidle(this->dev);
154 		return ret;
155 	}
156 
157 	ret = gpmi_reset_block(r->gpmi_regs, false);
158 	if (ret)
159 		goto err_out;
160 
161 	/*
162 	 * Reset BCH here, too. We got failures otherwise :(
163 	 * See later BCH reset for explanation of MX23 and MX28 handling
164 	 */
165 	ret = gpmi_reset_block(r->bch_regs, GPMI_IS_MXS(this));
166 	if (ret)
167 		goto err_out;
168 
169 	/* Choose NAND mode. */
170 	writel(BM_GPMI_CTRL1_GPMI_MODE, r->gpmi_regs + HW_GPMI_CTRL1_CLR);
171 
172 	/* Set the IRQ polarity. */
173 	writel(BM_GPMI_CTRL1_ATA_IRQRDY_POLARITY,
174 				r->gpmi_regs + HW_GPMI_CTRL1_SET);
175 
176 	/* Disable Write-Protection. */
177 	writel(BM_GPMI_CTRL1_DEV_RESET, r->gpmi_regs + HW_GPMI_CTRL1_SET);
178 
179 	/* Select BCH ECC. */
180 	writel(BM_GPMI_CTRL1_BCH_MODE, r->gpmi_regs + HW_GPMI_CTRL1_SET);
181 
182 	/*
183 	 * Decouple the chip select from dma channel. We use dma0 for all
184 	 * the chips, force all NAND RDY_BUSY inputs to be sourced from
185 	 * RDY_BUSY0.
186 	 */
187 	writel(BM_GPMI_CTRL1_DECOUPLE_CS | BM_GPMI_CTRL1_GANGED_RDYBUSY,
188 	       r->gpmi_regs + HW_GPMI_CTRL1_SET);
189 
190 err_out:
191 	pm_runtime_mark_last_busy(this->dev);
192 	pm_runtime_put_autosuspend(this->dev);
193 	return ret;
194 }
195 
196 /* This function is very useful. It is called only when the bug occur. */
197 static void gpmi_dump_info(struct gpmi_nand_data *this)
198 {
199 	struct resources *r = &this->resources;
200 	struct bch_geometry *geo = &this->bch_geometry;
201 	u32 reg;
202 	int i;
203 
204 	dev_err(this->dev, "Show GPMI registers :\n");
205 	for (i = 0; i <= HW_GPMI_DEBUG / 0x10 + 1; i++) {
206 		reg = readl(r->gpmi_regs + i * 0x10);
207 		dev_err(this->dev, "offset 0x%.3x : 0x%.8x\n", i * 0x10, reg);
208 	}
209 
210 	/* start to print out the BCH info */
211 	dev_err(this->dev, "Show BCH registers :\n");
212 	for (i = 0; i <= HW_BCH_VERSION / 0x10 + 1; i++) {
213 		reg = readl(r->bch_regs + i * 0x10);
214 		dev_err(this->dev, "offset 0x%.3x : 0x%.8x\n", i * 0x10, reg);
215 	}
216 	dev_err(this->dev, "BCH Geometry :\n"
217 		"GF length              : %u\n"
218 		"ECC Strength           : %u\n"
219 		"Page Size in Bytes     : %u\n"
220 		"Metadata Size in Bytes : %u\n"
221 		"ECC Chunk Size in Bytes: %u\n"
222 		"ECC Chunk Count        : %u\n"
223 		"Payload Size in Bytes  : %u\n"
224 		"Auxiliary Size in Bytes: %u\n"
225 		"Auxiliary Status Offset: %u\n"
226 		"Block Mark Byte Offset : %u\n"
227 		"Block Mark Bit Offset  : %u\n",
228 		geo->gf_len,
229 		geo->ecc_strength,
230 		geo->page_size,
231 		geo->metadata_size,
232 		geo->ecc_chunk_size,
233 		geo->ecc_chunk_count,
234 		geo->payload_size,
235 		geo->auxiliary_size,
236 		geo->auxiliary_status_offset,
237 		geo->block_mark_byte_offset,
238 		geo->block_mark_bit_offset);
239 }
240 
241 static inline bool gpmi_check_ecc(struct gpmi_nand_data *this)
242 {
243 	struct bch_geometry *geo = &this->bch_geometry;
244 
245 	/* Do the sanity check. */
246 	if (GPMI_IS_MXS(this)) {
247 		/* The mx23/mx28 only support the GF13. */
248 		if (geo->gf_len == 14)
249 			return false;
250 	}
251 	return geo->ecc_strength <= this->devdata->bch_max_ecc_strength;
252 }
253 
254 /*
255  * If we can get the ECC information from the nand chip, we do not
256  * need to calculate them ourselves.
257  *
258  * We may have available oob space in this case.
259  */
260 static int set_geometry_by_ecc_info(struct gpmi_nand_data *this,
261 				    unsigned int ecc_strength,
262 				    unsigned int ecc_step)
263 {
264 	struct bch_geometry *geo = &this->bch_geometry;
265 	struct nand_chip *chip = &this->nand;
266 	struct mtd_info *mtd = nand_to_mtd(chip);
267 	unsigned int block_mark_bit_offset;
268 
269 	switch (ecc_step) {
270 	case SZ_512:
271 		geo->gf_len = 13;
272 		break;
273 	case SZ_1K:
274 		geo->gf_len = 14;
275 		break;
276 	default:
277 		dev_err(this->dev,
278 			"unsupported nand chip. ecc bits : %d, ecc size : %d\n",
279 			nanddev_get_ecc_requirements(&chip->base)->strength,
280 			nanddev_get_ecc_requirements(&chip->base)->step_size);
281 		return -EINVAL;
282 	}
283 	geo->ecc_chunk_size = ecc_step;
284 	geo->ecc_strength = round_up(ecc_strength, 2);
285 	if (!gpmi_check_ecc(this))
286 		return -EINVAL;
287 
288 	/* Keep the C >= O */
289 	if (geo->ecc_chunk_size < mtd->oobsize) {
290 		dev_err(this->dev,
291 			"unsupported nand chip. ecc size: %d, oob size : %d\n",
292 			ecc_step, mtd->oobsize);
293 		return -EINVAL;
294 	}
295 
296 	/* The default value, see comment in the legacy_set_geometry(). */
297 	geo->metadata_size = 10;
298 
299 	geo->ecc_chunk_count = mtd->writesize / geo->ecc_chunk_size;
300 
301 	/*
302 	 * Now, the NAND chip with 2K page(data chunk is 512byte) shows below:
303 	 *
304 	 *    |                          P                            |
305 	 *    |<----------------------------------------------------->|
306 	 *    |                                                       |
307 	 *    |                                        (Block Mark)   |
308 	 *    |                      P'                      |      | |     |
309 	 *    |<-------------------------------------------->|  D   | |  O' |
310 	 *    |                                              |<---->| |<--->|
311 	 *    V                                              V      V V     V
312 	 *    +---+----------+-+----------+-+----------+-+----------+-+-----+
313 	 *    | M |   data   |E|   data   |E|   data   |E|   data   |E|     |
314 	 *    +---+----------+-+----------+-+----------+-+----------+-+-----+
315 	 *                                                   ^              ^
316 	 *                                                   |      O       |
317 	 *                                                   |<------------>|
318 	 *                                                   |              |
319 	 *
320 	 *	P : the page size for BCH module.
321 	 *	E : The ECC strength.
322 	 *	G : the length of Galois Field.
323 	 *	N : The chunk count of per page.
324 	 *	M : the metasize of per page.
325 	 *	C : the ecc chunk size, aka the "data" above.
326 	 *	P': the nand chip's page size.
327 	 *	O : the nand chip's oob size.
328 	 *	O': the free oob.
329 	 *
330 	 *	The formula for P is :
331 	 *
332 	 *	            E * G * N
333 	 *	       P = ------------ + P' + M
334 	 *                      8
335 	 *
336 	 * The position of block mark moves forward in the ECC-based view
337 	 * of page, and the delta is:
338 	 *
339 	 *                   E * G * (N - 1)
340 	 *             D = (---------------- + M)
341 	 *                          8
342 	 *
343 	 * Please see the comment in legacy_set_geometry().
344 	 * With the condition C >= O , we still can get same result.
345 	 * So the bit position of the physical block mark within the ECC-based
346 	 * view of the page is :
347 	 *             (P' - D) * 8
348 	 */
349 	geo->page_size = mtd->writesize + geo->metadata_size +
350 		(geo->gf_len * geo->ecc_strength * geo->ecc_chunk_count) / 8;
351 
352 	geo->payload_size = mtd->writesize;
353 
354 	geo->auxiliary_status_offset = ALIGN(geo->metadata_size, 4);
355 	geo->auxiliary_size = ALIGN(geo->metadata_size, 4)
356 				+ ALIGN(geo->ecc_chunk_count, 4);
357 
358 	if (!this->swap_block_mark)
359 		return 0;
360 
361 	/* For bit swap. */
362 	block_mark_bit_offset = mtd->writesize * 8 -
363 		(geo->ecc_strength * geo->gf_len * (geo->ecc_chunk_count - 1)
364 				+ geo->metadata_size * 8);
365 
366 	geo->block_mark_byte_offset = block_mark_bit_offset / 8;
367 	geo->block_mark_bit_offset  = block_mark_bit_offset % 8;
368 	return 0;
369 }
370 
371 /*
372  *  Calculate the ECC strength by hand:
373  *	E : The ECC strength.
374  *	G : the length of Galois Field.
375  *	N : The chunk count of per page.
376  *	O : the oobsize of the NAND chip.
377  *	M : the metasize of per page.
378  *
379  *	The formula is :
380  *		E * G * N
381  *	      ------------ <= (O - M)
382  *                  8
383  *
384  *      So, we get E by:
385  *                    (O - M) * 8
386  *              E <= -------------
387  *                       G * N
388  */
389 static inline int get_ecc_strength(struct gpmi_nand_data *this)
390 {
391 	struct bch_geometry *geo = &this->bch_geometry;
392 	struct mtd_info	*mtd = nand_to_mtd(&this->nand);
393 	int ecc_strength;
394 
395 	ecc_strength = ((mtd->oobsize - geo->metadata_size) * 8)
396 			/ (geo->gf_len * geo->ecc_chunk_count);
397 
398 	/* We need the minor even number. */
399 	return round_down(ecc_strength, 2);
400 }
401 
402 static int legacy_set_geometry(struct gpmi_nand_data *this)
403 {
404 	struct bch_geometry *geo = &this->bch_geometry;
405 	struct mtd_info *mtd = nand_to_mtd(&this->nand);
406 	unsigned int metadata_size;
407 	unsigned int status_size;
408 	unsigned int block_mark_bit_offset;
409 
410 	/*
411 	 * The size of the metadata can be changed, though we set it to 10
412 	 * bytes now. But it can't be too large, because we have to save
413 	 * enough space for BCH.
414 	 */
415 	geo->metadata_size = 10;
416 
417 	/* The default for the length of Galois Field. */
418 	geo->gf_len = 13;
419 
420 	/* The default for chunk size. */
421 	geo->ecc_chunk_size = 512;
422 	while (geo->ecc_chunk_size < mtd->oobsize) {
423 		geo->ecc_chunk_size *= 2; /* keep C >= O */
424 		geo->gf_len = 14;
425 	}
426 
427 	geo->ecc_chunk_count = mtd->writesize / geo->ecc_chunk_size;
428 
429 	/* We use the same ECC strength for all chunks. */
430 	geo->ecc_strength = get_ecc_strength(this);
431 	if (!gpmi_check_ecc(this)) {
432 		dev_err(this->dev,
433 			"ecc strength: %d cannot be supported by the controller (%d)\n"
434 			"try to use minimum ecc strength that NAND chip required\n",
435 			geo->ecc_strength,
436 			this->devdata->bch_max_ecc_strength);
437 		return -EINVAL;
438 	}
439 
440 	geo->page_size = mtd->writesize + geo->metadata_size +
441 		(geo->gf_len * geo->ecc_strength * geo->ecc_chunk_count) / 8;
442 	geo->payload_size = mtd->writesize;
443 
444 	/*
445 	 * The auxiliary buffer contains the metadata and the ECC status. The
446 	 * metadata is padded to the nearest 32-bit boundary. The ECC status
447 	 * contains one byte for every ECC chunk, and is also padded to the
448 	 * nearest 32-bit boundary.
449 	 */
450 	metadata_size = ALIGN(geo->metadata_size, 4);
451 	status_size   = ALIGN(geo->ecc_chunk_count, 4);
452 
453 	geo->auxiliary_size = metadata_size + status_size;
454 	geo->auxiliary_status_offset = metadata_size;
455 
456 	if (!this->swap_block_mark)
457 		return 0;
458 
459 	/*
460 	 * We need to compute the byte and bit offsets of
461 	 * the physical block mark within the ECC-based view of the page.
462 	 *
463 	 * NAND chip with 2K page shows below:
464 	 *                                             (Block Mark)
465 	 *                                                   |      |
466 	 *                                                   |  D   |
467 	 *                                                   |<---->|
468 	 *                                                   V      V
469 	 *    +---+----------+-+----------+-+----------+-+----------+-+
470 	 *    | M |   data   |E|   data   |E|   data   |E|   data   |E|
471 	 *    +---+----------+-+----------+-+----------+-+----------+-+
472 	 *
473 	 * The position of block mark moves forward in the ECC-based view
474 	 * of page, and the delta is:
475 	 *
476 	 *                   E * G * (N - 1)
477 	 *             D = (---------------- + M)
478 	 *                          8
479 	 *
480 	 * With the formula to compute the ECC strength, and the condition
481 	 *       : C >= O         (C is the ecc chunk size)
482 	 *
483 	 * It's easy to deduce to the following result:
484 	 *
485 	 *         E * G       (O - M)      C - M         C - M
486 	 *      ----------- <= ------- <=  --------  <  ---------
487 	 *           8            N           N          (N - 1)
488 	 *
489 	 *  So, we get:
490 	 *
491 	 *                   E * G * (N - 1)
492 	 *             D = (---------------- + M) < C
493 	 *                          8
494 	 *
495 	 *  The above inequality means the position of block mark
496 	 *  within the ECC-based view of the page is still in the data chunk,
497 	 *  and it's NOT in the ECC bits of the chunk.
498 	 *
499 	 *  Use the following to compute the bit position of the
500 	 *  physical block mark within the ECC-based view of the page:
501 	 *          (page_size - D) * 8
502 	 *
503 	 *  --Huang Shijie
504 	 */
505 	block_mark_bit_offset = mtd->writesize * 8 -
506 		(geo->ecc_strength * geo->gf_len * (geo->ecc_chunk_count - 1)
507 				+ geo->metadata_size * 8);
508 
509 	geo->block_mark_byte_offset = block_mark_bit_offset / 8;
510 	geo->block_mark_bit_offset  = block_mark_bit_offset % 8;
511 	return 0;
512 }
513 
514 static int common_nfc_set_geometry(struct gpmi_nand_data *this)
515 {
516 	struct nand_chip *chip = &this->nand;
517 	const struct nand_ecc_props *requirements =
518 		nanddev_get_ecc_requirements(&chip->base);
519 
520 	if (chip->ecc.strength > 0 && chip->ecc.size > 0)
521 		return set_geometry_by_ecc_info(this, chip->ecc.strength,
522 						chip->ecc.size);
523 
524 	if ((of_property_read_bool(this->dev->of_node, "fsl,use-minimum-ecc"))
525 				|| legacy_set_geometry(this)) {
526 		if (!(requirements->strength > 0 && requirements->step_size > 0))
527 			return -EINVAL;
528 
529 		return set_geometry_by_ecc_info(this,
530 						requirements->strength,
531 						requirements->step_size);
532 	}
533 
534 	return 0;
535 }
536 
537 /* Configures the geometry for BCH.  */
538 static int bch_set_geometry(struct gpmi_nand_data *this)
539 {
540 	struct resources *r = &this->resources;
541 	int ret;
542 
543 	ret = common_nfc_set_geometry(this);
544 	if (ret)
545 		return ret;
546 
547 	ret = pm_runtime_get_sync(this->dev);
548 	if (ret < 0) {
549 		pm_runtime_put_autosuspend(this->dev);
550 		return ret;
551 	}
552 
553 	/*
554 	* Due to erratum #2847 of the MX23, the BCH cannot be soft reset on this
555 	* chip, otherwise it will lock up. So we skip resetting BCH on the MX23.
556 	* and MX28.
557 	*/
558 	ret = gpmi_reset_block(r->bch_regs, GPMI_IS_MXS(this));
559 	if (ret)
560 		goto err_out;
561 
562 	/* Set *all* chip selects to use layout 0. */
563 	writel(0, r->bch_regs + HW_BCH_LAYOUTSELECT);
564 
565 	ret = 0;
566 err_out:
567 	pm_runtime_mark_last_busy(this->dev);
568 	pm_runtime_put_autosuspend(this->dev);
569 
570 	return ret;
571 }
572 
573 /*
574  * <1> Firstly, we should know what's the GPMI-clock means.
575  *     The GPMI-clock is the internal clock in the gpmi nand controller.
576  *     If you set 100MHz to gpmi nand controller, the GPMI-clock's period
577  *     is 10ns. Mark the GPMI-clock's period as GPMI-clock-period.
578  *
579  * <2> Secondly, we should know what's the frequency on the nand chip pins.
580  *     The frequency on the nand chip pins is derived from the GPMI-clock.
581  *     We can get it from the following equation:
582  *
583  *         F = G / (DS + DH)
584  *
585  *         F  : the frequency on the nand chip pins.
586  *         G  : the GPMI clock, such as 100MHz.
587  *         DS : GPMI_HW_GPMI_TIMING0:DATA_SETUP
588  *         DH : GPMI_HW_GPMI_TIMING0:DATA_HOLD
589  *
590  * <3> Thirdly, when the frequency on the nand chip pins is above 33MHz,
591  *     the nand EDO(extended Data Out) timing could be applied.
592  *     The GPMI implements a feedback read strobe to sample the read data.
593  *     The feedback read strobe can be delayed to support the nand EDO timing
594  *     where the read strobe may deasserts before the read data is valid, and
595  *     read data is valid for some time after read strobe.
596  *
597  *     The following figure illustrates some aspects of a NAND Flash read:
598  *
599  *                   |<---tREA---->|
600  *                   |             |
601  *                   |         |   |
602  *                   |<--tRP-->|   |
603  *                   |         |   |
604  *                  __          ___|__________________________________
605  *     RDN            \________/   |
606  *                                 |
607  *                                 /---------\
608  *     Read Data    --------------<           >---------
609  *                                 \---------/
610  *                                |     |
611  *                                |<-D->|
612  *     FeedbackRDN  ________             ____________
613  *                          \___________/
614  *
615  *          D stands for delay, set in the HW_GPMI_CTRL1:RDN_DELAY.
616  *
617  *
618  * <4> Now, we begin to describe how to compute the right RDN_DELAY.
619  *
620  *  4.1) From the aspect of the nand chip pins:
621  *        Delay = (tREA + C - tRP)               {1}
622  *
623  *        tREA : the maximum read access time.
624  *        C    : a constant to adjust the delay. default is 4000ps.
625  *        tRP  : the read pulse width, which is exactly:
626  *                   tRP = (GPMI-clock-period) * DATA_SETUP
627  *
628  *  4.2) From the aspect of the GPMI nand controller:
629  *         Delay = RDN_DELAY * 0.125 * RP        {2}
630  *
631  *         RP   : the DLL reference period.
632  *            if (GPMI-clock-period > DLL_THRETHOLD)
633  *                   RP = GPMI-clock-period / 2;
634  *            else
635  *                   RP = GPMI-clock-period;
636  *
637  *            Set the HW_GPMI_CTRL1:HALF_PERIOD if GPMI-clock-period
638  *            is greater DLL_THRETHOLD. In other SOCs, the DLL_THRETHOLD
639  *            is 16000ps, but in mx6q, we use 12000ps.
640  *
641  *  4.3) since {1} equals {2}, we get:
642  *
643  *                     (tREA + 4000 - tRP) * 8
644  *         RDN_DELAY = -----------------------     {3}
645  *                           RP
646  */
647 static void gpmi_nfc_compute_timings(struct gpmi_nand_data *this,
648 				     const struct nand_sdr_timings *sdr)
649 {
650 	struct gpmi_nfc_hardware_timing *hw = &this->hw;
651 	unsigned int dll_threshold_ps = this->devdata->max_chain_delay;
652 	unsigned int period_ps, reference_period_ps;
653 	unsigned int data_setup_cycles, data_hold_cycles, addr_setup_cycles;
654 	unsigned int tRP_ps;
655 	bool use_half_period;
656 	int sample_delay_ps, sample_delay_factor;
657 	u16 busy_timeout_cycles;
658 	u8 wrn_dly_sel;
659 
660 	if (sdr->tRC_min >= 30000) {
661 		/* ONFI non-EDO modes [0-3] */
662 		hw->clk_rate = 22000000;
663 		wrn_dly_sel = BV_GPMI_CTRL1_WRN_DLY_SEL_4_TO_8NS;
664 	} else if (sdr->tRC_min >= 25000) {
665 		/* ONFI EDO mode 4 */
666 		hw->clk_rate = 80000000;
667 		wrn_dly_sel = BV_GPMI_CTRL1_WRN_DLY_SEL_NO_DELAY;
668 	} else {
669 		/* ONFI EDO mode 5 */
670 		hw->clk_rate = 100000000;
671 		wrn_dly_sel = BV_GPMI_CTRL1_WRN_DLY_SEL_NO_DELAY;
672 	}
673 
674 	/* SDR core timings are given in picoseconds */
675 	period_ps = div_u64((u64)NSEC_PER_SEC * 1000, hw->clk_rate);
676 
677 	addr_setup_cycles = TO_CYCLES(sdr->tALS_min, period_ps);
678 	data_setup_cycles = TO_CYCLES(sdr->tDS_min, period_ps);
679 	data_hold_cycles = TO_CYCLES(sdr->tDH_min, period_ps);
680 	busy_timeout_cycles = TO_CYCLES(sdr->tWB_max + sdr->tR_max, period_ps);
681 
682 	hw->timing0 = BF_GPMI_TIMING0_ADDRESS_SETUP(addr_setup_cycles) |
683 		      BF_GPMI_TIMING0_DATA_HOLD(data_hold_cycles) |
684 		      BF_GPMI_TIMING0_DATA_SETUP(data_setup_cycles);
685 	hw->timing1 = BF_GPMI_TIMING1_BUSY_TIMEOUT(busy_timeout_cycles * 4096);
686 
687 	/*
688 	 * Derive NFC ideal delay from {3}:
689 	 *
690 	 *                     (tREA + 4000 - tRP) * 8
691 	 *         RDN_DELAY = -----------------------
692 	 *                                RP
693 	 */
694 	if (period_ps > dll_threshold_ps) {
695 		use_half_period = true;
696 		reference_period_ps = period_ps / 2;
697 	} else {
698 		use_half_period = false;
699 		reference_period_ps = period_ps;
700 	}
701 
702 	tRP_ps = data_setup_cycles * period_ps;
703 	sample_delay_ps = (sdr->tREA_max + 4000 - tRP_ps) * 8;
704 	if (sample_delay_ps > 0)
705 		sample_delay_factor = sample_delay_ps / reference_period_ps;
706 	else
707 		sample_delay_factor = 0;
708 
709 	hw->ctrl1n = BF_GPMI_CTRL1_WRN_DLY_SEL(wrn_dly_sel);
710 	if (sample_delay_factor)
711 		hw->ctrl1n |= BF_GPMI_CTRL1_RDN_DELAY(sample_delay_factor) |
712 			      BM_GPMI_CTRL1_DLL_ENABLE |
713 			      (use_half_period ? BM_GPMI_CTRL1_HALF_PERIOD : 0);
714 }
715 
716 static int gpmi_nfc_apply_timings(struct gpmi_nand_data *this)
717 {
718 	struct gpmi_nfc_hardware_timing *hw = &this->hw;
719 	struct resources *r = &this->resources;
720 	void __iomem *gpmi_regs = r->gpmi_regs;
721 	unsigned int dll_wait_time_us;
722 	int ret;
723 
724 	/* Clock dividers do NOT guarantee a clean clock signal on its output
725 	 * during the change of the divide factor on i.MX6Q/UL/SX. On i.MX7/8,
726 	 * all clock dividers provide these guarantee.
727 	 */
728 	if (GPMI_IS_MX6Q(this) || GPMI_IS_MX6SX(this))
729 		clk_disable_unprepare(r->clock[0]);
730 
731 	ret = clk_set_rate(r->clock[0], hw->clk_rate);
732 	if (ret) {
733 		dev_err(this->dev, "cannot set clock rate to %lu Hz: %d\n", hw->clk_rate, ret);
734 		return ret;
735 	}
736 
737 	if (GPMI_IS_MX6Q(this) || GPMI_IS_MX6SX(this)) {
738 		ret = clk_prepare_enable(r->clock[0]);
739 		if (ret)
740 			return ret;
741 	}
742 
743 	writel(hw->timing0, gpmi_regs + HW_GPMI_TIMING0);
744 	writel(hw->timing1, gpmi_regs + HW_GPMI_TIMING1);
745 
746 	/*
747 	 * Clear several CTRL1 fields, DLL must be disabled when setting
748 	 * RDN_DELAY or HALF_PERIOD.
749 	 */
750 	writel(BM_GPMI_CTRL1_CLEAR_MASK, gpmi_regs + HW_GPMI_CTRL1_CLR);
751 	writel(hw->ctrl1n, gpmi_regs + HW_GPMI_CTRL1_SET);
752 
753 	/* Wait 64 clock cycles before using the GPMI after enabling the DLL */
754 	dll_wait_time_us = USEC_PER_SEC / hw->clk_rate * 64;
755 	if (!dll_wait_time_us)
756 		dll_wait_time_us = 1;
757 
758 	/* Wait for the DLL to settle. */
759 	udelay(dll_wait_time_us);
760 
761 	return 0;
762 }
763 
764 static int gpmi_setup_interface(struct nand_chip *chip, int chipnr,
765 				const struct nand_interface_config *conf)
766 {
767 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
768 	const struct nand_sdr_timings *sdr;
769 
770 	/* Retrieve required NAND timings */
771 	sdr = nand_get_sdr_timings(conf);
772 	if (IS_ERR(sdr))
773 		return PTR_ERR(sdr);
774 
775 	/* Only MX6 GPMI controller can reach EDO timings */
776 	if (sdr->tRC_min <= 25000 && !GPMI_IS_MX6(this))
777 		return -ENOTSUPP;
778 
779 	/* Stop here if this call was just a check */
780 	if (chipnr < 0)
781 		return 0;
782 
783 	/* Do the actual derivation of the controller timings */
784 	gpmi_nfc_compute_timings(this, sdr);
785 
786 	this->hw.must_apply_timings = true;
787 
788 	return 0;
789 }
790 
791 /* Clears a BCH interrupt. */
792 static void gpmi_clear_bch(struct gpmi_nand_data *this)
793 {
794 	struct resources *r = &this->resources;
795 	writel(BM_BCH_CTRL_COMPLETE_IRQ, r->bch_regs + HW_BCH_CTRL_CLR);
796 }
797 
798 static struct dma_chan *get_dma_chan(struct gpmi_nand_data *this)
799 {
800 	/* We use the DMA channel 0 to access all the nand chips. */
801 	return this->dma_chans[0];
802 }
803 
804 /* This will be called after the DMA operation is finished. */
805 static void dma_irq_callback(void *param)
806 {
807 	struct gpmi_nand_data *this = param;
808 	struct completion *dma_c = &this->dma_done;
809 
810 	complete(dma_c);
811 }
812 
813 static irqreturn_t bch_irq(int irq, void *cookie)
814 {
815 	struct gpmi_nand_data *this = cookie;
816 
817 	gpmi_clear_bch(this);
818 	complete(&this->bch_done);
819 	return IRQ_HANDLED;
820 }
821 
822 static int gpmi_raw_len_to_len(struct gpmi_nand_data *this, int raw_len)
823 {
824 	/*
825 	 * raw_len is the length to read/write including bch data which
826 	 * we are passed in exec_op. Calculate the data length from it.
827 	 */
828 	if (this->bch)
829 		return ALIGN_DOWN(raw_len, this->bch_geometry.ecc_chunk_size);
830 	else
831 		return raw_len;
832 }
833 
834 /* Can we use the upper's buffer directly for DMA? */
835 static bool prepare_data_dma(struct gpmi_nand_data *this, const void *buf,
836 			     int raw_len, struct scatterlist *sgl,
837 			     enum dma_data_direction dr)
838 {
839 	int ret;
840 	int len = gpmi_raw_len_to_len(this, raw_len);
841 
842 	/* first try to map the upper buffer directly */
843 	if (virt_addr_valid(buf) && !object_is_on_stack(buf)) {
844 		sg_init_one(sgl, buf, len);
845 		ret = dma_map_sg(this->dev, sgl, 1, dr);
846 		if (ret == 0)
847 			goto map_fail;
848 
849 		return true;
850 	}
851 
852 map_fail:
853 	/* We have to use our own DMA buffer. */
854 	sg_init_one(sgl, this->data_buffer_dma, len);
855 
856 	if (dr == DMA_TO_DEVICE && buf != this->data_buffer_dma)
857 		memcpy(this->data_buffer_dma, buf, len);
858 
859 	dma_map_sg(this->dev, sgl, 1, dr);
860 
861 	return false;
862 }
863 
864 /* add our owner bbt descriptor */
865 static uint8_t scan_ff_pattern[] = { 0xff };
866 static struct nand_bbt_descr gpmi_bbt_descr = {
867 	.options	= 0,
868 	.offs		= 0,
869 	.len		= 1,
870 	.pattern	= scan_ff_pattern
871 };
872 
873 /*
874  * We may change the layout if we can get the ECC info from the datasheet,
875  * else we will use all the (page + OOB).
876  */
877 static int gpmi_ooblayout_ecc(struct mtd_info *mtd, int section,
878 			      struct mtd_oob_region *oobregion)
879 {
880 	struct nand_chip *chip = mtd_to_nand(mtd);
881 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
882 	struct bch_geometry *geo = &this->bch_geometry;
883 
884 	if (section)
885 		return -ERANGE;
886 
887 	oobregion->offset = 0;
888 	oobregion->length = geo->page_size - mtd->writesize;
889 
890 	return 0;
891 }
892 
893 static int gpmi_ooblayout_free(struct mtd_info *mtd, int section,
894 			       struct mtd_oob_region *oobregion)
895 {
896 	struct nand_chip *chip = mtd_to_nand(mtd);
897 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
898 	struct bch_geometry *geo = &this->bch_geometry;
899 
900 	if (section)
901 		return -ERANGE;
902 
903 	/* The available oob size we have. */
904 	if (geo->page_size < mtd->writesize + mtd->oobsize) {
905 		oobregion->offset = geo->page_size - mtd->writesize;
906 		oobregion->length = mtd->oobsize - oobregion->offset;
907 	}
908 
909 	return 0;
910 }
911 
912 static const char * const gpmi_clks_for_mx2x[] = {
913 	"gpmi_io",
914 };
915 
916 static const struct mtd_ooblayout_ops gpmi_ooblayout_ops = {
917 	.ecc = gpmi_ooblayout_ecc,
918 	.free = gpmi_ooblayout_free,
919 };
920 
921 static const struct gpmi_devdata gpmi_devdata_imx23 = {
922 	.type = IS_MX23,
923 	.bch_max_ecc_strength = 20,
924 	.max_chain_delay = 16000,
925 	.clks = gpmi_clks_for_mx2x,
926 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx2x),
927 };
928 
929 static const struct gpmi_devdata gpmi_devdata_imx28 = {
930 	.type = IS_MX28,
931 	.bch_max_ecc_strength = 20,
932 	.max_chain_delay = 16000,
933 	.clks = gpmi_clks_for_mx2x,
934 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx2x),
935 };
936 
937 static const char * const gpmi_clks_for_mx6[] = {
938 	"gpmi_io", "gpmi_apb", "gpmi_bch", "gpmi_bch_apb", "per1_bch",
939 };
940 
941 static const struct gpmi_devdata gpmi_devdata_imx6q = {
942 	.type = IS_MX6Q,
943 	.bch_max_ecc_strength = 40,
944 	.max_chain_delay = 12000,
945 	.clks = gpmi_clks_for_mx6,
946 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx6),
947 };
948 
949 static const struct gpmi_devdata gpmi_devdata_imx6sx = {
950 	.type = IS_MX6SX,
951 	.bch_max_ecc_strength = 62,
952 	.max_chain_delay = 12000,
953 	.clks = gpmi_clks_for_mx6,
954 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx6),
955 };
956 
957 static const char * const gpmi_clks_for_mx7d[] = {
958 	"gpmi_io", "gpmi_bch_apb",
959 };
960 
961 static const struct gpmi_devdata gpmi_devdata_imx7d = {
962 	.type = IS_MX7D,
963 	.bch_max_ecc_strength = 62,
964 	.max_chain_delay = 12000,
965 	.clks = gpmi_clks_for_mx7d,
966 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx7d),
967 };
968 
969 static int acquire_register_block(struct gpmi_nand_data *this,
970 				  const char *res_name)
971 {
972 	struct platform_device *pdev = this->pdev;
973 	struct resources *res = &this->resources;
974 	void __iomem *p;
975 
976 	p = devm_platform_ioremap_resource_byname(pdev, res_name);
977 	if (IS_ERR(p))
978 		return PTR_ERR(p);
979 
980 	if (!strcmp(res_name, GPMI_NAND_GPMI_REGS_ADDR_RES_NAME))
981 		res->gpmi_regs = p;
982 	else if (!strcmp(res_name, GPMI_NAND_BCH_REGS_ADDR_RES_NAME))
983 		res->bch_regs = p;
984 	else
985 		dev_err(this->dev, "unknown resource name : %s\n", res_name);
986 
987 	return 0;
988 }
989 
990 static int acquire_bch_irq(struct gpmi_nand_data *this, irq_handler_t irq_h)
991 {
992 	struct platform_device *pdev = this->pdev;
993 	const char *res_name = GPMI_NAND_BCH_INTERRUPT_RES_NAME;
994 	int err;
995 
996 	err = platform_get_irq_byname(pdev, res_name);
997 	if (err < 0)
998 		return err;
999 
1000 	err = devm_request_irq(this->dev, err, irq_h, 0, res_name, this);
1001 	if (err)
1002 		dev_err(this->dev, "error requesting BCH IRQ\n");
1003 
1004 	return err;
1005 }
1006 
1007 static void release_dma_channels(struct gpmi_nand_data *this)
1008 {
1009 	unsigned int i;
1010 	for (i = 0; i < DMA_CHANS; i++)
1011 		if (this->dma_chans[i]) {
1012 			dma_release_channel(this->dma_chans[i]);
1013 			this->dma_chans[i] = NULL;
1014 		}
1015 }
1016 
1017 static int acquire_dma_channels(struct gpmi_nand_data *this)
1018 {
1019 	struct platform_device *pdev = this->pdev;
1020 	struct dma_chan *dma_chan;
1021 	int ret = 0;
1022 
1023 	/* request dma channel */
1024 	dma_chan = dma_request_chan(&pdev->dev, "rx-tx");
1025 	if (IS_ERR(dma_chan)) {
1026 		ret = dev_err_probe(this->dev, PTR_ERR(dma_chan),
1027 				    "DMA channel request failed\n");
1028 		release_dma_channels(this);
1029 	} else {
1030 		this->dma_chans[0] = dma_chan;
1031 	}
1032 
1033 	return ret;
1034 }
1035 
1036 static int gpmi_get_clks(struct gpmi_nand_data *this)
1037 {
1038 	struct resources *r = &this->resources;
1039 	struct clk *clk;
1040 	int err, i;
1041 
1042 	for (i = 0; i < this->devdata->clks_count; i++) {
1043 		clk = devm_clk_get(this->dev, this->devdata->clks[i]);
1044 		if (IS_ERR(clk)) {
1045 			err = PTR_ERR(clk);
1046 			goto err_clock;
1047 		}
1048 
1049 		r->clock[i] = clk;
1050 	}
1051 
1052 	return 0;
1053 
1054 err_clock:
1055 	dev_dbg(this->dev, "failed in finding the clocks.\n");
1056 	return err;
1057 }
1058 
1059 static int acquire_resources(struct gpmi_nand_data *this)
1060 {
1061 	int ret;
1062 
1063 	ret = acquire_register_block(this, GPMI_NAND_GPMI_REGS_ADDR_RES_NAME);
1064 	if (ret)
1065 		goto exit_regs;
1066 
1067 	ret = acquire_register_block(this, GPMI_NAND_BCH_REGS_ADDR_RES_NAME);
1068 	if (ret)
1069 		goto exit_regs;
1070 
1071 	ret = acquire_bch_irq(this, bch_irq);
1072 	if (ret)
1073 		goto exit_regs;
1074 
1075 	ret = acquire_dma_channels(this);
1076 	if (ret)
1077 		goto exit_regs;
1078 
1079 	ret = gpmi_get_clks(this);
1080 	if (ret)
1081 		goto exit_clock;
1082 	return 0;
1083 
1084 exit_clock:
1085 	release_dma_channels(this);
1086 exit_regs:
1087 	return ret;
1088 }
1089 
1090 static void release_resources(struct gpmi_nand_data *this)
1091 {
1092 	release_dma_channels(this);
1093 }
1094 
1095 static void gpmi_free_dma_buffer(struct gpmi_nand_data *this)
1096 {
1097 	struct device *dev = this->dev;
1098 	struct bch_geometry *geo = &this->bch_geometry;
1099 
1100 	if (this->auxiliary_virt && virt_addr_valid(this->auxiliary_virt))
1101 		dma_free_coherent(dev, geo->auxiliary_size,
1102 					this->auxiliary_virt,
1103 					this->auxiliary_phys);
1104 	kfree(this->data_buffer_dma);
1105 	kfree(this->raw_buffer);
1106 
1107 	this->data_buffer_dma	= NULL;
1108 	this->raw_buffer	= NULL;
1109 }
1110 
1111 /* Allocate the DMA buffers */
1112 static int gpmi_alloc_dma_buffer(struct gpmi_nand_data *this)
1113 {
1114 	struct bch_geometry *geo = &this->bch_geometry;
1115 	struct device *dev = this->dev;
1116 	struct mtd_info *mtd = nand_to_mtd(&this->nand);
1117 
1118 	/*
1119 	 * [2] Allocate a read/write data buffer.
1120 	 *     The gpmi_alloc_dma_buffer can be called twice.
1121 	 *     We allocate a PAGE_SIZE length buffer if gpmi_alloc_dma_buffer
1122 	 *     is called before the NAND identification; and we allocate a
1123 	 *     buffer of the real NAND page size when the gpmi_alloc_dma_buffer
1124 	 *     is called after.
1125 	 */
1126 	this->data_buffer_dma = kzalloc(mtd->writesize ?: PAGE_SIZE,
1127 					GFP_DMA | GFP_KERNEL);
1128 	if (this->data_buffer_dma == NULL)
1129 		goto error_alloc;
1130 
1131 	this->auxiliary_virt = dma_alloc_coherent(dev, geo->auxiliary_size,
1132 					&this->auxiliary_phys, GFP_DMA);
1133 	if (!this->auxiliary_virt)
1134 		goto error_alloc;
1135 
1136 	this->raw_buffer = kzalloc((mtd->writesize ?: PAGE_SIZE) + mtd->oobsize, GFP_KERNEL);
1137 	if (!this->raw_buffer)
1138 		goto error_alloc;
1139 
1140 	return 0;
1141 
1142 error_alloc:
1143 	gpmi_free_dma_buffer(this);
1144 	return -ENOMEM;
1145 }
1146 
1147 /*
1148  * Handles block mark swapping.
1149  * It can be called in swapping the block mark, or swapping it back,
1150  * because the the operations are the same.
1151  */
1152 static void block_mark_swapping(struct gpmi_nand_data *this,
1153 				void *payload, void *auxiliary)
1154 {
1155 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1156 	unsigned char *p;
1157 	unsigned char *a;
1158 	unsigned int  bit;
1159 	unsigned char mask;
1160 	unsigned char from_data;
1161 	unsigned char from_oob;
1162 
1163 	if (!this->swap_block_mark)
1164 		return;
1165 
1166 	/*
1167 	 * If control arrives here, we're swapping. Make some convenience
1168 	 * variables.
1169 	 */
1170 	bit = nfc_geo->block_mark_bit_offset;
1171 	p   = payload + nfc_geo->block_mark_byte_offset;
1172 	a   = auxiliary;
1173 
1174 	/*
1175 	 * Get the byte from the data area that overlays the block mark. Since
1176 	 * the ECC engine applies its own view to the bits in the page, the
1177 	 * physical block mark won't (in general) appear on a byte boundary in
1178 	 * the data.
1179 	 */
1180 	from_data = (p[0] >> bit) | (p[1] << (8 - bit));
1181 
1182 	/* Get the byte from the OOB. */
1183 	from_oob = a[0];
1184 
1185 	/* Swap them. */
1186 	a[0] = from_data;
1187 
1188 	mask = (0x1 << bit) - 1;
1189 	p[0] = (p[0] & mask) | (from_oob << bit);
1190 
1191 	mask = ~0 << bit;
1192 	p[1] = (p[1] & mask) | (from_oob >> (8 - bit));
1193 }
1194 
1195 static int gpmi_count_bitflips(struct nand_chip *chip, void *buf, int first,
1196 			       int last, int meta)
1197 {
1198 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1199 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1200 	struct mtd_info *mtd = nand_to_mtd(chip);
1201 	int i;
1202 	unsigned char *status;
1203 	unsigned int max_bitflips = 0;
1204 
1205 	/* Loop over status bytes, accumulating ECC status. */
1206 	status = this->auxiliary_virt + ALIGN(meta, 4);
1207 
1208 	for (i = first; i < last; i++, status++) {
1209 		if ((*status == STATUS_GOOD) || (*status == STATUS_ERASED))
1210 			continue;
1211 
1212 		if (*status == STATUS_UNCORRECTABLE) {
1213 			int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1214 			u8 *eccbuf = this->raw_buffer;
1215 			int offset, bitoffset;
1216 			int eccbytes;
1217 			int flips;
1218 
1219 			/* Read ECC bytes into our internal raw_buffer */
1220 			offset = nfc_geo->metadata_size * 8;
1221 			offset += ((8 * nfc_geo->ecc_chunk_size) + eccbits) * (i + 1);
1222 			offset -= eccbits;
1223 			bitoffset = offset % 8;
1224 			eccbytes = DIV_ROUND_UP(offset + eccbits, 8);
1225 			offset /= 8;
1226 			eccbytes -= offset;
1227 			nand_change_read_column_op(chip, offset, eccbuf,
1228 						   eccbytes, false);
1229 
1230 			/*
1231 			 * ECC data are not byte aligned and we may have
1232 			 * in-band data in the first and last byte of
1233 			 * eccbuf. Set non-eccbits to one so that
1234 			 * nand_check_erased_ecc_chunk() does not count them
1235 			 * as bitflips.
1236 			 */
1237 			if (bitoffset)
1238 				eccbuf[0] |= GENMASK(bitoffset - 1, 0);
1239 
1240 			bitoffset = (bitoffset + eccbits) % 8;
1241 			if (bitoffset)
1242 				eccbuf[eccbytes - 1] |= GENMASK(7, bitoffset);
1243 
1244 			/*
1245 			 * The ECC hardware has an uncorrectable ECC status
1246 			 * code in case we have bitflips in an erased page. As
1247 			 * nothing was written into this subpage the ECC is
1248 			 * obviously wrong and we can not trust it. We assume
1249 			 * at this point that we are reading an erased page and
1250 			 * try to correct the bitflips in buffer up to
1251 			 * ecc_strength bitflips. If this is a page with random
1252 			 * data, we exceed this number of bitflips and have a
1253 			 * ECC failure. Otherwise we use the corrected buffer.
1254 			 */
1255 			if (i == 0) {
1256 				/* The first block includes metadata */
1257 				flips = nand_check_erased_ecc_chunk(
1258 						buf + i * nfc_geo->ecc_chunk_size,
1259 						nfc_geo->ecc_chunk_size,
1260 						eccbuf, eccbytes,
1261 						this->auxiliary_virt,
1262 						nfc_geo->metadata_size,
1263 						nfc_geo->ecc_strength);
1264 			} else {
1265 				flips = nand_check_erased_ecc_chunk(
1266 						buf + i * nfc_geo->ecc_chunk_size,
1267 						nfc_geo->ecc_chunk_size,
1268 						eccbuf, eccbytes,
1269 						NULL, 0,
1270 						nfc_geo->ecc_strength);
1271 			}
1272 
1273 			if (flips > 0) {
1274 				max_bitflips = max_t(unsigned int, max_bitflips,
1275 						     flips);
1276 				mtd->ecc_stats.corrected += flips;
1277 				continue;
1278 			}
1279 
1280 			mtd->ecc_stats.failed++;
1281 			continue;
1282 		}
1283 
1284 		mtd->ecc_stats.corrected += *status;
1285 		max_bitflips = max_t(unsigned int, max_bitflips, *status);
1286 	}
1287 
1288 	return max_bitflips;
1289 }
1290 
1291 static void gpmi_bch_layout_std(struct gpmi_nand_data *this)
1292 {
1293 	struct bch_geometry *geo = &this->bch_geometry;
1294 	unsigned int ecc_strength = geo->ecc_strength >> 1;
1295 	unsigned int gf_len = geo->gf_len;
1296 	unsigned int block_size = geo->ecc_chunk_size;
1297 
1298 	this->bch_flashlayout0 =
1299 		BF_BCH_FLASH0LAYOUT0_NBLOCKS(geo->ecc_chunk_count - 1) |
1300 		BF_BCH_FLASH0LAYOUT0_META_SIZE(geo->metadata_size) |
1301 		BF_BCH_FLASH0LAYOUT0_ECC0(ecc_strength, this) |
1302 		BF_BCH_FLASH0LAYOUT0_GF(gf_len, this) |
1303 		BF_BCH_FLASH0LAYOUT0_DATA0_SIZE(block_size, this);
1304 
1305 	this->bch_flashlayout1 =
1306 		BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(geo->page_size) |
1307 		BF_BCH_FLASH0LAYOUT1_ECCN(ecc_strength, this) |
1308 		BF_BCH_FLASH0LAYOUT1_GF(gf_len, this) |
1309 		BF_BCH_FLASH0LAYOUT1_DATAN_SIZE(block_size, this);
1310 }
1311 
1312 static int gpmi_ecc_read_page(struct nand_chip *chip, uint8_t *buf,
1313 			      int oob_required, int page)
1314 {
1315 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1316 	struct mtd_info *mtd = nand_to_mtd(chip);
1317 	struct bch_geometry *geo = &this->bch_geometry;
1318 	unsigned int max_bitflips;
1319 	int ret;
1320 
1321 	gpmi_bch_layout_std(this);
1322 	this->bch = true;
1323 
1324 	ret = nand_read_page_op(chip, page, 0, buf, geo->page_size);
1325 	if (ret)
1326 		return ret;
1327 
1328 	max_bitflips = gpmi_count_bitflips(chip, buf, 0,
1329 					   geo->ecc_chunk_count,
1330 					   geo->auxiliary_status_offset);
1331 
1332 	/* handle the block mark swapping */
1333 	block_mark_swapping(this, buf, this->auxiliary_virt);
1334 
1335 	if (oob_required) {
1336 		/*
1337 		 * It's time to deliver the OOB bytes. See gpmi_ecc_read_oob()
1338 		 * for details about our policy for delivering the OOB.
1339 		 *
1340 		 * We fill the caller's buffer with set bits, and then copy the
1341 		 * block mark to th caller's buffer. Note that, if block mark
1342 		 * swapping was necessary, it has already been done, so we can
1343 		 * rely on the first byte of the auxiliary buffer to contain
1344 		 * the block mark.
1345 		 */
1346 		memset(chip->oob_poi, ~0, mtd->oobsize);
1347 		chip->oob_poi[0] = ((uint8_t *)this->auxiliary_virt)[0];
1348 	}
1349 
1350 	return max_bitflips;
1351 }
1352 
1353 /* Fake a virtual small page for the subpage read */
1354 static int gpmi_ecc_read_subpage(struct nand_chip *chip, uint32_t offs,
1355 				 uint32_t len, uint8_t *buf, int page)
1356 {
1357 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1358 	struct bch_geometry *geo = &this->bch_geometry;
1359 	int size = chip->ecc.size; /* ECC chunk size */
1360 	int meta, n, page_size;
1361 	unsigned int max_bitflips;
1362 	unsigned int ecc_strength;
1363 	int first, last, marker_pos;
1364 	int ecc_parity_size;
1365 	int col = 0;
1366 	int ret;
1367 
1368 	/* The size of ECC parity */
1369 	ecc_parity_size = geo->gf_len * geo->ecc_strength / 8;
1370 
1371 	/* Align it with the chunk size */
1372 	first = offs / size;
1373 	last = (offs + len - 1) / size;
1374 
1375 	if (this->swap_block_mark) {
1376 		/*
1377 		 * Find the chunk which contains the Block Marker.
1378 		 * If this chunk is in the range of [first, last],
1379 		 * we have to read out the whole page.
1380 		 * Why? since we had swapped the data at the position of Block
1381 		 * Marker to the metadata which is bound with the chunk 0.
1382 		 */
1383 		marker_pos = geo->block_mark_byte_offset / size;
1384 		if (last >= marker_pos && first <= marker_pos) {
1385 			dev_dbg(this->dev,
1386 				"page:%d, first:%d, last:%d, marker at:%d\n",
1387 				page, first, last, marker_pos);
1388 			return gpmi_ecc_read_page(chip, buf, 0, page);
1389 		}
1390 	}
1391 
1392 	meta = geo->metadata_size;
1393 	if (first) {
1394 		col = meta + (size + ecc_parity_size) * first;
1395 		meta = 0;
1396 		buf = buf + first * size;
1397 	}
1398 
1399 	ecc_parity_size = geo->gf_len * geo->ecc_strength / 8;
1400 
1401 	n = last - first + 1;
1402 	page_size = meta + (size + ecc_parity_size) * n;
1403 	ecc_strength = geo->ecc_strength >> 1;
1404 
1405 	this->bch_flashlayout0 = BF_BCH_FLASH0LAYOUT0_NBLOCKS(n - 1) |
1406 		BF_BCH_FLASH0LAYOUT0_META_SIZE(meta) |
1407 		BF_BCH_FLASH0LAYOUT0_ECC0(ecc_strength, this) |
1408 		BF_BCH_FLASH0LAYOUT0_GF(geo->gf_len, this) |
1409 		BF_BCH_FLASH0LAYOUT0_DATA0_SIZE(geo->ecc_chunk_size, this);
1410 
1411 	this->bch_flashlayout1 = BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(page_size) |
1412 		BF_BCH_FLASH0LAYOUT1_ECCN(ecc_strength, this) |
1413 		BF_BCH_FLASH0LAYOUT1_GF(geo->gf_len, this) |
1414 		BF_BCH_FLASH0LAYOUT1_DATAN_SIZE(geo->ecc_chunk_size, this);
1415 
1416 	this->bch = true;
1417 
1418 	ret = nand_read_page_op(chip, page, col, buf, page_size);
1419 	if (ret)
1420 		return ret;
1421 
1422 	dev_dbg(this->dev, "page:%d(%d:%d)%d, chunk:(%d:%d), BCH PG size:%d\n",
1423 		page, offs, len, col, first, n, page_size);
1424 
1425 	max_bitflips = gpmi_count_bitflips(chip, buf, first, last, meta);
1426 
1427 	return max_bitflips;
1428 }
1429 
1430 static int gpmi_ecc_write_page(struct nand_chip *chip, const uint8_t *buf,
1431 			       int oob_required, int page)
1432 {
1433 	struct mtd_info *mtd = nand_to_mtd(chip);
1434 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1435 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1436 
1437 	dev_dbg(this->dev, "ecc write page.\n");
1438 
1439 	gpmi_bch_layout_std(this);
1440 	this->bch = true;
1441 
1442 	memcpy(this->auxiliary_virt, chip->oob_poi, nfc_geo->auxiliary_size);
1443 
1444 	if (this->swap_block_mark) {
1445 		/*
1446 		 * When doing bad block marker swapping we must always copy the
1447 		 * input buffer as we can't modify the const buffer.
1448 		 */
1449 		memcpy(this->data_buffer_dma, buf, mtd->writesize);
1450 		buf = this->data_buffer_dma;
1451 		block_mark_swapping(this, this->data_buffer_dma,
1452 				    this->auxiliary_virt);
1453 	}
1454 
1455 	return nand_prog_page_op(chip, page, 0, buf, nfc_geo->page_size);
1456 }
1457 
1458 /*
1459  * There are several places in this driver where we have to handle the OOB and
1460  * block marks. This is the function where things are the most complicated, so
1461  * this is where we try to explain it all. All the other places refer back to
1462  * here.
1463  *
1464  * These are the rules, in order of decreasing importance:
1465  *
1466  * 1) Nothing the caller does can be allowed to imperil the block mark.
1467  *
1468  * 2) In read operations, the first byte of the OOB we return must reflect the
1469  *    true state of the block mark, no matter where that block mark appears in
1470  *    the physical page.
1471  *
1472  * 3) ECC-based read operations return an OOB full of set bits (since we never
1473  *    allow ECC-based writes to the OOB, it doesn't matter what ECC-based reads
1474  *    return).
1475  *
1476  * 4) "Raw" read operations return a direct view of the physical bytes in the
1477  *    page, using the conventional definition of which bytes are data and which
1478  *    are OOB. This gives the caller a way to see the actual, physical bytes
1479  *    in the page, without the distortions applied by our ECC engine.
1480  *
1481  *
1482  * What we do for this specific read operation depends on two questions:
1483  *
1484  * 1) Are we doing a "raw" read, or an ECC-based read?
1485  *
1486  * 2) Are we using block mark swapping or transcription?
1487  *
1488  * There are four cases, illustrated by the following Karnaugh map:
1489  *
1490  *                    |           Raw           |         ECC-based       |
1491  *       -------------+-------------------------+-------------------------+
1492  *                    | Read the conventional   |                         |
1493  *                    | OOB at the end of the   |                         |
1494  *       Swapping     | page and return it. It  |                         |
1495  *                    | contains exactly what   |                         |
1496  *                    | we want.                | Read the block mark and |
1497  *       -------------+-------------------------+ return it in a buffer   |
1498  *                    | Read the conventional   | full of set bits.       |
1499  *                    | OOB at the end of the   |                         |
1500  *                    | page and also the block |                         |
1501  *       Transcribing | mark in the metadata.   |                         |
1502  *                    | Copy the block mark     |                         |
1503  *                    | into the first byte of  |                         |
1504  *                    | the OOB.                |                         |
1505  *       -------------+-------------------------+-------------------------+
1506  *
1507  * Note that we break rule #4 in the Transcribing/Raw case because we're not
1508  * giving an accurate view of the actual, physical bytes in the page (we're
1509  * overwriting the block mark). That's OK because it's more important to follow
1510  * rule #2.
1511  *
1512  * It turns out that knowing whether we want an "ECC-based" or "raw" read is not
1513  * easy. When reading a page, for example, the NAND Flash MTD code calls our
1514  * ecc.read_page or ecc.read_page_raw function. Thus, the fact that MTD wants an
1515  * ECC-based or raw view of the page is implicit in which function it calls
1516  * (there is a similar pair of ECC-based/raw functions for writing).
1517  */
1518 static int gpmi_ecc_read_oob(struct nand_chip *chip, int page)
1519 {
1520 	struct mtd_info *mtd = nand_to_mtd(chip);
1521 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1522 	int ret;
1523 
1524 	/* clear the OOB buffer */
1525 	memset(chip->oob_poi, ~0, mtd->oobsize);
1526 
1527 	/* Read out the conventional OOB. */
1528 	ret = nand_read_page_op(chip, page, mtd->writesize, chip->oob_poi,
1529 				mtd->oobsize);
1530 	if (ret)
1531 		return ret;
1532 
1533 	/*
1534 	 * Now, we want to make sure the block mark is correct. In the
1535 	 * non-transcribing case (!GPMI_IS_MX23()), we already have it.
1536 	 * Otherwise, we need to explicitly read it.
1537 	 */
1538 	if (GPMI_IS_MX23(this)) {
1539 		/* Read the block mark into the first byte of the OOB buffer. */
1540 		ret = nand_read_page_op(chip, page, 0, chip->oob_poi, 1);
1541 		if (ret)
1542 			return ret;
1543 	}
1544 
1545 	return 0;
1546 }
1547 
1548 static int gpmi_ecc_write_oob(struct nand_chip *chip, int page)
1549 {
1550 	struct mtd_info *mtd = nand_to_mtd(chip);
1551 	struct mtd_oob_region of = { };
1552 
1553 	/* Do we have available oob area? */
1554 	mtd_ooblayout_free(mtd, 0, &of);
1555 	if (!of.length)
1556 		return -EPERM;
1557 
1558 	if (!nand_is_slc(chip))
1559 		return -EPERM;
1560 
1561 	return nand_prog_page_op(chip, page, mtd->writesize + of.offset,
1562 				 chip->oob_poi + of.offset, of.length);
1563 }
1564 
1565 /*
1566  * This function reads a NAND page without involving the ECC engine (no HW
1567  * ECC correction).
1568  * The tricky part in the GPMI/BCH controller is that it stores ECC bits
1569  * inline (interleaved with payload DATA), and do not align data chunk on
1570  * byte boundaries.
1571  * We thus need to take care moving the payload data and ECC bits stored in the
1572  * page into the provided buffers, which is why we're using nand_extract_bits().
1573  *
1574  * See set_geometry_by_ecc_info inline comments to have a full description
1575  * of the layout used by the GPMI controller.
1576  */
1577 static int gpmi_ecc_read_page_raw(struct nand_chip *chip, uint8_t *buf,
1578 				  int oob_required, int page)
1579 {
1580 	struct mtd_info *mtd = nand_to_mtd(chip);
1581 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1582 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1583 	int eccsize = nfc_geo->ecc_chunk_size;
1584 	int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1585 	u8 *tmp_buf = this->raw_buffer;
1586 	size_t src_bit_off;
1587 	size_t oob_bit_off;
1588 	size_t oob_byte_off;
1589 	uint8_t *oob = chip->oob_poi;
1590 	int step;
1591 	int ret;
1592 
1593 	ret = nand_read_page_op(chip, page, 0, tmp_buf,
1594 				mtd->writesize + mtd->oobsize);
1595 	if (ret)
1596 		return ret;
1597 
1598 	/*
1599 	 * If required, swap the bad block marker and the data stored in the
1600 	 * metadata section, so that we don't wrongly consider a block as bad.
1601 	 *
1602 	 * See the layout description for a detailed explanation on why this
1603 	 * is needed.
1604 	 */
1605 	if (this->swap_block_mark)
1606 		swap(tmp_buf[0], tmp_buf[mtd->writesize]);
1607 
1608 	/*
1609 	 * Copy the metadata section into the oob buffer (this section is
1610 	 * guaranteed to be aligned on a byte boundary).
1611 	 */
1612 	if (oob_required)
1613 		memcpy(oob, tmp_buf, nfc_geo->metadata_size);
1614 
1615 	oob_bit_off = nfc_geo->metadata_size * 8;
1616 	src_bit_off = oob_bit_off;
1617 
1618 	/* Extract interleaved payload data and ECC bits */
1619 	for (step = 0; step < nfc_geo->ecc_chunk_count; step++) {
1620 		if (buf)
1621 			nand_extract_bits(buf, step * eccsize * 8, tmp_buf,
1622 					  src_bit_off, eccsize * 8);
1623 		src_bit_off += eccsize * 8;
1624 
1625 		/* Align last ECC block to align a byte boundary */
1626 		if (step == nfc_geo->ecc_chunk_count - 1 &&
1627 		    (oob_bit_off + eccbits) % 8)
1628 			eccbits += 8 - ((oob_bit_off + eccbits) % 8);
1629 
1630 		if (oob_required)
1631 			nand_extract_bits(oob, oob_bit_off, tmp_buf,
1632 					  src_bit_off, eccbits);
1633 
1634 		src_bit_off += eccbits;
1635 		oob_bit_off += eccbits;
1636 	}
1637 
1638 	if (oob_required) {
1639 		oob_byte_off = oob_bit_off / 8;
1640 
1641 		if (oob_byte_off < mtd->oobsize)
1642 			memcpy(oob + oob_byte_off,
1643 			       tmp_buf + mtd->writesize + oob_byte_off,
1644 			       mtd->oobsize - oob_byte_off);
1645 	}
1646 
1647 	return 0;
1648 }
1649 
1650 /*
1651  * This function writes a NAND page without involving the ECC engine (no HW
1652  * ECC generation).
1653  * The tricky part in the GPMI/BCH controller is that it stores ECC bits
1654  * inline (interleaved with payload DATA), and do not align data chunk on
1655  * byte boundaries.
1656  * We thus need to take care moving the OOB area at the right place in the
1657  * final page, which is why we're using nand_extract_bits().
1658  *
1659  * See set_geometry_by_ecc_info inline comments to have a full description
1660  * of the layout used by the GPMI controller.
1661  */
1662 static int gpmi_ecc_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
1663 				   int oob_required, int page)
1664 {
1665 	struct mtd_info *mtd = nand_to_mtd(chip);
1666 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1667 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1668 	int eccsize = nfc_geo->ecc_chunk_size;
1669 	int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1670 	u8 *tmp_buf = this->raw_buffer;
1671 	uint8_t *oob = chip->oob_poi;
1672 	size_t dst_bit_off;
1673 	size_t oob_bit_off;
1674 	size_t oob_byte_off;
1675 	int step;
1676 
1677 	/*
1678 	 * Initialize all bits to 1 in case we don't have a buffer for the
1679 	 * payload or oob data in order to leave unspecified bits of data
1680 	 * to their initial state.
1681 	 */
1682 	if (!buf || !oob_required)
1683 		memset(tmp_buf, 0xff, mtd->writesize + mtd->oobsize);
1684 
1685 	/*
1686 	 * First copy the metadata section (stored in oob buffer) at the
1687 	 * beginning of the page, as imposed by the GPMI layout.
1688 	 */
1689 	memcpy(tmp_buf, oob, nfc_geo->metadata_size);
1690 	oob_bit_off = nfc_geo->metadata_size * 8;
1691 	dst_bit_off = oob_bit_off;
1692 
1693 	/* Interleave payload data and ECC bits */
1694 	for (step = 0; step < nfc_geo->ecc_chunk_count; step++) {
1695 		if (buf)
1696 			nand_extract_bits(tmp_buf, dst_bit_off, buf,
1697 					  step * eccsize * 8, eccsize * 8);
1698 		dst_bit_off += eccsize * 8;
1699 
1700 		/* Align last ECC block to align a byte boundary */
1701 		if (step == nfc_geo->ecc_chunk_count - 1 &&
1702 		    (oob_bit_off + eccbits) % 8)
1703 			eccbits += 8 - ((oob_bit_off + eccbits) % 8);
1704 
1705 		if (oob_required)
1706 			nand_extract_bits(tmp_buf, dst_bit_off, oob,
1707 					  oob_bit_off, eccbits);
1708 
1709 		dst_bit_off += eccbits;
1710 		oob_bit_off += eccbits;
1711 	}
1712 
1713 	oob_byte_off = oob_bit_off / 8;
1714 
1715 	if (oob_required && oob_byte_off < mtd->oobsize)
1716 		memcpy(tmp_buf + mtd->writesize + oob_byte_off,
1717 		       oob + oob_byte_off, mtd->oobsize - oob_byte_off);
1718 
1719 	/*
1720 	 * If required, swap the bad block marker and the first byte of the
1721 	 * metadata section, so that we don't modify the bad block marker.
1722 	 *
1723 	 * See the layout description for a detailed explanation on why this
1724 	 * is needed.
1725 	 */
1726 	if (this->swap_block_mark)
1727 		swap(tmp_buf[0], tmp_buf[mtd->writesize]);
1728 
1729 	return nand_prog_page_op(chip, page, 0, tmp_buf,
1730 				 mtd->writesize + mtd->oobsize);
1731 }
1732 
1733 static int gpmi_ecc_read_oob_raw(struct nand_chip *chip, int page)
1734 {
1735 	return gpmi_ecc_read_page_raw(chip, NULL, 1, page);
1736 }
1737 
1738 static int gpmi_ecc_write_oob_raw(struct nand_chip *chip, int page)
1739 {
1740 	return gpmi_ecc_write_page_raw(chip, NULL, 1, page);
1741 }
1742 
1743 static int gpmi_block_markbad(struct nand_chip *chip, loff_t ofs)
1744 {
1745 	struct mtd_info *mtd = nand_to_mtd(chip);
1746 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1747 	int ret = 0;
1748 	uint8_t *block_mark;
1749 	int column, page, chipnr;
1750 
1751 	chipnr = (int)(ofs >> chip->chip_shift);
1752 	nand_select_target(chip, chipnr);
1753 
1754 	column = !GPMI_IS_MX23(this) ? mtd->writesize : 0;
1755 
1756 	/* Write the block mark. */
1757 	block_mark = this->data_buffer_dma;
1758 	block_mark[0] = 0; /* bad block marker */
1759 
1760 	/* Shift to get page */
1761 	page = (int)(ofs >> chip->page_shift);
1762 
1763 	ret = nand_prog_page_op(chip, page, column, block_mark, 1);
1764 
1765 	nand_deselect_target(chip);
1766 
1767 	return ret;
1768 }
1769 
1770 static int nand_boot_set_geometry(struct gpmi_nand_data *this)
1771 {
1772 	struct boot_rom_geometry *geometry = &this->rom_geometry;
1773 
1774 	/*
1775 	 * Set the boot block stride size.
1776 	 *
1777 	 * In principle, we should be reading this from the OTP bits, since
1778 	 * that's where the ROM is going to get it. In fact, we don't have any
1779 	 * way to read the OTP bits, so we go with the default and hope for the
1780 	 * best.
1781 	 */
1782 	geometry->stride_size_in_pages = 64;
1783 
1784 	/*
1785 	 * Set the search area stride exponent.
1786 	 *
1787 	 * In principle, we should be reading this from the OTP bits, since
1788 	 * that's where the ROM is going to get it. In fact, we don't have any
1789 	 * way to read the OTP bits, so we go with the default and hope for the
1790 	 * best.
1791 	 */
1792 	geometry->search_area_stride_exponent = 2;
1793 	return 0;
1794 }
1795 
1796 static const char  *fingerprint = "STMP";
1797 static int mx23_check_transcription_stamp(struct gpmi_nand_data *this)
1798 {
1799 	struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1800 	struct device *dev = this->dev;
1801 	struct nand_chip *chip = &this->nand;
1802 	unsigned int search_area_size_in_strides;
1803 	unsigned int stride;
1804 	unsigned int page;
1805 	u8 *buffer = nand_get_data_buf(chip);
1806 	int found_an_ncb_fingerprint = false;
1807 	int ret;
1808 
1809 	/* Compute the number of strides in a search area. */
1810 	search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1811 
1812 	nand_select_target(chip, 0);
1813 
1814 	/*
1815 	 * Loop through the first search area, looking for the NCB fingerprint.
1816 	 */
1817 	dev_dbg(dev, "Scanning for an NCB fingerprint...\n");
1818 
1819 	for (stride = 0; stride < search_area_size_in_strides; stride++) {
1820 		/* Compute the page addresses. */
1821 		page = stride * rom_geo->stride_size_in_pages;
1822 
1823 		dev_dbg(dev, "Looking for a fingerprint in page 0x%x\n", page);
1824 
1825 		/*
1826 		 * Read the NCB fingerprint. The fingerprint is four bytes long
1827 		 * and starts in the 12th byte of the page.
1828 		 */
1829 		ret = nand_read_page_op(chip, page, 12, buffer,
1830 					strlen(fingerprint));
1831 		if (ret)
1832 			continue;
1833 
1834 		/* Look for the fingerprint. */
1835 		if (!memcmp(buffer, fingerprint, strlen(fingerprint))) {
1836 			found_an_ncb_fingerprint = true;
1837 			break;
1838 		}
1839 
1840 	}
1841 
1842 	nand_deselect_target(chip);
1843 
1844 	if (found_an_ncb_fingerprint)
1845 		dev_dbg(dev, "\tFound a fingerprint\n");
1846 	else
1847 		dev_dbg(dev, "\tNo fingerprint found\n");
1848 	return found_an_ncb_fingerprint;
1849 }
1850 
1851 /* Writes a transcription stamp. */
1852 static int mx23_write_transcription_stamp(struct gpmi_nand_data *this)
1853 {
1854 	struct device *dev = this->dev;
1855 	struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1856 	struct nand_chip *chip = &this->nand;
1857 	struct mtd_info *mtd = nand_to_mtd(chip);
1858 	unsigned int block_size_in_pages;
1859 	unsigned int search_area_size_in_strides;
1860 	unsigned int search_area_size_in_pages;
1861 	unsigned int search_area_size_in_blocks;
1862 	unsigned int block;
1863 	unsigned int stride;
1864 	unsigned int page;
1865 	u8 *buffer = nand_get_data_buf(chip);
1866 	int status;
1867 
1868 	/* Compute the search area geometry. */
1869 	block_size_in_pages = mtd->erasesize / mtd->writesize;
1870 	search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1871 	search_area_size_in_pages = search_area_size_in_strides *
1872 					rom_geo->stride_size_in_pages;
1873 	search_area_size_in_blocks =
1874 		  (search_area_size_in_pages + (block_size_in_pages - 1)) /
1875 				    block_size_in_pages;
1876 
1877 	dev_dbg(dev, "Search Area Geometry :\n");
1878 	dev_dbg(dev, "\tin Blocks : %u\n", search_area_size_in_blocks);
1879 	dev_dbg(dev, "\tin Strides: %u\n", search_area_size_in_strides);
1880 	dev_dbg(dev, "\tin Pages  : %u\n", search_area_size_in_pages);
1881 
1882 	nand_select_target(chip, 0);
1883 
1884 	/* Loop over blocks in the first search area, erasing them. */
1885 	dev_dbg(dev, "Erasing the search area...\n");
1886 
1887 	for (block = 0; block < search_area_size_in_blocks; block++) {
1888 		/* Erase this block. */
1889 		dev_dbg(dev, "\tErasing block 0x%x\n", block);
1890 		status = nand_erase_op(chip, block);
1891 		if (status)
1892 			dev_err(dev, "[%s] Erase failed.\n", __func__);
1893 	}
1894 
1895 	/* Write the NCB fingerprint into the page buffer. */
1896 	memset(buffer, ~0, mtd->writesize);
1897 	memcpy(buffer + 12, fingerprint, strlen(fingerprint));
1898 
1899 	/* Loop through the first search area, writing NCB fingerprints. */
1900 	dev_dbg(dev, "Writing NCB fingerprints...\n");
1901 	for (stride = 0; stride < search_area_size_in_strides; stride++) {
1902 		/* Compute the page addresses. */
1903 		page = stride * rom_geo->stride_size_in_pages;
1904 
1905 		/* Write the first page of the current stride. */
1906 		dev_dbg(dev, "Writing an NCB fingerprint in page 0x%x\n", page);
1907 
1908 		status = chip->ecc.write_page_raw(chip, buffer, 0, page);
1909 		if (status)
1910 			dev_err(dev, "[%s] Write failed.\n", __func__);
1911 	}
1912 
1913 	nand_deselect_target(chip);
1914 
1915 	return 0;
1916 }
1917 
1918 static int mx23_boot_init(struct gpmi_nand_data  *this)
1919 {
1920 	struct device *dev = this->dev;
1921 	struct nand_chip *chip = &this->nand;
1922 	struct mtd_info *mtd = nand_to_mtd(chip);
1923 	unsigned int block_count;
1924 	unsigned int block;
1925 	int     chipnr;
1926 	int     page;
1927 	loff_t  byte;
1928 	uint8_t block_mark;
1929 	int     ret = 0;
1930 
1931 	/*
1932 	 * If control arrives here, we can't use block mark swapping, which
1933 	 * means we're forced to use transcription. First, scan for the
1934 	 * transcription stamp. If we find it, then we don't have to do
1935 	 * anything -- the block marks are already transcribed.
1936 	 */
1937 	if (mx23_check_transcription_stamp(this))
1938 		return 0;
1939 
1940 	/*
1941 	 * If control arrives here, we couldn't find a transcription stamp, so
1942 	 * so we presume the block marks are in the conventional location.
1943 	 */
1944 	dev_dbg(dev, "Transcribing bad block marks...\n");
1945 
1946 	/* Compute the number of blocks in the entire medium. */
1947 	block_count = nanddev_eraseblocks_per_target(&chip->base);
1948 
1949 	/*
1950 	 * Loop over all the blocks in the medium, transcribing block marks as
1951 	 * we go.
1952 	 */
1953 	for (block = 0; block < block_count; block++) {
1954 		/*
1955 		 * Compute the chip, page and byte addresses for this block's
1956 		 * conventional mark.
1957 		 */
1958 		chipnr = block >> (chip->chip_shift - chip->phys_erase_shift);
1959 		page = block << (chip->phys_erase_shift - chip->page_shift);
1960 		byte = block <<  chip->phys_erase_shift;
1961 
1962 		/* Send the command to read the conventional block mark. */
1963 		nand_select_target(chip, chipnr);
1964 		ret = nand_read_page_op(chip, page, mtd->writesize, &block_mark,
1965 					1);
1966 		nand_deselect_target(chip);
1967 
1968 		if (ret)
1969 			continue;
1970 
1971 		/*
1972 		 * Check if the block is marked bad. If so, we need to mark it
1973 		 * again, but this time the result will be a mark in the
1974 		 * location where we transcribe block marks.
1975 		 */
1976 		if (block_mark != 0xff) {
1977 			dev_dbg(dev, "Transcribing mark in block %u\n", block);
1978 			ret = chip->legacy.block_markbad(chip, byte);
1979 			if (ret)
1980 				dev_err(dev,
1981 					"Failed to mark block bad with ret %d\n",
1982 					ret);
1983 		}
1984 	}
1985 
1986 	/* Write the stamp that indicates we've transcribed the block marks. */
1987 	mx23_write_transcription_stamp(this);
1988 	return 0;
1989 }
1990 
1991 static int nand_boot_init(struct gpmi_nand_data  *this)
1992 {
1993 	nand_boot_set_geometry(this);
1994 
1995 	/* This is ROM arch-specific initilization before the BBT scanning. */
1996 	if (GPMI_IS_MX23(this))
1997 		return mx23_boot_init(this);
1998 	return 0;
1999 }
2000 
2001 static int gpmi_set_geometry(struct gpmi_nand_data *this)
2002 {
2003 	int ret;
2004 
2005 	/* Free the temporary DMA memory for reading ID. */
2006 	gpmi_free_dma_buffer(this);
2007 
2008 	/* Set up the NFC geometry which is used by BCH. */
2009 	ret = bch_set_geometry(this);
2010 	if (ret) {
2011 		dev_err(this->dev, "Error setting BCH geometry : %d\n", ret);
2012 		return ret;
2013 	}
2014 
2015 	/* Alloc the new DMA buffers according to the pagesize and oobsize */
2016 	return gpmi_alloc_dma_buffer(this);
2017 }
2018 
2019 static int gpmi_init_last(struct gpmi_nand_data *this)
2020 {
2021 	struct nand_chip *chip = &this->nand;
2022 	struct mtd_info *mtd = nand_to_mtd(chip);
2023 	struct nand_ecc_ctrl *ecc = &chip->ecc;
2024 	struct bch_geometry *bch_geo = &this->bch_geometry;
2025 	int ret;
2026 
2027 	/* Set up the medium geometry */
2028 	ret = gpmi_set_geometry(this);
2029 	if (ret)
2030 		return ret;
2031 
2032 	/* Init the nand_ecc_ctrl{} */
2033 	ecc->read_page	= gpmi_ecc_read_page;
2034 	ecc->write_page	= gpmi_ecc_write_page;
2035 	ecc->read_oob	= gpmi_ecc_read_oob;
2036 	ecc->write_oob	= gpmi_ecc_write_oob;
2037 	ecc->read_page_raw = gpmi_ecc_read_page_raw;
2038 	ecc->write_page_raw = gpmi_ecc_write_page_raw;
2039 	ecc->read_oob_raw = gpmi_ecc_read_oob_raw;
2040 	ecc->write_oob_raw = gpmi_ecc_write_oob_raw;
2041 	ecc->engine_type = NAND_ECC_ENGINE_TYPE_ON_HOST;
2042 	ecc->size	= bch_geo->ecc_chunk_size;
2043 	ecc->strength	= bch_geo->ecc_strength;
2044 	mtd_set_ooblayout(mtd, &gpmi_ooblayout_ops);
2045 
2046 	/*
2047 	 * We only enable the subpage read when:
2048 	 *  (1) the chip is imx6, and
2049 	 *  (2) the size of the ECC parity is byte aligned.
2050 	 */
2051 	if (GPMI_IS_MX6(this) &&
2052 		((bch_geo->gf_len * bch_geo->ecc_strength) % 8) == 0) {
2053 		ecc->read_subpage = gpmi_ecc_read_subpage;
2054 		chip->options |= NAND_SUBPAGE_READ;
2055 	}
2056 
2057 	return 0;
2058 }
2059 
2060 static int gpmi_nand_attach_chip(struct nand_chip *chip)
2061 {
2062 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
2063 	int ret;
2064 
2065 	if (chip->bbt_options & NAND_BBT_USE_FLASH) {
2066 		chip->bbt_options |= NAND_BBT_NO_OOB;
2067 
2068 		if (of_property_read_bool(this->dev->of_node,
2069 					  "fsl,no-blockmark-swap"))
2070 			this->swap_block_mark = false;
2071 	}
2072 	dev_dbg(this->dev, "Blockmark swapping %sabled\n",
2073 		this->swap_block_mark ? "en" : "dis");
2074 
2075 	ret = gpmi_init_last(this);
2076 	if (ret)
2077 		return ret;
2078 
2079 	chip->options |= NAND_SKIP_BBTSCAN;
2080 
2081 	return 0;
2082 }
2083 
2084 static struct gpmi_transfer *get_next_transfer(struct gpmi_nand_data *this)
2085 {
2086 	struct gpmi_transfer *transfer = &this->transfers[this->ntransfers];
2087 
2088 	this->ntransfers++;
2089 
2090 	if (this->ntransfers == GPMI_MAX_TRANSFERS)
2091 		return NULL;
2092 
2093 	return transfer;
2094 }
2095 
2096 static struct dma_async_tx_descriptor *gpmi_chain_command(
2097 	struct gpmi_nand_data *this, u8 cmd, const u8 *addr, int naddr)
2098 {
2099 	struct dma_chan *channel = get_dma_chan(this);
2100 	struct dma_async_tx_descriptor *desc;
2101 	struct gpmi_transfer *transfer;
2102 	int chip = this->nand.cur_cs;
2103 	u32 pio[3];
2104 
2105 	/* [1] send out the PIO words */
2106 	pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__WRITE)
2107 		| BM_GPMI_CTRL0_WORD_LENGTH
2108 		| BF_GPMI_CTRL0_CS(chip, this)
2109 		| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
2110 		| BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_CLE)
2111 		| BM_GPMI_CTRL0_ADDRESS_INCREMENT
2112 		| BF_GPMI_CTRL0_XFER_COUNT(naddr + 1);
2113 	pio[1] = 0;
2114 	pio[2] = 0;
2115 	desc = mxs_dmaengine_prep_pio(channel, pio, ARRAY_SIZE(pio),
2116 				      DMA_TRANS_NONE, 0);
2117 	if (!desc)
2118 		return NULL;
2119 
2120 	transfer = get_next_transfer(this);
2121 	if (!transfer)
2122 		return NULL;
2123 
2124 	transfer->cmdbuf[0] = cmd;
2125 	if (naddr)
2126 		memcpy(&transfer->cmdbuf[1], addr, naddr);
2127 
2128 	sg_init_one(&transfer->sgl, transfer->cmdbuf, naddr + 1);
2129 	dma_map_sg(this->dev, &transfer->sgl, 1, DMA_TO_DEVICE);
2130 
2131 	transfer->direction = DMA_TO_DEVICE;
2132 
2133 	desc = dmaengine_prep_slave_sg(channel, &transfer->sgl, 1, DMA_MEM_TO_DEV,
2134 				       MXS_DMA_CTRL_WAIT4END);
2135 	return desc;
2136 }
2137 
2138 static struct dma_async_tx_descriptor *gpmi_chain_wait_ready(
2139 	struct gpmi_nand_data *this)
2140 {
2141 	struct dma_chan *channel = get_dma_chan(this);
2142 	u32 pio[2];
2143 
2144 	pio[0] =  BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY)
2145 		| BM_GPMI_CTRL0_WORD_LENGTH
2146 		| BF_GPMI_CTRL0_CS(this->nand.cur_cs, this)
2147 		| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
2148 		| BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_DATA)
2149 		| BF_GPMI_CTRL0_XFER_COUNT(0);
2150 	pio[1] = 0;
2151 
2152 	return mxs_dmaengine_prep_pio(channel, pio, 2, DMA_TRANS_NONE,
2153 				MXS_DMA_CTRL_WAIT4END | MXS_DMA_CTRL_WAIT4RDY);
2154 }
2155 
2156 static struct dma_async_tx_descriptor *gpmi_chain_data_read(
2157 	struct gpmi_nand_data *this, void *buf, int raw_len, bool *direct)
2158 {
2159 	struct dma_async_tx_descriptor *desc;
2160 	struct dma_chan *channel = get_dma_chan(this);
2161 	struct gpmi_transfer *transfer;
2162 	u32 pio[6] = {};
2163 
2164 	transfer = get_next_transfer(this);
2165 	if (!transfer)
2166 		return NULL;
2167 
2168 	transfer->direction = DMA_FROM_DEVICE;
2169 
2170 	*direct = prepare_data_dma(this, buf, raw_len, &transfer->sgl,
2171 				   DMA_FROM_DEVICE);
2172 
2173 	pio[0] =  BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__READ)
2174 		| BM_GPMI_CTRL0_WORD_LENGTH
2175 		| BF_GPMI_CTRL0_CS(this->nand.cur_cs, this)
2176 		| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
2177 		| BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_DATA)
2178 		| BF_GPMI_CTRL0_XFER_COUNT(raw_len);
2179 
2180 	if (this->bch) {
2181 		pio[2] =  BM_GPMI_ECCCTRL_ENABLE_ECC
2182 			| BF_GPMI_ECCCTRL_ECC_CMD(BV_GPMI_ECCCTRL_ECC_CMD__BCH_DECODE)
2183 			| BF_GPMI_ECCCTRL_BUFFER_MASK(BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE
2184 				| BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY);
2185 		pio[3] = raw_len;
2186 		pio[4] = transfer->sgl.dma_address;
2187 		pio[5] = this->auxiliary_phys;
2188 	}
2189 
2190 	desc = mxs_dmaengine_prep_pio(channel, pio, ARRAY_SIZE(pio),
2191 				      DMA_TRANS_NONE, 0);
2192 	if (!desc)
2193 		return NULL;
2194 
2195 	if (!this->bch)
2196 		desc = dmaengine_prep_slave_sg(channel, &transfer->sgl, 1,
2197 					     DMA_DEV_TO_MEM,
2198 					     MXS_DMA_CTRL_WAIT4END);
2199 
2200 	return desc;
2201 }
2202 
2203 static struct dma_async_tx_descriptor *gpmi_chain_data_write(
2204 	struct gpmi_nand_data *this, const void *buf, int raw_len)
2205 {
2206 	struct dma_chan *channel = get_dma_chan(this);
2207 	struct dma_async_tx_descriptor *desc;
2208 	struct gpmi_transfer *transfer;
2209 	u32 pio[6] = {};
2210 
2211 	transfer = get_next_transfer(this);
2212 	if (!transfer)
2213 		return NULL;
2214 
2215 	transfer->direction = DMA_TO_DEVICE;
2216 
2217 	prepare_data_dma(this, buf, raw_len, &transfer->sgl, DMA_TO_DEVICE);
2218 
2219 	pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__WRITE)
2220 		| BM_GPMI_CTRL0_WORD_LENGTH
2221 		| BF_GPMI_CTRL0_CS(this->nand.cur_cs, this)
2222 		| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
2223 		| BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_DATA)
2224 		| BF_GPMI_CTRL0_XFER_COUNT(raw_len);
2225 
2226 	if (this->bch) {
2227 		pio[2] = BM_GPMI_ECCCTRL_ENABLE_ECC
2228 			| BF_GPMI_ECCCTRL_ECC_CMD(BV_GPMI_ECCCTRL_ECC_CMD__BCH_ENCODE)
2229 			| BF_GPMI_ECCCTRL_BUFFER_MASK(BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE |
2230 					BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY);
2231 		pio[3] = raw_len;
2232 		pio[4] = transfer->sgl.dma_address;
2233 		pio[5] = this->auxiliary_phys;
2234 	}
2235 
2236 	desc = mxs_dmaengine_prep_pio(channel, pio, ARRAY_SIZE(pio),
2237 				      DMA_TRANS_NONE,
2238 				      (this->bch ? MXS_DMA_CTRL_WAIT4END : 0));
2239 	if (!desc)
2240 		return NULL;
2241 
2242 	if (!this->bch)
2243 		desc = dmaengine_prep_slave_sg(channel, &transfer->sgl, 1,
2244 					       DMA_MEM_TO_DEV,
2245 					       MXS_DMA_CTRL_WAIT4END);
2246 
2247 	return desc;
2248 }
2249 
2250 static int gpmi_nfc_exec_op(struct nand_chip *chip,
2251 			     const struct nand_operation *op,
2252 			     bool check_only)
2253 {
2254 	const struct nand_op_instr *instr;
2255 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
2256 	struct dma_async_tx_descriptor *desc = NULL;
2257 	int i, ret, buf_len = 0, nbufs = 0;
2258 	u8 cmd = 0;
2259 	void *buf_read = NULL;
2260 	const void *buf_write = NULL;
2261 	bool direct = false;
2262 	struct completion *dma_completion, *bch_completion;
2263 	unsigned long to;
2264 
2265 	if (check_only)
2266 		return 0;
2267 
2268 	this->ntransfers = 0;
2269 	for (i = 0; i < GPMI_MAX_TRANSFERS; i++)
2270 		this->transfers[i].direction = DMA_NONE;
2271 
2272 	ret = pm_runtime_get_sync(this->dev);
2273 	if (ret < 0) {
2274 		pm_runtime_put_noidle(this->dev);
2275 		return ret;
2276 	}
2277 
2278 	/*
2279 	 * This driver currently supports only one NAND chip. Plus, dies share
2280 	 * the same configuration. So once timings have been applied on the
2281 	 * controller side, they will not change anymore. When the time will
2282 	 * come, the check on must_apply_timings will have to be dropped.
2283 	 */
2284 	if (this->hw.must_apply_timings) {
2285 		this->hw.must_apply_timings = false;
2286 		ret = gpmi_nfc_apply_timings(this);
2287 		if (ret)
2288 			return ret;
2289 	}
2290 
2291 	dev_dbg(this->dev, "%s: %d instructions\n", __func__, op->ninstrs);
2292 
2293 	for (i = 0; i < op->ninstrs; i++) {
2294 		instr = &op->instrs[i];
2295 
2296 		nand_op_trace("  ", instr);
2297 
2298 		switch (instr->type) {
2299 		case NAND_OP_WAITRDY_INSTR:
2300 			desc = gpmi_chain_wait_ready(this);
2301 			break;
2302 		case NAND_OP_CMD_INSTR:
2303 			cmd = instr->ctx.cmd.opcode;
2304 
2305 			/*
2306 			 * When this command has an address cycle chain it
2307 			 * together with the address cycle
2308 			 */
2309 			if (i + 1 != op->ninstrs &&
2310 			    op->instrs[i + 1].type == NAND_OP_ADDR_INSTR)
2311 				continue;
2312 
2313 			desc = gpmi_chain_command(this, cmd, NULL, 0);
2314 
2315 			break;
2316 		case NAND_OP_ADDR_INSTR:
2317 			desc = gpmi_chain_command(this, cmd, instr->ctx.addr.addrs,
2318 						  instr->ctx.addr.naddrs);
2319 			break;
2320 		case NAND_OP_DATA_OUT_INSTR:
2321 			buf_write = instr->ctx.data.buf.out;
2322 			buf_len = instr->ctx.data.len;
2323 			nbufs++;
2324 
2325 			desc = gpmi_chain_data_write(this, buf_write, buf_len);
2326 
2327 			break;
2328 		case NAND_OP_DATA_IN_INSTR:
2329 			if (!instr->ctx.data.len)
2330 				break;
2331 			buf_read = instr->ctx.data.buf.in;
2332 			buf_len = instr->ctx.data.len;
2333 			nbufs++;
2334 
2335 			desc = gpmi_chain_data_read(this, buf_read, buf_len,
2336 						   &direct);
2337 			break;
2338 		}
2339 
2340 		if (!desc) {
2341 			ret = -ENXIO;
2342 			goto unmap;
2343 		}
2344 	}
2345 
2346 	dev_dbg(this->dev, "%s setup done\n", __func__);
2347 
2348 	if (nbufs > 1) {
2349 		dev_err(this->dev, "Multiple data instructions not supported\n");
2350 		ret = -EINVAL;
2351 		goto unmap;
2352 	}
2353 
2354 	if (this->bch) {
2355 		writel(this->bch_flashlayout0,
2356 		       this->resources.bch_regs + HW_BCH_FLASH0LAYOUT0);
2357 		writel(this->bch_flashlayout1,
2358 		       this->resources.bch_regs + HW_BCH_FLASH0LAYOUT1);
2359 	}
2360 
2361 	desc->callback = dma_irq_callback;
2362 	desc->callback_param = this;
2363 	dma_completion = &this->dma_done;
2364 	bch_completion = NULL;
2365 
2366 	init_completion(dma_completion);
2367 
2368 	if (this->bch && buf_read) {
2369 		writel(BM_BCH_CTRL_COMPLETE_IRQ_EN,
2370 		       this->resources.bch_regs + HW_BCH_CTRL_SET);
2371 		bch_completion = &this->bch_done;
2372 		init_completion(bch_completion);
2373 	}
2374 
2375 	dmaengine_submit(desc);
2376 	dma_async_issue_pending(get_dma_chan(this));
2377 
2378 	to = wait_for_completion_timeout(dma_completion, msecs_to_jiffies(1000));
2379 	if (!to) {
2380 		dev_err(this->dev, "DMA timeout, last DMA\n");
2381 		gpmi_dump_info(this);
2382 		ret = -ETIMEDOUT;
2383 		goto unmap;
2384 	}
2385 
2386 	if (this->bch && buf_read) {
2387 		to = wait_for_completion_timeout(bch_completion, msecs_to_jiffies(1000));
2388 		if (!to) {
2389 			dev_err(this->dev, "BCH timeout, last DMA\n");
2390 			gpmi_dump_info(this);
2391 			ret = -ETIMEDOUT;
2392 			goto unmap;
2393 		}
2394 	}
2395 
2396 	writel(BM_BCH_CTRL_COMPLETE_IRQ_EN,
2397 	       this->resources.bch_regs + HW_BCH_CTRL_CLR);
2398 	gpmi_clear_bch(this);
2399 
2400 	ret = 0;
2401 
2402 unmap:
2403 	for (i = 0; i < this->ntransfers; i++) {
2404 		struct gpmi_transfer *transfer = &this->transfers[i];
2405 
2406 		if (transfer->direction != DMA_NONE)
2407 			dma_unmap_sg(this->dev, &transfer->sgl, 1,
2408 				     transfer->direction);
2409 	}
2410 
2411 	if (!ret && buf_read && !direct)
2412 		memcpy(buf_read, this->data_buffer_dma,
2413 		       gpmi_raw_len_to_len(this, buf_len));
2414 
2415 	this->bch = false;
2416 
2417 	pm_runtime_mark_last_busy(this->dev);
2418 	pm_runtime_put_autosuspend(this->dev);
2419 
2420 	return ret;
2421 }
2422 
2423 static const struct nand_controller_ops gpmi_nand_controller_ops = {
2424 	.attach_chip = gpmi_nand_attach_chip,
2425 	.setup_interface = gpmi_setup_interface,
2426 	.exec_op = gpmi_nfc_exec_op,
2427 };
2428 
2429 static int gpmi_nand_init(struct gpmi_nand_data *this)
2430 {
2431 	struct nand_chip *chip = &this->nand;
2432 	struct mtd_info  *mtd = nand_to_mtd(chip);
2433 	int ret;
2434 
2435 	/* init the MTD data structures */
2436 	mtd->name		= "gpmi-nand";
2437 	mtd->dev.parent		= this->dev;
2438 
2439 	/* init the nand_chip{}, we don't support a 16-bit NAND Flash bus. */
2440 	nand_set_controller_data(chip, this);
2441 	nand_set_flash_node(chip, this->pdev->dev.of_node);
2442 	chip->legacy.block_markbad = gpmi_block_markbad;
2443 	chip->badblock_pattern	= &gpmi_bbt_descr;
2444 	chip->options		|= NAND_NO_SUBPAGE_WRITE;
2445 
2446 	/* Set up swap_block_mark, must be set before the gpmi_set_geometry() */
2447 	this->swap_block_mark = !GPMI_IS_MX23(this);
2448 
2449 	/*
2450 	 * Allocate a temporary DMA buffer for reading ID in the
2451 	 * nand_scan_ident().
2452 	 */
2453 	this->bch_geometry.payload_size = 1024;
2454 	this->bch_geometry.auxiliary_size = 128;
2455 	ret = gpmi_alloc_dma_buffer(this);
2456 	if (ret)
2457 		return ret;
2458 
2459 	nand_controller_init(&this->base);
2460 	this->base.ops = &gpmi_nand_controller_ops;
2461 	chip->controller = &this->base;
2462 
2463 	ret = nand_scan(chip, GPMI_IS_MX6(this) ? 2 : 1);
2464 	if (ret)
2465 		goto err_out;
2466 
2467 	ret = nand_boot_init(this);
2468 	if (ret)
2469 		goto err_nand_cleanup;
2470 	ret = nand_create_bbt(chip);
2471 	if (ret)
2472 		goto err_nand_cleanup;
2473 
2474 	ret = mtd_device_register(mtd, NULL, 0);
2475 	if (ret)
2476 		goto err_nand_cleanup;
2477 	return 0;
2478 
2479 err_nand_cleanup:
2480 	nand_cleanup(chip);
2481 err_out:
2482 	gpmi_free_dma_buffer(this);
2483 	return ret;
2484 }
2485 
2486 static const struct of_device_id gpmi_nand_id_table[] = {
2487 	{ .compatible = "fsl,imx23-gpmi-nand", .data = &gpmi_devdata_imx23, },
2488 	{ .compatible = "fsl,imx28-gpmi-nand", .data = &gpmi_devdata_imx28, },
2489 	{ .compatible = "fsl,imx6q-gpmi-nand", .data = &gpmi_devdata_imx6q, },
2490 	{ .compatible = "fsl,imx6sx-gpmi-nand", .data = &gpmi_devdata_imx6sx, },
2491 	{ .compatible = "fsl,imx7d-gpmi-nand", .data = &gpmi_devdata_imx7d,},
2492 	{}
2493 };
2494 MODULE_DEVICE_TABLE(of, gpmi_nand_id_table);
2495 
2496 static int gpmi_nand_probe(struct platform_device *pdev)
2497 {
2498 	struct gpmi_nand_data *this;
2499 	int ret;
2500 
2501 	this = devm_kzalloc(&pdev->dev, sizeof(*this), GFP_KERNEL);
2502 	if (!this)
2503 		return -ENOMEM;
2504 
2505 	this->devdata = of_device_get_match_data(&pdev->dev);
2506 	platform_set_drvdata(pdev, this);
2507 	this->pdev  = pdev;
2508 	this->dev   = &pdev->dev;
2509 
2510 	ret = acquire_resources(this);
2511 	if (ret)
2512 		goto exit_acquire_resources;
2513 
2514 	ret = __gpmi_enable_clk(this, true);
2515 	if (ret)
2516 		goto exit_acquire_resources;
2517 
2518 	pm_runtime_set_autosuspend_delay(&pdev->dev, 500);
2519 	pm_runtime_use_autosuspend(&pdev->dev);
2520 	pm_runtime_set_active(&pdev->dev);
2521 	pm_runtime_enable(&pdev->dev);
2522 	pm_runtime_get_sync(&pdev->dev);
2523 
2524 	ret = gpmi_init(this);
2525 	if (ret)
2526 		goto exit_nfc_init;
2527 
2528 	ret = gpmi_nand_init(this);
2529 	if (ret)
2530 		goto exit_nfc_init;
2531 
2532 	pm_runtime_mark_last_busy(&pdev->dev);
2533 	pm_runtime_put_autosuspend(&pdev->dev);
2534 
2535 	dev_info(this->dev, "driver registered.\n");
2536 
2537 	return 0;
2538 
2539 exit_nfc_init:
2540 	pm_runtime_put(&pdev->dev);
2541 	pm_runtime_disable(&pdev->dev);
2542 	release_resources(this);
2543 exit_acquire_resources:
2544 
2545 	return ret;
2546 }
2547 
2548 static int gpmi_nand_remove(struct platform_device *pdev)
2549 {
2550 	struct gpmi_nand_data *this = platform_get_drvdata(pdev);
2551 	struct nand_chip *chip = &this->nand;
2552 	int ret;
2553 
2554 	pm_runtime_put_sync(&pdev->dev);
2555 	pm_runtime_disable(&pdev->dev);
2556 
2557 	ret = mtd_device_unregister(nand_to_mtd(chip));
2558 	WARN_ON(ret);
2559 	nand_cleanup(chip);
2560 	gpmi_free_dma_buffer(this);
2561 	release_resources(this);
2562 	return 0;
2563 }
2564 
2565 #ifdef CONFIG_PM_SLEEP
2566 static int gpmi_pm_suspend(struct device *dev)
2567 {
2568 	struct gpmi_nand_data *this = dev_get_drvdata(dev);
2569 
2570 	release_dma_channels(this);
2571 	return 0;
2572 }
2573 
2574 static int gpmi_pm_resume(struct device *dev)
2575 {
2576 	struct gpmi_nand_data *this = dev_get_drvdata(dev);
2577 	int ret;
2578 
2579 	ret = acquire_dma_channels(this);
2580 	if (ret < 0)
2581 		return ret;
2582 
2583 	/* re-init the GPMI registers */
2584 	ret = gpmi_init(this);
2585 	if (ret) {
2586 		dev_err(this->dev, "Error setting GPMI : %d\n", ret);
2587 		return ret;
2588 	}
2589 
2590 	/* Set flag to get timing setup restored for next exec_op */
2591 	if (this->hw.clk_rate)
2592 		this->hw.must_apply_timings = true;
2593 
2594 	/* re-init the BCH registers */
2595 	ret = bch_set_geometry(this);
2596 	if (ret) {
2597 		dev_err(this->dev, "Error setting BCH : %d\n", ret);
2598 		return ret;
2599 	}
2600 
2601 	return 0;
2602 }
2603 #endif /* CONFIG_PM_SLEEP */
2604 
2605 static int __maybe_unused gpmi_runtime_suspend(struct device *dev)
2606 {
2607 	struct gpmi_nand_data *this = dev_get_drvdata(dev);
2608 
2609 	return __gpmi_enable_clk(this, false);
2610 }
2611 
2612 static int __maybe_unused gpmi_runtime_resume(struct device *dev)
2613 {
2614 	struct gpmi_nand_data *this = dev_get_drvdata(dev);
2615 
2616 	return __gpmi_enable_clk(this, true);
2617 }
2618 
2619 static const struct dev_pm_ops gpmi_pm_ops = {
2620 	SET_SYSTEM_SLEEP_PM_OPS(gpmi_pm_suspend, gpmi_pm_resume)
2621 	SET_RUNTIME_PM_OPS(gpmi_runtime_suspend, gpmi_runtime_resume, NULL)
2622 };
2623 
2624 static struct platform_driver gpmi_nand_driver = {
2625 	.driver = {
2626 		.name = "gpmi-nand",
2627 		.pm = &gpmi_pm_ops,
2628 		.of_match_table = gpmi_nand_id_table,
2629 	},
2630 	.probe   = gpmi_nand_probe,
2631 	.remove  = gpmi_nand_remove,
2632 };
2633 module_platform_driver(gpmi_nand_driver);
2634 
2635 MODULE_AUTHOR("Freescale Semiconductor, Inc.");
2636 MODULE_DESCRIPTION("i.MX GPMI NAND Flash Controller Driver");
2637 MODULE_LICENSE("GPL");
2638