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