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