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 void 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 
723 	clk_set_rate(r->clock[0], hw->clk_rate);
724 
725 	writel(hw->timing0, gpmi_regs + HW_GPMI_TIMING0);
726 	writel(hw->timing1, gpmi_regs + HW_GPMI_TIMING1);
727 
728 	/*
729 	 * Clear several CTRL1 fields, DLL must be disabled when setting
730 	 * RDN_DELAY or HALF_PERIOD.
731 	 */
732 	writel(BM_GPMI_CTRL1_CLEAR_MASK, gpmi_regs + HW_GPMI_CTRL1_CLR);
733 	writel(hw->ctrl1n, gpmi_regs + HW_GPMI_CTRL1_SET);
734 
735 	/* Wait 64 clock cycles before using the GPMI after enabling the DLL */
736 	dll_wait_time_us = USEC_PER_SEC / hw->clk_rate * 64;
737 	if (!dll_wait_time_us)
738 		dll_wait_time_us = 1;
739 
740 	/* Wait for the DLL to settle. */
741 	udelay(dll_wait_time_us);
742 }
743 
744 static int gpmi_setup_interface(struct nand_chip *chip, int chipnr,
745 				const struct nand_interface_config *conf)
746 {
747 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
748 	const struct nand_sdr_timings *sdr;
749 
750 	/* Retrieve required NAND timings */
751 	sdr = nand_get_sdr_timings(conf);
752 	if (IS_ERR(sdr))
753 		return PTR_ERR(sdr);
754 
755 	/* Only MX6 GPMI controller can reach EDO timings */
756 	if (sdr->tRC_min <= 25000 && !GPMI_IS_MX6(this))
757 		return -ENOTSUPP;
758 
759 	/* Stop here if this call was just a check */
760 	if (chipnr < 0)
761 		return 0;
762 
763 	/* Do the actual derivation of the controller timings */
764 	gpmi_nfc_compute_timings(this, sdr);
765 
766 	this->hw.must_apply_timings = true;
767 
768 	return 0;
769 }
770 
771 /* Clears a BCH interrupt. */
772 static void gpmi_clear_bch(struct gpmi_nand_data *this)
773 {
774 	struct resources *r = &this->resources;
775 	writel(BM_BCH_CTRL_COMPLETE_IRQ, r->bch_regs + HW_BCH_CTRL_CLR);
776 }
777 
778 static struct dma_chan *get_dma_chan(struct gpmi_nand_data *this)
779 {
780 	/* We use the DMA channel 0 to access all the nand chips. */
781 	return this->dma_chans[0];
782 }
783 
784 /* This will be called after the DMA operation is finished. */
785 static void dma_irq_callback(void *param)
786 {
787 	struct gpmi_nand_data *this = param;
788 	struct completion *dma_c = &this->dma_done;
789 
790 	complete(dma_c);
791 }
792 
793 static irqreturn_t bch_irq(int irq, void *cookie)
794 {
795 	struct gpmi_nand_data *this = cookie;
796 
797 	gpmi_clear_bch(this);
798 	complete(&this->bch_done);
799 	return IRQ_HANDLED;
800 }
801 
802 static int gpmi_raw_len_to_len(struct gpmi_nand_data *this, int raw_len)
803 {
804 	/*
805 	 * raw_len is the length to read/write including bch data which
806 	 * we are passed in exec_op. Calculate the data length from it.
807 	 */
808 	if (this->bch)
809 		return ALIGN_DOWN(raw_len, this->bch_geometry.ecc_chunk_size);
810 	else
811 		return raw_len;
812 }
813 
814 /* Can we use the upper's buffer directly for DMA? */
815 static bool prepare_data_dma(struct gpmi_nand_data *this, const void *buf,
816 			     int raw_len, struct scatterlist *sgl,
817 			     enum dma_data_direction dr)
818 {
819 	int ret;
820 	int len = gpmi_raw_len_to_len(this, raw_len);
821 
822 	/* first try to map the upper buffer directly */
823 	if (virt_addr_valid(buf) && !object_is_on_stack(buf)) {
824 		sg_init_one(sgl, buf, len);
825 		ret = dma_map_sg(this->dev, sgl, 1, dr);
826 		if (ret == 0)
827 			goto map_fail;
828 
829 		return true;
830 	}
831 
832 map_fail:
833 	/* We have to use our own DMA buffer. */
834 	sg_init_one(sgl, this->data_buffer_dma, len);
835 
836 	if (dr == DMA_TO_DEVICE && buf != this->data_buffer_dma)
837 		memcpy(this->data_buffer_dma, buf, len);
838 
839 	dma_map_sg(this->dev, sgl, 1, dr);
840 
841 	return false;
842 }
843 
844 /* add our owner bbt descriptor */
845 static uint8_t scan_ff_pattern[] = { 0xff };
846 static struct nand_bbt_descr gpmi_bbt_descr = {
847 	.options	= 0,
848 	.offs		= 0,
849 	.len		= 1,
850 	.pattern	= scan_ff_pattern
851 };
852 
853 /*
854  * We may change the layout if we can get the ECC info from the datasheet,
855  * else we will use all the (page + OOB).
856  */
857 static int gpmi_ooblayout_ecc(struct mtd_info *mtd, int section,
858 			      struct mtd_oob_region *oobregion)
859 {
860 	struct nand_chip *chip = mtd_to_nand(mtd);
861 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
862 	struct bch_geometry *geo = &this->bch_geometry;
863 
864 	if (section)
865 		return -ERANGE;
866 
867 	oobregion->offset = 0;
868 	oobregion->length = geo->page_size - mtd->writesize;
869 
870 	return 0;
871 }
872 
873 static int gpmi_ooblayout_free(struct mtd_info *mtd, int section,
874 			       struct mtd_oob_region *oobregion)
875 {
876 	struct nand_chip *chip = mtd_to_nand(mtd);
877 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
878 	struct bch_geometry *geo = &this->bch_geometry;
879 
880 	if (section)
881 		return -ERANGE;
882 
883 	/* The available oob size we have. */
884 	if (geo->page_size < mtd->writesize + mtd->oobsize) {
885 		oobregion->offset = geo->page_size - mtd->writesize;
886 		oobregion->length = mtd->oobsize - oobregion->offset;
887 	}
888 
889 	return 0;
890 }
891 
892 static const char * const gpmi_clks_for_mx2x[] = {
893 	"gpmi_io",
894 };
895 
896 static const struct mtd_ooblayout_ops gpmi_ooblayout_ops = {
897 	.ecc = gpmi_ooblayout_ecc,
898 	.free = gpmi_ooblayout_free,
899 };
900 
901 static const struct gpmi_devdata gpmi_devdata_imx23 = {
902 	.type = IS_MX23,
903 	.bch_max_ecc_strength = 20,
904 	.max_chain_delay = 16000,
905 	.clks = gpmi_clks_for_mx2x,
906 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx2x),
907 };
908 
909 static const struct gpmi_devdata gpmi_devdata_imx28 = {
910 	.type = IS_MX28,
911 	.bch_max_ecc_strength = 20,
912 	.max_chain_delay = 16000,
913 	.clks = gpmi_clks_for_mx2x,
914 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx2x),
915 };
916 
917 static const char * const gpmi_clks_for_mx6[] = {
918 	"gpmi_io", "gpmi_apb", "gpmi_bch", "gpmi_bch_apb", "per1_bch",
919 };
920 
921 static const struct gpmi_devdata gpmi_devdata_imx6q = {
922 	.type = IS_MX6Q,
923 	.bch_max_ecc_strength = 40,
924 	.max_chain_delay = 12000,
925 	.clks = gpmi_clks_for_mx6,
926 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx6),
927 };
928 
929 static const struct gpmi_devdata gpmi_devdata_imx6sx = {
930 	.type = IS_MX6SX,
931 	.bch_max_ecc_strength = 62,
932 	.max_chain_delay = 12000,
933 	.clks = gpmi_clks_for_mx6,
934 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx6),
935 };
936 
937 static const char * const gpmi_clks_for_mx7d[] = {
938 	"gpmi_io", "gpmi_bch_apb",
939 };
940 
941 static const struct gpmi_devdata gpmi_devdata_imx7d = {
942 	.type = IS_MX7D,
943 	.bch_max_ecc_strength = 62,
944 	.max_chain_delay = 12000,
945 	.clks = gpmi_clks_for_mx7d,
946 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx7d),
947 };
948 
949 static int acquire_register_block(struct gpmi_nand_data *this,
950 				  const char *res_name)
951 {
952 	struct platform_device *pdev = this->pdev;
953 	struct resources *res = &this->resources;
954 	void __iomem *p;
955 
956 	p = devm_platform_ioremap_resource_byname(pdev, res_name);
957 	if (IS_ERR(p))
958 		return PTR_ERR(p);
959 
960 	if (!strcmp(res_name, GPMI_NAND_GPMI_REGS_ADDR_RES_NAME))
961 		res->gpmi_regs = p;
962 	else if (!strcmp(res_name, GPMI_NAND_BCH_REGS_ADDR_RES_NAME))
963 		res->bch_regs = p;
964 	else
965 		dev_err(this->dev, "unknown resource name : %s\n", res_name);
966 
967 	return 0;
968 }
969 
970 static int acquire_bch_irq(struct gpmi_nand_data *this, irq_handler_t irq_h)
971 {
972 	struct platform_device *pdev = this->pdev;
973 	const char *res_name = GPMI_NAND_BCH_INTERRUPT_RES_NAME;
974 	struct resource *r;
975 	int err;
976 
977 	r = platform_get_resource_byname(pdev, IORESOURCE_IRQ, res_name);
978 	if (!r) {
979 		dev_err(this->dev, "Can't get resource for %s\n", res_name);
980 		return -ENODEV;
981 	}
982 
983 	err = devm_request_irq(this->dev, r->start, irq_h, 0, res_name, this);
984 	if (err)
985 		dev_err(this->dev, "error requesting BCH IRQ\n");
986 
987 	return err;
988 }
989 
990 static void release_dma_channels(struct gpmi_nand_data *this)
991 {
992 	unsigned int i;
993 	for (i = 0; i < DMA_CHANS; i++)
994 		if (this->dma_chans[i]) {
995 			dma_release_channel(this->dma_chans[i]);
996 			this->dma_chans[i] = NULL;
997 		}
998 }
999 
1000 static int acquire_dma_channels(struct gpmi_nand_data *this)
1001 {
1002 	struct platform_device *pdev = this->pdev;
1003 	struct dma_chan *dma_chan;
1004 	int ret = 0;
1005 
1006 	/* request dma channel */
1007 	dma_chan = dma_request_chan(&pdev->dev, "rx-tx");
1008 	if (IS_ERR(dma_chan)) {
1009 		ret = dev_err_probe(this->dev, PTR_ERR(dma_chan),
1010 				    "DMA channel request failed\n");
1011 		release_dma_channels(this);
1012 	} else {
1013 		this->dma_chans[0] = dma_chan;
1014 	}
1015 
1016 	return ret;
1017 }
1018 
1019 static int gpmi_get_clks(struct gpmi_nand_data *this)
1020 {
1021 	struct resources *r = &this->resources;
1022 	struct clk *clk;
1023 	int err, i;
1024 
1025 	for (i = 0; i < this->devdata->clks_count; i++) {
1026 		clk = devm_clk_get(this->dev, this->devdata->clks[i]);
1027 		if (IS_ERR(clk)) {
1028 			err = PTR_ERR(clk);
1029 			goto err_clock;
1030 		}
1031 
1032 		r->clock[i] = clk;
1033 	}
1034 
1035 	if (GPMI_IS_MX6(this))
1036 		/*
1037 		 * Set the default value for the gpmi clock.
1038 		 *
1039 		 * If you want to use the ONFI nand which is in the
1040 		 * Synchronous Mode, you should change the clock as you need.
1041 		 */
1042 		clk_set_rate(r->clock[0], 22000000);
1043 
1044 	return 0;
1045 
1046 err_clock:
1047 	dev_dbg(this->dev, "failed in finding the clocks.\n");
1048 	return err;
1049 }
1050 
1051 static int acquire_resources(struct gpmi_nand_data *this)
1052 {
1053 	int ret;
1054 
1055 	ret = acquire_register_block(this, GPMI_NAND_GPMI_REGS_ADDR_RES_NAME);
1056 	if (ret)
1057 		goto exit_regs;
1058 
1059 	ret = acquire_register_block(this, GPMI_NAND_BCH_REGS_ADDR_RES_NAME);
1060 	if (ret)
1061 		goto exit_regs;
1062 
1063 	ret = acquire_bch_irq(this, bch_irq);
1064 	if (ret)
1065 		goto exit_regs;
1066 
1067 	ret = acquire_dma_channels(this);
1068 	if (ret)
1069 		goto exit_regs;
1070 
1071 	ret = gpmi_get_clks(this);
1072 	if (ret)
1073 		goto exit_clock;
1074 	return 0;
1075 
1076 exit_clock:
1077 	release_dma_channels(this);
1078 exit_regs:
1079 	return ret;
1080 }
1081 
1082 static void release_resources(struct gpmi_nand_data *this)
1083 {
1084 	release_dma_channels(this);
1085 }
1086 
1087 static void gpmi_free_dma_buffer(struct gpmi_nand_data *this)
1088 {
1089 	struct device *dev = this->dev;
1090 	struct bch_geometry *geo = &this->bch_geometry;
1091 
1092 	if (this->auxiliary_virt && virt_addr_valid(this->auxiliary_virt))
1093 		dma_free_coherent(dev, geo->auxiliary_size,
1094 					this->auxiliary_virt,
1095 					this->auxiliary_phys);
1096 	kfree(this->data_buffer_dma);
1097 	kfree(this->raw_buffer);
1098 
1099 	this->data_buffer_dma	= NULL;
1100 	this->raw_buffer	= NULL;
1101 }
1102 
1103 /* Allocate the DMA buffers */
1104 static int gpmi_alloc_dma_buffer(struct gpmi_nand_data *this)
1105 {
1106 	struct bch_geometry *geo = &this->bch_geometry;
1107 	struct device *dev = this->dev;
1108 	struct mtd_info *mtd = nand_to_mtd(&this->nand);
1109 
1110 	/*
1111 	 * [2] Allocate a read/write data buffer.
1112 	 *     The gpmi_alloc_dma_buffer can be called twice.
1113 	 *     We allocate a PAGE_SIZE length buffer if gpmi_alloc_dma_buffer
1114 	 *     is called before the NAND identification; and we allocate a
1115 	 *     buffer of the real NAND page size when the gpmi_alloc_dma_buffer
1116 	 *     is called after.
1117 	 */
1118 	this->data_buffer_dma = kzalloc(mtd->writesize ?: PAGE_SIZE,
1119 					GFP_DMA | GFP_KERNEL);
1120 	if (this->data_buffer_dma == NULL)
1121 		goto error_alloc;
1122 
1123 	this->auxiliary_virt = dma_alloc_coherent(dev, geo->auxiliary_size,
1124 					&this->auxiliary_phys, GFP_DMA);
1125 	if (!this->auxiliary_virt)
1126 		goto error_alloc;
1127 
1128 	this->raw_buffer = kzalloc((mtd->writesize ?: PAGE_SIZE) + mtd->oobsize, GFP_KERNEL);
1129 	if (!this->raw_buffer)
1130 		goto error_alloc;
1131 
1132 	return 0;
1133 
1134 error_alloc:
1135 	gpmi_free_dma_buffer(this);
1136 	return -ENOMEM;
1137 }
1138 
1139 /*
1140  * Handles block mark swapping.
1141  * It can be called in swapping the block mark, or swapping it back,
1142  * because the the operations are the same.
1143  */
1144 static void block_mark_swapping(struct gpmi_nand_data *this,
1145 				void *payload, void *auxiliary)
1146 {
1147 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1148 	unsigned char *p;
1149 	unsigned char *a;
1150 	unsigned int  bit;
1151 	unsigned char mask;
1152 	unsigned char from_data;
1153 	unsigned char from_oob;
1154 
1155 	if (!this->swap_block_mark)
1156 		return;
1157 
1158 	/*
1159 	 * If control arrives here, we're swapping. Make some convenience
1160 	 * variables.
1161 	 */
1162 	bit = nfc_geo->block_mark_bit_offset;
1163 	p   = payload + nfc_geo->block_mark_byte_offset;
1164 	a   = auxiliary;
1165 
1166 	/*
1167 	 * Get the byte from the data area that overlays the block mark. Since
1168 	 * the ECC engine applies its own view to the bits in the page, the
1169 	 * physical block mark won't (in general) appear on a byte boundary in
1170 	 * the data.
1171 	 */
1172 	from_data = (p[0] >> bit) | (p[1] << (8 - bit));
1173 
1174 	/* Get the byte from the OOB. */
1175 	from_oob = a[0];
1176 
1177 	/* Swap them. */
1178 	a[0] = from_data;
1179 
1180 	mask = (0x1 << bit) - 1;
1181 	p[0] = (p[0] & mask) | (from_oob << bit);
1182 
1183 	mask = ~0 << bit;
1184 	p[1] = (p[1] & mask) | (from_oob >> (8 - bit));
1185 }
1186 
1187 static int gpmi_count_bitflips(struct nand_chip *chip, void *buf, int first,
1188 			       int last, int meta)
1189 {
1190 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1191 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1192 	struct mtd_info *mtd = nand_to_mtd(chip);
1193 	int i;
1194 	unsigned char *status;
1195 	unsigned int max_bitflips = 0;
1196 
1197 	/* Loop over status bytes, accumulating ECC status. */
1198 	status = this->auxiliary_virt + ALIGN(meta, 4);
1199 
1200 	for (i = first; i < last; i++, status++) {
1201 		if ((*status == STATUS_GOOD) || (*status == STATUS_ERASED))
1202 			continue;
1203 
1204 		if (*status == STATUS_UNCORRECTABLE) {
1205 			int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1206 			u8 *eccbuf = this->raw_buffer;
1207 			int offset, bitoffset;
1208 			int eccbytes;
1209 			int flips;
1210 
1211 			/* Read ECC bytes into our internal raw_buffer */
1212 			offset = nfc_geo->metadata_size * 8;
1213 			offset += ((8 * nfc_geo->ecc_chunk_size) + eccbits) * (i + 1);
1214 			offset -= eccbits;
1215 			bitoffset = offset % 8;
1216 			eccbytes = DIV_ROUND_UP(offset + eccbits, 8);
1217 			offset /= 8;
1218 			eccbytes -= offset;
1219 			nand_change_read_column_op(chip, offset, eccbuf,
1220 						   eccbytes, false);
1221 
1222 			/*
1223 			 * ECC data are not byte aligned and we may have
1224 			 * in-band data in the first and last byte of
1225 			 * eccbuf. Set non-eccbits to one so that
1226 			 * nand_check_erased_ecc_chunk() does not count them
1227 			 * as bitflips.
1228 			 */
1229 			if (bitoffset)
1230 				eccbuf[0] |= GENMASK(bitoffset - 1, 0);
1231 
1232 			bitoffset = (bitoffset + eccbits) % 8;
1233 			if (bitoffset)
1234 				eccbuf[eccbytes - 1] |= GENMASK(7, bitoffset);
1235 
1236 			/*
1237 			 * The ECC hardware has an uncorrectable ECC status
1238 			 * code in case we have bitflips in an erased page. As
1239 			 * nothing was written into this subpage the ECC is
1240 			 * obviously wrong and we can not trust it. We assume
1241 			 * at this point that we are reading an erased page and
1242 			 * try to correct the bitflips in buffer up to
1243 			 * ecc_strength bitflips. If this is a page with random
1244 			 * data, we exceed this number of bitflips and have a
1245 			 * ECC failure. Otherwise we use the corrected buffer.
1246 			 */
1247 			if (i == 0) {
1248 				/* The first block includes metadata */
1249 				flips = nand_check_erased_ecc_chunk(
1250 						buf + i * nfc_geo->ecc_chunk_size,
1251 						nfc_geo->ecc_chunk_size,
1252 						eccbuf, eccbytes,
1253 						this->auxiliary_virt,
1254 						nfc_geo->metadata_size,
1255 						nfc_geo->ecc_strength);
1256 			} else {
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 						NULL, 0,
1262 						nfc_geo->ecc_strength);
1263 			}
1264 
1265 			if (flips > 0) {
1266 				max_bitflips = max_t(unsigned int, max_bitflips,
1267 						     flips);
1268 				mtd->ecc_stats.corrected += flips;
1269 				continue;
1270 			}
1271 
1272 			mtd->ecc_stats.failed++;
1273 			continue;
1274 		}
1275 
1276 		mtd->ecc_stats.corrected += *status;
1277 		max_bitflips = max_t(unsigned int, max_bitflips, *status);
1278 	}
1279 
1280 	return max_bitflips;
1281 }
1282 
1283 static void gpmi_bch_layout_std(struct gpmi_nand_data *this)
1284 {
1285 	struct bch_geometry *geo = &this->bch_geometry;
1286 	unsigned int ecc_strength = geo->ecc_strength >> 1;
1287 	unsigned int gf_len = geo->gf_len;
1288 	unsigned int block_size = geo->ecc_chunk_size;
1289 
1290 	this->bch_flashlayout0 =
1291 		BF_BCH_FLASH0LAYOUT0_NBLOCKS(geo->ecc_chunk_count - 1) |
1292 		BF_BCH_FLASH0LAYOUT0_META_SIZE(geo->metadata_size) |
1293 		BF_BCH_FLASH0LAYOUT0_ECC0(ecc_strength, this) |
1294 		BF_BCH_FLASH0LAYOUT0_GF(gf_len, this) |
1295 		BF_BCH_FLASH0LAYOUT0_DATA0_SIZE(block_size, this);
1296 
1297 	this->bch_flashlayout1 =
1298 		BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(geo->page_size) |
1299 		BF_BCH_FLASH0LAYOUT1_ECCN(ecc_strength, this) |
1300 		BF_BCH_FLASH0LAYOUT1_GF(gf_len, this) |
1301 		BF_BCH_FLASH0LAYOUT1_DATAN_SIZE(block_size, this);
1302 }
1303 
1304 static int gpmi_ecc_read_page(struct nand_chip *chip, uint8_t *buf,
1305 			      int oob_required, int page)
1306 {
1307 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1308 	struct mtd_info *mtd = nand_to_mtd(chip);
1309 	struct bch_geometry *geo = &this->bch_geometry;
1310 	unsigned int max_bitflips;
1311 	int ret;
1312 
1313 	gpmi_bch_layout_std(this);
1314 	this->bch = true;
1315 
1316 	ret = nand_read_page_op(chip, page, 0, buf, geo->page_size);
1317 	if (ret)
1318 		return ret;
1319 
1320 	max_bitflips = gpmi_count_bitflips(chip, buf, 0,
1321 					   geo->ecc_chunk_count,
1322 					   geo->auxiliary_status_offset);
1323 
1324 	/* handle the block mark swapping */
1325 	block_mark_swapping(this, buf, this->auxiliary_virt);
1326 
1327 	if (oob_required) {
1328 		/*
1329 		 * It's time to deliver the OOB bytes. See gpmi_ecc_read_oob()
1330 		 * for details about our policy for delivering the OOB.
1331 		 *
1332 		 * We fill the caller's buffer with set bits, and then copy the
1333 		 * block mark to th caller's buffer. Note that, if block mark
1334 		 * swapping was necessary, it has already been done, so we can
1335 		 * rely on the first byte of the auxiliary buffer to contain
1336 		 * the block mark.
1337 		 */
1338 		memset(chip->oob_poi, ~0, mtd->oobsize);
1339 		chip->oob_poi[0] = ((uint8_t *)this->auxiliary_virt)[0];
1340 	}
1341 
1342 	return max_bitflips;
1343 }
1344 
1345 /* Fake a virtual small page for the subpage read */
1346 static int gpmi_ecc_read_subpage(struct nand_chip *chip, uint32_t offs,
1347 				 uint32_t len, uint8_t *buf, int page)
1348 {
1349 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1350 	struct bch_geometry *geo = &this->bch_geometry;
1351 	int size = chip->ecc.size; /* ECC chunk size */
1352 	int meta, n, page_size;
1353 	unsigned int max_bitflips;
1354 	unsigned int ecc_strength;
1355 	int first, last, marker_pos;
1356 	int ecc_parity_size;
1357 	int col = 0;
1358 	int ret;
1359 
1360 	/* The size of ECC parity */
1361 	ecc_parity_size = geo->gf_len * geo->ecc_strength / 8;
1362 
1363 	/* Align it with the chunk size */
1364 	first = offs / size;
1365 	last = (offs + len - 1) / size;
1366 
1367 	if (this->swap_block_mark) {
1368 		/*
1369 		 * Find the chunk which contains the Block Marker.
1370 		 * If this chunk is in the range of [first, last],
1371 		 * we have to read out the whole page.
1372 		 * Why? since we had swapped the data at the position of Block
1373 		 * Marker to the metadata which is bound with the chunk 0.
1374 		 */
1375 		marker_pos = geo->block_mark_byte_offset / size;
1376 		if (last >= marker_pos && first <= marker_pos) {
1377 			dev_dbg(this->dev,
1378 				"page:%d, first:%d, last:%d, marker at:%d\n",
1379 				page, first, last, marker_pos);
1380 			return gpmi_ecc_read_page(chip, buf, 0, page);
1381 		}
1382 	}
1383 
1384 	meta = geo->metadata_size;
1385 	if (first) {
1386 		col = meta + (size + ecc_parity_size) * first;
1387 		meta = 0;
1388 		buf = buf + first * size;
1389 	}
1390 
1391 	ecc_parity_size = geo->gf_len * geo->ecc_strength / 8;
1392 
1393 	n = last - first + 1;
1394 	page_size = meta + (size + ecc_parity_size) * n;
1395 	ecc_strength = geo->ecc_strength >> 1;
1396 
1397 	this->bch_flashlayout0 = BF_BCH_FLASH0LAYOUT0_NBLOCKS(n - 1) |
1398 		BF_BCH_FLASH0LAYOUT0_META_SIZE(meta) |
1399 		BF_BCH_FLASH0LAYOUT0_ECC0(ecc_strength, this) |
1400 		BF_BCH_FLASH0LAYOUT0_GF(geo->gf_len, this) |
1401 		BF_BCH_FLASH0LAYOUT0_DATA0_SIZE(geo->ecc_chunk_size, this);
1402 
1403 	this->bch_flashlayout1 = BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(page_size) |
1404 		BF_BCH_FLASH0LAYOUT1_ECCN(ecc_strength, this) |
1405 		BF_BCH_FLASH0LAYOUT1_GF(geo->gf_len, this) |
1406 		BF_BCH_FLASH0LAYOUT1_DATAN_SIZE(geo->ecc_chunk_size, this);
1407 
1408 	this->bch = true;
1409 
1410 	ret = nand_read_page_op(chip, page, col, buf, page_size);
1411 	if (ret)
1412 		return ret;
1413 
1414 	dev_dbg(this->dev, "page:%d(%d:%d)%d, chunk:(%d:%d), BCH PG size:%d\n",
1415 		page, offs, len, col, first, n, page_size);
1416 
1417 	max_bitflips = gpmi_count_bitflips(chip, buf, first, last, meta);
1418 
1419 	return max_bitflips;
1420 }
1421 
1422 static int gpmi_ecc_write_page(struct nand_chip *chip, const uint8_t *buf,
1423 			       int oob_required, int page)
1424 {
1425 	struct mtd_info *mtd = nand_to_mtd(chip);
1426 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1427 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1428 	int ret;
1429 
1430 	dev_dbg(this->dev, "ecc write page.\n");
1431 
1432 	gpmi_bch_layout_std(this);
1433 	this->bch = true;
1434 
1435 	memcpy(this->auxiliary_virt, chip->oob_poi, nfc_geo->auxiliary_size);
1436 
1437 	if (this->swap_block_mark) {
1438 		/*
1439 		 * When doing bad block marker swapping we must always copy the
1440 		 * input buffer as we can't modify the const buffer.
1441 		 */
1442 		memcpy(this->data_buffer_dma, buf, mtd->writesize);
1443 		buf = this->data_buffer_dma;
1444 		block_mark_swapping(this, this->data_buffer_dma,
1445 				    this->auxiliary_virt);
1446 	}
1447 
1448 	ret = nand_prog_page_op(chip, page, 0, buf, nfc_geo->page_size);
1449 
1450 	return ret;
1451 }
1452 
1453 /*
1454  * There are several places in this driver where we have to handle the OOB and
1455  * block marks. This is the function where things are the most complicated, so
1456  * this is where we try to explain it all. All the other places refer back to
1457  * here.
1458  *
1459  * These are the rules, in order of decreasing importance:
1460  *
1461  * 1) Nothing the caller does can be allowed to imperil the block mark.
1462  *
1463  * 2) In read operations, the first byte of the OOB we return must reflect the
1464  *    true state of the block mark, no matter where that block mark appears in
1465  *    the physical page.
1466  *
1467  * 3) ECC-based read operations return an OOB full of set bits (since we never
1468  *    allow ECC-based writes to the OOB, it doesn't matter what ECC-based reads
1469  *    return).
1470  *
1471  * 4) "Raw" read operations return a direct view of the physical bytes in the
1472  *    page, using the conventional definition of which bytes are data and which
1473  *    are OOB. This gives the caller a way to see the actual, physical bytes
1474  *    in the page, without the distortions applied by our ECC engine.
1475  *
1476  *
1477  * What we do for this specific read operation depends on two questions:
1478  *
1479  * 1) Are we doing a "raw" read, or an ECC-based read?
1480  *
1481  * 2) Are we using block mark swapping or transcription?
1482  *
1483  * There are four cases, illustrated by the following Karnaugh map:
1484  *
1485  *                    |           Raw           |         ECC-based       |
1486  *       -------------+-------------------------+-------------------------+
1487  *                    | Read the conventional   |                         |
1488  *                    | OOB at the end of the   |                         |
1489  *       Swapping     | page and return it. It  |                         |
1490  *                    | contains exactly what   |                         |
1491  *                    | we want.                | Read the block mark and |
1492  *       -------------+-------------------------+ return it in a buffer   |
1493  *                    | Read the conventional   | full of set bits.       |
1494  *                    | OOB at the end of the   |                         |
1495  *                    | page and also the block |                         |
1496  *       Transcribing | mark in the metadata.   |                         |
1497  *                    | Copy the block mark     |                         |
1498  *                    | into the first byte of  |                         |
1499  *                    | the OOB.                |                         |
1500  *       -------------+-------------------------+-------------------------+
1501  *
1502  * Note that we break rule #4 in the Transcribing/Raw case because we're not
1503  * giving an accurate view of the actual, physical bytes in the page (we're
1504  * overwriting the block mark). That's OK because it's more important to follow
1505  * rule #2.
1506  *
1507  * It turns out that knowing whether we want an "ECC-based" or "raw" read is not
1508  * easy. When reading a page, for example, the NAND Flash MTD code calls our
1509  * ecc.read_page or ecc.read_page_raw function. Thus, the fact that MTD wants an
1510  * ECC-based or raw view of the page is implicit in which function it calls
1511  * (there is a similar pair of ECC-based/raw functions for writing).
1512  */
1513 static int gpmi_ecc_read_oob(struct nand_chip *chip, int page)
1514 {
1515 	struct mtd_info *mtd = nand_to_mtd(chip);
1516 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1517 	int ret;
1518 
1519 	/* clear the OOB buffer */
1520 	memset(chip->oob_poi, ~0, mtd->oobsize);
1521 
1522 	/* Read out the conventional OOB. */
1523 	ret = nand_read_page_op(chip, page, mtd->writesize, chip->oob_poi,
1524 				mtd->oobsize);
1525 	if (ret)
1526 		return ret;
1527 
1528 	/*
1529 	 * Now, we want to make sure the block mark is correct. In the
1530 	 * non-transcribing case (!GPMI_IS_MX23()), we already have it.
1531 	 * Otherwise, we need to explicitly read it.
1532 	 */
1533 	if (GPMI_IS_MX23(this)) {
1534 		/* Read the block mark into the first byte of the OOB buffer. */
1535 		ret = nand_read_page_op(chip, page, 0, chip->oob_poi, 1);
1536 		if (ret)
1537 			return ret;
1538 	}
1539 
1540 	return 0;
1541 }
1542 
1543 static int gpmi_ecc_write_oob(struct nand_chip *chip, int page)
1544 {
1545 	struct mtd_info *mtd = nand_to_mtd(chip);
1546 	struct mtd_oob_region of = { };
1547 
1548 	/* Do we have available oob area? */
1549 	mtd_ooblayout_free(mtd, 0, &of);
1550 	if (!of.length)
1551 		return -EPERM;
1552 
1553 	if (!nand_is_slc(chip))
1554 		return -EPERM;
1555 
1556 	return nand_prog_page_op(chip, page, mtd->writesize + of.offset,
1557 				 chip->oob_poi + of.offset, of.length);
1558 }
1559 
1560 /*
1561  * This function reads a NAND page without involving the ECC engine (no HW
1562  * ECC correction).
1563  * The tricky part in the GPMI/BCH controller is that it stores ECC bits
1564  * inline (interleaved with payload DATA), and do not align data chunk on
1565  * byte boundaries.
1566  * We thus need to take care moving the payload data and ECC bits stored in the
1567  * page into the provided buffers, which is why we're using nand_extract_bits().
1568  *
1569  * See set_geometry_by_ecc_info inline comments to have a full description
1570  * of the layout used by the GPMI controller.
1571  */
1572 static int gpmi_ecc_read_page_raw(struct nand_chip *chip, uint8_t *buf,
1573 				  int oob_required, int page)
1574 {
1575 	struct mtd_info *mtd = nand_to_mtd(chip);
1576 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1577 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1578 	int eccsize = nfc_geo->ecc_chunk_size;
1579 	int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1580 	u8 *tmp_buf = this->raw_buffer;
1581 	size_t src_bit_off;
1582 	size_t oob_bit_off;
1583 	size_t oob_byte_off;
1584 	uint8_t *oob = chip->oob_poi;
1585 	int step;
1586 	int ret;
1587 
1588 	ret = nand_read_page_op(chip, page, 0, tmp_buf,
1589 				mtd->writesize + mtd->oobsize);
1590 	if (ret)
1591 		return ret;
1592 
1593 	/*
1594 	 * If required, swap the bad block marker and the data stored in the
1595 	 * metadata section, so that we don't wrongly consider a block as bad.
1596 	 *
1597 	 * See the layout description for a detailed explanation on why this
1598 	 * is needed.
1599 	 */
1600 	if (this->swap_block_mark)
1601 		swap(tmp_buf[0], tmp_buf[mtd->writesize]);
1602 
1603 	/*
1604 	 * Copy the metadata section into the oob buffer (this section is
1605 	 * guaranteed to be aligned on a byte boundary).
1606 	 */
1607 	if (oob_required)
1608 		memcpy(oob, tmp_buf, nfc_geo->metadata_size);
1609 
1610 	oob_bit_off = nfc_geo->metadata_size * 8;
1611 	src_bit_off = oob_bit_off;
1612 
1613 	/* Extract interleaved payload data and ECC bits */
1614 	for (step = 0; step < nfc_geo->ecc_chunk_count; step++) {
1615 		if (buf)
1616 			nand_extract_bits(buf, step * eccsize * 8, tmp_buf,
1617 					  src_bit_off, eccsize * 8);
1618 		src_bit_off += eccsize * 8;
1619 
1620 		/* Align last ECC block to align a byte boundary */
1621 		if (step == nfc_geo->ecc_chunk_count - 1 &&
1622 		    (oob_bit_off + eccbits) % 8)
1623 			eccbits += 8 - ((oob_bit_off + eccbits) % 8);
1624 
1625 		if (oob_required)
1626 			nand_extract_bits(oob, oob_bit_off, tmp_buf,
1627 					  src_bit_off, eccbits);
1628 
1629 		src_bit_off += eccbits;
1630 		oob_bit_off += eccbits;
1631 	}
1632 
1633 	if (oob_required) {
1634 		oob_byte_off = oob_bit_off / 8;
1635 
1636 		if (oob_byte_off < mtd->oobsize)
1637 			memcpy(oob + oob_byte_off,
1638 			       tmp_buf + mtd->writesize + oob_byte_off,
1639 			       mtd->oobsize - oob_byte_off);
1640 	}
1641 
1642 	return 0;
1643 }
1644 
1645 /*
1646  * This function writes a NAND page without involving the ECC engine (no HW
1647  * ECC generation).
1648  * The tricky part in the GPMI/BCH controller is that it stores ECC bits
1649  * inline (interleaved with payload DATA), and do not align data chunk on
1650  * byte boundaries.
1651  * We thus need to take care moving the OOB area at the right place in the
1652  * final page, which is why we're using nand_extract_bits().
1653  *
1654  * See set_geometry_by_ecc_info inline comments to have a full description
1655  * of the layout used by the GPMI controller.
1656  */
1657 static int gpmi_ecc_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
1658 				   int oob_required, int page)
1659 {
1660 	struct mtd_info *mtd = nand_to_mtd(chip);
1661 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1662 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1663 	int eccsize = nfc_geo->ecc_chunk_size;
1664 	int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1665 	u8 *tmp_buf = this->raw_buffer;
1666 	uint8_t *oob = chip->oob_poi;
1667 	size_t dst_bit_off;
1668 	size_t oob_bit_off;
1669 	size_t oob_byte_off;
1670 	int step;
1671 
1672 	/*
1673 	 * Initialize all bits to 1 in case we don't have a buffer for the
1674 	 * payload or oob data in order to leave unspecified bits of data
1675 	 * to their initial state.
1676 	 */
1677 	if (!buf || !oob_required)
1678 		memset(tmp_buf, 0xff, mtd->writesize + mtd->oobsize);
1679 
1680 	/*
1681 	 * First copy the metadata section (stored in oob buffer) at the
1682 	 * beginning of the page, as imposed by the GPMI layout.
1683 	 */
1684 	memcpy(tmp_buf, oob, nfc_geo->metadata_size);
1685 	oob_bit_off = nfc_geo->metadata_size * 8;
1686 	dst_bit_off = oob_bit_off;
1687 
1688 	/* Interleave payload data and ECC bits */
1689 	for (step = 0; step < nfc_geo->ecc_chunk_count; step++) {
1690 		if (buf)
1691 			nand_extract_bits(tmp_buf, dst_bit_off, buf,
1692 					  step * eccsize * 8, eccsize * 8);
1693 		dst_bit_off += eccsize * 8;
1694 
1695 		/* Align last ECC block to align a byte boundary */
1696 		if (step == nfc_geo->ecc_chunk_count - 1 &&
1697 		    (oob_bit_off + eccbits) % 8)
1698 			eccbits += 8 - ((oob_bit_off + eccbits) % 8);
1699 
1700 		if (oob_required)
1701 			nand_extract_bits(tmp_buf, dst_bit_off, oob,
1702 					  oob_bit_off, eccbits);
1703 
1704 		dst_bit_off += eccbits;
1705 		oob_bit_off += eccbits;
1706 	}
1707 
1708 	oob_byte_off = oob_bit_off / 8;
1709 
1710 	if (oob_required && oob_byte_off < mtd->oobsize)
1711 		memcpy(tmp_buf + mtd->writesize + oob_byte_off,
1712 		       oob + oob_byte_off, mtd->oobsize - oob_byte_off);
1713 
1714 	/*
1715 	 * If required, swap the bad block marker and the first byte of the
1716 	 * metadata section, so that we don't modify the bad block marker.
1717 	 *
1718 	 * See the layout description for a detailed explanation on why this
1719 	 * is needed.
1720 	 */
1721 	if (this->swap_block_mark)
1722 		swap(tmp_buf[0], tmp_buf[mtd->writesize]);
1723 
1724 	return nand_prog_page_op(chip, page, 0, tmp_buf,
1725 				 mtd->writesize + mtd->oobsize);
1726 }
1727 
1728 static int gpmi_ecc_read_oob_raw(struct nand_chip *chip, int page)
1729 {
1730 	return gpmi_ecc_read_page_raw(chip, NULL, 1, page);
1731 }
1732 
1733 static int gpmi_ecc_write_oob_raw(struct nand_chip *chip, int page)
1734 {
1735 	return gpmi_ecc_write_page_raw(chip, NULL, 1, page);
1736 }
1737 
1738 static int gpmi_block_markbad(struct nand_chip *chip, loff_t ofs)
1739 {
1740 	struct mtd_info *mtd = nand_to_mtd(chip);
1741 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1742 	int ret = 0;
1743 	uint8_t *block_mark;
1744 	int column, page, chipnr;
1745 
1746 	chipnr = (int)(ofs >> chip->chip_shift);
1747 	nand_select_target(chip, chipnr);
1748 
1749 	column = !GPMI_IS_MX23(this) ? mtd->writesize : 0;
1750 
1751 	/* Write the block mark. */
1752 	block_mark = this->data_buffer_dma;
1753 	block_mark[0] = 0; /* bad block marker */
1754 
1755 	/* Shift to get page */
1756 	page = (int)(ofs >> chip->page_shift);
1757 
1758 	ret = nand_prog_page_op(chip, page, column, block_mark, 1);
1759 
1760 	nand_deselect_target(chip);
1761 
1762 	return ret;
1763 }
1764 
1765 static int nand_boot_set_geometry(struct gpmi_nand_data *this)
1766 {
1767 	struct boot_rom_geometry *geometry = &this->rom_geometry;
1768 
1769 	/*
1770 	 * Set the boot block stride size.
1771 	 *
1772 	 * In principle, we should be reading this from the OTP bits, since
1773 	 * that's where the ROM is going to get it. In fact, we don't have any
1774 	 * way to read the OTP bits, so we go with the default and hope for the
1775 	 * best.
1776 	 */
1777 	geometry->stride_size_in_pages = 64;
1778 
1779 	/*
1780 	 * Set the search area stride exponent.
1781 	 *
1782 	 * In principle, we should be reading this from the OTP bits, since
1783 	 * that's where the ROM is going to get it. In fact, we don't have any
1784 	 * way to read the OTP bits, so we go with the default and hope for the
1785 	 * best.
1786 	 */
1787 	geometry->search_area_stride_exponent = 2;
1788 	return 0;
1789 }
1790 
1791 static const char  *fingerprint = "STMP";
1792 static int mx23_check_transcription_stamp(struct gpmi_nand_data *this)
1793 {
1794 	struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1795 	struct device *dev = this->dev;
1796 	struct nand_chip *chip = &this->nand;
1797 	unsigned int search_area_size_in_strides;
1798 	unsigned int stride;
1799 	unsigned int page;
1800 	u8 *buffer = nand_get_data_buf(chip);
1801 	int found_an_ncb_fingerprint = false;
1802 	int ret;
1803 
1804 	/* Compute the number of strides in a search area. */
1805 	search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1806 
1807 	nand_select_target(chip, 0);
1808 
1809 	/*
1810 	 * Loop through the first search area, looking for the NCB fingerprint.
1811 	 */
1812 	dev_dbg(dev, "Scanning for an NCB fingerprint...\n");
1813 
1814 	for (stride = 0; stride < search_area_size_in_strides; stride++) {
1815 		/* Compute the page addresses. */
1816 		page = stride * rom_geo->stride_size_in_pages;
1817 
1818 		dev_dbg(dev, "Looking for a fingerprint in page 0x%x\n", page);
1819 
1820 		/*
1821 		 * Read the NCB fingerprint. The fingerprint is four bytes long
1822 		 * and starts in the 12th byte of the page.
1823 		 */
1824 		ret = nand_read_page_op(chip, page, 12, buffer,
1825 					strlen(fingerprint));
1826 		if (ret)
1827 			continue;
1828 
1829 		/* Look for the fingerprint. */
1830 		if (!memcmp(buffer, fingerprint, strlen(fingerprint))) {
1831 			found_an_ncb_fingerprint = true;
1832 			break;
1833 		}
1834 
1835 	}
1836 
1837 	nand_deselect_target(chip);
1838 
1839 	if (found_an_ncb_fingerprint)
1840 		dev_dbg(dev, "\tFound a fingerprint\n");
1841 	else
1842 		dev_dbg(dev, "\tNo fingerprint found\n");
1843 	return found_an_ncb_fingerprint;
1844 }
1845 
1846 /* Writes a transcription stamp. */
1847 static int mx23_write_transcription_stamp(struct gpmi_nand_data *this)
1848 {
1849 	struct device *dev = this->dev;
1850 	struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1851 	struct nand_chip *chip = &this->nand;
1852 	struct mtd_info *mtd = nand_to_mtd(chip);
1853 	unsigned int block_size_in_pages;
1854 	unsigned int search_area_size_in_strides;
1855 	unsigned int search_area_size_in_pages;
1856 	unsigned int search_area_size_in_blocks;
1857 	unsigned int block;
1858 	unsigned int stride;
1859 	unsigned int page;
1860 	u8 *buffer = nand_get_data_buf(chip);
1861 	int status;
1862 
1863 	/* Compute the search area geometry. */
1864 	block_size_in_pages = mtd->erasesize / mtd->writesize;
1865 	search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1866 	search_area_size_in_pages = search_area_size_in_strides *
1867 					rom_geo->stride_size_in_pages;
1868 	search_area_size_in_blocks =
1869 		  (search_area_size_in_pages + (block_size_in_pages - 1)) /
1870 				    block_size_in_pages;
1871 
1872 	dev_dbg(dev, "Search Area Geometry :\n");
1873 	dev_dbg(dev, "\tin Blocks : %u\n", search_area_size_in_blocks);
1874 	dev_dbg(dev, "\tin Strides: %u\n", search_area_size_in_strides);
1875 	dev_dbg(dev, "\tin Pages  : %u\n", search_area_size_in_pages);
1876 
1877 	nand_select_target(chip, 0);
1878 
1879 	/* Loop over blocks in the first search area, erasing them. */
1880 	dev_dbg(dev, "Erasing the search area...\n");
1881 
1882 	for (block = 0; block < search_area_size_in_blocks; block++) {
1883 		/* Erase this block. */
1884 		dev_dbg(dev, "\tErasing block 0x%x\n", block);
1885 		status = nand_erase_op(chip, block);
1886 		if (status)
1887 			dev_err(dev, "[%s] Erase failed.\n", __func__);
1888 	}
1889 
1890 	/* Write the NCB fingerprint into the page buffer. */
1891 	memset(buffer, ~0, mtd->writesize);
1892 	memcpy(buffer + 12, fingerprint, strlen(fingerprint));
1893 
1894 	/* Loop through the first search area, writing NCB fingerprints. */
1895 	dev_dbg(dev, "Writing NCB fingerprints...\n");
1896 	for (stride = 0; stride < search_area_size_in_strides; stride++) {
1897 		/* Compute the page addresses. */
1898 		page = stride * rom_geo->stride_size_in_pages;
1899 
1900 		/* Write the first page of the current stride. */
1901 		dev_dbg(dev, "Writing an NCB fingerprint in page 0x%x\n", page);
1902 
1903 		status = chip->ecc.write_page_raw(chip, buffer, 0, page);
1904 		if (status)
1905 			dev_err(dev, "[%s] Write failed.\n", __func__);
1906 	}
1907 
1908 	nand_deselect_target(chip);
1909 
1910 	return 0;
1911 }
1912 
1913 static int mx23_boot_init(struct gpmi_nand_data  *this)
1914 {
1915 	struct device *dev = this->dev;
1916 	struct nand_chip *chip = &this->nand;
1917 	struct mtd_info *mtd = nand_to_mtd(chip);
1918 	unsigned int block_count;
1919 	unsigned int block;
1920 	int     chipnr;
1921 	int     page;
1922 	loff_t  byte;
1923 	uint8_t block_mark;
1924 	int     ret = 0;
1925 
1926 	/*
1927 	 * If control arrives here, we can't use block mark swapping, which
1928 	 * means we're forced to use transcription. First, scan for the
1929 	 * transcription stamp. If we find it, then we don't have to do
1930 	 * anything -- the block marks are already transcribed.
1931 	 */
1932 	if (mx23_check_transcription_stamp(this))
1933 		return 0;
1934 
1935 	/*
1936 	 * If control arrives here, we couldn't find a transcription stamp, so
1937 	 * so we presume the block marks are in the conventional location.
1938 	 */
1939 	dev_dbg(dev, "Transcribing bad block marks...\n");
1940 
1941 	/* Compute the number of blocks in the entire medium. */
1942 	block_count = nanddev_eraseblocks_per_target(&chip->base);
1943 
1944 	/*
1945 	 * Loop over all the blocks in the medium, transcribing block marks as
1946 	 * we go.
1947 	 */
1948 	for (block = 0; block < block_count; block++) {
1949 		/*
1950 		 * Compute the chip, page and byte addresses for this block's
1951 		 * conventional mark.
1952 		 */
1953 		chipnr = block >> (chip->chip_shift - chip->phys_erase_shift);
1954 		page = block << (chip->phys_erase_shift - chip->page_shift);
1955 		byte = block <<  chip->phys_erase_shift;
1956 
1957 		/* Send the command to read the conventional block mark. */
1958 		nand_select_target(chip, chipnr);
1959 		ret = nand_read_page_op(chip, page, mtd->writesize, &block_mark,
1960 					1);
1961 		nand_deselect_target(chip);
1962 
1963 		if (ret)
1964 			continue;
1965 
1966 		/*
1967 		 * Check if the block is marked bad. If so, we need to mark it
1968 		 * again, but this time the result will be a mark in the
1969 		 * location where we transcribe block marks.
1970 		 */
1971 		if (block_mark != 0xff) {
1972 			dev_dbg(dev, "Transcribing mark in block %u\n", block);
1973 			ret = chip->legacy.block_markbad(chip, byte);
1974 			if (ret)
1975 				dev_err(dev,
1976 					"Failed to mark block bad with ret %d\n",
1977 					ret);
1978 		}
1979 	}
1980 
1981 	/* Write the stamp that indicates we've transcribed the block marks. */
1982 	mx23_write_transcription_stamp(this);
1983 	return 0;
1984 }
1985 
1986 static int nand_boot_init(struct gpmi_nand_data  *this)
1987 {
1988 	nand_boot_set_geometry(this);
1989 
1990 	/* This is ROM arch-specific initilization before the BBT scanning. */
1991 	if (GPMI_IS_MX23(this))
1992 		return mx23_boot_init(this);
1993 	return 0;
1994 }
1995 
1996 static int gpmi_set_geometry(struct gpmi_nand_data *this)
1997 {
1998 	int ret;
1999 
2000 	/* Free the temporary DMA memory for reading ID. */
2001 	gpmi_free_dma_buffer(this);
2002 
2003 	/* Set up the NFC geometry which is used by BCH. */
2004 	ret = bch_set_geometry(this);
2005 	if (ret) {
2006 		dev_err(this->dev, "Error setting BCH geometry : %d\n", ret);
2007 		return ret;
2008 	}
2009 
2010 	/* Alloc the new DMA buffers according to the pagesize and oobsize */
2011 	return gpmi_alloc_dma_buffer(this);
2012 }
2013 
2014 static int gpmi_init_last(struct gpmi_nand_data *this)
2015 {
2016 	struct nand_chip *chip = &this->nand;
2017 	struct mtd_info *mtd = nand_to_mtd(chip);
2018 	struct nand_ecc_ctrl *ecc = &chip->ecc;
2019 	struct bch_geometry *bch_geo = &this->bch_geometry;
2020 	int ret;
2021 
2022 	/* Set up the medium geometry */
2023 	ret = gpmi_set_geometry(this);
2024 	if (ret)
2025 		return ret;
2026 
2027 	/* Init the nand_ecc_ctrl{} */
2028 	ecc->read_page	= gpmi_ecc_read_page;
2029 	ecc->write_page	= gpmi_ecc_write_page;
2030 	ecc->read_oob	= gpmi_ecc_read_oob;
2031 	ecc->write_oob	= gpmi_ecc_write_oob;
2032 	ecc->read_page_raw = gpmi_ecc_read_page_raw;
2033 	ecc->write_page_raw = gpmi_ecc_write_page_raw;
2034 	ecc->read_oob_raw = gpmi_ecc_read_oob_raw;
2035 	ecc->write_oob_raw = gpmi_ecc_write_oob_raw;
2036 	ecc->engine_type = NAND_ECC_ENGINE_TYPE_ON_HOST;
2037 	ecc->size	= bch_geo->ecc_chunk_size;
2038 	ecc->strength	= bch_geo->ecc_strength;
2039 	mtd_set_ooblayout(mtd, &gpmi_ooblayout_ops);
2040 
2041 	/*
2042 	 * We only enable the subpage read when:
2043 	 *  (1) the chip is imx6, and
2044 	 *  (2) the size of the ECC parity is byte aligned.
2045 	 */
2046 	if (GPMI_IS_MX6(this) &&
2047 		((bch_geo->gf_len * bch_geo->ecc_strength) % 8) == 0) {
2048 		ecc->read_subpage = gpmi_ecc_read_subpage;
2049 		chip->options |= NAND_SUBPAGE_READ;
2050 	}
2051 
2052 	return 0;
2053 }
2054 
2055 static int gpmi_nand_attach_chip(struct nand_chip *chip)
2056 {
2057 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
2058 	int ret;
2059 
2060 	if (chip->bbt_options & NAND_BBT_USE_FLASH) {
2061 		chip->bbt_options |= NAND_BBT_NO_OOB;
2062 
2063 		if (of_property_read_bool(this->dev->of_node,
2064 					  "fsl,no-blockmark-swap"))
2065 			this->swap_block_mark = false;
2066 	}
2067 	dev_dbg(this->dev, "Blockmark swapping %sabled\n",
2068 		this->swap_block_mark ? "en" : "dis");
2069 
2070 	ret = gpmi_init_last(this);
2071 	if (ret)
2072 		return ret;
2073 
2074 	chip->options |= NAND_SKIP_BBTSCAN;
2075 
2076 	return 0;
2077 }
2078 
2079 static struct gpmi_transfer *get_next_transfer(struct gpmi_nand_data *this)
2080 {
2081 	struct gpmi_transfer *transfer = &this->transfers[this->ntransfers];
2082 
2083 	this->ntransfers++;
2084 
2085 	if (this->ntransfers == GPMI_MAX_TRANSFERS)
2086 		return NULL;
2087 
2088 	return transfer;
2089 }
2090 
2091 static struct dma_async_tx_descriptor *gpmi_chain_command(
2092 	struct gpmi_nand_data *this, u8 cmd, const u8 *addr, int naddr)
2093 {
2094 	struct dma_chan *channel = get_dma_chan(this);
2095 	struct dma_async_tx_descriptor *desc;
2096 	struct gpmi_transfer *transfer;
2097 	int chip = this->nand.cur_cs;
2098 	u32 pio[3];
2099 
2100 	/* [1] send out the PIO words */
2101 	pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__WRITE)
2102 		| BM_GPMI_CTRL0_WORD_LENGTH
2103 		| BF_GPMI_CTRL0_CS(chip, this)
2104 		| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
2105 		| BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_CLE)
2106 		| BM_GPMI_CTRL0_ADDRESS_INCREMENT
2107 		| BF_GPMI_CTRL0_XFER_COUNT(naddr + 1);
2108 	pio[1] = 0;
2109 	pio[2] = 0;
2110 	desc = mxs_dmaengine_prep_pio(channel, pio, ARRAY_SIZE(pio),
2111 				      DMA_TRANS_NONE, 0);
2112 	if (!desc)
2113 		return NULL;
2114 
2115 	transfer = get_next_transfer(this);
2116 	if (!transfer)
2117 		return NULL;
2118 
2119 	transfer->cmdbuf[0] = cmd;
2120 	if (naddr)
2121 		memcpy(&transfer->cmdbuf[1], addr, naddr);
2122 
2123 	sg_init_one(&transfer->sgl, transfer->cmdbuf, naddr + 1);
2124 	dma_map_sg(this->dev, &transfer->sgl, 1, DMA_TO_DEVICE);
2125 
2126 	transfer->direction = DMA_TO_DEVICE;
2127 
2128 	desc = dmaengine_prep_slave_sg(channel, &transfer->sgl, 1, DMA_MEM_TO_DEV,
2129 				       MXS_DMA_CTRL_WAIT4END);
2130 	return desc;
2131 }
2132 
2133 static struct dma_async_tx_descriptor *gpmi_chain_wait_ready(
2134 	struct gpmi_nand_data *this)
2135 {
2136 	struct dma_chan *channel = get_dma_chan(this);
2137 	u32 pio[2];
2138 
2139 	pio[0] =  BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY)
2140 		| BM_GPMI_CTRL0_WORD_LENGTH
2141 		| BF_GPMI_CTRL0_CS(this->nand.cur_cs, this)
2142 		| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
2143 		| BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_DATA)
2144 		| BF_GPMI_CTRL0_XFER_COUNT(0);
2145 	pio[1] = 0;
2146 
2147 	return mxs_dmaengine_prep_pio(channel, pio, 2, DMA_TRANS_NONE,
2148 				MXS_DMA_CTRL_WAIT4END | MXS_DMA_CTRL_WAIT4RDY);
2149 }
2150 
2151 static struct dma_async_tx_descriptor *gpmi_chain_data_read(
2152 	struct gpmi_nand_data *this, void *buf, int raw_len, bool *direct)
2153 {
2154 	struct dma_async_tx_descriptor *desc;
2155 	struct dma_chan *channel = get_dma_chan(this);
2156 	struct gpmi_transfer *transfer;
2157 	u32 pio[6] = {};
2158 
2159 	transfer = get_next_transfer(this);
2160 	if (!transfer)
2161 		return NULL;
2162 
2163 	transfer->direction = DMA_FROM_DEVICE;
2164 
2165 	*direct = prepare_data_dma(this, buf, raw_len, &transfer->sgl,
2166 				   DMA_FROM_DEVICE);
2167 
2168 	pio[0] =  BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__READ)
2169 		| BM_GPMI_CTRL0_WORD_LENGTH
2170 		| BF_GPMI_CTRL0_CS(this->nand.cur_cs, this)
2171 		| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
2172 		| BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_DATA)
2173 		| BF_GPMI_CTRL0_XFER_COUNT(raw_len);
2174 
2175 	if (this->bch) {
2176 		pio[2] =  BM_GPMI_ECCCTRL_ENABLE_ECC
2177 			| BF_GPMI_ECCCTRL_ECC_CMD(BV_GPMI_ECCCTRL_ECC_CMD__BCH_DECODE)
2178 			| BF_GPMI_ECCCTRL_BUFFER_MASK(BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE
2179 				| BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY);
2180 		pio[3] = raw_len;
2181 		pio[4] = transfer->sgl.dma_address;
2182 		pio[5] = this->auxiliary_phys;
2183 	}
2184 
2185 	desc = mxs_dmaengine_prep_pio(channel, pio, ARRAY_SIZE(pio),
2186 				      DMA_TRANS_NONE, 0);
2187 	if (!desc)
2188 		return NULL;
2189 
2190 	if (!this->bch)
2191 		desc = dmaengine_prep_slave_sg(channel, &transfer->sgl, 1,
2192 					     DMA_DEV_TO_MEM,
2193 					     MXS_DMA_CTRL_WAIT4END);
2194 
2195 	return desc;
2196 }
2197 
2198 static struct dma_async_tx_descriptor *gpmi_chain_data_write(
2199 	struct gpmi_nand_data *this, const void *buf, int raw_len)
2200 {
2201 	struct dma_chan *channel = get_dma_chan(this);
2202 	struct dma_async_tx_descriptor *desc;
2203 	struct gpmi_transfer *transfer;
2204 	u32 pio[6] = {};
2205 
2206 	transfer = get_next_transfer(this);
2207 	if (!transfer)
2208 		return NULL;
2209 
2210 	transfer->direction = DMA_TO_DEVICE;
2211 
2212 	prepare_data_dma(this, buf, raw_len, &transfer->sgl, DMA_TO_DEVICE);
2213 
2214 	pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__WRITE)
2215 		| BM_GPMI_CTRL0_WORD_LENGTH
2216 		| BF_GPMI_CTRL0_CS(this->nand.cur_cs, this)
2217 		| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
2218 		| BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_DATA)
2219 		| BF_GPMI_CTRL0_XFER_COUNT(raw_len);
2220 
2221 	if (this->bch) {
2222 		pio[2] = BM_GPMI_ECCCTRL_ENABLE_ECC
2223 			| BF_GPMI_ECCCTRL_ECC_CMD(BV_GPMI_ECCCTRL_ECC_CMD__BCH_ENCODE)
2224 			| BF_GPMI_ECCCTRL_BUFFER_MASK(BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE |
2225 					BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY);
2226 		pio[3] = raw_len;
2227 		pio[4] = transfer->sgl.dma_address;
2228 		pio[5] = this->auxiliary_phys;
2229 	}
2230 
2231 	desc = mxs_dmaengine_prep_pio(channel, pio, ARRAY_SIZE(pio),
2232 				      DMA_TRANS_NONE,
2233 				      (this->bch ? MXS_DMA_CTRL_WAIT4END : 0));
2234 	if (!desc)
2235 		return NULL;
2236 
2237 	if (!this->bch)
2238 		desc = dmaengine_prep_slave_sg(channel, &transfer->sgl, 1,
2239 					       DMA_MEM_TO_DEV,
2240 					       MXS_DMA_CTRL_WAIT4END);
2241 
2242 	return desc;
2243 }
2244 
2245 static int gpmi_nfc_exec_op(struct nand_chip *chip,
2246 			     const struct nand_operation *op,
2247 			     bool check_only)
2248 {
2249 	const struct nand_op_instr *instr;
2250 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
2251 	struct dma_async_tx_descriptor *desc = NULL;
2252 	int i, ret, buf_len = 0, nbufs = 0;
2253 	u8 cmd = 0;
2254 	void *buf_read = NULL;
2255 	const void *buf_write = NULL;
2256 	bool direct = false;
2257 	struct completion *dma_completion, *bch_completion;
2258 	unsigned long to;
2259 
2260 	if (check_only)
2261 		return 0;
2262 
2263 	this->ntransfers = 0;
2264 	for (i = 0; i < GPMI_MAX_TRANSFERS; i++)
2265 		this->transfers[i].direction = DMA_NONE;
2266 
2267 	ret = pm_runtime_get_sync(this->dev);
2268 	if (ret < 0) {
2269 		pm_runtime_put_noidle(this->dev);
2270 		return ret;
2271 	}
2272 
2273 	/*
2274 	 * This driver currently supports only one NAND chip. Plus, dies share
2275 	 * the same configuration. So once timings have been applied on the
2276 	 * controller side, they will not change anymore. When the time will
2277 	 * come, the check on must_apply_timings will have to be dropped.
2278 	 */
2279 	if (this->hw.must_apply_timings) {
2280 		this->hw.must_apply_timings = false;
2281 		gpmi_nfc_apply_timings(this);
2282 	}
2283 
2284 	dev_dbg(this->dev, "%s: %d instructions\n", __func__, op->ninstrs);
2285 
2286 	for (i = 0; i < op->ninstrs; i++) {
2287 		instr = &op->instrs[i];
2288 
2289 		nand_op_trace("  ", instr);
2290 
2291 		switch (instr->type) {
2292 		case NAND_OP_WAITRDY_INSTR:
2293 			desc = gpmi_chain_wait_ready(this);
2294 			break;
2295 		case NAND_OP_CMD_INSTR:
2296 			cmd = instr->ctx.cmd.opcode;
2297 
2298 			/*
2299 			 * When this command has an address cycle chain it
2300 			 * together with the address cycle
2301 			 */
2302 			if (i + 1 != op->ninstrs &&
2303 			    op->instrs[i + 1].type == NAND_OP_ADDR_INSTR)
2304 				continue;
2305 
2306 			desc = gpmi_chain_command(this, cmd, NULL, 0);
2307 
2308 			break;
2309 		case NAND_OP_ADDR_INSTR:
2310 			desc = gpmi_chain_command(this, cmd, instr->ctx.addr.addrs,
2311 						  instr->ctx.addr.naddrs);
2312 			break;
2313 		case NAND_OP_DATA_OUT_INSTR:
2314 			buf_write = instr->ctx.data.buf.out;
2315 			buf_len = instr->ctx.data.len;
2316 			nbufs++;
2317 
2318 			desc = gpmi_chain_data_write(this, buf_write, buf_len);
2319 
2320 			break;
2321 		case NAND_OP_DATA_IN_INSTR:
2322 			if (!instr->ctx.data.len)
2323 				break;
2324 			buf_read = instr->ctx.data.buf.in;
2325 			buf_len = instr->ctx.data.len;
2326 			nbufs++;
2327 
2328 			desc = gpmi_chain_data_read(this, buf_read, buf_len,
2329 						   &direct);
2330 			break;
2331 		}
2332 
2333 		if (!desc) {
2334 			ret = -ENXIO;
2335 			goto unmap;
2336 		}
2337 	}
2338 
2339 	dev_dbg(this->dev, "%s setup done\n", __func__);
2340 
2341 	if (nbufs > 1) {
2342 		dev_err(this->dev, "Multiple data instructions not supported\n");
2343 		ret = -EINVAL;
2344 		goto unmap;
2345 	}
2346 
2347 	if (this->bch) {
2348 		writel(this->bch_flashlayout0,
2349 		       this->resources.bch_regs + HW_BCH_FLASH0LAYOUT0);
2350 		writel(this->bch_flashlayout1,
2351 		       this->resources.bch_regs + HW_BCH_FLASH0LAYOUT1);
2352 	}
2353 
2354 	desc->callback = dma_irq_callback;
2355 	desc->callback_param = this;
2356 	dma_completion = &this->dma_done;
2357 	bch_completion = NULL;
2358 
2359 	init_completion(dma_completion);
2360 
2361 	if (this->bch && buf_read) {
2362 		writel(BM_BCH_CTRL_COMPLETE_IRQ_EN,
2363 		       this->resources.bch_regs + HW_BCH_CTRL_SET);
2364 		bch_completion = &this->bch_done;
2365 		init_completion(bch_completion);
2366 	}
2367 
2368 	dmaengine_submit(desc);
2369 	dma_async_issue_pending(get_dma_chan(this));
2370 
2371 	to = wait_for_completion_timeout(dma_completion, msecs_to_jiffies(1000));
2372 	if (!to) {
2373 		dev_err(this->dev, "DMA timeout, last DMA\n");
2374 		gpmi_dump_info(this);
2375 		ret = -ETIMEDOUT;
2376 		goto unmap;
2377 	}
2378 
2379 	if (this->bch && buf_read) {
2380 		to = wait_for_completion_timeout(bch_completion, msecs_to_jiffies(1000));
2381 		if (!to) {
2382 			dev_err(this->dev, "BCH timeout, last DMA\n");
2383 			gpmi_dump_info(this);
2384 			ret = -ETIMEDOUT;
2385 			goto unmap;
2386 		}
2387 	}
2388 
2389 	writel(BM_BCH_CTRL_COMPLETE_IRQ_EN,
2390 	       this->resources.bch_regs + HW_BCH_CTRL_CLR);
2391 	gpmi_clear_bch(this);
2392 
2393 	ret = 0;
2394 
2395 unmap:
2396 	for (i = 0; i < this->ntransfers; i++) {
2397 		struct gpmi_transfer *transfer = &this->transfers[i];
2398 
2399 		if (transfer->direction != DMA_NONE)
2400 			dma_unmap_sg(this->dev, &transfer->sgl, 1,
2401 				     transfer->direction);
2402 	}
2403 
2404 	if (!ret && buf_read && !direct)
2405 		memcpy(buf_read, this->data_buffer_dma,
2406 		       gpmi_raw_len_to_len(this, buf_len));
2407 
2408 	this->bch = false;
2409 
2410 	pm_runtime_mark_last_busy(this->dev);
2411 	pm_runtime_put_autosuspend(this->dev);
2412 
2413 	return ret;
2414 }
2415 
2416 static const struct nand_controller_ops gpmi_nand_controller_ops = {
2417 	.attach_chip = gpmi_nand_attach_chip,
2418 	.setup_interface = gpmi_setup_interface,
2419 	.exec_op = gpmi_nfc_exec_op,
2420 };
2421 
2422 static int gpmi_nand_init(struct gpmi_nand_data *this)
2423 {
2424 	struct nand_chip *chip = &this->nand;
2425 	struct mtd_info  *mtd = nand_to_mtd(chip);
2426 	int ret;
2427 
2428 	/* init the MTD data structures */
2429 	mtd->name		= "gpmi-nand";
2430 	mtd->dev.parent		= this->dev;
2431 
2432 	/* init the nand_chip{}, we don't support a 16-bit NAND Flash bus. */
2433 	nand_set_controller_data(chip, this);
2434 	nand_set_flash_node(chip, this->pdev->dev.of_node);
2435 	chip->legacy.block_markbad = gpmi_block_markbad;
2436 	chip->badblock_pattern	= &gpmi_bbt_descr;
2437 	chip->options		|= NAND_NO_SUBPAGE_WRITE;
2438 
2439 	/* Set up swap_block_mark, must be set before the gpmi_set_geometry() */
2440 	this->swap_block_mark = !GPMI_IS_MX23(this);
2441 
2442 	/*
2443 	 * Allocate a temporary DMA buffer for reading ID in the
2444 	 * nand_scan_ident().
2445 	 */
2446 	this->bch_geometry.payload_size = 1024;
2447 	this->bch_geometry.auxiliary_size = 128;
2448 	ret = gpmi_alloc_dma_buffer(this);
2449 	if (ret)
2450 		return ret;
2451 
2452 	nand_controller_init(&this->base);
2453 	this->base.ops = &gpmi_nand_controller_ops;
2454 	chip->controller = &this->base;
2455 
2456 	ret = nand_scan(chip, GPMI_IS_MX6(this) ? 2 : 1);
2457 	if (ret)
2458 		goto err_out;
2459 
2460 	ret = nand_boot_init(this);
2461 	if (ret)
2462 		goto err_nand_cleanup;
2463 	ret = nand_create_bbt(chip);
2464 	if (ret)
2465 		goto err_nand_cleanup;
2466 
2467 	ret = mtd_device_register(mtd, NULL, 0);
2468 	if (ret)
2469 		goto err_nand_cleanup;
2470 	return 0;
2471 
2472 err_nand_cleanup:
2473 	nand_cleanup(chip);
2474 err_out:
2475 	gpmi_free_dma_buffer(this);
2476 	return ret;
2477 }
2478 
2479 static const struct of_device_id gpmi_nand_id_table[] = {
2480 	{ .compatible = "fsl,imx23-gpmi-nand", .data = &gpmi_devdata_imx23, },
2481 	{ .compatible = "fsl,imx28-gpmi-nand", .data = &gpmi_devdata_imx28, },
2482 	{ .compatible = "fsl,imx6q-gpmi-nand", .data = &gpmi_devdata_imx6q, },
2483 	{ .compatible = "fsl,imx6sx-gpmi-nand", .data = &gpmi_devdata_imx6sx, },
2484 	{ .compatible = "fsl,imx7d-gpmi-nand", .data = &gpmi_devdata_imx7d,},
2485 	{}
2486 };
2487 MODULE_DEVICE_TABLE(of, gpmi_nand_id_table);
2488 
2489 static int gpmi_nand_probe(struct platform_device *pdev)
2490 {
2491 	struct gpmi_nand_data *this;
2492 	int ret;
2493 
2494 	this = devm_kzalloc(&pdev->dev, sizeof(*this), GFP_KERNEL);
2495 	if (!this)
2496 		return -ENOMEM;
2497 
2498 	this->devdata = of_device_get_match_data(&pdev->dev);
2499 	platform_set_drvdata(pdev, this);
2500 	this->pdev  = pdev;
2501 	this->dev   = &pdev->dev;
2502 
2503 	ret = acquire_resources(this);
2504 	if (ret)
2505 		goto exit_acquire_resources;
2506 
2507 	ret = __gpmi_enable_clk(this, true);
2508 	if (ret)
2509 		goto exit_acquire_resources;
2510 
2511 	pm_runtime_set_autosuspend_delay(&pdev->dev, 500);
2512 	pm_runtime_use_autosuspend(&pdev->dev);
2513 	pm_runtime_set_active(&pdev->dev);
2514 	pm_runtime_enable(&pdev->dev);
2515 	pm_runtime_get_sync(&pdev->dev);
2516 
2517 	ret = gpmi_init(this);
2518 	if (ret)
2519 		goto exit_nfc_init;
2520 
2521 	ret = gpmi_nand_init(this);
2522 	if (ret)
2523 		goto exit_nfc_init;
2524 
2525 	pm_runtime_mark_last_busy(&pdev->dev);
2526 	pm_runtime_put_autosuspend(&pdev->dev);
2527 
2528 	dev_info(this->dev, "driver registered.\n");
2529 
2530 	return 0;
2531 
2532 exit_nfc_init:
2533 	pm_runtime_put(&pdev->dev);
2534 	pm_runtime_disable(&pdev->dev);
2535 	release_resources(this);
2536 exit_acquire_resources:
2537 
2538 	return ret;
2539 }
2540 
2541 static int gpmi_nand_remove(struct platform_device *pdev)
2542 {
2543 	struct gpmi_nand_data *this = platform_get_drvdata(pdev);
2544 	struct nand_chip *chip = &this->nand;
2545 	int ret;
2546 
2547 	pm_runtime_put_sync(&pdev->dev);
2548 	pm_runtime_disable(&pdev->dev);
2549 
2550 	ret = mtd_device_unregister(nand_to_mtd(chip));
2551 	WARN_ON(ret);
2552 	nand_cleanup(chip);
2553 	gpmi_free_dma_buffer(this);
2554 	release_resources(this);
2555 	return 0;
2556 }
2557 
2558 #ifdef CONFIG_PM_SLEEP
2559 static int gpmi_pm_suspend(struct device *dev)
2560 {
2561 	struct gpmi_nand_data *this = dev_get_drvdata(dev);
2562 
2563 	release_dma_channels(this);
2564 	return 0;
2565 }
2566 
2567 static int gpmi_pm_resume(struct device *dev)
2568 {
2569 	struct gpmi_nand_data *this = dev_get_drvdata(dev);
2570 	int ret;
2571 
2572 	ret = acquire_dma_channels(this);
2573 	if (ret < 0)
2574 		return ret;
2575 
2576 	/* re-init the GPMI registers */
2577 	ret = gpmi_init(this);
2578 	if (ret) {
2579 		dev_err(this->dev, "Error setting GPMI : %d\n", ret);
2580 		return ret;
2581 	}
2582 
2583 	/* Set flag to get timing setup restored for next exec_op */
2584 	if (this->hw.clk_rate)
2585 		this->hw.must_apply_timings = true;
2586 
2587 	/* re-init the BCH registers */
2588 	ret = bch_set_geometry(this);
2589 	if (ret) {
2590 		dev_err(this->dev, "Error setting BCH : %d\n", ret);
2591 		return ret;
2592 	}
2593 
2594 	return 0;
2595 }
2596 #endif /* CONFIG_PM_SLEEP */
2597 
2598 static int __maybe_unused gpmi_runtime_suspend(struct device *dev)
2599 {
2600 	struct gpmi_nand_data *this = dev_get_drvdata(dev);
2601 
2602 	return __gpmi_enable_clk(this, false);
2603 }
2604 
2605 static int __maybe_unused gpmi_runtime_resume(struct device *dev)
2606 {
2607 	struct gpmi_nand_data *this = dev_get_drvdata(dev);
2608 
2609 	return __gpmi_enable_clk(this, true);
2610 }
2611 
2612 static const struct dev_pm_ops gpmi_pm_ops = {
2613 	SET_SYSTEM_SLEEP_PM_OPS(gpmi_pm_suspend, gpmi_pm_resume)
2614 	SET_RUNTIME_PM_OPS(gpmi_runtime_suspend, gpmi_runtime_resume, NULL)
2615 };
2616 
2617 static struct platform_driver gpmi_nand_driver = {
2618 	.driver = {
2619 		.name = "gpmi-nand",
2620 		.pm = &gpmi_pm_ops,
2621 		.of_match_table = gpmi_nand_id_table,
2622 	},
2623 	.probe   = gpmi_nand_probe,
2624 	.remove  = gpmi_nand_remove,
2625 };
2626 module_platform_driver(gpmi_nand_driver);
2627 
2628 MODULE_AUTHOR("Freescale Semiconductor, Inc.");
2629 MODULE_DESCRIPTION("i.MX GPMI NAND Flash Controller Driver");
2630 MODULE_LICENSE("GPL");
2631