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