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