1 /*
2  * Freescale GPMI NAND Flash Driver
3  *
4  * Copyright (C) 2010-2015 Freescale Semiconductor, Inc.
5  * Copyright (C) 2008 Embedded Alley Solutions, Inc.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21 #include <linux/clk.h>
22 #include <linux/slab.h>
23 #include <linux/sched/task_stack.h>
24 #include <linux/interrupt.h>
25 #include <linux/module.h>
26 #include <linux/mtd/partitions.h>
27 #include <linux/of.h>
28 #include <linux/of_device.h>
29 #include "gpmi-nand.h"
30 #include "bch-regs.h"
31 
32 /* Resource names for the GPMI NAND driver. */
33 #define GPMI_NAND_GPMI_REGS_ADDR_RES_NAME  "gpmi-nand"
34 #define GPMI_NAND_BCH_REGS_ADDR_RES_NAME   "bch"
35 #define GPMI_NAND_BCH_INTERRUPT_RES_NAME   "bch"
36 
37 /* add our owner bbt descriptor */
38 static uint8_t scan_ff_pattern[] = { 0xff };
39 static struct nand_bbt_descr gpmi_bbt_descr = {
40 	.options	= 0,
41 	.offs		= 0,
42 	.len		= 1,
43 	.pattern	= scan_ff_pattern
44 };
45 
46 /*
47  * We may change the layout if we can get the ECC info from the datasheet,
48  * else we will use all the (page + OOB).
49  */
50 static int gpmi_ooblayout_ecc(struct mtd_info *mtd, int section,
51 			      struct mtd_oob_region *oobregion)
52 {
53 	struct nand_chip *chip = mtd_to_nand(mtd);
54 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
55 	struct bch_geometry *geo = &this->bch_geometry;
56 
57 	if (section)
58 		return -ERANGE;
59 
60 	oobregion->offset = 0;
61 	oobregion->length = geo->page_size - mtd->writesize;
62 
63 	return 0;
64 }
65 
66 static int gpmi_ooblayout_free(struct mtd_info *mtd, int section,
67 			       struct mtd_oob_region *oobregion)
68 {
69 	struct nand_chip *chip = mtd_to_nand(mtd);
70 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
71 	struct bch_geometry *geo = &this->bch_geometry;
72 
73 	if (section)
74 		return -ERANGE;
75 
76 	/* The available oob size we have. */
77 	if (geo->page_size < mtd->writesize + mtd->oobsize) {
78 		oobregion->offset = geo->page_size - mtd->writesize;
79 		oobregion->length = mtd->oobsize - oobregion->offset;
80 	}
81 
82 	return 0;
83 }
84 
85 static const char * const gpmi_clks_for_mx2x[] = {
86 	"gpmi_io",
87 };
88 
89 static const struct mtd_ooblayout_ops gpmi_ooblayout_ops = {
90 	.ecc = gpmi_ooblayout_ecc,
91 	.free = gpmi_ooblayout_free,
92 };
93 
94 static const struct gpmi_devdata gpmi_devdata_imx23 = {
95 	.type = IS_MX23,
96 	.bch_max_ecc_strength = 20,
97 	.max_chain_delay = 16000,
98 	.clks = gpmi_clks_for_mx2x,
99 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx2x),
100 };
101 
102 static const struct gpmi_devdata gpmi_devdata_imx28 = {
103 	.type = IS_MX28,
104 	.bch_max_ecc_strength = 20,
105 	.max_chain_delay = 16000,
106 	.clks = gpmi_clks_for_mx2x,
107 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx2x),
108 };
109 
110 static const char * const gpmi_clks_for_mx6[] = {
111 	"gpmi_io", "gpmi_apb", "gpmi_bch", "gpmi_bch_apb", "per1_bch",
112 };
113 
114 static const struct gpmi_devdata gpmi_devdata_imx6q = {
115 	.type = IS_MX6Q,
116 	.bch_max_ecc_strength = 40,
117 	.max_chain_delay = 12000,
118 	.clks = gpmi_clks_for_mx6,
119 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx6),
120 };
121 
122 static const struct gpmi_devdata gpmi_devdata_imx6sx = {
123 	.type = IS_MX6SX,
124 	.bch_max_ecc_strength = 62,
125 	.max_chain_delay = 12000,
126 	.clks = gpmi_clks_for_mx6,
127 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx6),
128 };
129 
130 static const char * const gpmi_clks_for_mx7d[] = {
131 	"gpmi_io", "gpmi_bch_apb",
132 };
133 
134 static const struct gpmi_devdata gpmi_devdata_imx7d = {
135 	.type = IS_MX7D,
136 	.bch_max_ecc_strength = 62,
137 	.max_chain_delay = 12000,
138 	.clks = gpmi_clks_for_mx7d,
139 	.clks_count = ARRAY_SIZE(gpmi_clks_for_mx7d),
140 };
141 
142 static irqreturn_t bch_irq(int irq, void *cookie)
143 {
144 	struct gpmi_nand_data *this = cookie;
145 
146 	gpmi_clear_bch(this);
147 	complete(&this->bch_done);
148 	return IRQ_HANDLED;
149 }
150 
151 /*
152  *  Calculate the ECC strength by hand:
153  *	E : The ECC strength.
154  *	G : the length of Galois Field.
155  *	N : The chunk count of per page.
156  *	O : the oobsize of the NAND chip.
157  *	M : the metasize of per page.
158  *
159  *	The formula is :
160  *		E * G * N
161  *	      ------------ <= (O - M)
162  *                  8
163  *
164  *      So, we get E by:
165  *                    (O - M) * 8
166  *              E <= -------------
167  *                       G * N
168  */
169 static inline int get_ecc_strength(struct gpmi_nand_data *this)
170 {
171 	struct bch_geometry *geo = &this->bch_geometry;
172 	struct mtd_info	*mtd = nand_to_mtd(&this->nand);
173 	int ecc_strength;
174 
175 	ecc_strength = ((mtd->oobsize - geo->metadata_size) * 8)
176 			/ (geo->gf_len * geo->ecc_chunk_count);
177 
178 	/* We need the minor even number. */
179 	return round_down(ecc_strength, 2);
180 }
181 
182 static inline bool gpmi_check_ecc(struct gpmi_nand_data *this)
183 {
184 	struct bch_geometry *geo = &this->bch_geometry;
185 
186 	/* Do the sanity check. */
187 	if (GPMI_IS_MX23(this) || GPMI_IS_MX28(this)) {
188 		/* The mx23/mx28 only support the GF13. */
189 		if (geo->gf_len == 14)
190 			return false;
191 	}
192 	return geo->ecc_strength <= this->devdata->bch_max_ecc_strength;
193 }
194 
195 /*
196  * If we can get the ECC information from the nand chip, we do not
197  * need to calculate them ourselves.
198  *
199  * We may have available oob space in this case.
200  */
201 static int set_geometry_by_ecc_info(struct gpmi_nand_data *this,
202 				    unsigned int ecc_strength,
203 				    unsigned int ecc_step)
204 {
205 	struct bch_geometry *geo = &this->bch_geometry;
206 	struct nand_chip *chip = &this->nand;
207 	struct mtd_info *mtd = nand_to_mtd(chip);
208 	unsigned int block_mark_bit_offset;
209 
210 	switch (ecc_step) {
211 	case SZ_512:
212 		geo->gf_len = 13;
213 		break;
214 	case SZ_1K:
215 		geo->gf_len = 14;
216 		break;
217 	default:
218 		dev_err(this->dev,
219 			"unsupported nand chip. ecc bits : %d, ecc size : %d\n",
220 			chip->ecc_strength_ds, chip->ecc_step_ds);
221 		return -EINVAL;
222 	}
223 	geo->ecc_chunk_size = ecc_step;
224 	geo->ecc_strength = round_up(ecc_strength, 2);
225 	if (!gpmi_check_ecc(this))
226 		return -EINVAL;
227 
228 	/* Keep the C >= O */
229 	if (geo->ecc_chunk_size < mtd->oobsize) {
230 		dev_err(this->dev,
231 			"unsupported nand chip. ecc size: %d, oob size : %d\n",
232 			ecc_step, mtd->oobsize);
233 		return -EINVAL;
234 	}
235 
236 	/* The default value, see comment in the legacy_set_geometry(). */
237 	geo->metadata_size = 10;
238 
239 	geo->ecc_chunk_count = mtd->writesize / geo->ecc_chunk_size;
240 
241 	/*
242 	 * Now, the NAND chip with 2K page(data chunk is 512byte) shows below:
243 	 *
244 	 *    |                          P                            |
245 	 *    |<----------------------------------------------------->|
246 	 *    |                                                       |
247 	 *    |                                        (Block Mark)   |
248 	 *    |                      P'                      |      | |     |
249 	 *    |<-------------------------------------------->|  D   | |  O' |
250 	 *    |                                              |<---->| |<--->|
251 	 *    V                                              V      V V     V
252 	 *    +---+----------+-+----------+-+----------+-+----------+-+-----+
253 	 *    | M |   data   |E|   data   |E|   data   |E|   data   |E|     |
254 	 *    +---+----------+-+----------+-+----------+-+----------+-+-----+
255 	 *                                                   ^              ^
256 	 *                                                   |      O       |
257 	 *                                                   |<------------>|
258 	 *                                                   |              |
259 	 *
260 	 *	P : the page size for BCH module.
261 	 *	E : The ECC strength.
262 	 *	G : the length of Galois Field.
263 	 *	N : The chunk count of per page.
264 	 *	M : the metasize of per page.
265 	 *	C : the ecc chunk size, aka the "data" above.
266 	 *	P': the nand chip's page size.
267 	 *	O : the nand chip's oob size.
268 	 *	O': the free oob.
269 	 *
270 	 *	The formula for P is :
271 	 *
272 	 *	            E * G * N
273 	 *	       P = ------------ + P' + M
274 	 *                      8
275 	 *
276 	 * The position of block mark moves forward in the ECC-based view
277 	 * of page, and the delta is:
278 	 *
279 	 *                   E * G * (N - 1)
280 	 *             D = (---------------- + M)
281 	 *                          8
282 	 *
283 	 * Please see the comment in legacy_set_geometry().
284 	 * With the condition C >= O , we still can get same result.
285 	 * So the bit position of the physical block mark within the ECC-based
286 	 * view of the page is :
287 	 *             (P' - D) * 8
288 	 */
289 	geo->page_size = mtd->writesize + geo->metadata_size +
290 		(geo->gf_len * geo->ecc_strength * geo->ecc_chunk_count) / 8;
291 
292 	geo->payload_size = mtd->writesize;
293 
294 	geo->auxiliary_status_offset = ALIGN(geo->metadata_size, 4);
295 	geo->auxiliary_size = ALIGN(geo->metadata_size, 4)
296 				+ ALIGN(geo->ecc_chunk_count, 4);
297 
298 	if (!this->swap_block_mark)
299 		return 0;
300 
301 	/* For bit swap. */
302 	block_mark_bit_offset = mtd->writesize * 8 -
303 		(geo->ecc_strength * geo->gf_len * (geo->ecc_chunk_count - 1)
304 				+ geo->metadata_size * 8);
305 
306 	geo->block_mark_byte_offset = block_mark_bit_offset / 8;
307 	geo->block_mark_bit_offset  = block_mark_bit_offset % 8;
308 	return 0;
309 }
310 
311 static int legacy_set_geometry(struct gpmi_nand_data *this)
312 {
313 	struct bch_geometry *geo = &this->bch_geometry;
314 	struct mtd_info *mtd = nand_to_mtd(&this->nand);
315 	unsigned int metadata_size;
316 	unsigned int status_size;
317 	unsigned int block_mark_bit_offset;
318 
319 	/*
320 	 * The size of the metadata can be changed, though we set it to 10
321 	 * bytes now. But it can't be too large, because we have to save
322 	 * enough space for BCH.
323 	 */
324 	geo->metadata_size = 10;
325 
326 	/* The default for the length of Galois Field. */
327 	geo->gf_len = 13;
328 
329 	/* The default for chunk size. */
330 	geo->ecc_chunk_size = 512;
331 	while (geo->ecc_chunk_size < mtd->oobsize) {
332 		geo->ecc_chunk_size *= 2; /* keep C >= O */
333 		geo->gf_len = 14;
334 	}
335 
336 	geo->ecc_chunk_count = mtd->writesize / geo->ecc_chunk_size;
337 
338 	/* We use the same ECC strength for all chunks. */
339 	geo->ecc_strength = get_ecc_strength(this);
340 	if (!gpmi_check_ecc(this)) {
341 		dev_err(this->dev,
342 			"ecc strength: %d cannot be supported by the controller (%d)\n"
343 			"try to use minimum ecc strength that NAND chip required\n",
344 			geo->ecc_strength,
345 			this->devdata->bch_max_ecc_strength);
346 		return -EINVAL;
347 	}
348 
349 	geo->page_size = mtd->writesize + geo->metadata_size +
350 		(geo->gf_len * geo->ecc_strength * geo->ecc_chunk_count) / 8;
351 	geo->payload_size = mtd->writesize;
352 
353 	/*
354 	 * The auxiliary buffer contains the metadata and the ECC status. The
355 	 * metadata is padded to the nearest 32-bit boundary. The ECC status
356 	 * contains one byte for every ECC chunk, and is also padded to the
357 	 * nearest 32-bit boundary.
358 	 */
359 	metadata_size = ALIGN(geo->metadata_size, 4);
360 	status_size   = ALIGN(geo->ecc_chunk_count, 4);
361 
362 	geo->auxiliary_size = metadata_size + status_size;
363 	geo->auxiliary_status_offset = metadata_size;
364 
365 	if (!this->swap_block_mark)
366 		return 0;
367 
368 	/*
369 	 * We need to compute the byte and bit offsets of
370 	 * the physical block mark within the ECC-based view of the page.
371 	 *
372 	 * NAND chip with 2K page shows below:
373 	 *                                             (Block Mark)
374 	 *                                                   |      |
375 	 *                                                   |  D   |
376 	 *                                                   |<---->|
377 	 *                                                   V      V
378 	 *    +---+----------+-+----------+-+----------+-+----------+-+
379 	 *    | M |   data   |E|   data   |E|   data   |E|   data   |E|
380 	 *    +---+----------+-+----------+-+----------+-+----------+-+
381 	 *
382 	 * The position of block mark moves forward in the ECC-based view
383 	 * of page, and the delta is:
384 	 *
385 	 *                   E * G * (N - 1)
386 	 *             D = (---------------- + M)
387 	 *                          8
388 	 *
389 	 * With the formula to compute the ECC strength, and the condition
390 	 *       : C >= O         (C is the ecc chunk size)
391 	 *
392 	 * It's easy to deduce to the following result:
393 	 *
394 	 *         E * G       (O - M)      C - M         C - M
395 	 *      ----------- <= ------- <=  --------  <  ---------
396 	 *           8            N           N          (N - 1)
397 	 *
398 	 *  So, we get:
399 	 *
400 	 *                   E * G * (N - 1)
401 	 *             D = (---------------- + M) < C
402 	 *                          8
403 	 *
404 	 *  The above inequality means the position of block mark
405 	 *  within the ECC-based view of the page is still in the data chunk,
406 	 *  and it's NOT in the ECC bits of the chunk.
407 	 *
408 	 *  Use the following to compute the bit position of the
409 	 *  physical block mark within the ECC-based view of the page:
410 	 *          (page_size - D) * 8
411 	 *
412 	 *  --Huang Shijie
413 	 */
414 	block_mark_bit_offset = mtd->writesize * 8 -
415 		(geo->ecc_strength * geo->gf_len * (geo->ecc_chunk_count - 1)
416 				+ geo->metadata_size * 8);
417 
418 	geo->block_mark_byte_offset = block_mark_bit_offset / 8;
419 	geo->block_mark_bit_offset  = block_mark_bit_offset % 8;
420 	return 0;
421 }
422 
423 int common_nfc_set_geometry(struct gpmi_nand_data *this)
424 {
425 	struct nand_chip *chip = &this->nand;
426 
427 	if (chip->ecc.strength > 0 && chip->ecc.size > 0)
428 		return set_geometry_by_ecc_info(this, chip->ecc.strength,
429 						chip->ecc.size);
430 
431 	if ((of_property_read_bool(this->dev->of_node, "fsl,use-minimum-ecc"))
432 				|| legacy_set_geometry(this)) {
433 		if (!(chip->ecc_strength_ds > 0 && chip->ecc_step_ds > 0))
434 			return -EINVAL;
435 
436 		return set_geometry_by_ecc_info(this, chip->ecc_strength_ds,
437 						chip->ecc_step_ds);
438 	}
439 
440 	return 0;
441 }
442 
443 struct dma_chan *get_dma_chan(struct gpmi_nand_data *this)
444 {
445 	/* We use the DMA channel 0 to access all the nand chips. */
446 	return this->dma_chans[0];
447 }
448 
449 /* Can we use the upper's buffer directly for DMA? */
450 bool prepare_data_dma(struct gpmi_nand_data *this, const void *buf, int len,
451 		      enum dma_data_direction dr)
452 {
453 	struct scatterlist *sgl = &this->data_sgl;
454 	int ret;
455 
456 	/* first try to map the upper buffer directly */
457 	if (virt_addr_valid(buf) && !object_is_on_stack(buf)) {
458 		sg_init_one(sgl, buf, len);
459 		ret = dma_map_sg(this->dev, sgl, 1, dr);
460 		if (ret == 0)
461 			goto map_fail;
462 
463 		return true;
464 	}
465 
466 map_fail:
467 	/* We have to use our own DMA buffer. */
468 	sg_init_one(sgl, this->data_buffer_dma, len);
469 
470 	if (dr == DMA_TO_DEVICE)
471 		memcpy(this->data_buffer_dma, buf, len);
472 
473 	dma_map_sg(this->dev, sgl, 1, dr);
474 
475 	return false;
476 }
477 
478 /* This will be called after the DMA operation is finished. */
479 static void dma_irq_callback(void *param)
480 {
481 	struct gpmi_nand_data *this = param;
482 	struct completion *dma_c = &this->dma_done;
483 
484 	complete(dma_c);
485 }
486 
487 int start_dma_without_bch_irq(struct gpmi_nand_data *this,
488 				struct dma_async_tx_descriptor *desc)
489 {
490 	struct completion *dma_c = &this->dma_done;
491 	unsigned long timeout;
492 
493 	init_completion(dma_c);
494 
495 	desc->callback		= dma_irq_callback;
496 	desc->callback_param	= this;
497 	dmaengine_submit(desc);
498 	dma_async_issue_pending(get_dma_chan(this));
499 
500 	/* Wait for the interrupt from the DMA block. */
501 	timeout = wait_for_completion_timeout(dma_c, msecs_to_jiffies(1000));
502 	if (!timeout) {
503 		dev_err(this->dev, "DMA timeout, last DMA\n");
504 		gpmi_dump_info(this);
505 		return -ETIMEDOUT;
506 	}
507 	return 0;
508 }
509 
510 /*
511  * This function is used in BCH reading or BCH writing pages.
512  * It will wait for the BCH interrupt as long as ONE second.
513  * Actually, we must wait for two interrupts :
514  *	[1] firstly the DMA interrupt and
515  *	[2] secondly the BCH interrupt.
516  */
517 int start_dma_with_bch_irq(struct gpmi_nand_data *this,
518 			struct dma_async_tx_descriptor *desc)
519 {
520 	struct completion *bch_c = &this->bch_done;
521 	unsigned long timeout;
522 
523 	/* Prepare to receive an interrupt from the BCH block. */
524 	init_completion(bch_c);
525 
526 	/* start the DMA */
527 	start_dma_without_bch_irq(this, desc);
528 
529 	/* Wait for the interrupt from the BCH block. */
530 	timeout = wait_for_completion_timeout(bch_c, msecs_to_jiffies(1000));
531 	if (!timeout) {
532 		dev_err(this->dev, "BCH timeout\n");
533 		gpmi_dump_info(this);
534 		return -ETIMEDOUT;
535 	}
536 	return 0;
537 }
538 
539 static int acquire_register_block(struct gpmi_nand_data *this,
540 				  const char *res_name)
541 {
542 	struct platform_device *pdev = this->pdev;
543 	struct resources *res = &this->resources;
544 	struct resource *r;
545 	void __iomem *p;
546 
547 	r = platform_get_resource_byname(pdev, IORESOURCE_MEM, res_name);
548 	p = devm_ioremap_resource(&pdev->dev, r);
549 	if (IS_ERR(p))
550 		return PTR_ERR(p);
551 
552 	if (!strcmp(res_name, GPMI_NAND_GPMI_REGS_ADDR_RES_NAME))
553 		res->gpmi_regs = p;
554 	else if (!strcmp(res_name, GPMI_NAND_BCH_REGS_ADDR_RES_NAME))
555 		res->bch_regs = p;
556 	else
557 		dev_err(this->dev, "unknown resource name : %s\n", res_name);
558 
559 	return 0;
560 }
561 
562 static int acquire_bch_irq(struct gpmi_nand_data *this, irq_handler_t irq_h)
563 {
564 	struct platform_device *pdev = this->pdev;
565 	const char *res_name = GPMI_NAND_BCH_INTERRUPT_RES_NAME;
566 	struct resource *r;
567 	int err;
568 
569 	r = platform_get_resource_byname(pdev, IORESOURCE_IRQ, res_name);
570 	if (!r) {
571 		dev_err(this->dev, "Can't get resource for %s\n", res_name);
572 		return -ENODEV;
573 	}
574 
575 	err = devm_request_irq(this->dev, r->start, irq_h, 0, res_name, this);
576 	if (err)
577 		dev_err(this->dev, "error requesting BCH IRQ\n");
578 
579 	return err;
580 }
581 
582 static void release_dma_channels(struct gpmi_nand_data *this)
583 {
584 	unsigned int i;
585 	for (i = 0; i < DMA_CHANS; i++)
586 		if (this->dma_chans[i]) {
587 			dma_release_channel(this->dma_chans[i]);
588 			this->dma_chans[i] = NULL;
589 		}
590 }
591 
592 static int acquire_dma_channels(struct gpmi_nand_data *this)
593 {
594 	struct platform_device *pdev = this->pdev;
595 	struct dma_chan *dma_chan;
596 
597 	/* request dma channel */
598 	dma_chan = dma_request_slave_channel(&pdev->dev, "rx-tx");
599 	if (!dma_chan) {
600 		dev_err(this->dev, "Failed to request DMA channel.\n");
601 		goto acquire_err;
602 	}
603 
604 	this->dma_chans[0] = dma_chan;
605 	return 0;
606 
607 acquire_err:
608 	release_dma_channels(this);
609 	return -EINVAL;
610 }
611 
612 static int gpmi_get_clks(struct gpmi_nand_data *this)
613 {
614 	struct resources *r = &this->resources;
615 	struct clk *clk;
616 	int err, i;
617 
618 	for (i = 0; i < this->devdata->clks_count; i++) {
619 		clk = devm_clk_get(this->dev, this->devdata->clks[i]);
620 		if (IS_ERR(clk)) {
621 			err = PTR_ERR(clk);
622 			goto err_clock;
623 		}
624 
625 		r->clock[i] = clk;
626 	}
627 
628 	if (GPMI_IS_MX6(this))
629 		/*
630 		 * Set the default value for the gpmi clock.
631 		 *
632 		 * If you want to use the ONFI nand which is in the
633 		 * Synchronous Mode, you should change the clock as you need.
634 		 */
635 		clk_set_rate(r->clock[0], 22000000);
636 
637 	return 0;
638 
639 err_clock:
640 	dev_dbg(this->dev, "failed in finding the clocks.\n");
641 	return err;
642 }
643 
644 static int acquire_resources(struct gpmi_nand_data *this)
645 {
646 	int ret;
647 
648 	ret = acquire_register_block(this, GPMI_NAND_GPMI_REGS_ADDR_RES_NAME);
649 	if (ret)
650 		goto exit_regs;
651 
652 	ret = acquire_register_block(this, GPMI_NAND_BCH_REGS_ADDR_RES_NAME);
653 	if (ret)
654 		goto exit_regs;
655 
656 	ret = acquire_bch_irq(this, bch_irq);
657 	if (ret)
658 		goto exit_regs;
659 
660 	ret = acquire_dma_channels(this);
661 	if (ret)
662 		goto exit_regs;
663 
664 	ret = gpmi_get_clks(this);
665 	if (ret)
666 		goto exit_clock;
667 	return 0;
668 
669 exit_clock:
670 	release_dma_channels(this);
671 exit_regs:
672 	return ret;
673 }
674 
675 static void release_resources(struct gpmi_nand_data *this)
676 {
677 	release_dma_channels(this);
678 }
679 
680 static int send_page_prepare(struct gpmi_nand_data *this,
681 			const void *source, unsigned length,
682 			void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
683 			const void **use_virt, dma_addr_t *use_phys)
684 {
685 	struct device *dev = this->dev;
686 
687 	if (virt_addr_valid(source)) {
688 		dma_addr_t source_phys;
689 
690 		source_phys = dma_map_single(dev, (void *)source, length,
691 						DMA_TO_DEVICE);
692 		if (dma_mapping_error(dev, source_phys)) {
693 			if (alt_size < length) {
694 				dev_err(dev, "Alternate buffer is too small\n");
695 				return -ENOMEM;
696 			}
697 			goto map_failed;
698 		}
699 		*use_virt = source;
700 		*use_phys = source_phys;
701 		return 0;
702 	}
703 map_failed:
704 	/*
705 	 * Copy the content of the source buffer into the alternate
706 	 * buffer and set up the return values accordingly.
707 	 */
708 	memcpy(alt_virt, source, length);
709 
710 	*use_virt = alt_virt;
711 	*use_phys = alt_phys;
712 	return 0;
713 }
714 
715 static void send_page_end(struct gpmi_nand_data *this,
716 			const void *source, unsigned length,
717 			void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
718 			const void *used_virt, dma_addr_t used_phys)
719 {
720 	struct device *dev = this->dev;
721 	if (used_virt == source)
722 		dma_unmap_single(dev, used_phys, length, DMA_TO_DEVICE);
723 }
724 
725 static void gpmi_free_dma_buffer(struct gpmi_nand_data *this)
726 {
727 	struct device *dev = this->dev;
728 
729 	if (this->page_buffer_virt && virt_addr_valid(this->page_buffer_virt))
730 		dma_free_coherent(dev, this->page_buffer_size,
731 					this->page_buffer_virt,
732 					this->page_buffer_phys);
733 	kfree(this->cmd_buffer);
734 	kfree(this->data_buffer_dma);
735 	kfree(this->raw_buffer);
736 
737 	this->cmd_buffer	= NULL;
738 	this->data_buffer_dma	= NULL;
739 	this->raw_buffer	= NULL;
740 	this->page_buffer_virt	= NULL;
741 	this->page_buffer_size	=  0;
742 }
743 
744 /* Allocate the DMA buffers */
745 static int gpmi_alloc_dma_buffer(struct gpmi_nand_data *this)
746 {
747 	struct bch_geometry *geo = &this->bch_geometry;
748 	struct device *dev = this->dev;
749 	struct mtd_info *mtd = nand_to_mtd(&this->nand);
750 
751 	/* [1] Allocate a command buffer. PAGE_SIZE is enough. */
752 	this->cmd_buffer = kzalloc(PAGE_SIZE, GFP_DMA | GFP_KERNEL);
753 	if (this->cmd_buffer == NULL)
754 		goto error_alloc;
755 
756 	/*
757 	 * [2] Allocate a read/write data buffer.
758 	 *     The gpmi_alloc_dma_buffer can be called twice.
759 	 *     We allocate a PAGE_SIZE length buffer if gpmi_alloc_dma_buffer
760 	 *     is called before the nand_scan_ident; and we allocate a buffer
761 	 *     of the real NAND page size when the gpmi_alloc_dma_buffer is
762 	 *     called after the nand_scan_ident.
763 	 */
764 	this->data_buffer_dma = kzalloc(mtd->writesize ?: PAGE_SIZE,
765 					GFP_DMA | GFP_KERNEL);
766 	if (this->data_buffer_dma == NULL)
767 		goto error_alloc;
768 
769 	/*
770 	 * [3] Allocate the page buffer.
771 	 *
772 	 * Both the payload buffer and the auxiliary buffer must appear on
773 	 * 32-bit boundaries. We presume the size of the payload buffer is a
774 	 * power of two and is much larger than four, which guarantees the
775 	 * auxiliary buffer will appear on a 32-bit boundary.
776 	 */
777 	this->page_buffer_size = geo->payload_size + geo->auxiliary_size;
778 	this->page_buffer_virt = dma_alloc_coherent(dev, this->page_buffer_size,
779 					&this->page_buffer_phys, GFP_DMA);
780 	if (!this->page_buffer_virt)
781 		goto error_alloc;
782 
783 	this->raw_buffer = kzalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
784 	if (!this->raw_buffer)
785 		goto error_alloc;
786 
787 	/* Slice up the page buffer. */
788 	this->payload_virt = this->page_buffer_virt;
789 	this->payload_phys = this->page_buffer_phys;
790 	this->auxiliary_virt = this->payload_virt + geo->payload_size;
791 	this->auxiliary_phys = this->payload_phys + geo->payload_size;
792 	return 0;
793 
794 error_alloc:
795 	gpmi_free_dma_buffer(this);
796 	return -ENOMEM;
797 }
798 
799 static void gpmi_cmd_ctrl(struct mtd_info *mtd, int data, unsigned int ctrl)
800 {
801 	struct nand_chip *chip = mtd_to_nand(mtd);
802 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
803 	int ret;
804 
805 	/*
806 	 * Every operation begins with a command byte and a series of zero or
807 	 * more address bytes. These are distinguished by either the Address
808 	 * Latch Enable (ALE) or Command Latch Enable (CLE) signals being
809 	 * asserted. When MTD is ready to execute the command, it will deassert
810 	 * both latch enables.
811 	 *
812 	 * Rather than run a separate DMA operation for every single byte, we
813 	 * queue them up and run a single DMA operation for the entire series
814 	 * of command and data bytes. NAND_CMD_NONE means the END of the queue.
815 	 */
816 	if ((ctrl & (NAND_ALE | NAND_CLE))) {
817 		if (data != NAND_CMD_NONE)
818 			this->cmd_buffer[this->command_length++] = data;
819 		return;
820 	}
821 
822 	if (!this->command_length)
823 		return;
824 
825 	ret = gpmi_send_command(this);
826 	if (ret)
827 		dev_err(this->dev, "Chip: %u, Error %d\n",
828 			this->current_chip, ret);
829 
830 	this->command_length = 0;
831 }
832 
833 static int gpmi_dev_ready(struct mtd_info *mtd)
834 {
835 	struct nand_chip *chip = mtd_to_nand(mtd);
836 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
837 
838 	return gpmi_is_ready(this, this->current_chip);
839 }
840 
841 static void gpmi_select_chip(struct mtd_info *mtd, int chipnr)
842 {
843 	struct nand_chip *chip = mtd_to_nand(mtd);
844 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
845 	int ret;
846 
847 	/*
848 	 * For power consumption matters, disable/enable the clock each time a
849 	 * die is selected/unselected.
850 	 */
851 	if (this->current_chip < 0 && chipnr >= 0) {
852 		ret = gpmi_enable_clk(this);
853 		if (ret)
854 			dev_err(this->dev, "Failed to enable the clock\n");
855 	} else if (this->current_chip >= 0 && chipnr < 0) {
856 		ret = gpmi_disable_clk(this);
857 		if (ret)
858 			dev_err(this->dev, "Failed to disable the clock\n");
859 	}
860 
861 	/*
862 	 * This driver currently supports only one NAND chip. Plus, dies share
863 	 * the same configuration. So once timings have been applied on the
864 	 * controller side, they will not change anymore. When the time will
865 	 * come, the check on must_apply_timings will have to be dropped.
866 	 */
867 	if (chipnr >= 0 && this->hw.must_apply_timings) {
868 		this->hw.must_apply_timings = false;
869 		gpmi_nfc_apply_timings(this);
870 	}
871 
872 	this->current_chip = chipnr;
873 }
874 
875 static void gpmi_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
876 {
877 	struct nand_chip *chip = mtd_to_nand(mtd);
878 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
879 
880 	dev_dbg(this->dev, "len is %d\n", len);
881 
882 	gpmi_read_data(this, buf, len);
883 }
884 
885 static void gpmi_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
886 {
887 	struct nand_chip *chip = mtd_to_nand(mtd);
888 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
889 
890 	dev_dbg(this->dev, "len is %d\n", len);
891 
892 	gpmi_send_data(this, buf, len);
893 }
894 
895 static uint8_t gpmi_read_byte(struct mtd_info *mtd)
896 {
897 	struct nand_chip *chip = mtd_to_nand(mtd);
898 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
899 	uint8_t *buf = this->data_buffer_dma;
900 
901 	gpmi_read_buf(mtd, buf, 1);
902 	return buf[0];
903 }
904 
905 /*
906  * Handles block mark swapping.
907  * It can be called in swapping the block mark, or swapping it back,
908  * because the the operations are the same.
909  */
910 static void block_mark_swapping(struct gpmi_nand_data *this,
911 				void *payload, void *auxiliary)
912 {
913 	struct bch_geometry *nfc_geo = &this->bch_geometry;
914 	unsigned char *p;
915 	unsigned char *a;
916 	unsigned int  bit;
917 	unsigned char mask;
918 	unsigned char from_data;
919 	unsigned char from_oob;
920 
921 	if (!this->swap_block_mark)
922 		return;
923 
924 	/*
925 	 * If control arrives here, we're swapping. Make some convenience
926 	 * variables.
927 	 */
928 	bit = nfc_geo->block_mark_bit_offset;
929 	p   = payload + nfc_geo->block_mark_byte_offset;
930 	a   = auxiliary;
931 
932 	/*
933 	 * Get the byte from the data area that overlays the block mark. Since
934 	 * the ECC engine applies its own view to the bits in the page, the
935 	 * physical block mark won't (in general) appear on a byte boundary in
936 	 * the data.
937 	 */
938 	from_data = (p[0] >> bit) | (p[1] << (8 - bit));
939 
940 	/* Get the byte from the OOB. */
941 	from_oob = a[0];
942 
943 	/* Swap them. */
944 	a[0] = from_data;
945 
946 	mask = (0x1 << bit) - 1;
947 	p[0] = (p[0] & mask) | (from_oob << bit);
948 
949 	mask = ~0 << bit;
950 	p[1] = (p[1] & mask) | (from_oob >> (8 - bit));
951 }
952 
953 static int gpmi_ecc_read_page_data(struct nand_chip *chip,
954 				   uint8_t *buf, int oob_required,
955 				   int page)
956 {
957 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
958 	struct bch_geometry *nfc_geo = &this->bch_geometry;
959 	struct mtd_info *mtd = nand_to_mtd(chip);
960 	void          *payload_virt;
961 	dma_addr_t    payload_phys;
962 	unsigned int  i;
963 	unsigned char *status;
964 	unsigned int  max_bitflips = 0;
965 	int           ret;
966 	bool          direct = false;
967 
968 	dev_dbg(this->dev, "page number is : %d\n", page);
969 
970 	payload_virt = this->payload_virt;
971 	payload_phys = this->payload_phys;
972 
973 	if (virt_addr_valid(buf)) {
974 		dma_addr_t dest_phys;
975 
976 		dest_phys = dma_map_single(this->dev, buf, nfc_geo->payload_size,
977 					   DMA_FROM_DEVICE);
978 		if (!dma_mapping_error(this->dev, dest_phys)) {
979 			payload_virt = buf;
980 			payload_phys = dest_phys;
981 			direct = true;
982 		}
983 	}
984 
985 	/* go! */
986 	ret = gpmi_read_page(this, payload_phys, this->auxiliary_phys);
987 
988 	if (direct)
989 		dma_unmap_single(this->dev, payload_phys, nfc_geo->payload_size,
990 				 DMA_FROM_DEVICE);
991 
992 	if (ret) {
993 		dev_err(this->dev, "Error in ECC-based read: %d\n", ret);
994 		return ret;
995 	}
996 
997 	/* Loop over status bytes, accumulating ECC status. */
998 	status = this->auxiliary_virt + nfc_geo->auxiliary_status_offset;
999 
1000 	if (!direct)
1001 		memcpy(buf, this->payload_virt, nfc_geo->payload_size);
1002 
1003 	for (i = 0; i < nfc_geo->ecc_chunk_count; i++, status++) {
1004 		if ((*status == STATUS_GOOD) || (*status == STATUS_ERASED))
1005 			continue;
1006 
1007 		if (*status == STATUS_UNCORRECTABLE) {
1008 			int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1009 			u8 *eccbuf = this->raw_buffer;
1010 			int offset, bitoffset;
1011 			int eccbytes;
1012 			int flips;
1013 
1014 			/* Read ECC bytes into our internal raw_buffer */
1015 			offset = nfc_geo->metadata_size * 8;
1016 			offset += ((8 * nfc_geo->ecc_chunk_size) + eccbits) * (i + 1);
1017 			offset -= eccbits;
1018 			bitoffset = offset % 8;
1019 			eccbytes = DIV_ROUND_UP(offset + eccbits, 8);
1020 			offset /= 8;
1021 			eccbytes -= offset;
1022 			nand_change_read_column_op(chip, offset, eccbuf,
1023 						   eccbytes, false);
1024 
1025 			/*
1026 			 * ECC data are not byte aligned and we may have
1027 			 * in-band data in the first and last byte of
1028 			 * eccbuf. Set non-eccbits to one so that
1029 			 * nand_check_erased_ecc_chunk() does not count them
1030 			 * as bitflips.
1031 			 */
1032 			if (bitoffset)
1033 				eccbuf[0] |= GENMASK(bitoffset - 1, 0);
1034 
1035 			bitoffset = (bitoffset + eccbits) % 8;
1036 			if (bitoffset)
1037 				eccbuf[eccbytes - 1] |= GENMASK(7, bitoffset);
1038 
1039 			/*
1040 			 * The ECC hardware has an uncorrectable ECC status
1041 			 * code in case we have bitflips in an erased page. As
1042 			 * nothing was written into this subpage the ECC is
1043 			 * obviously wrong and we can not trust it. We assume
1044 			 * at this point that we are reading an erased page and
1045 			 * try to correct the bitflips in buffer up to
1046 			 * ecc_strength bitflips. If this is a page with random
1047 			 * data, we exceed this number of bitflips and have a
1048 			 * ECC failure. Otherwise we use the corrected buffer.
1049 			 */
1050 			if (i == 0) {
1051 				/* The first block includes metadata */
1052 				flips = nand_check_erased_ecc_chunk(
1053 						buf + i * nfc_geo->ecc_chunk_size,
1054 						nfc_geo->ecc_chunk_size,
1055 						eccbuf, eccbytes,
1056 						this->auxiliary_virt,
1057 						nfc_geo->metadata_size,
1058 						nfc_geo->ecc_strength);
1059 			} else {
1060 				flips = nand_check_erased_ecc_chunk(
1061 						buf + i * nfc_geo->ecc_chunk_size,
1062 						nfc_geo->ecc_chunk_size,
1063 						eccbuf, eccbytes,
1064 						NULL, 0,
1065 						nfc_geo->ecc_strength);
1066 			}
1067 
1068 			if (flips > 0) {
1069 				max_bitflips = max_t(unsigned int, max_bitflips,
1070 						     flips);
1071 				mtd->ecc_stats.corrected += flips;
1072 				continue;
1073 			}
1074 
1075 			mtd->ecc_stats.failed++;
1076 			continue;
1077 		}
1078 
1079 		mtd->ecc_stats.corrected += *status;
1080 		max_bitflips = max_t(unsigned int, max_bitflips, *status);
1081 	}
1082 
1083 	/* handle the block mark swapping */
1084 	block_mark_swapping(this, buf, this->auxiliary_virt);
1085 
1086 	if (oob_required) {
1087 		/*
1088 		 * It's time to deliver the OOB bytes. See gpmi_ecc_read_oob()
1089 		 * for details about our policy for delivering the OOB.
1090 		 *
1091 		 * We fill the caller's buffer with set bits, and then copy the
1092 		 * block mark to th caller's buffer. Note that, if block mark
1093 		 * swapping was necessary, it has already been done, so we can
1094 		 * rely on the first byte of the auxiliary buffer to contain
1095 		 * the block mark.
1096 		 */
1097 		memset(chip->oob_poi, ~0, mtd->oobsize);
1098 		chip->oob_poi[0] = ((uint8_t *)this->auxiliary_virt)[0];
1099 	}
1100 
1101 	return max_bitflips;
1102 }
1103 
1104 static int gpmi_ecc_read_page(struct mtd_info *mtd, struct nand_chip *chip,
1105 			      uint8_t *buf, int oob_required, int page)
1106 {
1107 	nand_read_page_op(chip, page, 0, NULL, 0);
1108 
1109 	return gpmi_ecc_read_page_data(chip, buf, oob_required, page);
1110 }
1111 
1112 /* Fake a virtual small page for the subpage read */
1113 static int gpmi_ecc_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1114 			uint32_t offs, uint32_t len, uint8_t *buf, int page)
1115 {
1116 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1117 	void __iomem *bch_regs = this->resources.bch_regs;
1118 	struct bch_geometry old_geo = this->bch_geometry;
1119 	struct bch_geometry *geo = &this->bch_geometry;
1120 	int size = chip->ecc.size; /* ECC chunk size */
1121 	int meta, n, page_size;
1122 	u32 r1_old, r2_old, r1_new, r2_new;
1123 	unsigned int max_bitflips;
1124 	int first, last, marker_pos;
1125 	int ecc_parity_size;
1126 	int col = 0;
1127 	int old_swap_block_mark = this->swap_block_mark;
1128 
1129 	/* The size of ECC parity */
1130 	ecc_parity_size = geo->gf_len * geo->ecc_strength / 8;
1131 
1132 	/* Align it with the chunk size */
1133 	first = offs / size;
1134 	last = (offs + len - 1) / size;
1135 
1136 	if (this->swap_block_mark) {
1137 		/*
1138 		 * Find the chunk which contains the Block Marker.
1139 		 * If this chunk is in the range of [first, last],
1140 		 * we have to read out the whole page.
1141 		 * Why? since we had swapped the data at the position of Block
1142 		 * Marker to the metadata which is bound with the chunk 0.
1143 		 */
1144 		marker_pos = geo->block_mark_byte_offset / size;
1145 		if (last >= marker_pos && first <= marker_pos) {
1146 			dev_dbg(this->dev,
1147 				"page:%d, first:%d, last:%d, marker at:%d\n",
1148 				page, first, last, marker_pos);
1149 			return gpmi_ecc_read_page(mtd, chip, buf, 0, page);
1150 		}
1151 	}
1152 
1153 	meta = geo->metadata_size;
1154 	if (first) {
1155 		col = meta + (size + ecc_parity_size) * first;
1156 		meta = 0;
1157 		buf = buf + first * size;
1158 	}
1159 
1160 	nand_read_page_op(chip, page, col, NULL, 0);
1161 
1162 	/* Save the old environment */
1163 	r1_old = r1_new = readl(bch_regs + HW_BCH_FLASH0LAYOUT0);
1164 	r2_old = r2_new = readl(bch_regs + HW_BCH_FLASH0LAYOUT1);
1165 
1166 	/* change the BCH registers and bch_geometry{} */
1167 	n = last - first + 1;
1168 	page_size = meta + (size + ecc_parity_size) * n;
1169 
1170 	r1_new &= ~(BM_BCH_FLASH0LAYOUT0_NBLOCKS |
1171 			BM_BCH_FLASH0LAYOUT0_META_SIZE);
1172 	r1_new |= BF_BCH_FLASH0LAYOUT0_NBLOCKS(n - 1)
1173 			| BF_BCH_FLASH0LAYOUT0_META_SIZE(meta);
1174 	writel(r1_new, bch_regs + HW_BCH_FLASH0LAYOUT0);
1175 
1176 	r2_new &= ~BM_BCH_FLASH0LAYOUT1_PAGE_SIZE;
1177 	r2_new |= BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(page_size);
1178 	writel(r2_new, bch_regs + HW_BCH_FLASH0LAYOUT1);
1179 
1180 	geo->ecc_chunk_count = n;
1181 	geo->payload_size = n * size;
1182 	geo->page_size = page_size;
1183 	geo->auxiliary_status_offset = ALIGN(meta, 4);
1184 
1185 	dev_dbg(this->dev, "page:%d(%d:%d)%d, chunk:(%d:%d), BCH PG size:%d\n",
1186 		page, offs, len, col, first, n, page_size);
1187 
1188 	/* Read the subpage now */
1189 	this->swap_block_mark = false;
1190 	max_bitflips = gpmi_ecc_read_page_data(chip, buf, 0, page);
1191 
1192 	/* Restore */
1193 	writel(r1_old, bch_regs + HW_BCH_FLASH0LAYOUT0);
1194 	writel(r2_old, bch_regs + HW_BCH_FLASH0LAYOUT1);
1195 	this->bch_geometry = old_geo;
1196 	this->swap_block_mark = old_swap_block_mark;
1197 
1198 	return max_bitflips;
1199 }
1200 
1201 static int gpmi_ecc_write_page(struct mtd_info *mtd, struct nand_chip *chip,
1202 				const uint8_t *buf, int oob_required, int page)
1203 {
1204 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1205 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1206 	const void *payload_virt;
1207 	dma_addr_t payload_phys;
1208 	const void *auxiliary_virt;
1209 	dma_addr_t auxiliary_phys;
1210 	int        ret;
1211 
1212 	dev_dbg(this->dev, "ecc write page.\n");
1213 
1214 	nand_prog_page_begin_op(chip, page, 0, NULL, 0);
1215 
1216 	if (this->swap_block_mark) {
1217 		/*
1218 		 * If control arrives here, we're doing block mark swapping.
1219 		 * Since we can't modify the caller's buffers, we must copy them
1220 		 * into our own.
1221 		 */
1222 		memcpy(this->payload_virt, buf, mtd->writesize);
1223 		payload_virt = this->payload_virt;
1224 		payload_phys = this->payload_phys;
1225 
1226 		memcpy(this->auxiliary_virt, chip->oob_poi,
1227 				nfc_geo->auxiliary_size);
1228 		auxiliary_virt = this->auxiliary_virt;
1229 		auxiliary_phys = this->auxiliary_phys;
1230 
1231 		/* Handle block mark swapping. */
1232 		block_mark_swapping(this,
1233 				(void *)payload_virt, (void *)auxiliary_virt);
1234 	} else {
1235 		/*
1236 		 * If control arrives here, we're not doing block mark swapping,
1237 		 * so we can to try and use the caller's buffers.
1238 		 */
1239 		ret = send_page_prepare(this,
1240 				buf, mtd->writesize,
1241 				this->payload_virt, this->payload_phys,
1242 				nfc_geo->payload_size,
1243 				&payload_virt, &payload_phys);
1244 		if (ret) {
1245 			dev_err(this->dev, "Inadequate payload DMA buffer\n");
1246 			return 0;
1247 		}
1248 
1249 		ret = send_page_prepare(this,
1250 				chip->oob_poi, mtd->oobsize,
1251 				this->auxiliary_virt, this->auxiliary_phys,
1252 				nfc_geo->auxiliary_size,
1253 				&auxiliary_virt, &auxiliary_phys);
1254 		if (ret) {
1255 			dev_err(this->dev, "Inadequate auxiliary DMA buffer\n");
1256 			goto exit_auxiliary;
1257 		}
1258 	}
1259 
1260 	/* Ask the NFC. */
1261 	ret = gpmi_send_page(this, payload_phys, auxiliary_phys);
1262 	if (ret)
1263 		dev_err(this->dev, "Error in ECC-based write: %d\n", ret);
1264 
1265 	if (!this->swap_block_mark) {
1266 		send_page_end(this, chip->oob_poi, mtd->oobsize,
1267 				this->auxiliary_virt, this->auxiliary_phys,
1268 				nfc_geo->auxiliary_size,
1269 				auxiliary_virt, auxiliary_phys);
1270 exit_auxiliary:
1271 		send_page_end(this, buf, mtd->writesize,
1272 				this->payload_virt, this->payload_phys,
1273 				nfc_geo->payload_size,
1274 				payload_virt, payload_phys);
1275 	}
1276 
1277 	if (ret)
1278 		return ret;
1279 
1280 	return nand_prog_page_end_op(chip);
1281 }
1282 
1283 /*
1284  * There are several places in this driver where we have to handle the OOB and
1285  * block marks. This is the function where things are the most complicated, so
1286  * this is where we try to explain it all. All the other places refer back to
1287  * here.
1288  *
1289  * These are the rules, in order of decreasing importance:
1290  *
1291  * 1) Nothing the caller does can be allowed to imperil the block mark.
1292  *
1293  * 2) In read operations, the first byte of the OOB we return must reflect the
1294  *    true state of the block mark, no matter where that block mark appears in
1295  *    the physical page.
1296  *
1297  * 3) ECC-based read operations return an OOB full of set bits (since we never
1298  *    allow ECC-based writes to the OOB, it doesn't matter what ECC-based reads
1299  *    return).
1300  *
1301  * 4) "Raw" read operations return a direct view of the physical bytes in the
1302  *    page, using the conventional definition of which bytes are data and which
1303  *    are OOB. This gives the caller a way to see the actual, physical bytes
1304  *    in the page, without the distortions applied by our ECC engine.
1305  *
1306  *
1307  * What we do for this specific read operation depends on two questions:
1308  *
1309  * 1) Are we doing a "raw" read, or an ECC-based read?
1310  *
1311  * 2) Are we using block mark swapping or transcription?
1312  *
1313  * There are four cases, illustrated by the following Karnaugh map:
1314  *
1315  *                    |           Raw           |         ECC-based       |
1316  *       -------------+-------------------------+-------------------------+
1317  *                    | Read the conventional   |                         |
1318  *                    | OOB at the end of the   |                         |
1319  *       Swapping     | page and return it. It  |                         |
1320  *                    | contains exactly what   |                         |
1321  *                    | we want.                | Read the block mark and |
1322  *       -------------+-------------------------+ return it in a buffer   |
1323  *                    | Read the conventional   | full of set bits.       |
1324  *                    | OOB at the end of the   |                         |
1325  *                    | page and also the block |                         |
1326  *       Transcribing | mark in the metadata.   |                         |
1327  *                    | Copy the block mark     |                         |
1328  *                    | into the first byte of  |                         |
1329  *                    | the OOB.                |                         |
1330  *       -------------+-------------------------+-------------------------+
1331  *
1332  * Note that we break rule #4 in the Transcribing/Raw case because we're not
1333  * giving an accurate view of the actual, physical bytes in the page (we're
1334  * overwriting the block mark). That's OK because it's more important to follow
1335  * rule #2.
1336  *
1337  * It turns out that knowing whether we want an "ECC-based" or "raw" read is not
1338  * easy. When reading a page, for example, the NAND Flash MTD code calls our
1339  * ecc.read_page or ecc.read_page_raw function. Thus, the fact that MTD wants an
1340  * ECC-based or raw view of the page is implicit in which function it calls
1341  * (there is a similar pair of ECC-based/raw functions for writing).
1342  */
1343 static int gpmi_ecc_read_oob(struct mtd_info *mtd, struct nand_chip *chip,
1344 				int page)
1345 {
1346 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1347 
1348 	dev_dbg(this->dev, "page number is %d\n", page);
1349 	/* clear the OOB buffer */
1350 	memset(chip->oob_poi, ~0, mtd->oobsize);
1351 
1352 	/* Read out the conventional OOB. */
1353 	nand_read_page_op(chip, page, mtd->writesize, NULL, 0);
1354 	chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1355 
1356 	/*
1357 	 * Now, we want to make sure the block mark is correct. In the
1358 	 * non-transcribing case (!GPMI_IS_MX23()), we already have it.
1359 	 * Otherwise, we need to explicitly read it.
1360 	 */
1361 	if (GPMI_IS_MX23(this)) {
1362 		/* Read the block mark into the first byte of the OOB buffer. */
1363 		nand_read_page_op(chip, page, 0, NULL, 0);
1364 		chip->oob_poi[0] = chip->read_byte(mtd);
1365 	}
1366 
1367 	return 0;
1368 }
1369 
1370 static int
1371 gpmi_ecc_write_oob(struct mtd_info *mtd, struct nand_chip *chip, int page)
1372 {
1373 	struct mtd_oob_region of = { };
1374 
1375 	/* Do we have available oob area? */
1376 	mtd_ooblayout_free(mtd, 0, &of);
1377 	if (!of.length)
1378 		return -EPERM;
1379 
1380 	if (!nand_is_slc(chip))
1381 		return -EPERM;
1382 
1383 	return nand_prog_page_op(chip, page, mtd->writesize + of.offset,
1384 				 chip->oob_poi + of.offset, of.length);
1385 }
1386 
1387 /*
1388  * This function reads a NAND page without involving the ECC engine (no HW
1389  * ECC correction).
1390  * The tricky part in the GPMI/BCH controller is that it stores ECC bits
1391  * inline (interleaved with payload DATA), and do not align data chunk on
1392  * byte boundaries.
1393  * We thus need to take care moving the payload data and ECC bits stored in the
1394  * page into the provided buffers, which is why we're using gpmi_copy_bits.
1395  *
1396  * See set_geometry_by_ecc_info inline comments to have a full description
1397  * of the layout used by the GPMI controller.
1398  */
1399 static int gpmi_ecc_read_page_raw(struct mtd_info *mtd,
1400 				  struct nand_chip *chip, uint8_t *buf,
1401 				  int oob_required, int page)
1402 {
1403 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1404 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1405 	int eccsize = nfc_geo->ecc_chunk_size;
1406 	int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1407 	u8 *tmp_buf = this->raw_buffer;
1408 	size_t src_bit_off;
1409 	size_t oob_bit_off;
1410 	size_t oob_byte_off;
1411 	uint8_t *oob = chip->oob_poi;
1412 	int step;
1413 
1414 	nand_read_page_op(chip, page, 0, tmp_buf,
1415 			  mtd->writesize + mtd->oobsize);
1416 
1417 	/*
1418 	 * If required, swap the bad block marker and the data stored in the
1419 	 * metadata section, so that we don't wrongly consider a block as bad.
1420 	 *
1421 	 * See the layout description for a detailed explanation on why this
1422 	 * is needed.
1423 	 */
1424 	if (this->swap_block_mark)
1425 		swap(tmp_buf[0], tmp_buf[mtd->writesize]);
1426 
1427 	/*
1428 	 * Copy the metadata section into the oob buffer (this section is
1429 	 * guaranteed to be aligned on a byte boundary).
1430 	 */
1431 	if (oob_required)
1432 		memcpy(oob, tmp_buf, nfc_geo->metadata_size);
1433 
1434 	oob_bit_off = nfc_geo->metadata_size * 8;
1435 	src_bit_off = oob_bit_off;
1436 
1437 	/* Extract interleaved payload data and ECC bits */
1438 	for (step = 0; step < nfc_geo->ecc_chunk_count; step++) {
1439 		if (buf)
1440 			gpmi_copy_bits(buf, step * eccsize * 8,
1441 				       tmp_buf, src_bit_off,
1442 				       eccsize * 8);
1443 		src_bit_off += eccsize * 8;
1444 
1445 		/* Align last ECC block to align a byte boundary */
1446 		if (step == nfc_geo->ecc_chunk_count - 1 &&
1447 		    (oob_bit_off + eccbits) % 8)
1448 			eccbits += 8 - ((oob_bit_off + eccbits) % 8);
1449 
1450 		if (oob_required)
1451 			gpmi_copy_bits(oob, oob_bit_off,
1452 				       tmp_buf, src_bit_off,
1453 				       eccbits);
1454 
1455 		src_bit_off += eccbits;
1456 		oob_bit_off += eccbits;
1457 	}
1458 
1459 	if (oob_required) {
1460 		oob_byte_off = oob_bit_off / 8;
1461 
1462 		if (oob_byte_off < mtd->oobsize)
1463 			memcpy(oob + oob_byte_off,
1464 			       tmp_buf + mtd->writesize + oob_byte_off,
1465 			       mtd->oobsize - oob_byte_off);
1466 	}
1467 
1468 	return 0;
1469 }
1470 
1471 /*
1472  * This function writes a NAND page without involving the ECC engine (no HW
1473  * ECC generation).
1474  * The tricky part in the GPMI/BCH controller is that it stores ECC bits
1475  * inline (interleaved with payload DATA), and do not align data chunk on
1476  * byte boundaries.
1477  * We thus need to take care moving the OOB area at the right place in the
1478  * final page, which is why we're using gpmi_copy_bits.
1479  *
1480  * See set_geometry_by_ecc_info inline comments to have a full description
1481  * of the layout used by the GPMI controller.
1482  */
1483 static int gpmi_ecc_write_page_raw(struct mtd_info *mtd,
1484 				   struct nand_chip *chip,
1485 				   const uint8_t *buf,
1486 				   int oob_required, int page)
1487 {
1488 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1489 	struct bch_geometry *nfc_geo = &this->bch_geometry;
1490 	int eccsize = nfc_geo->ecc_chunk_size;
1491 	int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1492 	u8 *tmp_buf = this->raw_buffer;
1493 	uint8_t *oob = chip->oob_poi;
1494 	size_t dst_bit_off;
1495 	size_t oob_bit_off;
1496 	size_t oob_byte_off;
1497 	int step;
1498 
1499 	/*
1500 	 * Initialize all bits to 1 in case we don't have a buffer for the
1501 	 * payload or oob data in order to leave unspecified bits of data
1502 	 * to their initial state.
1503 	 */
1504 	if (!buf || !oob_required)
1505 		memset(tmp_buf, 0xff, mtd->writesize + mtd->oobsize);
1506 
1507 	/*
1508 	 * First copy the metadata section (stored in oob buffer) at the
1509 	 * beginning of the page, as imposed by the GPMI layout.
1510 	 */
1511 	memcpy(tmp_buf, oob, nfc_geo->metadata_size);
1512 	oob_bit_off = nfc_geo->metadata_size * 8;
1513 	dst_bit_off = oob_bit_off;
1514 
1515 	/* Interleave payload data and ECC bits */
1516 	for (step = 0; step < nfc_geo->ecc_chunk_count; step++) {
1517 		if (buf)
1518 			gpmi_copy_bits(tmp_buf, dst_bit_off,
1519 				       buf, step * eccsize * 8, eccsize * 8);
1520 		dst_bit_off += eccsize * 8;
1521 
1522 		/* Align last ECC block to align a byte boundary */
1523 		if (step == nfc_geo->ecc_chunk_count - 1 &&
1524 		    (oob_bit_off + eccbits) % 8)
1525 			eccbits += 8 - ((oob_bit_off + eccbits) % 8);
1526 
1527 		if (oob_required)
1528 			gpmi_copy_bits(tmp_buf, dst_bit_off,
1529 				       oob, oob_bit_off, eccbits);
1530 
1531 		dst_bit_off += eccbits;
1532 		oob_bit_off += eccbits;
1533 	}
1534 
1535 	oob_byte_off = oob_bit_off / 8;
1536 
1537 	if (oob_required && oob_byte_off < mtd->oobsize)
1538 		memcpy(tmp_buf + mtd->writesize + oob_byte_off,
1539 		       oob + oob_byte_off, mtd->oobsize - oob_byte_off);
1540 
1541 	/*
1542 	 * If required, swap the bad block marker and the first byte of the
1543 	 * metadata section, so that we don't modify the bad block marker.
1544 	 *
1545 	 * See the layout description for a detailed explanation on why this
1546 	 * is needed.
1547 	 */
1548 	if (this->swap_block_mark)
1549 		swap(tmp_buf[0], tmp_buf[mtd->writesize]);
1550 
1551 	return nand_prog_page_op(chip, page, 0, tmp_buf,
1552 				 mtd->writesize + mtd->oobsize);
1553 }
1554 
1555 static int gpmi_ecc_read_oob_raw(struct mtd_info *mtd, struct nand_chip *chip,
1556 				 int page)
1557 {
1558 	return gpmi_ecc_read_page_raw(mtd, chip, NULL, 1, page);
1559 }
1560 
1561 static int gpmi_ecc_write_oob_raw(struct mtd_info *mtd, struct nand_chip *chip,
1562 				 int page)
1563 {
1564 	return gpmi_ecc_write_page_raw(mtd, chip, NULL, 1, page);
1565 }
1566 
1567 static int gpmi_block_markbad(struct mtd_info *mtd, loff_t ofs)
1568 {
1569 	struct nand_chip *chip = mtd_to_nand(mtd);
1570 	struct gpmi_nand_data *this = nand_get_controller_data(chip);
1571 	int ret = 0;
1572 	uint8_t *block_mark;
1573 	int column, page, chipnr;
1574 
1575 	chipnr = (int)(ofs >> chip->chip_shift);
1576 	chip->select_chip(mtd, chipnr);
1577 
1578 	column = !GPMI_IS_MX23(this) ? mtd->writesize : 0;
1579 
1580 	/* Write the block mark. */
1581 	block_mark = this->data_buffer_dma;
1582 	block_mark[0] = 0; /* bad block marker */
1583 
1584 	/* Shift to get page */
1585 	page = (int)(ofs >> chip->page_shift);
1586 
1587 	ret = nand_prog_page_op(chip, page, column, block_mark, 1);
1588 
1589 	chip->select_chip(mtd, -1);
1590 
1591 	return ret;
1592 }
1593 
1594 static int nand_boot_set_geometry(struct gpmi_nand_data *this)
1595 {
1596 	struct boot_rom_geometry *geometry = &this->rom_geometry;
1597 
1598 	/*
1599 	 * Set the boot block stride size.
1600 	 *
1601 	 * In principle, we should be reading this from the OTP bits, since
1602 	 * that's where the ROM is going to get it. In fact, we don't have any
1603 	 * way to read the OTP bits, so we go with the default and hope for the
1604 	 * best.
1605 	 */
1606 	geometry->stride_size_in_pages = 64;
1607 
1608 	/*
1609 	 * Set the search area stride exponent.
1610 	 *
1611 	 * In principle, we should be reading this from the OTP bits, since
1612 	 * that's where the ROM is going to get it. In fact, we don't have any
1613 	 * way to read the OTP bits, so we go with the default and hope for the
1614 	 * best.
1615 	 */
1616 	geometry->search_area_stride_exponent = 2;
1617 	return 0;
1618 }
1619 
1620 static const char  *fingerprint = "STMP";
1621 static int mx23_check_transcription_stamp(struct gpmi_nand_data *this)
1622 {
1623 	struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1624 	struct device *dev = this->dev;
1625 	struct nand_chip *chip = &this->nand;
1626 	struct mtd_info *mtd = nand_to_mtd(chip);
1627 	unsigned int search_area_size_in_strides;
1628 	unsigned int stride;
1629 	unsigned int page;
1630 	uint8_t *buffer = chip->data_buf;
1631 	int saved_chip_number;
1632 	int found_an_ncb_fingerprint = false;
1633 
1634 	/* Compute the number of strides in a search area. */
1635 	search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1636 
1637 	saved_chip_number = this->current_chip;
1638 	chip->select_chip(mtd, 0);
1639 
1640 	/*
1641 	 * Loop through the first search area, looking for the NCB fingerprint.
1642 	 */
1643 	dev_dbg(dev, "Scanning for an NCB fingerprint...\n");
1644 
1645 	for (stride = 0; stride < search_area_size_in_strides; stride++) {
1646 		/* Compute the page addresses. */
1647 		page = stride * rom_geo->stride_size_in_pages;
1648 
1649 		dev_dbg(dev, "Looking for a fingerprint in page 0x%x\n", page);
1650 
1651 		/*
1652 		 * Read the NCB fingerprint. The fingerprint is four bytes long
1653 		 * and starts in the 12th byte of the page.
1654 		 */
1655 		nand_read_page_op(chip, page, 12, NULL, 0);
1656 		chip->read_buf(mtd, buffer, strlen(fingerprint));
1657 
1658 		/* Look for the fingerprint. */
1659 		if (!memcmp(buffer, fingerprint, strlen(fingerprint))) {
1660 			found_an_ncb_fingerprint = true;
1661 			break;
1662 		}
1663 
1664 	}
1665 
1666 	chip->select_chip(mtd, saved_chip_number);
1667 
1668 	if (found_an_ncb_fingerprint)
1669 		dev_dbg(dev, "\tFound a fingerprint\n");
1670 	else
1671 		dev_dbg(dev, "\tNo fingerprint found\n");
1672 	return found_an_ncb_fingerprint;
1673 }
1674 
1675 /* Writes a transcription stamp. */
1676 static int mx23_write_transcription_stamp(struct gpmi_nand_data *this)
1677 {
1678 	struct device *dev = this->dev;
1679 	struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1680 	struct nand_chip *chip = &this->nand;
1681 	struct mtd_info *mtd = nand_to_mtd(chip);
1682 	unsigned int block_size_in_pages;
1683 	unsigned int search_area_size_in_strides;
1684 	unsigned int search_area_size_in_pages;
1685 	unsigned int search_area_size_in_blocks;
1686 	unsigned int block;
1687 	unsigned int stride;
1688 	unsigned int page;
1689 	uint8_t      *buffer = chip->data_buf;
1690 	int saved_chip_number;
1691 	int status;
1692 
1693 	/* Compute the search area geometry. */
1694 	block_size_in_pages = mtd->erasesize / mtd->writesize;
1695 	search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1696 	search_area_size_in_pages = search_area_size_in_strides *
1697 					rom_geo->stride_size_in_pages;
1698 	search_area_size_in_blocks =
1699 		  (search_area_size_in_pages + (block_size_in_pages - 1)) /
1700 				    block_size_in_pages;
1701 
1702 	dev_dbg(dev, "Search Area Geometry :\n");
1703 	dev_dbg(dev, "\tin Blocks : %u\n", search_area_size_in_blocks);
1704 	dev_dbg(dev, "\tin Strides: %u\n", search_area_size_in_strides);
1705 	dev_dbg(dev, "\tin Pages  : %u\n", search_area_size_in_pages);
1706 
1707 	/* Select chip 0. */
1708 	saved_chip_number = this->current_chip;
1709 	chip->select_chip(mtd, 0);
1710 
1711 	/* Loop over blocks in the first search area, erasing them. */
1712 	dev_dbg(dev, "Erasing the search area...\n");
1713 
1714 	for (block = 0; block < search_area_size_in_blocks; block++) {
1715 		/* Erase this block. */
1716 		dev_dbg(dev, "\tErasing block 0x%x\n", block);
1717 		status = nand_erase_op(chip, block);
1718 		if (status)
1719 			dev_err(dev, "[%s] Erase failed.\n", __func__);
1720 	}
1721 
1722 	/* Write the NCB fingerprint into the page buffer. */
1723 	memset(buffer, ~0, mtd->writesize);
1724 	memcpy(buffer + 12, fingerprint, strlen(fingerprint));
1725 
1726 	/* Loop through the first search area, writing NCB fingerprints. */
1727 	dev_dbg(dev, "Writing NCB fingerprints...\n");
1728 	for (stride = 0; stride < search_area_size_in_strides; stride++) {
1729 		/* Compute the page addresses. */
1730 		page = stride * rom_geo->stride_size_in_pages;
1731 
1732 		/* Write the first page of the current stride. */
1733 		dev_dbg(dev, "Writing an NCB fingerprint in page 0x%x\n", page);
1734 
1735 		status = chip->ecc.write_page_raw(mtd, chip, buffer, 0, page);
1736 		if (status)
1737 			dev_err(dev, "[%s] Write failed.\n", __func__);
1738 	}
1739 
1740 	/* Deselect chip 0. */
1741 	chip->select_chip(mtd, saved_chip_number);
1742 	return 0;
1743 }
1744 
1745 static int mx23_boot_init(struct gpmi_nand_data  *this)
1746 {
1747 	struct device *dev = this->dev;
1748 	struct nand_chip *chip = &this->nand;
1749 	struct mtd_info *mtd = nand_to_mtd(chip);
1750 	unsigned int block_count;
1751 	unsigned int block;
1752 	int     chipnr;
1753 	int     page;
1754 	loff_t  byte;
1755 	uint8_t block_mark;
1756 	int     ret = 0;
1757 
1758 	/*
1759 	 * If control arrives here, we can't use block mark swapping, which
1760 	 * means we're forced to use transcription. First, scan for the
1761 	 * transcription stamp. If we find it, then we don't have to do
1762 	 * anything -- the block marks are already transcribed.
1763 	 */
1764 	if (mx23_check_transcription_stamp(this))
1765 		return 0;
1766 
1767 	/*
1768 	 * If control arrives here, we couldn't find a transcription stamp, so
1769 	 * so we presume the block marks are in the conventional location.
1770 	 */
1771 	dev_dbg(dev, "Transcribing bad block marks...\n");
1772 
1773 	/* Compute the number of blocks in the entire medium. */
1774 	block_count = chip->chipsize >> chip->phys_erase_shift;
1775 
1776 	/*
1777 	 * Loop over all the blocks in the medium, transcribing block marks as
1778 	 * we go.
1779 	 */
1780 	for (block = 0; block < block_count; block++) {
1781 		/*
1782 		 * Compute the chip, page and byte addresses for this block's
1783 		 * conventional mark.
1784 		 */
1785 		chipnr = block >> (chip->chip_shift - chip->phys_erase_shift);
1786 		page = block << (chip->phys_erase_shift - chip->page_shift);
1787 		byte = block <<  chip->phys_erase_shift;
1788 
1789 		/* Send the command to read the conventional block mark. */
1790 		chip->select_chip(mtd, chipnr);
1791 		nand_read_page_op(chip, page, mtd->writesize, NULL, 0);
1792 		block_mark = chip->read_byte(mtd);
1793 		chip->select_chip(mtd, -1);
1794 
1795 		/*
1796 		 * Check if the block is marked bad. If so, we need to mark it
1797 		 * again, but this time the result will be a mark in the
1798 		 * location where we transcribe block marks.
1799 		 */
1800 		if (block_mark != 0xff) {
1801 			dev_dbg(dev, "Transcribing mark in block %u\n", block);
1802 			ret = chip->block_markbad(mtd, byte);
1803 			if (ret)
1804 				dev_err(dev,
1805 					"Failed to mark block bad with ret %d\n",
1806 					ret);
1807 		}
1808 	}
1809 
1810 	/* Write the stamp that indicates we've transcribed the block marks. */
1811 	mx23_write_transcription_stamp(this);
1812 	return 0;
1813 }
1814 
1815 static int nand_boot_init(struct gpmi_nand_data  *this)
1816 {
1817 	nand_boot_set_geometry(this);
1818 
1819 	/* This is ROM arch-specific initilization before the BBT scanning. */
1820 	if (GPMI_IS_MX23(this))
1821 		return mx23_boot_init(this);
1822 	return 0;
1823 }
1824 
1825 static int gpmi_set_geometry(struct gpmi_nand_data *this)
1826 {
1827 	int ret;
1828 
1829 	/* Free the temporary DMA memory for reading ID. */
1830 	gpmi_free_dma_buffer(this);
1831 
1832 	/* Set up the NFC geometry which is used by BCH. */
1833 	ret = bch_set_geometry(this);
1834 	if (ret) {
1835 		dev_err(this->dev, "Error setting BCH geometry : %d\n", ret);
1836 		return ret;
1837 	}
1838 
1839 	/* Alloc the new DMA buffers according to the pagesize and oobsize */
1840 	return gpmi_alloc_dma_buffer(this);
1841 }
1842 
1843 static int gpmi_init_last(struct gpmi_nand_data *this)
1844 {
1845 	struct nand_chip *chip = &this->nand;
1846 	struct mtd_info *mtd = nand_to_mtd(chip);
1847 	struct nand_ecc_ctrl *ecc = &chip->ecc;
1848 	struct bch_geometry *bch_geo = &this->bch_geometry;
1849 	int ret;
1850 
1851 	/* Set up the medium geometry */
1852 	ret = gpmi_set_geometry(this);
1853 	if (ret)
1854 		return ret;
1855 
1856 	/* Init the nand_ecc_ctrl{} */
1857 	ecc->read_page	= gpmi_ecc_read_page;
1858 	ecc->write_page	= gpmi_ecc_write_page;
1859 	ecc->read_oob	= gpmi_ecc_read_oob;
1860 	ecc->write_oob	= gpmi_ecc_write_oob;
1861 	ecc->read_page_raw = gpmi_ecc_read_page_raw;
1862 	ecc->write_page_raw = gpmi_ecc_write_page_raw;
1863 	ecc->read_oob_raw = gpmi_ecc_read_oob_raw;
1864 	ecc->write_oob_raw = gpmi_ecc_write_oob_raw;
1865 	ecc->mode	= NAND_ECC_HW;
1866 	ecc->size	= bch_geo->ecc_chunk_size;
1867 	ecc->strength	= bch_geo->ecc_strength;
1868 	mtd_set_ooblayout(mtd, &gpmi_ooblayout_ops);
1869 
1870 	/*
1871 	 * We only enable the subpage read when:
1872 	 *  (1) the chip is imx6, and
1873 	 *  (2) the size of the ECC parity is byte aligned.
1874 	 */
1875 	if (GPMI_IS_MX6(this) &&
1876 		((bch_geo->gf_len * bch_geo->ecc_strength) % 8) == 0) {
1877 		ecc->read_subpage = gpmi_ecc_read_subpage;
1878 		chip->options |= NAND_SUBPAGE_READ;
1879 	}
1880 
1881 	return 0;
1882 }
1883 
1884 static int gpmi_nand_init(struct gpmi_nand_data *this)
1885 {
1886 	struct nand_chip *chip = &this->nand;
1887 	struct mtd_info  *mtd = nand_to_mtd(chip);
1888 	int ret;
1889 
1890 	/* init current chip */
1891 	this->current_chip	= -1;
1892 
1893 	/* init the MTD data structures */
1894 	mtd->name		= "gpmi-nand";
1895 	mtd->dev.parent		= this->dev;
1896 
1897 	/* init the nand_chip{}, we don't support a 16-bit NAND Flash bus. */
1898 	nand_set_controller_data(chip, this);
1899 	nand_set_flash_node(chip, this->pdev->dev.of_node);
1900 	chip->select_chip	= gpmi_select_chip;
1901 	chip->setup_data_interface = gpmi_setup_data_interface;
1902 	chip->cmd_ctrl		= gpmi_cmd_ctrl;
1903 	chip->dev_ready		= gpmi_dev_ready;
1904 	chip->read_byte		= gpmi_read_byte;
1905 	chip->read_buf		= gpmi_read_buf;
1906 	chip->write_buf		= gpmi_write_buf;
1907 	chip->badblock_pattern	= &gpmi_bbt_descr;
1908 	chip->block_markbad	= gpmi_block_markbad;
1909 	chip->options		|= NAND_NO_SUBPAGE_WRITE;
1910 
1911 	/* Set up swap_block_mark, must be set before the gpmi_set_geometry() */
1912 	this->swap_block_mark = !GPMI_IS_MX23(this);
1913 
1914 	/*
1915 	 * Allocate a temporary DMA buffer for reading ID in the
1916 	 * nand_scan_ident().
1917 	 */
1918 	this->bch_geometry.payload_size = 1024;
1919 	this->bch_geometry.auxiliary_size = 128;
1920 	ret = gpmi_alloc_dma_buffer(this);
1921 	if (ret)
1922 		goto err_out;
1923 
1924 	ret = nand_scan_ident(mtd, GPMI_IS_MX6(this) ? 2 : 1, NULL);
1925 	if (ret)
1926 		goto err_out;
1927 
1928 	if (chip->bbt_options & NAND_BBT_USE_FLASH) {
1929 		chip->bbt_options |= NAND_BBT_NO_OOB;
1930 
1931 		if (of_property_read_bool(this->dev->of_node,
1932 						"fsl,no-blockmark-swap"))
1933 			this->swap_block_mark = false;
1934 	}
1935 	dev_dbg(this->dev, "Blockmark swapping %sabled\n",
1936 		this->swap_block_mark ? "en" : "dis");
1937 
1938 	ret = gpmi_init_last(this);
1939 	if (ret)
1940 		goto err_out;
1941 
1942 	chip->options |= NAND_SKIP_BBTSCAN;
1943 	ret = nand_scan_tail(mtd);
1944 	if (ret)
1945 		goto err_out;
1946 
1947 	ret = nand_boot_init(this);
1948 	if (ret)
1949 		goto err_nand_cleanup;
1950 	ret = chip->scan_bbt(mtd);
1951 	if (ret)
1952 		goto err_nand_cleanup;
1953 
1954 	ret = mtd_device_register(mtd, NULL, 0);
1955 	if (ret)
1956 		goto err_nand_cleanup;
1957 	return 0;
1958 
1959 err_nand_cleanup:
1960 	nand_cleanup(chip);
1961 err_out:
1962 	gpmi_free_dma_buffer(this);
1963 	return ret;
1964 }
1965 
1966 static const struct of_device_id gpmi_nand_id_table[] = {
1967 	{
1968 		.compatible = "fsl,imx23-gpmi-nand",
1969 		.data = &gpmi_devdata_imx23,
1970 	}, {
1971 		.compatible = "fsl,imx28-gpmi-nand",
1972 		.data = &gpmi_devdata_imx28,
1973 	}, {
1974 		.compatible = "fsl,imx6q-gpmi-nand",
1975 		.data = &gpmi_devdata_imx6q,
1976 	}, {
1977 		.compatible = "fsl,imx6sx-gpmi-nand",
1978 		.data = &gpmi_devdata_imx6sx,
1979 	}, {
1980 		.compatible = "fsl,imx7d-gpmi-nand",
1981 		.data = &gpmi_devdata_imx7d,
1982 	}, {}
1983 };
1984 MODULE_DEVICE_TABLE(of, gpmi_nand_id_table);
1985 
1986 static int gpmi_nand_probe(struct platform_device *pdev)
1987 {
1988 	struct gpmi_nand_data *this;
1989 	const struct of_device_id *of_id;
1990 	int ret;
1991 
1992 	this = devm_kzalloc(&pdev->dev, sizeof(*this), GFP_KERNEL);
1993 	if (!this)
1994 		return -ENOMEM;
1995 
1996 	of_id = of_match_device(gpmi_nand_id_table, &pdev->dev);
1997 	if (of_id) {
1998 		this->devdata = of_id->data;
1999 	} else {
2000 		dev_err(&pdev->dev, "Failed to find the right device id.\n");
2001 		return -ENODEV;
2002 	}
2003 
2004 	platform_set_drvdata(pdev, this);
2005 	this->pdev  = pdev;
2006 	this->dev   = &pdev->dev;
2007 
2008 	ret = acquire_resources(this);
2009 	if (ret)
2010 		goto exit_acquire_resources;
2011 
2012 	ret = gpmi_init(this);
2013 	if (ret)
2014 		goto exit_nfc_init;
2015 
2016 	ret = gpmi_nand_init(this);
2017 	if (ret)
2018 		goto exit_nfc_init;
2019 
2020 	dev_info(this->dev, "driver registered.\n");
2021 
2022 	return 0;
2023 
2024 exit_nfc_init:
2025 	release_resources(this);
2026 exit_acquire_resources:
2027 
2028 	return ret;
2029 }
2030 
2031 static int gpmi_nand_remove(struct platform_device *pdev)
2032 {
2033 	struct gpmi_nand_data *this = platform_get_drvdata(pdev);
2034 
2035 	nand_release(nand_to_mtd(&this->nand));
2036 	gpmi_free_dma_buffer(this);
2037 	release_resources(this);
2038 	return 0;
2039 }
2040 
2041 #ifdef CONFIG_PM_SLEEP
2042 static int gpmi_pm_suspend(struct device *dev)
2043 {
2044 	struct gpmi_nand_data *this = dev_get_drvdata(dev);
2045 
2046 	release_dma_channels(this);
2047 	return 0;
2048 }
2049 
2050 static int gpmi_pm_resume(struct device *dev)
2051 {
2052 	struct gpmi_nand_data *this = dev_get_drvdata(dev);
2053 	int ret;
2054 
2055 	ret = acquire_dma_channels(this);
2056 	if (ret < 0)
2057 		return ret;
2058 
2059 	/* re-init the GPMI registers */
2060 	ret = gpmi_init(this);
2061 	if (ret) {
2062 		dev_err(this->dev, "Error setting GPMI : %d\n", ret);
2063 		return ret;
2064 	}
2065 
2066 	/* re-init the BCH registers */
2067 	ret = bch_set_geometry(this);
2068 	if (ret) {
2069 		dev_err(this->dev, "Error setting BCH : %d\n", ret);
2070 		return ret;
2071 	}
2072 
2073 	return 0;
2074 }
2075 #endif /* CONFIG_PM_SLEEP */
2076 
2077 static const struct dev_pm_ops gpmi_pm_ops = {
2078 	SET_SYSTEM_SLEEP_PM_OPS(gpmi_pm_suspend, gpmi_pm_resume)
2079 };
2080 
2081 static struct platform_driver gpmi_nand_driver = {
2082 	.driver = {
2083 		.name = "gpmi-nand",
2084 		.pm = &gpmi_pm_ops,
2085 		.of_match_table = gpmi_nand_id_table,
2086 	},
2087 	.probe   = gpmi_nand_probe,
2088 	.remove  = gpmi_nand_remove,
2089 };
2090 module_platform_driver(gpmi_nand_driver);
2091 
2092 MODULE_AUTHOR("Freescale Semiconductor, Inc.");
2093 MODULE_DESCRIPTION("i.MX GPMI NAND Flash Controller Driver");
2094 MODULE_LICENSE("GPL");
2095