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