]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/mtd/nand/gpmi-nand/gpmi-nand.c
mtd: gpmi: use devm_ioremap_resource
[karo-tx-linux.git] / drivers / mtd / nand / gpmi-nand / gpmi-nand.c
1 /*
2  * Freescale GPMI NAND Flash Driver
3  *
4  * Copyright (C) 2010-2011 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
22 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
23
24 #include <linux/clk.h>
25 #include <linux/slab.h>
26 #include <linux/interrupt.h>
27 #include <linux/module.h>
28 #include <linux/mtd/partitions.h>
29 #include <linux/of.h>
30 #include <linux/of_device.h>
31 #include <linux/of_mtd.h>
32 #include "gpmi-nand.h"
33
34 /* Resource names for the GPMI NAND driver. */
35 #define GPMI_NAND_GPMI_REGS_ADDR_RES_NAME  "gpmi-nand"
36 #define GPMI_NAND_BCH_REGS_ADDR_RES_NAME   "bch"
37 #define GPMI_NAND_BCH_INTERRUPT_RES_NAME   "bch"
38
39 /* add our owner bbt descriptor */
40 static uint8_t scan_ff_pattern[] = { 0xff };
41 static struct nand_bbt_descr gpmi_bbt_descr = {
42         .options        = 0,
43         .offs           = 0,
44         .len            = 1,
45         .pattern        = scan_ff_pattern
46 };
47
48 /*
49  * We may change the layout if we can get the ECC info from the datasheet,
50  * else we will use all the (page + OOB).
51  */
52 static struct nand_ecclayout gpmi_hw_ecclayout = {
53         .eccbytes = 0,
54         .eccpos = { 0, },
55         .oobfree = { {.offset = 0, .length = 0} }
56 };
57
58 static irqreturn_t bch_irq(int irq, void *cookie)
59 {
60         struct gpmi_nand_data *this = cookie;
61
62         gpmi_clear_bch(this);
63         complete(&this->bch_done);
64         return IRQ_HANDLED;
65 }
66
67 /*
68  *  Calculate the ECC strength by hand:
69  *      E : The ECC strength.
70  *      G : the length of Galois Field.
71  *      N : The chunk count of per page.
72  *      O : the oobsize of the NAND chip.
73  *      M : the metasize of per page.
74  *
75  *      The formula is :
76  *              E * G * N
77  *            ------------ <= (O - M)
78  *                  8
79  *
80  *      So, we get E by:
81  *                    (O - M) * 8
82  *              E <= -------------
83  *                       G * N
84  */
85 static inline int get_ecc_strength(struct gpmi_nand_data *this)
86 {
87         struct bch_geometry *geo = &this->bch_geometry;
88         struct mtd_info *mtd = &this->mtd;
89         int ecc_strength;
90
91         ecc_strength = ((mtd->oobsize - geo->metadata_size) * 8)
92                         / (geo->gf_len * geo->ecc_chunk_count);
93
94         /* We need the minor even number. */
95         return round_down(ecc_strength, 2);
96 }
97
98 static inline bool gpmi_check_ecc(struct gpmi_nand_data *this)
99 {
100         struct bch_geometry *geo = &this->bch_geometry;
101
102         /* Do the sanity check. */
103         if (GPMI_IS_MX23(this) || GPMI_IS_MX28(this)) {
104                 /* The mx23/mx28 only support the GF13. */
105                 if (geo->gf_len == 14)
106                         return false;
107
108                 if (geo->ecc_strength > MXS_ECC_STRENGTH_MAX)
109                         return false;
110         } else if (GPMI_IS_MX6Q(this)) {
111                 if (geo->ecc_strength > MX6_ECC_STRENGTH_MAX)
112                         return false;
113         }
114         return true;
115 }
116
117 /*
118  * If we can get the ECC information from the nand chip, we do not
119  * need to calculate them ourselves.
120  *
121  * We may have available oob space in this case.
122  */
123 static bool set_geometry_by_ecc_info(struct gpmi_nand_data *this)
124 {
125         struct bch_geometry *geo = &this->bch_geometry;
126         struct mtd_info *mtd = &this->mtd;
127         struct nand_chip *chip = mtd->priv;
128         struct nand_oobfree *of = gpmi_hw_ecclayout.oobfree;
129         unsigned int block_mark_bit_offset;
130
131         if (!(chip->ecc_strength_ds > 0 && chip->ecc_step_ds > 0))
132                 return false;
133
134         switch (chip->ecc_step_ds) {
135         case SZ_512:
136                 geo->gf_len = 13;
137                 break;
138         case SZ_1K:
139                 geo->gf_len = 14;
140                 break;
141         default:
142                 dev_err(this->dev,
143                         "unsupported nand chip. ecc bits : %d, ecc size : %d\n",
144                         chip->ecc_strength_ds, chip->ecc_step_ds);
145                 return false;
146         }
147         geo->ecc_chunk_size = chip->ecc_step_ds;
148         geo->ecc_strength = round_up(chip->ecc_strength_ds, 2);
149         if (!gpmi_check_ecc(this))
150                 return false;
151
152         /* Keep the C >= O */
153         if (geo->ecc_chunk_size < mtd->oobsize) {
154                 dev_err(this->dev,
155                         "unsupported nand chip. ecc size: %d, oob size : %d\n",
156                         chip->ecc_step_ds, mtd->oobsize);
157                 return false;
158         }
159
160         /* The default value, see comment in the legacy_set_geometry(). */
161         geo->metadata_size = 10;
162
163         geo->ecc_chunk_count = mtd->writesize / geo->ecc_chunk_size;
164
165         /*
166          * Now, the NAND chip with 2K page(data chunk is 512byte) shows below:
167          *
168          *    |                          P                            |
169          *    |<----------------------------------------------------->|
170          *    |                                                       |
171          *    |                                        (Block Mark)   |
172          *    |                      P'                      |      | |     |
173          *    |<-------------------------------------------->|  D   | |  O' |
174          *    |                                              |<---->| |<--->|
175          *    V                                              V      V V     V
176          *    +---+----------+-+----------+-+----------+-+----------+-+-----+
177          *    | M |   data   |E|   data   |E|   data   |E|   data   |E|     |
178          *    +---+----------+-+----------+-+----------+-+----------+-+-----+
179          *                                                   ^              ^
180          *                                                   |      O       |
181          *                                                   |<------------>|
182          *                                                   |              |
183          *
184          *      P : the page size for BCH module.
185          *      E : The ECC strength.
186          *      G : the length of Galois Field.
187          *      N : The chunk count of per page.
188          *      M : the metasize of per page.
189          *      C : the ecc chunk size, aka the "data" above.
190          *      P': the nand chip's page size.
191          *      O : the nand chip's oob size.
192          *      O': the free oob.
193          *
194          *      The formula for P is :
195          *
196          *                  E * G * N
197          *             P = ------------ + P' + M
198          *                      8
199          *
200          * The position of block mark moves forward in the ECC-based view
201          * of page, and the delta is:
202          *
203          *                   E * G * (N - 1)
204          *             D = (---------------- + M)
205          *                          8
206          *
207          * Please see the comment in legacy_set_geometry().
208          * With the condition C >= O , we still can get same result.
209          * So the bit position of the physical block mark within the ECC-based
210          * view of the page is :
211          *             (P' - D) * 8
212          */
213         geo->page_size = mtd->writesize + geo->metadata_size +
214                 (geo->gf_len * geo->ecc_strength * geo->ecc_chunk_count) / 8;
215
216         /* The available oob size we have. */
217         if (geo->page_size < mtd->writesize + mtd->oobsize) {
218                 of->offset = geo->page_size - mtd->writesize;
219                 of->length = mtd->oobsize - of->offset;
220         }
221
222         geo->payload_size = mtd->writesize;
223
224         geo->auxiliary_status_offset = ALIGN(geo->metadata_size, 4);
225         geo->auxiliary_size = ALIGN(geo->metadata_size, 4)
226                                 + ALIGN(geo->ecc_chunk_count, 4);
227
228         if (!this->swap_block_mark)
229                 return true;
230
231         /* For bit swap. */
232         block_mark_bit_offset = mtd->writesize * 8 -
233                 (geo->ecc_strength * geo->gf_len * (geo->ecc_chunk_count - 1)
234                                 + geo->metadata_size * 8);
235
236         geo->block_mark_byte_offset = block_mark_bit_offset / 8;
237         geo->block_mark_bit_offset  = block_mark_bit_offset % 8;
238         return true;
239 }
240
241 static int legacy_set_geometry(struct gpmi_nand_data *this)
242 {
243         struct bch_geometry *geo = &this->bch_geometry;
244         struct mtd_info *mtd = &this->mtd;
245         unsigned int metadata_size;
246         unsigned int status_size;
247         unsigned int block_mark_bit_offset;
248
249         /*
250          * The size of the metadata can be changed, though we set it to 10
251          * bytes now. But it can't be too large, because we have to save
252          * enough space for BCH.
253          */
254         geo->metadata_size = 10;
255
256         /* The default for the length of Galois Field. */
257         geo->gf_len = 13;
258
259         /* The default for chunk size. */
260         geo->ecc_chunk_size = 512;
261         while (geo->ecc_chunk_size < mtd->oobsize) {
262                 geo->ecc_chunk_size *= 2; /* keep C >= O */
263                 geo->gf_len = 14;
264         }
265
266         geo->ecc_chunk_count = mtd->writesize / geo->ecc_chunk_size;
267
268         /* We use the same ECC strength for all chunks. */
269         geo->ecc_strength = get_ecc_strength(this);
270         if (!gpmi_check_ecc(this)) {
271                 dev_err(this->dev,
272                         "We can not support this nand chip."
273                         " Its required ecc strength(%d) is beyond our"
274                         " capability(%d).\n", geo->ecc_strength,
275                         (GPMI_IS_MX6Q(this) ? MX6_ECC_STRENGTH_MAX
276                                         : MXS_ECC_STRENGTH_MAX));
277                 return -EINVAL;
278         }
279
280         geo->page_size = mtd->writesize + mtd->oobsize;
281         geo->payload_size = mtd->writesize;
282
283         /*
284          * The auxiliary buffer contains the metadata and the ECC status. The
285          * metadata is padded to the nearest 32-bit boundary. The ECC status
286          * contains one byte for every ECC chunk, and is also padded to the
287          * nearest 32-bit boundary.
288          */
289         metadata_size = ALIGN(geo->metadata_size, 4);
290         status_size   = ALIGN(geo->ecc_chunk_count, 4);
291
292         geo->auxiliary_size = metadata_size + status_size;
293         geo->auxiliary_status_offset = metadata_size;
294
295         if (!this->swap_block_mark)
296                 return 0;
297
298         /*
299          * We need to compute the byte and bit offsets of
300          * the physical block mark within the ECC-based view of the page.
301          *
302          * NAND chip with 2K page shows below:
303          *                                             (Block Mark)
304          *                                                   |      |
305          *                                                   |  D   |
306          *                                                   |<---->|
307          *                                                   V      V
308          *    +---+----------+-+----------+-+----------+-+----------+-+
309          *    | M |   data   |E|   data   |E|   data   |E|   data   |E|
310          *    +---+----------+-+----------+-+----------+-+----------+-+
311          *
312          * The position of block mark moves forward in the ECC-based view
313          * of page, and the delta is:
314          *
315          *                   E * G * (N - 1)
316          *             D = (---------------- + M)
317          *                          8
318          *
319          * With the formula to compute the ECC strength, and the condition
320          *       : C >= O         (C is the ecc chunk size)
321          *
322          * It's easy to deduce to the following result:
323          *
324          *         E * G       (O - M)      C - M         C - M
325          *      ----------- <= ------- <=  --------  <  ---------
326          *           8            N           N          (N - 1)
327          *
328          *  So, we get:
329          *
330          *                   E * G * (N - 1)
331          *             D = (---------------- + M) < C
332          *                          8
333          *
334          *  The above inequality means the position of block mark
335          *  within the ECC-based view of the page is still in the data chunk,
336          *  and it's NOT in the ECC bits of the chunk.
337          *
338          *  Use the following to compute the bit position of the
339          *  physical block mark within the ECC-based view of the page:
340          *          (page_size - D) * 8
341          *
342          *  --Huang Shijie
343          */
344         block_mark_bit_offset = mtd->writesize * 8 -
345                 (geo->ecc_strength * geo->gf_len * (geo->ecc_chunk_count - 1)
346                                 + geo->metadata_size * 8);
347
348         geo->block_mark_byte_offset = block_mark_bit_offset / 8;
349         geo->block_mark_bit_offset  = block_mark_bit_offset % 8;
350         return 0;
351 }
352
353 int common_nfc_set_geometry(struct gpmi_nand_data *this)
354 {
355         if (of_property_read_bool(this->dev->of_node, "fsl,use-minimum-ecc")
356                 && set_geometry_by_ecc_info(this))
357                 return 0;
358         return legacy_set_geometry(this);
359 }
360
361 struct dma_chan *get_dma_chan(struct gpmi_nand_data *this)
362 {
363         /* We use the DMA channel 0 to access all the nand chips. */
364         return this->dma_chans[0];
365 }
366
367 /* Can we use the upper's buffer directly for DMA? */
368 void prepare_data_dma(struct gpmi_nand_data *this, enum dma_data_direction dr)
369 {
370         struct scatterlist *sgl = &this->data_sgl;
371         int ret;
372
373         this->direct_dma_map_ok = true;
374
375         /* first try to map the upper buffer directly */
376         sg_init_one(sgl, this->upper_buf, this->upper_len);
377         ret = dma_map_sg(this->dev, sgl, 1, dr);
378         if (ret == 0) {
379                 /* We have to use our own DMA buffer. */
380                 sg_init_one(sgl, this->data_buffer_dma, PAGE_SIZE);
381
382                 if (dr == DMA_TO_DEVICE)
383                         memcpy(this->data_buffer_dma, this->upper_buf,
384                                 this->upper_len);
385
386                 ret = dma_map_sg(this->dev, sgl, 1, dr);
387                 if (ret == 0)
388                         pr_err("DMA mapping failed.\n");
389
390                 this->direct_dma_map_ok = false;
391         }
392 }
393
394 /* This will be called after the DMA operation is finished. */
395 static void dma_irq_callback(void *param)
396 {
397         struct gpmi_nand_data *this = param;
398         struct completion *dma_c = &this->dma_done;
399
400         switch (this->dma_type) {
401         case DMA_FOR_COMMAND:
402                 dma_unmap_sg(this->dev, &this->cmd_sgl, 1, DMA_TO_DEVICE);
403                 break;
404
405         case DMA_FOR_READ_DATA:
406                 dma_unmap_sg(this->dev, &this->data_sgl, 1, DMA_FROM_DEVICE);
407                 if (this->direct_dma_map_ok == false)
408                         memcpy(this->upper_buf, this->data_buffer_dma,
409                                 this->upper_len);
410                 break;
411
412         case DMA_FOR_WRITE_DATA:
413                 dma_unmap_sg(this->dev, &this->data_sgl, 1, DMA_TO_DEVICE);
414                 break;
415
416         case DMA_FOR_READ_ECC_PAGE:
417         case DMA_FOR_WRITE_ECC_PAGE:
418                 /* We have to wait the BCH interrupt to finish. */
419                 break;
420
421         default:
422                 pr_err("in wrong DMA operation.\n");
423         }
424
425         complete(dma_c);
426 }
427
428 int start_dma_without_bch_irq(struct gpmi_nand_data *this,
429                                 struct dma_async_tx_descriptor *desc)
430 {
431         struct completion *dma_c = &this->dma_done;
432         int err;
433
434         init_completion(dma_c);
435
436         desc->callback          = dma_irq_callback;
437         desc->callback_param    = this;
438         dmaengine_submit(desc);
439         dma_async_issue_pending(get_dma_chan(this));
440
441         /* Wait for the interrupt from the DMA block. */
442         err = wait_for_completion_timeout(dma_c, msecs_to_jiffies(1000));
443         if (!err) {
444                 pr_err("DMA timeout, last DMA :%d\n", this->last_dma_type);
445                 gpmi_dump_info(this);
446                 return -ETIMEDOUT;
447         }
448         return 0;
449 }
450
451 /*
452  * This function is used in BCH reading or BCH writing pages.
453  * It will wait for the BCH interrupt as long as ONE second.
454  * Actually, we must wait for two interrupts :
455  *      [1] firstly the DMA interrupt and
456  *      [2] secondly the BCH interrupt.
457  */
458 int start_dma_with_bch_irq(struct gpmi_nand_data *this,
459                         struct dma_async_tx_descriptor *desc)
460 {
461         struct completion *bch_c = &this->bch_done;
462         int err;
463
464         /* Prepare to receive an interrupt from the BCH block. */
465         init_completion(bch_c);
466
467         /* start the DMA */
468         start_dma_without_bch_irq(this, desc);
469
470         /* Wait for the interrupt from the BCH block. */
471         err = wait_for_completion_timeout(bch_c, msecs_to_jiffies(1000));
472         if (!err) {
473                 pr_err("BCH timeout, last DMA :%d\n", this->last_dma_type);
474                 gpmi_dump_info(this);
475                 return -ETIMEDOUT;
476         }
477         return 0;
478 }
479
480 static int acquire_register_block(struct gpmi_nand_data *this,
481                                   const char *res_name)
482 {
483         struct platform_device *pdev = this->pdev;
484         struct resources *res = &this->resources;
485         struct resource *r;
486         void __iomem *p;
487
488         r = platform_get_resource_byname(pdev, IORESOURCE_MEM, res_name);
489         p = devm_ioremap_resource(&pdev->dev, r);
490         if (IS_ERR(p))
491                 return PTR_ERR(p);
492
493         if (!strcmp(res_name, GPMI_NAND_GPMI_REGS_ADDR_RES_NAME))
494                 res->gpmi_regs = p;
495         else if (!strcmp(res_name, GPMI_NAND_BCH_REGS_ADDR_RES_NAME))
496                 res->bch_regs = p;
497         else
498                 pr_err("unknown resource name : %s\n", res_name);
499
500         return 0;
501 }
502
503 static int acquire_bch_irq(struct gpmi_nand_data *this, irq_handler_t irq_h)
504 {
505         struct platform_device *pdev = this->pdev;
506         struct resources *res = &this->resources;
507         const char *res_name = GPMI_NAND_BCH_INTERRUPT_RES_NAME;
508         struct resource *r;
509         int err;
510
511         r = platform_get_resource_byname(pdev, IORESOURCE_IRQ, res_name);
512         if (!r) {
513                 pr_err("Can't get resource for %s\n", res_name);
514                 return -ENODEV;
515         }
516
517         err = request_irq(r->start, irq_h, 0, res_name, this);
518         if (err) {
519                 pr_err("Can't own %s\n", res_name);
520                 return err;
521         }
522
523         res->bch_low_interrupt = r->start;
524         res->bch_high_interrupt = r->end;
525         return 0;
526 }
527
528 static void release_bch_irq(struct gpmi_nand_data *this)
529 {
530         struct resources *res = &this->resources;
531         int i = res->bch_low_interrupt;
532
533         for (; i <= res->bch_high_interrupt; i++)
534                 free_irq(i, this);
535 }
536
537 static void release_dma_channels(struct gpmi_nand_data *this)
538 {
539         unsigned int i;
540         for (i = 0; i < DMA_CHANS; i++)
541                 if (this->dma_chans[i]) {
542                         dma_release_channel(this->dma_chans[i]);
543                         this->dma_chans[i] = NULL;
544                 }
545 }
546
547 static int acquire_dma_channels(struct gpmi_nand_data *this)
548 {
549         struct platform_device *pdev = this->pdev;
550         struct dma_chan *dma_chan;
551
552         /* request dma channel */
553         dma_chan = dma_request_slave_channel(&pdev->dev, "rx-tx");
554         if (!dma_chan) {
555                 pr_err("Failed to request DMA channel.\n");
556                 goto acquire_err;
557         }
558
559         this->dma_chans[0] = dma_chan;
560         return 0;
561
562 acquire_err:
563         release_dma_channels(this);
564         return -EINVAL;
565 }
566
567 static char *extra_clks_for_mx6q[GPMI_CLK_MAX] = {
568         "gpmi_apb", "gpmi_bch", "gpmi_bch_apb", "per1_bch",
569 };
570
571 static int gpmi_get_clks(struct gpmi_nand_data *this)
572 {
573         struct resources *r = &this->resources;
574         char **extra_clks = NULL;
575         struct clk *clk;
576         int err, i;
577
578         /* The main clock is stored in the first. */
579         r->clock[0] = devm_clk_get(this->dev, "gpmi_io");
580         if (IS_ERR(r->clock[0])) {
581                 err = PTR_ERR(r->clock[0]);
582                 goto err_clock;
583         }
584
585         /* Get extra clocks */
586         if (GPMI_IS_MX6Q(this))
587                 extra_clks = extra_clks_for_mx6q;
588         if (!extra_clks)
589                 return 0;
590
591         for (i = 1; i < GPMI_CLK_MAX; i++) {
592                 if (extra_clks[i - 1] == NULL)
593                         break;
594
595                 clk = devm_clk_get(this->dev, extra_clks[i - 1]);
596                 if (IS_ERR(clk)) {
597                         err = PTR_ERR(clk);
598                         goto err_clock;
599                 }
600
601                 r->clock[i] = clk;
602         }
603
604         if (GPMI_IS_MX6Q(this))
605                 /*
606                  * Set the default value for the gpmi clock in mx6q:
607                  *
608                  * If you want to use the ONFI nand which is in the
609                  * Synchronous Mode, you should change the clock as you need.
610                  */
611                 clk_set_rate(r->clock[0], 22000000);
612
613         return 0;
614
615 err_clock:
616         dev_dbg(this->dev, "failed in finding the clocks.\n");
617         return err;
618 }
619
620 static int acquire_resources(struct gpmi_nand_data *this)
621 {
622         int ret;
623
624         ret = acquire_register_block(this, GPMI_NAND_GPMI_REGS_ADDR_RES_NAME);
625         if (ret)
626                 goto exit_regs;
627
628         ret = acquire_register_block(this, GPMI_NAND_BCH_REGS_ADDR_RES_NAME);
629         if (ret)
630                 goto exit_regs;
631
632         ret = acquire_bch_irq(this, bch_irq);
633         if (ret)
634                 goto exit_regs;
635
636         ret = acquire_dma_channels(this);
637         if (ret)
638                 goto exit_dma_channels;
639
640         ret = gpmi_get_clks(this);
641         if (ret)
642                 goto exit_clock;
643         return 0;
644
645 exit_clock:
646         release_dma_channels(this);
647 exit_dma_channels:
648         release_bch_irq(this);
649 exit_regs:
650         return ret;
651 }
652
653 static void release_resources(struct gpmi_nand_data *this)
654 {
655         release_bch_irq(this);
656         release_dma_channels(this);
657 }
658
659 static int init_hardware(struct gpmi_nand_data *this)
660 {
661         int ret;
662
663         /*
664          * This structure contains the "safe" GPMI timing that should succeed
665          * with any NAND Flash device
666          * (although, with less-than-optimal performance).
667          */
668         struct nand_timing  safe_timing = {
669                 .data_setup_in_ns        = 80,
670                 .data_hold_in_ns         = 60,
671                 .address_setup_in_ns     = 25,
672                 .gpmi_sample_delay_in_ns =  6,
673                 .tREA_in_ns              = -1,
674                 .tRLOH_in_ns             = -1,
675                 .tRHOH_in_ns             = -1,
676         };
677
678         /* Initialize the hardwares. */
679         ret = gpmi_init(this);
680         if (ret)
681                 return ret;
682
683         this->timing = safe_timing;
684         return 0;
685 }
686
687 static int read_page_prepare(struct gpmi_nand_data *this,
688                         void *destination, unsigned length,
689                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
690                         void **use_virt, dma_addr_t *use_phys)
691 {
692         struct device *dev = this->dev;
693
694         if (virt_addr_valid(destination)) {
695                 dma_addr_t dest_phys;
696
697                 dest_phys = dma_map_single(dev, destination,
698                                                 length, DMA_FROM_DEVICE);
699                 if (dma_mapping_error(dev, dest_phys)) {
700                         if (alt_size < length) {
701                                 pr_err("%s, Alternate buffer is too small\n",
702                                         __func__);
703                                 return -ENOMEM;
704                         }
705                         goto map_failed;
706                 }
707                 *use_virt = destination;
708                 *use_phys = dest_phys;
709                 this->direct_dma_map_ok = true;
710                 return 0;
711         }
712
713 map_failed:
714         *use_virt = alt_virt;
715         *use_phys = alt_phys;
716         this->direct_dma_map_ok = false;
717         return 0;
718 }
719
720 static inline void read_page_end(struct gpmi_nand_data *this,
721                         void *destination, unsigned length,
722                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
723                         void *used_virt, dma_addr_t used_phys)
724 {
725         if (this->direct_dma_map_ok)
726                 dma_unmap_single(this->dev, used_phys, length, DMA_FROM_DEVICE);
727 }
728
729 static inline void read_page_swap_end(struct gpmi_nand_data *this,
730                         void *destination, unsigned length,
731                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
732                         void *used_virt, dma_addr_t used_phys)
733 {
734         if (!this->direct_dma_map_ok)
735                 memcpy(destination, alt_virt, length);
736 }
737
738 static int send_page_prepare(struct gpmi_nand_data *this,
739                         const void *source, unsigned length,
740                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
741                         const void **use_virt, dma_addr_t *use_phys)
742 {
743         struct device *dev = this->dev;
744
745         if (virt_addr_valid(source)) {
746                 dma_addr_t source_phys;
747
748                 source_phys = dma_map_single(dev, (void *)source, length,
749                                                 DMA_TO_DEVICE);
750                 if (dma_mapping_error(dev, source_phys)) {
751                         if (alt_size < length) {
752                                 pr_err("%s, Alternate buffer is too small\n",
753                                         __func__);
754                                 return -ENOMEM;
755                         }
756                         goto map_failed;
757                 }
758                 *use_virt = source;
759                 *use_phys = source_phys;
760                 return 0;
761         }
762 map_failed:
763         /*
764          * Copy the content of the source buffer into the alternate
765          * buffer and set up the return values accordingly.
766          */
767         memcpy(alt_virt, source, length);
768
769         *use_virt = alt_virt;
770         *use_phys = alt_phys;
771         return 0;
772 }
773
774 static void send_page_end(struct gpmi_nand_data *this,
775                         const void *source, unsigned length,
776                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
777                         const void *used_virt, dma_addr_t used_phys)
778 {
779         struct device *dev = this->dev;
780         if (used_virt == source)
781                 dma_unmap_single(dev, used_phys, length, DMA_TO_DEVICE);
782 }
783
784 static void gpmi_free_dma_buffer(struct gpmi_nand_data *this)
785 {
786         struct device *dev = this->dev;
787
788         if (this->page_buffer_virt && virt_addr_valid(this->page_buffer_virt))
789                 dma_free_coherent(dev, this->page_buffer_size,
790                                         this->page_buffer_virt,
791                                         this->page_buffer_phys);
792         kfree(this->cmd_buffer);
793         kfree(this->data_buffer_dma);
794
795         this->cmd_buffer        = NULL;
796         this->data_buffer_dma   = NULL;
797         this->page_buffer_virt  = NULL;
798         this->page_buffer_size  =  0;
799 }
800
801 /* Allocate the DMA buffers */
802 static int gpmi_alloc_dma_buffer(struct gpmi_nand_data *this)
803 {
804         struct bch_geometry *geo = &this->bch_geometry;
805         struct device *dev = this->dev;
806
807         /* [1] Allocate a command buffer. PAGE_SIZE is enough. */
808         this->cmd_buffer = kzalloc(PAGE_SIZE, GFP_DMA | GFP_KERNEL);
809         if (this->cmd_buffer == NULL)
810                 goto error_alloc;
811
812         /* [2] Allocate a read/write data buffer. PAGE_SIZE is enough. */
813         this->data_buffer_dma = kzalloc(PAGE_SIZE, GFP_DMA | GFP_KERNEL);
814         if (this->data_buffer_dma == NULL)
815                 goto error_alloc;
816
817         /*
818          * [3] Allocate the page buffer.
819          *
820          * Both the payload buffer and the auxiliary buffer must appear on
821          * 32-bit boundaries. We presume the size of the payload buffer is a
822          * power of two and is much larger than four, which guarantees the
823          * auxiliary buffer will appear on a 32-bit boundary.
824          */
825         this->page_buffer_size = geo->payload_size + geo->auxiliary_size;
826         this->page_buffer_virt = dma_alloc_coherent(dev, this->page_buffer_size,
827                                         &this->page_buffer_phys, GFP_DMA);
828         if (!this->page_buffer_virt)
829                 goto error_alloc;
830
831
832         /* Slice up the page buffer. */
833         this->payload_virt = this->page_buffer_virt;
834         this->payload_phys = this->page_buffer_phys;
835         this->auxiliary_virt = this->payload_virt + geo->payload_size;
836         this->auxiliary_phys = this->payload_phys + geo->payload_size;
837         return 0;
838
839 error_alloc:
840         gpmi_free_dma_buffer(this);
841         pr_err("Error allocating DMA buffers!\n");
842         return -ENOMEM;
843 }
844
845 static void gpmi_cmd_ctrl(struct mtd_info *mtd, int data, unsigned int ctrl)
846 {
847         struct nand_chip *chip = mtd->priv;
848         struct gpmi_nand_data *this = chip->priv;
849         int ret;
850
851         /*
852          * Every operation begins with a command byte and a series of zero or
853          * more address bytes. These are distinguished by either the Address
854          * Latch Enable (ALE) or Command Latch Enable (CLE) signals being
855          * asserted. When MTD is ready to execute the command, it will deassert
856          * both latch enables.
857          *
858          * Rather than run a separate DMA operation for every single byte, we
859          * queue them up and run a single DMA operation for the entire series
860          * of command and data bytes. NAND_CMD_NONE means the END of the queue.
861          */
862         if ((ctrl & (NAND_ALE | NAND_CLE))) {
863                 if (data != NAND_CMD_NONE)
864                         this->cmd_buffer[this->command_length++] = data;
865                 return;
866         }
867
868         if (!this->command_length)
869                 return;
870
871         ret = gpmi_send_command(this);
872         if (ret)
873                 pr_err("Chip: %u, Error %d\n", this->current_chip, ret);
874
875         this->command_length = 0;
876 }
877
878 static int gpmi_dev_ready(struct mtd_info *mtd)
879 {
880         struct nand_chip *chip = mtd->priv;
881         struct gpmi_nand_data *this = chip->priv;
882
883         return gpmi_is_ready(this, this->current_chip);
884 }
885
886 static void gpmi_select_chip(struct mtd_info *mtd, int chipnr)
887 {
888         struct nand_chip *chip = mtd->priv;
889         struct gpmi_nand_data *this = chip->priv;
890
891         if ((this->current_chip < 0) && (chipnr >= 0))
892                 gpmi_begin(this);
893         else if ((this->current_chip >= 0) && (chipnr < 0))
894                 gpmi_end(this);
895
896         this->current_chip = chipnr;
897 }
898
899 static void gpmi_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
900 {
901         struct nand_chip *chip = mtd->priv;
902         struct gpmi_nand_data *this = chip->priv;
903
904         pr_debug("len is %d\n", len);
905         this->upper_buf = buf;
906         this->upper_len = len;
907
908         gpmi_read_data(this);
909 }
910
911 static void gpmi_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
912 {
913         struct nand_chip *chip = mtd->priv;
914         struct gpmi_nand_data *this = chip->priv;
915
916         pr_debug("len is %d\n", len);
917         this->upper_buf = (uint8_t *)buf;
918         this->upper_len = len;
919
920         gpmi_send_data(this);
921 }
922
923 static uint8_t gpmi_read_byte(struct mtd_info *mtd)
924 {
925         struct nand_chip *chip = mtd->priv;
926         struct gpmi_nand_data *this = chip->priv;
927         uint8_t *buf = this->data_buffer_dma;
928
929         gpmi_read_buf(mtd, buf, 1);
930         return buf[0];
931 }
932
933 /*
934  * Handles block mark swapping.
935  * It can be called in swapping the block mark, or swapping it back,
936  * because the the operations are the same.
937  */
938 static void block_mark_swapping(struct gpmi_nand_data *this,
939                                 void *payload, void *auxiliary)
940 {
941         struct bch_geometry *nfc_geo = &this->bch_geometry;
942         unsigned char *p;
943         unsigned char *a;
944         unsigned int  bit;
945         unsigned char mask;
946         unsigned char from_data;
947         unsigned char from_oob;
948
949         if (!this->swap_block_mark)
950                 return;
951
952         /*
953          * If control arrives here, we're swapping. Make some convenience
954          * variables.
955          */
956         bit = nfc_geo->block_mark_bit_offset;
957         p   = payload + nfc_geo->block_mark_byte_offset;
958         a   = auxiliary;
959
960         /*
961          * Get the byte from the data area that overlays the block mark. Since
962          * the ECC engine applies its own view to the bits in the page, the
963          * physical block mark won't (in general) appear on a byte boundary in
964          * the data.
965          */
966         from_data = (p[0] >> bit) | (p[1] << (8 - bit));
967
968         /* Get the byte from the OOB. */
969         from_oob = a[0];
970
971         /* Swap them. */
972         a[0] = from_data;
973
974         mask = (0x1 << bit) - 1;
975         p[0] = (p[0] & mask) | (from_oob << bit);
976
977         mask = ~0 << bit;
978         p[1] = (p[1] & mask) | (from_oob >> (8 - bit));
979 }
980
981 static int gpmi_ecc_read_page(struct mtd_info *mtd, struct nand_chip *chip,
982                                 uint8_t *buf, int oob_required, int page)
983 {
984         struct gpmi_nand_data *this = chip->priv;
985         struct bch_geometry *nfc_geo = &this->bch_geometry;
986         void          *payload_virt;
987         dma_addr_t    payload_phys;
988         void          *auxiliary_virt;
989         dma_addr_t    auxiliary_phys;
990         unsigned int  i;
991         unsigned char *status;
992         unsigned int  max_bitflips = 0;
993         int           ret;
994
995         pr_debug("page number is : %d\n", page);
996         ret = read_page_prepare(this, buf, mtd->writesize,
997                                         this->payload_virt, this->payload_phys,
998                                         nfc_geo->payload_size,
999                                         &payload_virt, &payload_phys);
1000         if (ret) {
1001                 pr_err("Inadequate DMA buffer\n");
1002                 ret = -ENOMEM;
1003                 return ret;
1004         }
1005         auxiliary_virt = this->auxiliary_virt;
1006         auxiliary_phys = this->auxiliary_phys;
1007
1008         /* go! */
1009         ret = gpmi_read_page(this, payload_phys, auxiliary_phys);
1010         read_page_end(this, buf, mtd->writesize,
1011                         this->payload_virt, this->payload_phys,
1012                         nfc_geo->payload_size,
1013                         payload_virt, payload_phys);
1014         if (ret) {
1015                 pr_err("Error in ECC-based read: %d\n", ret);
1016                 return ret;
1017         }
1018
1019         /* handle the block mark swapping */
1020         block_mark_swapping(this, payload_virt, auxiliary_virt);
1021
1022         /* Loop over status bytes, accumulating ECC status. */
1023         status = auxiliary_virt + nfc_geo->auxiliary_status_offset;
1024
1025         for (i = 0; i < nfc_geo->ecc_chunk_count; i++, status++) {
1026                 if ((*status == STATUS_GOOD) || (*status == STATUS_ERASED))
1027                         continue;
1028
1029                 if (*status == STATUS_UNCORRECTABLE) {
1030                         mtd->ecc_stats.failed++;
1031                         continue;
1032                 }
1033                 mtd->ecc_stats.corrected += *status;
1034                 max_bitflips = max_t(unsigned int, max_bitflips, *status);
1035         }
1036
1037         if (oob_required) {
1038                 /*
1039                  * It's time to deliver the OOB bytes. See gpmi_ecc_read_oob()
1040                  * for details about our policy for delivering the OOB.
1041                  *
1042                  * We fill the caller's buffer with set bits, and then copy the
1043                  * block mark to th caller's buffer. Note that, if block mark
1044                  * swapping was necessary, it has already been done, so we can
1045                  * rely on the first byte of the auxiliary buffer to contain
1046                  * the block mark.
1047                  */
1048                 memset(chip->oob_poi, ~0, mtd->oobsize);
1049                 chip->oob_poi[0] = ((uint8_t *) auxiliary_virt)[0];
1050         }
1051
1052         read_page_swap_end(this, buf, mtd->writesize,
1053                         this->payload_virt, this->payload_phys,
1054                         nfc_geo->payload_size,
1055                         payload_virt, payload_phys);
1056
1057         return max_bitflips;
1058 }
1059
1060 static int gpmi_ecc_write_page(struct mtd_info *mtd, struct nand_chip *chip,
1061                                 const uint8_t *buf, int oob_required)
1062 {
1063         struct gpmi_nand_data *this = chip->priv;
1064         struct bch_geometry *nfc_geo = &this->bch_geometry;
1065         const void *payload_virt;
1066         dma_addr_t payload_phys;
1067         const void *auxiliary_virt;
1068         dma_addr_t auxiliary_phys;
1069         int        ret;
1070
1071         pr_debug("ecc write page.\n");
1072         if (this->swap_block_mark) {
1073                 /*
1074                  * If control arrives here, we're doing block mark swapping.
1075                  * Since we can't modify the caller's buffers, we must copy them
1076                  * into our own.
1077                  */
1078                 memcpy(this->payload_virt, buf, mtd->writesize);
1079                 payload_virt = this->payload_virt;
1080                 payload_phys = this->payload_phys;
1081
1082                 memcpy(this->auxiliary_virt, chip->oob_poi,
1083                                 nfc_geo->auxiliary_size);
1084                 auxiliary_virt = this->auxiliary_virt;
1085                 auxiliary_phys = this->auxiliary_phys;
1086
1087                 /* Handle block mark swapping. */
1088                 block_mark_swapping(this,
1089                                 (void *) payload_virt, (void *) auxiliary_virt);
1090         } else {
1091                 /*
1092                  * If control arrives here, we're not doing block mark swapping,
1093                  * so we can to try and use the caller's buffers.
1094                  */
1095                 ret = send_page_prepare(this,
1096                                 buf, mtd->writesize,
1097                                 this->payload_virt, this->payload_phys,
1098                                 nfc_geo->payload_size,
1099                                 &payload_virt, &payload_phys);
1100                 if (ret) {
1101                         pr_err("Inadequate payload DMA buffer\n");
1102                         return 0;
1103                 }
1104
1105                 ret = send_page_prepare(this,
1106                                 chip->oob_poi, mtd->oobsize,
1107                                 this->auxiliary_virt, this->auxiliary_phys,
1108                                 nfc_geo->auxiliary_size,
1109                                 &auxiliary_virt, &auxiliary_phys);
1110                 if (ret) {
1111                         pr_err("Inadequate auxiliary DMA buffer\n");
1112                         goto exit_auxiliary;
1113                 }
1114         }
1115
1116         /* Ask the NFC. */
1117         ret = gpmi_send_page(this, payload_phys, auxiliary_phys);
1118         if (ret)
1119                 pr_err("Error in ECC-based write: %d\n", ret);
1120
1121         if (!this->swap_block_mark) {
1122                 send_page_end(this, chip->oob_poi, mtd->oobsize,
1123                                 this->auxiliary_virt, this->auxiliary_phys,
1124                                 nfc_geo->auxiliary_size,
1125                                 auxiliary_virt, auxiliary_phys);
1126 exit_auxiliary:
1127                 send_page_end(this, buf, mtd->writesize,
1128                                 this->payload_virt, this->payload_phys,
1129                                 nfc_geo->payload_size,
1130                                 payload_virt, payload_phys);
1131         }
1132
1133         return 0;
1134 }
1135
1136 /*
1137  * There are several places in this driver where we have to handle the OOB and
1138  * block marks. This is the function where things are the most complicated, so
1139  * this is where we try to explain it all. All the other places refer back to
1140  * here.
1141  *
1142  * These are the rules, in order of decreasing importance:
1143  *
1144  * 1) Nothing the caller does can be allowed to imperil the block mark.
1145  *
1146  * 2) In read operations, the first byte of the OOB we return must reflect the
1147  *    true state of the block mark, no matter where that block mark appears in
1148  *    the physical page.
1149  *
1150  * 3) ECC-based read operations return an OOB full of set bits (since we never
1151  *    allow ECC-based writes to the OOB, it doesn't matter what ECC-based reads
1152  *    return).
1153  *
1154  * 4) "Raw" read operations return a direct view of the physical bytes in the
1155  *    page, using the conventional definition of which bytes are data and which
1156  *    are OOB. This gives the caller a way to see the actual, physical bytes
1157  *    in the page, without the distortions applied by our ECC engine.
1158  *
1159  *
1160  * What we do for this specific read operation depends on two questions:
1161  *
1162  * 1) Are we doing a "raw" read, or an ECC-based read?
1163  *
1164  * 2) Are we using block mark swapping or transcription?
1165  *
1166  * There are four cases, illustrated by the following Karnaugh map:
1167  *
1168  *                    |           Raw           |         ECC-based       |
1169  *       -------------+-------------------------+-------------------------+
1170  *                    | Read the conventional   |                         |
1171  *                    | OOB at the end of the   |                         |
1172  *       Swapping     | page and return it. It  |                         |
1173  *                    | contains exactly what   |                         |
1174  *                    | we want.                | Read the block mark and |
1175  *       -------------+-------------------------+ return it in a buffer   |
1176  *                    | Read the conventional   | full of set bits.       |
1177  *                    | OOB at the end of the   |                         |
1178  *                    | page and also the block |                         |
1179  *       Transcribing | mark in the metadata.   |                         |
1180  *                    | Copy the block mark     |                         |
1181  *                    | into the first byte of  |                         |
1182  *                    | the OOB.                |                         |
1183  *       -------------+-------------------------+-------------------------+
1184  *
1185  * Note that we break rule #4 in the Transcribing/Raw case because we're not
1186  * giving an accurate view of the actual, physical bytes in the page (we're
1187  * overwriting the block mark). That's OK because it's more important to follow
1188  * rule #2.
1189  *
1190  * It turns out that knowing whether we want an "ECC-based" or "raw" read is not
1191  * easy. When reading a page, for example, the NAND Flash MTD code calls our
1192  * ecc.read_page or ecc.read_page_raw function. Thus, the fact that MTD wants an
1193  * ECC-based or raw view of the page is implicit in which function it calls
1194  * (there is a similar pair of ECC-based/raw functions for writing).
1195  *
1196  * FIXME: The following paragraph is incorrect, now that there exist
1197  * ecc.read_oob_raw and ecc.write_oob_raw functions.
1198  *
1199  * Since MTD assumes the OOB is not covered by ECC, there is no pair of
1200  * ECC-based/raw functions for reading or or writing the OOB. The fact that the
1201  * caller wants an ECC-based or raw view of the page is not propagated down to
1202  * this driver.
1203  */
1204 static int gpmi_ecc_read_oob(struct mtd_info *mtd, struct nand_chip *chip,
1205                                 int page)
1206 {
1207         struct gpmi_nand_data *this = chip->priv;
1208
1209         pr_debug("page number is %d\n", page);
1210         /* clear the OOB buffer */
1211         memset(chip->oob_poi, ~0, mtd->oobsize);
1212
1213         /* Read out the conventional OOB. */
1214         chip->cmdfunc(mtd, NAND_CMD_READ0, mtd->writesize, page);
1215         chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1216
1217         /*
1218          * Now, we want to make sure the block mark is correct. In the
1219          * Swapping/Raw case, we already have it. Otherwise, we need to
1220          * explicitly read it.
1221          */
1222         if (!this->swap_block_mark) {
1223                 /* Read the block mark into the first byte of the OOB buffer. */
1224                 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1225                 chip->oob_poi[0] = chip->read_byte(mtd);
1226         }
1227
1228         return 0;
1229 }
1230
1231 static int
1232 gpmi_ecc_write_oob(struct mtd_info *mtd, struct nand_chip *chip, int page)
1233 {
1234         struct nand_oobfree *of = mtd->ecclayout->oobfree;
1235         int status = 0;
1236
1237         /* Do we have available oob area? */
1238         if (!of->length)
1239                 return -EPERM;
1240
1241         if (!nand_is_slc(chip))
1242                 return -EPERM;
1243
1244         chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize + of->offset, page);
1245         chip->write_buf(mtd, chip->oob_poi + of->offset, of->length);
1246         chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1247
1248         status = chip->waitfunc(mtd, chip);
1249         return status & NAND_STATUS_FAIL ? -EIO : 0;
1250 }
1251
1252 static int gpmi_block_markbad(struct mtd_info *mtd, loff_t ofs)
1253 {
1254         struct nand_chip *chip = mtd->priv;
1255         struct gpmi_nand_data *this = chip->priv;
1256         int ret = 0;
1257         uint8_t *block_mark;
1258         int column, page, status, chipnr;
1259
1260         chipnr = (int)(ofs >> chip->chip_shift);
1261         chip->select_chip(mtd, chipnr);
1262
1263         column = this->swap_block_mark ? mtd->writesize : 0;
1264
1265         /* Write the block mark. */
1266         block_mark = this->data_buffer_dma;
1267         block_mark[0] = 0; /* bad block marker */
1268
1269         /* Shift to get page */
1270         page = (int)(ofs >> chip->page_shift);
1271
1272         chip->cmdfunc(mtd, NAND_CMD_SEQIN, column, page);
1273         chip->write_buf(mtd, block_mark, 1);
1274         chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1275
1276         status = chip->waitfunc(mtd, chip);
1277         if (status & NAND_STATUS_FAIL)
1278                 ret = -EIO;
1279
1280         chip->select_chip(mtd, -1);
1281
1282         return ret;
1283 }
1284
1285 static int nand_boot_set_geometry(struct gpmi_nand_data *this)
1286 {
1287         struct boot_rom_geometry *geometry = &this->rom_geometry;
1288
1289         /*
1290          * Set the boot block stride size.
1291          *
1292          * In principle, we should be reading this from the OTP bits, since
1293          * that's where the ROM is going to get it. In fact, we don't have any
1294          * way to read the OTP bits, so we go with the default and hope for the
1295          * best.
1296          */
1297         geometry->stride_size_in_pages = 64;
1298
1299         /*
1300          * Set the search area stride exponent.
1301          *
1302          * In principle, we should be reading this from the OTP bits, since
1303          * that's where the ROM is going to get it. In fact, we don't have any
1304          * way to read the OTP bits, so we go with the default and hope for the
1305          * best.
1306          */
1307         geometry->search_area_stride_exponent = 2;
1308         return 0;
1309 }
1310
1311 static const char  *fingerprint = "STMP";
1312 static int mx23_check_transcription_stamp(struct gpmi_nand_data *this)
1313 {
1314         struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1315         struct device *dev = this->dev;
1316         struct mtd_info *mtd = &this->mtd;
1317         struct nand_chip *chip = &this->nand;
1318         unsigned int search_area_size_in_strides;
1319         unsigned int stride;
1320         unsigned int page;
1321         uint8_t *buffer = chip->buffers->databuf;
1322         int saved_chip_number;
1323         int found_an_ncb_fingerprint = false;
1324
1325         /* Compute the number of strides in a search area. */
1326         search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1327
1328         saved_chip_number = this->current_chip;
1329         chip->select_chip(mtd, 0);
1330
1331         /*
1332          * Loop through the first search area, looking for the NCB fingerprint.
1333          */
1334         dev_dbg(dev, "Scanning for an NCB fingerprint...\n");
1335
1336         for (stride = 0; stride < search_area_size_in_strides; stride++) {
1337                 /* Compute the page addresses. */
1338                 page = stride * rom_geo->stride_size_in_pages;
1339
1340                 dev_dbg(dev, "Looking for a fingerprint in page 0x%x\n", page);
1341
1342                 /*
1343                  * Read the NCB fingerprint. The fingerprint is four bytes long
1344                  * and starts in the 12th byte of the page.
1345                  */
1346                 chip->cmdfunc(mtd, NAND_CMD_READ0, 12, page);
1347                 chip->read_buf(mtd, buffer, strlen(fingerprint));
1348
1349                 /* Look for the fingerprint. */
1350                 if (!memcmp(buffer, fingerprint, strlen(fingerprint))) {
1351                         found_an_ncb_fingerprint = true;
1352                         break;
1353                 }
1354
1355         }
1356
1357         chip->select_chip(mtd, saved_chip_number);
1358
1359         if (found_an_ncb_fingerprint)
1360                 dev_dbg(dev, "\tFound a fingerprint\n");
1361         else
1362                 dev_dbg(dev, "\tNo fingerprint found\n");
1363         return found_an_ncb_fingerprint;
1364 }
1365
1366 /* Writes a transcription stamp. */
1367 static int mx23_write_transcription_stamp(struct gpmi_nand_data *this)
1368 {
1369         struct device *dev = this->dev;
1370         struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1371         struct mtd_info *mtd = &this->mtd;
1372         struct nand_chip *chip = &this->nand;
1373         unsigned int block_size_in_pages;
1374         unsigned int search_area_size_in_strides;
1375         unsigned int search_area_size_in_pages;
1376         unsigned int search_area_size_in_blocks;
1377         unsigned int block;
1378         unsigned int stride;
1379         unsigned int page;
1380         uint8_t      *buffer = chip->buffers->databuf;
1381         int saved_chip_number;
1382         int status;
1383
1384         /* Compute the search area geometry. */
1385         block_size_in_pages = mtd->erasesize / mtd->writesize;
1386         search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1387         search_area_size_in_pages = search_area_size_in_strides *
1388                                         rom_geo->stride_size_in_pages;
1389         search_area_size_in_blocks =
1390                   (search_area_size_in_pages + (block_size_in_pages - 1)) /
1391                                     block_size_in_pages;
1392
1393         dev_dbg(dev, "Search Area Geometry :\n");
1394         dev_dbg(dev, "\tin Blocks : %u\n", search_area_size_in_blocks);
1395         dev_dbg(dev, "\tin Strides: %u\n", search_area_size_in_strides);
1396         dev_dbg(dev, "\tin Pages  : %u\n", search_area_size_in_pages);
1397
1398         /* Select chip 0. */
1399         saved_chip_number = this->current_chip;
1400         chip->select_chip(mtd, 0);
1401
1402         /* Loop over blocks in the first search area, erasing them. */
1403         dev_dbg(dev, "Erasing the search area...\n");
1404
1405         for (block = 0; block < search_area_size_in_blocks; block++) {
1406                 /* Compute the page address. */
1407                 page = block * block_size_in_pages;
1408
1409                 /* Erase this block. */
1410                 dev_dbg(dev, "\tErasing block 0x%x\n", block);
1411                 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1412                 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1413
1414                 /* Wait for the erase to finish. */
1415                 status = chip->waitfunc(mtd, chip);
1416                 if (status & NAND_STATUS_FAIL)
1417                         dev_err(dev, "[%s] Erase failed.\n", __func__);
1418         }
1419
1420         /* Write the NCB fingerprint into the page buffer. */
1421         memset(buffer, ~0, mtd->writesize);
1422         memcpy(buffer + 12, fingerprint, strlen(fingerprint));
1423
1424         /* Loop through the first search area, writing NCB fingerprints. */
1425         dev_dbg(dev, "Writing NCB fingerprints...\n");
1426         for (stride = 0; stride < search_area_size_in_strides; stride++) {
1427                 /* Compute the page addresses. */
1428                 page = stride * rom_geo->stride_size_in_pages;
1429
1430                 /* Write the first page of the current stride. */
1431                 dev_dbg(dev, "Writing an NCB fingerprint in page 0x%x\n", page);
1432                 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
1433                 chip->ecc.write_page_raw(mtd, chip, buffer, 0);
1434                 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1435
1436                 /* Wait for the write to finish. */
1437                 status = chip->waitfunc(mtd, chip);
1438                 if (status & NAND_STATUS_FAIL)
1439                         dev_err(dev, "[%s] Write failed.\n", __func__);
1440         }
1441
1442         /* Deselect chip 0. */
1443         chip->select_chip(mtd, saved_chip_number);
1444         return 0;
1445 }
1446
1447 static int mx23_boot_init(struct gpmi_nand_data  *this)
1448 {
1449         struct device *dev = this->dev;
1450         struct nand_chip *chip = &this->nand;
1451         struct mtd_info *mtd = &this->mtd;
1452         unsigned int block_count;
1453         unsigned int block;
1454         int     chipnr;
1455         int     page;
1456         loff_t  byte;
1457         uint8_t block_mark;
1458         int     ret = 0;
1459
1460         /*
1461          * If control arrives here, we can't use block mark swapping, which
1462          * means we're forced to use transcription. First, scan for the
1463          * transcription stamp. If we find it, then we don't have to do
1464          * anything -- the block marks are already transcribed.
1465          */
1466         if (mx23_check_transcription_stamp(this))
1467                 return 0;
1468
1469         /*
1470          * If control arrives here, we couldn't find a transcription stamp, so
1471          * so we presume the block marks are in the conventional location.
1472          */
1473         dev_dbg(dev, "Transcribing bad block marks...\n");
1474
1475         /* Compute the number of blocks in the entire medium. */
1476         block_count = chip->chipsize >> chip->phys_erase_shift;
1477
1478         /*
1479          * Loop over all the blocks in the medium, transcribing block marks as
1480          * we go.
1481          */
1482         for (block = 0; block < block_count; block++) {
1483                 /*
1484                  * Compute the chip, page and byte addresses for this block's
1485                  * conventional mark.
1486                  */
1487                 chipnr = block >> (chip->chip_shift - chip->phys_erase_shift);
1488                 page = block << (chip->phys_erase_shift - chip->page_shift);
1489                 byte = block <<  chip->phys_erase_shift;
1490
1491                 /* Send the command to read the conventional block mark. */
1492                 chip->select_chip(mtd, chipnr);
1493                 chip->cmdfunc(mtd, NAND_CMD_READ0, mtd->writesize, page);
1494                 block_mark = chip->read_byte(mtd);
1495                 chip->select_chip(mtd, -1);
1496
1497                 /*
1498                  * Check if the block is marked bad. If so, we need to mark it
1499                  * again, but this time the result will be a mark in the
1500                  * location where we transcribe block marks.
1501                  */
1502                 if (block_mark != 0xff) {
1503                         dev_dbg(dev, "Transcribing mark in block %u\n", block);
1504                         ret = chip->block_markbad(mtd, byte);
1505                         if (ret)
1506                                 dev_err(dev, "Failed to mark block bad with "
1507                                                         "ret %d\n", ret);
1508                 }
1509         }
1510
1511         /* Write the stamp that indicates we've transcribed the block marks. */
1512         mx23_write_transcription_stamp(this);
1513         return 0;
1514 }
1515
1516 static int nand_boot_init(struct gpmi_nand_data  *this)
1517 {
1518         nand_boot_set_geometry(this);
1519
1520         /* This is ROM arch-specific initilization before the BBT scanning. */
1521         if (GPMI_IS_MX23(this))
1522                 return mx23_boot_init(this);
1523         return 0;
1524 }
1525
1526 static int gpmi_set_geometry(struct gpmi_nand_data *this)
1527 {
1528         int ret;
1529
1530         /* Free the temporary DMA memory for reading ID. */
1531         gpmi_free_dma_buffer(this);
1532
1533         /* Set up the NFC geometry which is used by BCH. */
1534         ret = bch_set_geometry(this);
1535         if (ret) {
1536                 pr_err("Error setting BCH geometry : %d\n", ret);
1537                 return ret;
1538         }
1539
1540         /* Alloc the new DMA buffers according to the pagesize and oobsize */
1541         return gpmi_alloc_dma_buffer(this);
1542 }
1543
1544 static void gpmi_nand_exit(struct gpmi_nand_data *this)
1545 {
1546         nand_release(&this->mtd);
1547         gpmi_free_dma_buffer(this);
1548 }
1549
1550 static int gpmi_init_last(struct gpmi_nand_data *this)
1551 {
1552         struct mtd_info *mtd = &this->mtd;
1553         struct nand_chip *chip = mtd->priv;
1554         struct nand_ecc_ctrl *ecc = &chip->ecc;
1555         struct bch_geometry *bch_geo = &this->bch_geometry;
1556         int ret;
1557
1558         /* Set up swap_block_mark, must be set before the gpmi_set_geometry() */
1559         this->swap_block_mark = !GPMI_IS_MX23(this);
1560
1561         /* Set up the medium geometry */
1562         ret = gpmi_set_geometry(this);
1563         if (ret)
1564                 return ret;
1565
1566         /* Init the nand_ecc_ctrl{} */
1567         ecc->read_page  = gpmi_ecc_read_page;
1568         ecc->write_page = gpmi_ecc_write_page;
1569         ecc->read_oob   = gpmi_ecc_read_oob;
1570         ecc->write_oob  = gpmi_ecc_write_oob;
1571         ecc->mode       = NAND_ECC_HW;
1572         ecc->size       = bch_geo->ecc_chunk_size;
1573         ecc->strength   = bch_geo->ecc_strength;
1574         ecc->layout     = &gpmi_hw_ecclayout;
1575
1576         /*
1577          * Can we enable the extra features? such as EDO or Sync mode.
1578          *
1579          * We do not check the return value now. That's means if we fail in
1580          * enable the extra features, we still can run in the normal way.
1581          */
1582         gpmi_extra_init(this);
1583
1584         return 0;
1585 }
1586
1587 static int gpmi_nand_init(struct gpmi_nand_data *this)
1588 {
1589         struct mtd_info  *mtd = &this->mtd;
1590         struct nand_chip *chip = &this->nand;
1591         struct mtd_part_parser_data ppdata = {};
1592         int ret;
1593
1594         /* init current chip */
1595         this->current_chip      = -1;
1596
1597         /* init the MTD data structures */
1598         mtd->priv               = chip;
1599         mtd->name               = "gpmi-nand";
1600         mtd->owner              = THIS_MODULE;
1601
1602         /* init the nand_chip{}, we don't support a 16-bit NAND Flash bus. */
1603         chip->priv              = this;
1604         chip->select_chip       = gpmi_select_chip;
1605         chip->cmd_ctrl          = gpmi_cmd_ctrl;
1606         chip->dev_ready         = gpmi_dev_ready;
1607         chip->read_byte         = gpmi_read_byte;
1608         chip->read_buf          = gpmi_read_buf;
1609         chip->write_buf         = gpmi_write_buf;
1610         chip->badblock_pattern  = &gpmi_bbt_descr;
1611         chip->block_markbad     = gpmi_block_markbad;
1612         chip->options           |= NAND_NO_SUBPAGE_WRITE;
1613         if (of_get_nand_on_flash_bbt(this->dev->of_node))
1614                 chip->bbt_options |= NAND_BBT_USE_FLASH | NAND_BBT_NO_OOB;
1615
1616         /*
1617          * Allocate a temporary DMA buffer for reading ID in the
1618          * nand_scan_ident().
1619          */
1620         this->bch_geometry.payload_size = 1024;
1621         this->bch_geometry.auxiliary_size = 128;
1622         ret = gpmi_alloc_dma_buffer(this);
1623         if (ret)
1624                 goto err_out;
1625
1626         ret = nand_scan_ident(mtd, GPMI_IS_MX6Q(this) ? 2 : 1, NULL);
1627         if (ret)
1628                 goto err_out;
1629
1630         ret = gpmi_init_last(this);
1631         if (ret)
1632                 goto err_out;
1633
1634         chip->options |= NAND_SKIP_BBTSCAN;
1635         ret = nand_scan_tail(mtd);
1636         if (ret)
1637                 goto err_out;
1638
1639         ret = nand_boot_init(this);
1640         if (ret)
1641                 goto err_out;
1642         chip->scan_bbt(mtd);
1643
1644         ppdata.of_node = this->pdev->dev.of_node;
1645         ret = mtd_device_parse_register(mtd, NULL, &ppdata, NULL, 0);
1646         if (ret)
1647                 goto err_out;
1648         return 0;
1649
1650 err_out:
1651         gpmi_nand_exit(this);
1652         return ret;
1653 }
1654
1655 static const struct platform_device_id gpmi_ids[] = {
1656         { .name = "imx23-gpmi-nand", .driver_data = IS_MX23, },
1657         { .name = "imx28-gpmi-nand", .driver_data = IS_MX28, },
1658         { .name = "imx6q-gpmi-nand", .driver_data = IS_MX6Q, },
1659         {}
1660 };
1661
1662 static const struct of_device_id gpmi_nand_id_table[] = {
1663         {
1664                 .compatible = "fsl,imx23-gpmi-nand",
1665                 .data = (void *)&gpmi_ids[IS_MX23],
1666         }, {
1667                 .compatible = "fsl,imx28-gpmi-nand",
1668                 .data = (void *)&gpmi_ids[IS_MX28],
1669         }, {
1670                 .compatible = "fsl,imx6q-gpmi-nand",
1671                 .data = (void *)&gpmi_ids[IS_MX6Q],
1672         }, {}
1673 };
1674 MODULE_DEVICE_TABLE(of, gpmi_nand_id_table);
1675
1676 static int gpmi_nand_probe(struct platform_device *pdev)
1677 {
1678         struct gpmi_nand_data *this;
1679         const struct of_device_id *of_id;
1680         int ret;
1681
1682         of_id = of_match_device(gpmi_nand_id_table, &pdev->dev);
1683         if (of_id) {
1684                 pdev->id_entry = of_id->data;
1685         } else {
1686                 pr_err("Failed to find the right device id.\n");
1687                 return -ENODEV;
1688         }
1689
1690         this = devm_kzalloc(&pdev->dev, sizeof(*this), GFP_KERNEL);
1691         if (!this) {
1692                 pr_err("Failed to allocate per-device memory\n");
1693                 return -ENOMEM;
1694         }
1695
1696         platform_set_drvdata(pdev, this);
1697         this->pdev  = pdev;
1698         this->dev   = &pdev->dev;
1699
1700         ret = acquire_resources(this);
1701         if (ret)
1702                 goto exit_acquire_resources;
1703
1704         ret = init_hardware(this);
1705         if (ret)
1706                 goto exit_nfc_init;
1707
1708         ret = gpmi_nand_init(this);
1709         if (ret)
1710                 goto exit_nfc_init;
1711
1712         dev_info(this->dev, "driver registered.\n");
1713
1714         return 0;
1715
1716 exit_nfc_init:
1717         release_resources(this);
1718 exit_acquire_resources:
1719         dev_err(this->dev, "driver registration failed: %d\n", ret);
1720
1721         return ret;
1722 }
1723
1724 static int gpmi_nand_remove(struct platform_device *pdev)
1725 {
1726         struct gpmi_nand_data *this = platform_get_drvdata(pdev);
1727
1728         gpmi_nand_exit(this);
1729         release_resources(this);
1730         return 0;
1731 }
1732
1733 static struct platform_driver gpmi_nand_driver = {
1734         .driver = {
1735                 .name = "gpmi-nand",
1736                 .of_match_table = gpmi_nand_id_table,
1737         },
1738         .probe   = gpmi_nand_probe,
1739         .remove  = gpmi_nand_remove,
1740         .id_table = gpmi_ids,
1741 };
1742 module_platform_driver(gpmi_nand_driver);
1743
1744 MODULE_AUTHOR("Freescale Semiconductor, Inc.");
1745 MODULE_DESCRIPTION("i.MX GPMI NAND Flash Controller Driver");
1746 MODULE_LICENSE("GPL");