]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/mtd/nand/gpmi-nand/gpmi-nand.c
mtd: gpmi: use devm_request_irq
[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         const char *res_name = GPMI_NAND_BCH_INTERRUPT_RES_NAME;
507         struct resource *r;
508         int err;
509
510         r = platform_get_resource_byname(pdev, IORESOURCE_IRQ, res_name);
511         if (!r) {
512                 pr_err("Can't get resource for %s\n", res_name);
513                 return -ENODEV;
514         }
515
516         err = devm_request_irq(this->dev, r->start, irq_h, 0, res_name, this);
517         if (err)
518                 dev_err(this->dev, "error requesting BCH IRQ\n");
519
520         return err;
521 }
522
523 static void release_dma_channels(struct gpmi_nand_data *this)
524 {
525         unsigned int i;
526         for (i = 0; i < DMA_CHANS; i++)
527                 if (this->dma_chans[i]) {
528                         dma_release_channel(this->dma_chans[i]);
529                         this->dma_chans[i] = NULL;
530                 }
531 }
532
533 static int acquire_dma_channels(struct gpmi_nand_data *this)
534 {
535         struct platform_device *pdev = this->pdev;
536         struct dma_chan *dma_chan;
537
538         /* request dma channel */
539         dma_chan = dma_request_slave_channel(&pdev->dev, "rx-tx");
540         if (!dma_chan) {
541                 pr_err("Failed to request DMA channel.\n");
542                 goto acquire_err;
543         }
544
545         this->dma_chans[0] = dma_chan;
546         return 0;
547
548 acquire_err:
549         release_dma_channels(this);
550         return -EINVAL;
551 }
552
553 static char *extra_clks_for_mx6q[GPMI_CLK_MAX] = {
554         "gpmi_apb", "gpmi_bch", "gpmi_bch_apb", "per1_bch",
555 };
556
557 static int gpmi_get_clks(struct gpmi_nand_data *this)
558 {
559         struct resources *r = &this->resources;
560         char **extra_clks = NULL;
561         struct clk *clk;
562         int err, i;
563
564         /* The main clock is stored in the first. */
565         r->clock[0] = devm_clk_get(this->dev, "gpmi_io");
566         if (IS_ERR(r->clock[0])) {
567                 err = PTR_ERR(r->clock[0]);
568                 goto err_clock;
569         }
570
571         /* Get extra clocks */
572         if (GPMI_IS_MX6Q(this))
573                 extra_clks = extra_clks_for_mx6q;
574         if (!extra_clks)
575                 return 0;
576
577         for (i = 1; i < GPMI_CLK_MAX; i++) {
578                 if (extra_clks[i - 1] == NULL)
579                         break;
580
581                 clk = devm_clk_get(this->dev, extra_clks[i - 1]);
582                 if (IS_ERR(clk)) {
583                         err = PTR_ERR(clk);
584                         goto err_clock;
585                 }
586
587                 r->clock[i] = clk;
588         }
589
590         if (GPMI_IS_MX6Q(this))
591                 /*
592                  * Set the default value for the gpmi clock in mx6q:
593                  *
594                  * If you want to use the ONFI nand which is in the
595                  * Synchronous Mode, you should change the clock as you need.
596                  */
597                 clk_set_rate(r->clock[0], 22000000);
598
599         return 0;
600
601 err_clock:
602         dev_dbg(this->dev, "failed in finding the clocks.\n");
603         return err;
604 }
605
606 static int acquire_resources(struct gpmi_nand_data *this)
607 {
608         int ret;
609
610         ret = acquire_register_block(this, GPMI_NAND_GPMI_REGS_ADDR_RES_NAME);
611         if (ret)
612                 goto exit_regs;
613
614         ret = acquire_register_block(this, GPMI_NAND_BCH_REGS_ADDR_RES_NAME);
615         if (ret)
616                 goto exit_regs;
617
618         ret = acquire_bch_irq(this, bch_irq);
619         if (ret)
620                 goto exit_regs;
621
622         ret = acquire_dma_channels(this);
623         if (ret)
624                 goto exit_regs;
625
626         ret = gpmi_get_clks(this);
627         if (ret)
628                 goto exit_clock;
629         return 0;
630
631 exit_clock:
632         release_dma_channels(this);
633 exit_regs:
634         return ret;
635 }
636
637 static void release_resources(struct gpmi_nand_data *this)
638 {
639         release_dma_channels(this);
640 }
641
642 static int init_hardware(struct gpmi_nand_data *this)
643 {
644         int ret;
645
646         /*
647          * This structure contains the "safe" GPMI timing that should succeed
648          * with any NAND Flash device
649          * (although, with less-than-optimal performance).
650          */
651         struct nand_timing  safe_timing = {
652                 .data_setup_in_ns        = 80,
653                 .data_hold_in_ns         = 60,
654                 .address_setup_in_ns     = 25,
655                 .gpmi_sample_delay_in_ns =  6,
656                 .tREA_in_ns              = -1,
657                 .tRLOH_in_ns             = -1,
658                 .tRHOH_in_ns             = -1,
659         };
660
661         /* Initialize the hardwares. */
662         ret = gpmi_init(this);
663         if (ret)
664                 return ret;
665
666         this->timing = safe_timing;
667         return 0;
668 }
669
670 static int read_page_prepare(struct gpmi_nand_data *this,
671                         void *destination, unsigned length,
672                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
673                         void **use_virt, dma_addr_t *use_phys)
674 {
675         struct device *dev = this->dev;
676
677         if (virt_addr_valid(destination)) {
678                 dma_addr_t dest_phys;
679
680                 dest_phys = dma_map_single(dev, destination,
681                                                 length, DMA_FROM_DEVICE);
682                 if (dma_mapping_error(dev, dest_phys)) {
683                         if (alt_size < length) {
684                                 pr_err("%s, Alternate buffer is too small\n",
685                                         __func__);
686                                 return -ENOMEM;
687                         }
688                         goto map_failed;
689                 }
690                 *use_virt = destination;
691                 *use_phys = dest_phys;
692                 this->direct_dma_map_ok = true;
693                 return 0;
694         }
695
696 map_failed:
697         *use_virt = alt_virt;
698         *use_phys = alt_phys;
699         this->direct_dma_map_ok = false;
700         return 0;
701 }
702
703 static inline void read_page_end(struct gpmi_nand_data *this,
704                         void *destination, unsigned length,
705                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
706                         void *used_virt, dma_addr_t used_phys)
707 {
708         if (this->direct_dma_map_ok)
709                 dma_unmap_single(this->dev, used_phys, length, DMA_FROM_DEVICE);
710 }
711
712 static inline void read_page_swap_end(struct gpmi_nand_data *this,
713                         void *destination, unsigned length,
714                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
715                         void *used_virt, dma_addr_t used_phys)
716 {
717         if (!this->direct_dma_map_ok)
718                 memcpy(destination, alt_virt, length);
719 }
720
721 static int send_page_prepare(struct gpmi_nand_data *this,
722                         const void *source, unsigned length,
723                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
724                         const void **use_virt, dma_addr_t *use_phys)
725 {
726         struct device *dev = this->dev;
727
728         if (virt_addr_valid(source)) {
729                 dma_addr_t source_phys;
730
731                 source_phys = dma_map_single(dev, (void *)source, length,
732                                                 DMA_TO_DEVICE);
733                 if (dma_mapping_error(dev, source_phys)) {
734                         if (alt_size < length) {
735                                 pr_err("%s, Alternate buffer is too small\n",
736                                         __func__);
737                                 return -ENOMEM;
738                         }
739                         goto map_failed;
740                 }
741                 *use_virt = source;
742                 *use_phys = source_phys;
743                 return 0;
744         }
745 map_failed:
746         /*
747          * Copy the content of the source buffer into the alternate
748          * buffer and set up the return values accordingly.
749          */
750         memcpy(alt_virt, source, length);
751
752         *use_virt = alt_virt;
753         *use_phys = alt_phys;
754         return 0;
755 }
756
757 static void send_page_end(struct gpmi_nand_data *this,
758                         const void *source, unsigned length,
759                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
760                         const void *used_virt, dma_addr_t used_phys)
761 {
762         struct device *dev = this->dev;
763         if (used_virt == source)
764                 dma_unmap_single(dev, used_phys, length, DMA_TO_DEVICE);
765 }
766
767 static void gpmi_free_dma_buffer(struct gpmi_nand_data *this)
768 {
769         struct device *dev = this->dev;
770
771         if (this->page_buffer_virt && virt_addr_valid(this->page_buffer_virt))
772                 dma_free_coherent(dev, this->page_buffer_size,
773                                         this->page_buffer_virt,
774                                         this->page_buffer_phys);
775         kfree(this->cmd_buffer);
776         kfree(this->data_buffer_dma);
777
778         this->cmd_buffer        = NULL;
779         this->data_buffer_dma   = NULL;
780         this->page_buffer_virt  = NULL;
781         this->page_buffer_size  =  0;
782 }
783
784 /* Allocate the DMA buffers */
785 static int gpmi_alloc_dma_buffer(struct gpmi_nand_data *this)
786 {
787         struct bch_geometry *geo = &this->bch_geometry;
788         struct device *dev = this->dev;
789
790         /* [1] Allocate a command buffer. PAGE_SIZE is enough. */
791         this->cmd_buffer = kzalloc(PAGE_SIZE, GFP_DMA | GFP_KERNEL);
792         if (this->cmd_buffer == NULL)
793                 goto error_alloc;
794
795         /* [2] Allocate a read/write data buffer. PAGE_SIZE is enough. */
796         this->data_buffer_dma = kzalloc(PAGE_SIZE, GFP_DMA | GFP_KERNEL);
797         if (this->data_buffer_dma == NULL)
798                 goto error_alloc;
799
800         /*
801          * [3] Allocate the page buffer.
802          *
803          * Both the payload buffer and the auxiliary buffer must appear on
804          * 32-bit boundaries. We presume the size of the payload buffer is a
805          * power of two and is much larger than four, which guarantees the
806          * auxiliary buffer will appear on a 32-bit boundary.
807          */
808         this->page_buffer_size = geo->payload_size + geo->auxiliary_size;
809         this->page_buffer_virt = dma_alloc_coherent(dev, this->page_buffer_size,
810                                         &this->page_buffer_phys, GFP_DMA);
811         if (!this->page_buffer_virt)
812                 goto error_alloc;
813
814
815         /* Slice up the page buffer. */
816         this->payload_virt = this->page_buffer_virt;
817         this->payload_phys = this->page_buffer_phys;
818         this->auxiliary_virt = this->payload_virt + geo->payload_size;
819         this->auxiliary_phys = this->payload_phys + geo->payload_size;
820         return 0;
821
822 error_alloc:
823         gpmi_free_dma_buffer(this);
824         pr_err("Error allocating DMA buffers!\n");
825         return -ENOMEM;
826 }
827
828 static void gpmi_cmd_ctrl(struct mtd_info *mtd, int data, unsigned int ctrl)
829 {
830         struct nand_chip *chip = mtd->priv;
831         struct gpmi_nand_data *this = chip->priv;
832         int ret;
833
834         /*
835          * Every operation begins with a command byte and a series of zero or
836          * more address bytes. These are distinguished by either the Address
837          * Latch Enable (ALE) or Command Latch Enable (CLE) signals being
838          * asserted. When MTD is ready to execute the command, it will deassert
839          * both latch enables.
840          *
841          * Rather than run a separate DMA operation for every single byte, we
842          * queue them up and run a single DMA operation for the entire series
843          * of command and data bytes. NAND_CMD_NONE means the END of the queue.
844          */
845         if ((ctrl & (NAND_ALE | NAND_CLE))) {
846                 if (data != NAND_CMD_NONE)
847                         this->cmd_buffer[this->command_length++] = data;
848                 return;
849         }
850
851         if (!this->command_length)
852                 return;
853
854         ret = gpmi_send_command(this);
855         if (ret)
856                 pr_err("Chip: %u, Error %d\n", this->current_chip, ret);
857
858         this->command_length = 0;
859 }
860
861 static int gpmi_dev_ready(struct mtd_info *mtd)
862 {
863         struct nand_chip *chip = mtd->priv;
864         struct gpmi_nand_data *this = chip->priv;
865
866         return gpmi_is_ready(this, this->current_chip);
867 }
868
869 static void gpmi_select_chip(struct mtd_info *mtd, int chipnr)
870 {
871         struct nand_chip *chip = mtd->priv;
872         struct gpmi_nand_data *this = chip->priv;
873
874         if ((this->current_chip < 0) && (chipnr >= 0))
875                 gpmi_begin(this);
876         else if ((this->current_chip >= 0) && (chipnr < 0))
877                 gpmi_end(this);
878
879         this->current_chip = chipnr;
880 }
881
882 static void gpmi_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
883 {
884         struct nand_chip *chip = mtd->priv;
885         struct gpmi_nand_data *this = chip->priv;
886
887         pr_debug("len is %d\n", len);
888         this->upper_buf = buf;
889         this->upper_len = len;
890
891         gpmi_read_data(this);
892 }
893
894 static void gpmi_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
895 {
896         struct nand_chip *chip = mtd->priv;
897         struct gpmi_nand_data *this = chip->priv;
898
899         pr_debug("len is %d\n", len);
900         this->upper_buf = (uint8_t *)buf;
901         this->upper_len = len;
902
903         gpmi_send_data(this);
904 }
905
906 static uint8_t gpmi_read_byte(struct mtd_info *mtd)
907 {
908         struct nand_chip *chip = mtd->priv;
909         struct gpmi_nand_data *this = chip->priv;
910         uint8_t *buf = this->data_buffer_dma;
911
912         gpmi_read_buf(mtd, buf, 1);
913         return buf[0];
914 }
915
916 /*
917  * Handles block mark swapping.
918  * It can be called in swapping the block mark, or swapping it back,
919  * because the the operations are the same.
920  */
921 static void block_mark_swapping(struct gpmi_nand_data *this,
922                                 void *payload, void *auxiliary)
923 {
924         struct bch_geometry *nfc_geo = &this->bch_geometry;
925         unsigned char *p;
926         unsigned char *a;
927         unsigned int  bit;
928         unsigned char mask;
929         unsigned char from_data;
930         unsigned char from_oob;
931
932         if (!this->swap_block_mark)
933                 return;
934
935         /*
936          * If control arrives here, we're swapping. Make some convenience
937          * variables.
938          */
939         bit = nfc_geo->block_mark_bit_offset;
940         p   = payload + nfc_geo->block_mark_byte_offset;
941         a   = auxiliary;
942
943         /*
944          * Get the byte from the data area that overlays the block mark. Since
945          * the ECC engine applies its own view to the bits in the page, the
946          * physical block mark won't (in general) appear on a byte boundary in
947          * the data.
948          */
949         from_data = (p[0] >> bit) | (p[1] << (8 - bit));
950
951         /* Get the byte from the OOB. */
952         from_oob = a[0];
953
954         /* Swap them. */
955         a[0] = from_data;
956
957         mask = (0x1 << bit) - 1;
958         p[0] = (p[0] & mask) | (from_oob << bit);
959
960         mask = ~0 << bit;
961         p[1] = (p[1] & mask) | (from_oob >> (8 - bit));
962 }
963
964 static int gpmi_ecc_read_page(struct mtd_info *mtd, struct nand_chip *chip,
965                                 uint8_t *buf, int oob_required, int page)
966 {
967         struct gpmi_nand_data *this = chip->priv;
968         struct bch_geometry *nfc_geo = &this->bch_geometry;
969         void          *payload_virt;
970         dma_addr_t    payload_phys;
971         void          *auxiliary_virt;
972         dma_addr_t    auxiliary_phys;
973         unsigned int  i;
974         unsigned char *status;
975         unsigned int  max_bitflips = 0;
976         int           ret;
977
978         pr_debug("page number is : %d\n", page);
979         ret = read_page_prepare(this, buf, mtd->writesize,
980                                         this->payload_virt, this->payload_phys,
981                                         nfc_geo->payload_size,
982                                         &payload_virt, &payload_phys);
983         if (ret) {
984                 pr_err("Inadequate DMA buffer\n");
985                 ret = -ENOMEM;
986                 return ret;
987         }
988         auxiliary_virt = this->auxiliary_virt;
989         auxiliary_phys = this->auxiliary_phys;
990
991         /* go! */
992         ret = gpmi_read_page(this, payload_phys, auxiliary_phys);
993         read_page_end(this, buf, mtd->writesize,
994                         this->payload_virt, this->payload_phys,
995                         nfc_geo->payload_size,
996                         payload_virt, payload_phys);
997         if (ret) {
998                 pr_err("Error in ECC-based read: %d\n", ret);
999                 return ret;
1000         }
1001
1002         /* handle the block mark swapping */
1003         block_mark_swapping(this, payload_virt, auxiliary_virt);
1004
1005         /* Loop over status bytes, accumulating ECC status. */
1006         status = auxiliary_virt + nfc_geo->auxiliary_status_offset;
1007
1008         for (i = 0; i < nfc_geo->ecc_chunk_count; i++, status++) {
1009                 if ((*status == STATUS_GOOD) || (*status == STATUS_ERASED))
1010                         continue;
1011
1012                 if (*status == STATUS_UNCORRECTABLE) {
1013                         mtd->ecc_stats.failed++;
1014                         continue;
1015                 }
1016                 mtd->ecc_stats.corrected += *status;
1017                 max_bitflips = max_t(unsigned int, max_bitflips, *status);
1018         }
1019
1020         if (oob_required) {
1021                 /*
1022                  * It's time to deliver the OOB bytes. See gpmi_ecc_read_oob()
1023                  * for details about our policy for delivering the OOB.
1024                  *
1025                  * We fill the caller's buffer with set bits, and then copy the
1026                  * block mark to th caller's buffer. Note that, if block mark
1027                  * swapping was necessary, it has already been done, so we can
1028                  * rely on the first byte of the auxiliary buffer to contain
1029                  * the block mark.
1030                  */
1031                 memset(chip->oob_poi, ~0, mtd->oobsize);
1032                 chip->oob_poi[0] = ((uint8_t *) auxiliary_virt)[0];
1033         }
1034
1035         read_page_swap_end(this, buf, mtd->writesize,
1036                         this->payload_virt, this->payload_phys,
1037                         nfc_geo->payload_size,
1038                         payload_virt, payload_phys);
1039
1040         return max_bitflips;
1041 }
1042
1043 static int gpmi_ecc_write_page(struct mtd_info *mtd, struct nand_chip *chip,
1044                                 const uint8_t *buf, int oob_required)
1045 {
1046         struct gpmi_nand_data *this = chip->priv;
1047         struct bch_geometry *nfc_geo = &this->bch_geometry;
1048         const void *payload_virt;
1049         dma_addr_t payload_phys;
1050         const void *auxiliary_virt;
1051         dma_addr_t auxiliary_phys;
1052         int        ret;
1053
1054         pr_debug("ecc write page.\n");
1055         if (this->swap_block_mark) {
1056                 /*
1057                  * If control arrives here, we're doing block mark swapping.
1058                  * Since we can't modify the caller's buffers, we must copy them
1059                  * into our own.
1060                  */
1061                 memcpy(this->payload_virt, buf, mtd->writesize);
1062                 payload_virt = this->payload_virt;
1063                 payload_phys = this->payload_phys;
1064
1065                 memcpy(this->auxiliary_virt, chip->oob_poi,
1066                                 nfc_geo->auxiliary_size);
1067                 auxiliary_virt = this->auxiliary_virt;
1068                 auxiliary_phys = this->auxiliary_phys;
1069
1070                 /* Handle block mark swapping. */
1071                 block_mark_swapping(this,
1072                                 (void *) payload_virt, (void *) auxiliary_virt);
1073         } else {
1074                 /*
1075                  * If control arrives here, we're not doing block mark swapping,
1076                  * so we can to try and use the caller's buffers.
1077                  */
1078                 ret = send_page_prepare(this,
1079                                 buf, mtd->writesize,
1080                                 this->payload_virt, this->payload_phys,
1081                                 nfc_geo->payload_size,
1082                                 &payload_virt, &payload_phys);
1083                 if (ret) {
1084                         pr_err("Inadequate payload DMA buffer\n");
1085                         return 0;
1086                 }
1087
1088                 ret = send_page_prepare(this,
1089                                 chip->oob_poi, mtd->oobsize,
1090                                 this->auxiliary_virt, this->auxiliary_phys,
1091                                 nfc_geo->auxiliary_size,
1092                                 &auxiliary_virt, &auxiliary_phys);
1093                 if (ret) {
1094                         pr_err("Inadequate auxiliary DMA buffer\n");
1095                         goto exit_auxiliary;
1096                 }
1097         }
1098
1099         /* Ask the NFC. */
1100         ret = gpmi_send_page(this, payload_phys, auxiliary_phys);
1101         if (ret)
1102                 pr_err("Error in ECC-based write: %d\n", ret);
1103
1104         if (!this->swap_block_mark) {
1105                 send_page_end(this, chip->oob_poi, mtd->oobsize,
1106                                 this->auxiliary_virt, this->auxiliary_phys,
1107                                 nfc_geo->auxiliary_size,
1108                                 auxiliary_virt, auxiliary_phys);
1109 exit_auxiliary:
1110                 send_page_end(this, buf, mtd->writesize,
1111                                 this->payload_virt, this->payload_phys,
1112                                 nfc_geo->payload_size,
1113                                 payload_virt, payload_phys);
1114         }
1115
1116         return 0;
1117 }
1118
1119 /*
1120  * There are several places in this driver where we have to handle the OOB and
1121  * block marks. This is the function where things are the most complicated, so
1122  * this is where we try to explain it all. All the other places refer back to
1123  * here.
1124  *
1125  * These are the rules, in order of decreasing importance:
1126  *
1127  * 1) Nothing the caller does can be allowed to imperil the block mark.
1128  *
1129  * 2) In read operations, the first byte of the OOB we return must reflect the
1130  *    true state of the block mark, no matter where that block mark appears in
1131  *    the physical page.
1132  *
1133  * 3) ECC-based read operations return an OOB full of set bits (since we never
1134  *    allow ECC-based writes to the OOB, it doesn't matter what ECC-based reads
1135  *    return).
1136  *
1137  * 4) "Raw" read operations return a direct view of the physical bytes in the
1138  *    page, using the conventional definition of which bytes are data and which
1139  *    are OOB. This gives the caller a way to see the actual, physical bytes
1140  *    in the page, without the distortions applied by our ECC engine.
1141  *
1142  *
1143  * What we do for this specific read operation depends on two questions:
1144  *
1145  * 1) Are we doing a "raw" read, or an ECC-based read?
1146  *
1147  * 2) Are we using block mark swapping or transcription?
1148  *
1149  * There are four cases, illustrated by the following Karnaugh map:
1150  *
1151  *                    |           Raw           |         ECC-based       |
1152  *       -------------+-------------------------+-------------------------+
1153  *                    | Read the conventional   |                         |
1154  *                    | OOB at the end of the   |                         |
1155  *       Swapping     | page and return it. It  |                         |
1156  *                    | contains exactly what   |                         |
1157  *                    | we want.                | Read the block mark and |
1158  *       -------------+-------------------------+ return it in a buffer   |
1159  *                    | Read the conventional   | full of set bits.       |
1160  *                    | OOB at the end of the   |                         |
1161  *                    | page and also the block |                         |
1162  *       Transcribing | mark in the metadata.   |                         |
1163  *                    | Copy the block mark     |                         |
1164  *                    | into the first byte of  |                         |
1165  *                    | the OOB.                |                         |
1166  *       -------------+-------------------------+-------------------------+
1167  *
1168  * Note that we break rule #4 in the Transcribing/Raw case because we're not
1169  * giving an accurate view of the actual, physical bytes in the page (we're
1170  * overwriting the block mark). That's OK because it's more important to follow
1171  * rule #2.
1172  *
1173  * It turns out that knowing whether we want an "ECC-based" or "raw" read is not
1174  * easy. When reading a page, for example, the NAND Flash MTD code calls our
1175  * ecc.read_page or ecc.read_page_raw function. Thus, the fact that MTD wants an
1176  * ECC-based or raw view of the page is implicit in which function it calls
1177  * (there is a similar pair of ECC-based/raw functions for writing).
1178  *
1179  * FIXME: The following paragraph is incorrect, now that there exist
1180  * ecc.read_oob_raw and ecc.write_oob_raw functions.
1181  *
1182  * Since MTD assumes the OOB is not covered by ECC, there is no pair of
1183  * ECC-based/raw functions for reading or or writing the OOB. The fact that the
1184  * caller wants an ECC-based or raw view of the page is not propagated down to
1185  * this driver.
1186  */
1187 static int gpmi_ecc_read_oob(struct mtd_info *mtd, struct nand_chip *chip,
1188                                 int page)
1189 {
1190         struct gpmi_nand_data *this = chip->priv;
1191
1192         pr_debug("page number is %d\n", page);
1193         /* clear the OOB buffer */
1194         memset(chip->oob_poi, ~0, mtd->oobsize);
1195
1196         /* Read out the conventional OOB. */
1197         chip->cmdfunc(mtd, NAND_CMD_READ0, mtd->writesize, page);
1198         chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1199
1200         /*
1201          * Now, we want to make sure the block mark is correct. In the
1202          * Swapping/Raw case, we already have it. Otherwise, we need to
1203          * explicitly read it.
1204          */
1205         if (!this->swap_block_mark) {
1206                 /* Read the block mark into the first byte of the OOB buffer. */
1207                 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1208                 chip->oob_poi[0] = chip->read_byte(mtd);
1209         }
1210
1211         return 0;
1212 }
1213
1214 static int
1215 gpmi_ecc_write_oob(struct mtd_info *mtd, struct nand_chip *chip, int page)
1216 {
1217         struct nand_oobfree *of = mtd->ecclayout->oobfree;
1218         int status = 0;
1219
1220         /* Do we have available oob area? */
1221         if (!of->length)
1222                 return -EPERM;
1223
1224         if (!nand_is_slc(chip))
1225                 return -EPERM;
1226
1227         chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize + of->offset, page);
1228         chip->write_buf(mtd, chip->oob_poi + of->offset, of->length);
1229         chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1230
1231         status = chip->waitfunc(mtd, chip);
1232         return status & NAND_STATUS_FAIL ? -EIO : 0;
1233 }
1234
1235 static int gpmi_block_markbad(struct mtd_info *mtd, loff_t ofs)
1236 {
1237         struct nand_chip *chip = mtd->priv;
1238         struct gpmi_nand_data *this = chip->priv;
1239         int ret = 0;
1240         uint8_t *block_mark;
1241         int column, page, status, chipnr;
1242
1243         chipnr = (int)(ofs >> chip->chip_shift);
1244         chip->select_chip(mtd, chipnr);
1245
1246         column = this->swap_block_mark ? mtd->writesize : 0;
1247
1248         /* Write the block mark. */
1249         block_mark = this->data_buffer_dma;
1250         block_mark[0] = 0; /* bad block marker */
1251
1252         /* Shift to get page */
1253         page = (int)(ofs >> chip->page_shift);
1254
1255         chip->cmdfunc(mtd, NAND_CMD_SEQIN, column, page);
1256         chip->write_buf(mtd, block_mark, 1);
1257         chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1258
1259         status = chip->waitfunc(mtd, chip);
1260         if (status & NAND_STATUS_FAIL)
1261                 ret = -EIO;
1262
1263         chip->select_chip(mtd, -1);
1264
1265         return ret;
1266 }
1267
1268 static int nand_boot_set_geometry(struct gpmi_nand_data *this)
1269 {
1270         struct boot_rom_geometry *geometry = &this->rom_geometry;
1271
1272         /*
1273          * Set the boot block stride size.
1274          *
1275          * In principle, we should be reading this from the OTP bits, since
1276          * that's where the ROM is going to get it. In fact, we don't have any
1277          * way to read the OTP bits, so we go with the default and hope for the
1278          * best.
1279          */
1280         geometry->stride_size_in_pages = 64;
1281
1282         /*
1283          * Set the search area stride exponent.
1284          *
1285          * In principle, we should be reading this from the OTP bits, since
1286          * that's where the ROM is going to get it. In fact, we don't have any
1287          * way to read the OTP bits, so we go with the default and hope for the
1288          * best.
1289          */
1290         geometry->search_area_stride_exponent = 2;
1291         return 0;
1292 }
1293
1294 static const char  *fingerprint = "STMP";
1295 static int mx23_check_transcription_stamp(struct gpmi_nand_data *this)
1296 {
1297         struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1298         struct device *dev = this->dev;
1299         struct mtd_info *mtd = &this->mtd;
1300         struct nand_chip *chip = &this->nand;
1301         unsigned int search_area_size_in_strides;
1302         unsigned int stride;
1303         unsigned int page;
1304         uint8_t *buffer = chip->buffers->databuf;
1305         int saved_chip_number;
1306         int found_an_ncb_fingerprint = false;
1307
1308         /* Compute the number of strides in a search area. */
1309         search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1310
1311         saved_chip_number = this->current_chip;
1312         chip->select_chip(mtd, 0);
1313
1314         /*
1315          * Loop through the first search area, looking for the NCB fingerprint.
1316          */
1317         dev_dbg(dev, "Scanning for an NCB fingerprint...\n");
1318
1319         for (stride = 0; stride < search_area_size_in_strides; stride++) {
1320                 /* Compute the page addresses. */
1321                 page = stride * rom_geo->stride_size_in_pages;
1322
1323                 dev_dbg(dev, "Looking for a fingerprint in page 0x%x\n", page);
1324
1325                 /*
1326                  * Read the NCB fingerprint. The fingerprint is four bytes long
1327                  * and starts in the 12th byte of the page.
1328                  */
1329                 chip->cmdfunc(mtd, NAND_CMD_READ0, 12, page);
1330                 chip->read_buf(mtd, buffer, strlen(fingerprint));
1331
1332                 /* Look for the fingerprint. */
1333                 if (!memcmp(buffer, fingerprint, strlen(fingerprint))) {
1334                         found_an_ncb_fingerprint = true;
1335                         break;
1336                 }
1337
1338         }
1339
1340         chip->select_chip(mtd, saved_chip_number);
1341
1342         if (found_an_ncb_fingerprint)
1343                 dev_dbg(dev, "\tFound a fingerprint\n");
1344         else
1345                 dev_dbg(dev, "\tNo fingerprint found\n");
1346         return found_an_ncb_fingerprint;
1347 }
1348
1349 /* Writes a transcription stamp. */
1350 static int mx23_write_transcription_stamp(struct gpmi_nand_data *this)
1351 {
1352         struct device *dev = this->dev;
1353         struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1354         struct mtd_info *mtd = &this->mtd;
1355         struct nand_chip *chip = &this->nand;
1356         unsigned int block_size_in_pages;
1357         unsigned int search_area_size_in_strides;
1358         unsigned int search_area_size_in_pages;
1359         unsigned int search_area_size_in_blocks;
1360         unsigned int block;
1361         unsigned int stride;
1362         unsigned int page;
1363         uint8_t      *buffer = chip->buffers->databuf;
1364         int saved_chip_number;
1365         int status;
1366
1367         /* Compute the search area geometry. */
1368         block_size_in_pages = mtd->erasesize / mtd->writesize;
1369         search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1370         search_area_size_in_pages = search_area_size_in_strides *
1371                                         rom_geo->stride_size_in_pages;
1372         search_area_size_in_blocks =
1373                   (search_area_size_in_pages + (block_size_in_pages - 1)) /
1374                                     block_size_in_pages;
1375
1376         dev_dbg(dev, "Search Area Geometry :\n");
1377         dev_dbg(dev, "\tin Blocks : %u\n", search_area_size_in_blocks);
1378         dev_dbg(dev, "\tin Strides: %u\n", search_area_size_in_strides);
1379         dev_dbg(dev, "\tin Pages  : %u\n", search_area_size_in_pages);
1380
1381         /* Select chip 0. */
1382         saved_chip_number = this->current_chip;
1383         chip->select_chip(mtd, 0);
1384
1385         /* Loop over blocks in the first search area, erasing them. */
1386         dev_dbg(dev, "Erasing the search area...\n");
1387
1388         for (block = 0; block < search_area_size_in_blocks; block++) {
1389                 /* Compute the page address. */
1390                 page = block * block_size_in_pages;
1391
1392                 /* Erase this block. */
1393                 dev_dbg(dev, "\tErasing block 0x%x\n", block);
1394                 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1395                 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1396
1397                 /* Wait for the erase to finish. */
1398                 status = chip->waitfunc(mtd, chip);
1399                 if (status & NAND_STATUS_FAIL)
1400                         dev_err(dev, "[%s] Erase failed.\n", __func__);
1401         }
1402
1403         /* Write the NCB fingerprint into the page buffer. */
1404         memset(buffer, ~0, mtd->writesize);
1405         memcpy(buffer + 12, fingerprint, strlen(fingerprint));
1406
1407         /* Loop through the first search area, writing NCB fingerprints. */
1408         dev_dbg(dev, "Writing NCB fingerprints...\n");
1409         for (stride = 0; stride < search_area_size_in_strides; stride++) {
1410                 /* Compute the page addresses. */
1411                 page = stride * rom_geo->stride_size_in_pages;
1412
1413                 /* Write the first page of the current stride. */
1414                 dev_dbg(dev, "Writing an NCB fingerprint in page 0x%x\n", page);
1415                 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
1416                 chip->ecc.write_page_raw(mtd, chip, buffer, 0);
1417                 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1418
1419                 /* Wait for the write to finish. */
1420                 status = chip->waitfunc(mtd, chip);
1421                 if (status & NAND_STATUS_FAIL)
1422                         dev_err(dev, "[%s] Write failed.\n", __func__);
1423         }
1424
1425         /* Deselect chip 0. */
1426         chip->select_chip(mtd, saved_chip_number);
1427         return 0;
1428 }
1429
1430 static int mx23_boot_init(struct gpmi_nand_data  *this)
1431 {
1432         struct device *dev = this->dev;
1433         struct nand_chip *chip = &this->nand;
1434         struct mtd_info *mtd = &this->mtd;
1435         unsigned int block_count;
1436         unsigned int block;
1437         int     chipnr;
1438         int     page;
1439         loff_t  byte;
1440         uint8_t block_mark;
1441         int     ret = 0;
1442
1443         /*
1444          * If control arrives here, we can't use block mark swapping, which
1445          * means we're forced to use transcription. First, scan for the
1446          * transcription stamp. If we find it, then we don't have to do
1447          * anything -- the block marks are already transcribed.
1448          */
1449         if (mx23_check_transcription_stamp(this))
1450                 return 0;
1451
1452         /*
1453          * If control arrives here, we couldn't find a transcription stamp, so
1454          * so we presume the block marks are in the conventional location.
1455          */
1456         dev_dbg(dev, "Transcribing bad block marks...\n");
1457
1458         /* Compute the number of blocks in the entire medium. */
1459         block_count = chip->chipsize >> chip->phys_erase_shift;
1460
1461         /*
1462          * Loop over all the blocks in the medium, transcribing block marks as
1463          * we go.
1464          */
1465         for (block = 0; block < block_count; block++) {
1466                 /*
1467                  * Compute the chip, page and byte addresses for this block's
1468                  * conventional mark.
1469                  */
1470                 chipnr = block >> (chip->chip_shift - chip->phys_erase_shift);
1471                 page = block << (chip->phys_erase_shift - chip->page_shift);
1472                 byte = block <<  chip->phys_erase_shift;
1473
1474                 /* Send the command to read the conventional block mark. */
1475                 chip->select_chip(mtd, chipnr);
1476                 chip->cmdfunc(mtd, NAND_CMD_READ0, mtd->writesize, page);
1477                 block_mark = chip->read_byte(mtd);
1478                 chip->select_chip(mtd, -1);
1479
1480                 /*
1481                  * Check if the block is marked bad. If so, we need to mark it
1482                  * again, but this time the result will be a mark in the
1483                  * location where we transcribe block marks.
1484                  */
1485                 if (block_mark != 0xff) {
1486                         dev_dbg(dev, "Transcribing mark in block %u\n", block);
1487                         ret = chip->block_markbad(mtd, byte);
1488                         if (ret)
1489                                 dev_err(dev, "Failed to mark block bad with "
1490                                                         "ret %d\n", ret);
1491                 }
1492         }
1493
1494         /* Write the stamp that indicates we've transcribed the block marks. */
1495         mx23_write_transcription_stamp(this);
1496         return 0;
1497 }
1498
1499 static int nand_boot_init(struct gpmi_nand_data  *this)
1500 {
1501         nand_boot_set_geometry(this);
1502
1503         /* This is ROM arch-specific initilization before the BBT scanning. */
1504         if (GPMI_IS_MX23(this))
1505                 return mx23_boot_init(this);
1506         return 0;
1507 }
1508
1509 static int gpmi_set_geometry(struct gpmi_nand_data *this)
1510 {
1511         int ret;
1512
1513         /* Free the temporary DMA memory for reading ID. */
1514         gpmi_free_dma_buffer(this);
1515
1516         /* Set up the NFC geometry which is used by BCH. */
1517         ret = bch_set_geometry(this);
1518         if (ret) {
1519                 pr_err("Error setting BCH geometry : %d\n", ret);
1520                 return ret;
1521         }
1522
1523         /* Alloc the new DMA buffers according to the pagesize and oobsize */
1524         return gpmi_alloc_dma_buffer(this);
1525 }
1526
1527 static void gpmi_nand_exit(struct gpmi_nand_data *this)
1528 {
1529         nand_release(&this->mtd);
1530         gpmi_free_dma_buffer(this);
1531 }
1532
1533 static int gpmi_init_last(struct gpmi_nand_data *this)
1534 {
1535         struct mtd_info *mtd = &this->mtd;
1536         struct nand_chip *chip = mtd->priv;
1537         struct nand_ecc_ctrl *ecc = &chip->ecc;
1538         struct bch_geometry *bch_geo = &this->bch_geometry;
1539         int ret;
1540
1541         /* Set up swap_block_mark, must be set before the gpmi_set_geometry() */
1542         this->swap_block_mark = !GPMI_IS_MX23(this);
1543
1544         /* Set up the medium geometry */
1545         ret = gpmi_set_geometry(this);
1546         if (ret)
1547                 return ret;
1548
1549         /* Init the nand_ecc_ctrl{} */
1550         ecc->read_page  = gpmi_ecc_read_page;
1551         ecc->write_page = gpmi_ecc_write_page;
1552         ecc->read_oob   = gpmi_ecc_read_oob;
1553         ecc->write_oob  = gpmi_ecc_write_oob;
1554         ecc->mode       = NAND_ECC_HW;
1555         ecc->size       = bch_geo->ecc_chunk_size;
1556         ecc->strength   = bch_geo->ecc_strength;
1557         ecc->layout     = &gpmi_hw_ecclayout;
1558
1559         /*
1560          * Can we enable the extra features? such as EDO or Sync mode.
1561          *
1562          * We do not check the return value now. That's means if we fail in
1563          * enable the extra features, we still can run in the normal way.
1564          */
1565         gpmi_extra_init(this);
1566
1567         return 0;
1568 }
1569
1570 static int gpmi_nand_init(struct gpmi_nand_data *this)
1571 {
1572         struct mtd_info  *mtd = &this->mtd;
1573         struct nand_chip *chip = &this->nand;
1574         struct mtd_part_parser_data ppdata = {};
1575         int ret;
1576
1577         /* init current chip */
1578         this->current_chip      = -1;
1579
1580         /* init the MTD data structures */
1581         mtd->priv               = chip;
1582         mtd->name               = "gpmi-nand";
1583         mtd->owner              = THIS_MODULE;
1584
1585         /* init the nand_chip{}, we don't support a 16-bit NAND Flash bus. */
1586         chip->priv              = this;
1587         chip->select_chip       = gpmi_select_chip;
1588         chip->cmd_ctrl          = gpmi_cmd_ctrl;
1589         chip->dev_ready         = gpmi_dev_ready;
1590         chip->read_byte         = gpmi_read_byte;
1591         chip->read_buf          = gpmi_read_buf;
1592         chip->write_buf         = gpmi_write_buf;
1593         chip->badblock_pattern  = &gpmi_bbt_descr;
1594         chip->block_markbad     = gpmi_block_markbad;
1595         chip->options           |= NAND_NO_SUBPAGE_WRITE;
1596         if (of_get_nand_on_flash_bbt(this->dev->of_node))
1597                 chip->bbt_options |= NAND_BBT_USE_FLASH | NAND_BBT_NO_OOB;
1598
1599         /*
1600          * Allocate a temporary DMA buffer for reading ID in the
1601          * nand_scan_ident().
1602          */
1603         this->bch_geometry.payload_size = 1024;
1604         this->bch_geometry.auxiliary_size = 128;
1605         ret = gpmi_alloc_dma_buffer(this);
1606         if (ret)
1607                 goto err_out;
1608
1609         ret = nand_scan_ident(mtd, GPMI_IS_MX6Q(this) ? 2 : 1, NULL);
1610         if (ret)
1611                 goto err_out;
1612
1613         ret = gpmi_init_last(this);
1614         if (ret)
1615                 goto err_out;
1616
1617         chip->options |= NAND_SKIP_BBTSCAN;
1618         ret = nand_scan_tail(mtd);
1619         if (ret)
1620                 goto err_out;
1621
1622         ret = nand_boot_init(this);
1623         if (ret)
1624                 goto err_out;
1625         chip->scan_bbt(mtd);
1626
1627         ppdata.of_node = this->pdev->dev.of_node;
1628         ret = mtd_device_parse_register(mtd, NULL, &ppdata, NULL, 0);
1629         if (ret)
1630                 goto err_out;
1631         return 0;
1632
1633 err_out:
1634         gpmi_nand_exit(this);
1635         return ret;
1636 }
1637
1638 static const struct platform_device_id gpmi_ids[] = {
1639         { .name = "imx23-gpmi-nand", .driver_data = IS_MX23, },
1640         { .name = "imx28-gpmi-nand", .driver_data = IS_MX28, },
1641         { .name = "imx6q-gpmi-nand", .driver_data = IS_MX6Q, },
1642         {}
1643 };
1644
1645 static const struct of_device_id gpmi_nand_id_table[] = {
1646         {
1647                 .compatible = "fsl,imx23-gpmi-nand",
1648                 .data = (void *)&gpmi_ids[IS_MX23],
1649         }, {
1650                 .compatible = "fsl,imx28-gpmi-nand",
1651                 .data = (void *)&gpmi_ids[IS_MX28],
1652         }, {
1653                 .compatible = "fsl,imx6q-gpmi-nand",
1654                 .data = (void *)&gpmi_ids[IS_MX6Q],
1655         }, {}
1656 };
1657 MODULE_DEVICE_TABLE(of, gpmi_nand_id_table);
1658
1659 static int gpmi_nand_probe(struct platform_device *pdev)
1660 {
1661         struct gpmi_nand_data *this;
1662         const struct of_device_id *of_id;
1663         int ret;
1664
1665         of_id = of_match_device(gpmi_nand_id_table, &pdev->dev);
1666         if (of_id) {
1667                 pdev->id_entry = of_id->data;
1668         } else {
1669                 pr_err("Failed to find the right device id.\n");
1670                 return -ENODEV;
1671         }
1672
1673         this = devm_kzalloc(&pdev->dev, sizeof(*this), GFP_KERNEL);
1674         if (!this) {
1675                 pr_err("Failed to allocate per-device memory\n");
1676                 return -ENOMEM;
1677         }
1678
1679         platform_set_drvdata(pdev, this);
1680         this->pdev  = pdev;
1681         this->dev   = &pdev->dev;
1682
1683         ret = acquire_resources(this);
1684         if (ret)
1685                 goto exit_acquire_resources;
1686
1687         ret = init_hardware(this);
1688         if (ret)
1689                 goto exit_nfc_init;
1690
1691         ret = gpmi_nand_init(this);
1692         if (ret)
1693                 goto exit_nfc_init;
1694
1695         dev_info(this->dev, "driver registered.\n");
1696
1697         return 0;
1698
1699 exit_nfc_init:
1700         release_resources(this);
1701 exit_acquire_resources:
1702         dev_err(this->dev, "driver registration failed: %d\n", ret);
1703
1704         return ret;
1705 }
1706
1707 static int gpmi_nand_remove(struct platform_device *pdev)
1708 {
1709         struct gpmi_nand_data *this = platform_get_drvdata(pdev);
1710
1711         gpmi_nand_exit(this);
1712         release_resources(this);
1713         return 0;
1714 }
1715
1716 static struct platform_driver gpmi_nand_driver = {
1717         .driver = {
1718                 .name = "gpmi-nand",
1719                 .of_match_table = gpmi_nand_id_table,
1720         },
1721         .probe   = gpmi_nand_probe,
1722         .remove  = gpmi_nand_remove,
1723         .id_table = gpmi_ids,
1724 };
1725 module_platform_driver(gpmi_nand_driver);
1726
1727 MODULE_AUTHOR("Freescale Semiconductor, Inc.");
1728 MODULE_DESCRIPTION("i.MX GPMI NAND Flash Controller Driver");
1729 MODULE_LICENSE("GPL");