Version:  2.0.40 2.2.26 2.4.37 2.6.39 3.0 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14 3.15

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

This page was automatically generated by LXR 0.3.1 (source).  •  Linux is a registered trademark of Linus Torvalds  •  Contact us