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