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