]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/mtd/nand/gpmi-nfc/gpmi-nfc.c
e4edf5dfdc26f0618a9e92dabf489cd1c0772c70
[karo-tx-linux.git] / drivers / mtd / nand / gpmi-nfc / gpmi-nfc.c
1 /*
2  * Freescale GPMI NFC 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/slab.h>
22 #include "gpmi-nfc.h"
23
24 /* add our owner bbt descriptor */
25 static uint8_t scan_ff_pattern[] = { 0xff };
26 static struct nand_bbt_descr gpmi_bbt_descr = {
27         .options        = 0,
28         .offs           = 0,
29         .len            = 1,
30         .pattern        = scan_ff_pattern
31 };
32
33 /* debug control */
34 int gpmi_debug;
35 module_param(gpmi_debug, int, 0644);
36 MODULE_PARM_DESC(gpmi_debug, "print out the debug infomation.");
37
38 /* enable the gpmi-nfc */
39 static bool enable_gpmi_nand;
40
41 static ssize_t show_ignorebad(struct device *dev,
42                                 struct device_attribute *attr, char *buf)
43 {
44         struct gpmi_nfc_data *this = dev_get_drvdata(dev);
45         struct mil *mil = &this->mil;
46
47         return sprintf(buf, "%d\n", mil->ignore_bad_block_marks);
48 }
49
50 static ssize_t
51 store_ignorebad(struct device *dev, struct device_attribute *attr,
52                         const char *buf, size_t size)
53 {
54         struct gpmi_nfc_data *this = dev_get_drvdata(dev);
55         struct mil *mil = &this->mil;
56         const char *p = buf;
57         unsigned long v;
58
59         if (strict_strtoul(p, 0, &v) < 0)
60                 return -EINVAL;
61
62         if (v > 0)
63                 v = 1;
64
65         if (v != mil->ignore_bad_block_marks) {
66                 if (v) {
67                         /*
68                          * This will cause the NAND Flash MTD code to believe
69                          * that it never created a BBT and force it to call our
70                          * block_bad function.
71                          *
72                          * See mil_block_bad for more details.
73                          */
74                         mil->saved_bbt = mil->nand.bbt;
75                         mil->nand.bbt  = NULL;
76                 } else {
77                         /*
78                          * Restore the NAND Flash MTD's pointer
79                          * to its in-memory BBT.
80                          */
81                         mil->nand.bbt = mil->saved_bbt;
82                 }
83                 mil->ignore_bad_block_marks = v;
84         }
85         return size;
86 }
87
88 static DEVICE_ATTR(ignorebad, 0644, show_ignorebad, store_ignorebad);
89 static struct device_attribute *device_attributes[] = {
90         &dev_attr_ignorebad,
91 };
92
93 static irqreturn_t bch_irq(int irq, void *cookie)
94 {
95         struct gpmi_nfc_data *this = cookie;
96         struct nfc_hal *nfc = this->nfc;
97
98         /* Clear the BCH interrupt */
99         nfc->clear_bch(this);
100
101         complete(&nfc->bch_done);
102         return IRQ_HANDLED;
103 }
104
105 /* calculate the ECC strength by hand */
106 static inline int get_ecc_strength(struct gpmi_nfc_data *this)
107 {
108         struct mtd_info *mtd = &this->mil.mtd;
109         int ecc_strength = 0;
110
111         switch (mtd->writesize) {
112         case 2048:
113                 ecc_strength = 8;
114                 break;
115         case 4096:
116                 switch (mtd->oobsize) {
117                 case 128:
118                         ecc_strength = 8;
119                         break;
120                 case 224:
121                 case 218:
122                         ecc_strength = 16;
123                         break;
124                 }
125                 break;
126         case 8192:
127                 ecc_strength = 24;
128                 break;
129         }
130
131         return ecc_strength;
132 }
133
134 bool is_ddr_nand(struct gpmi_nfc_data *this)
135 {
136         struct nand_chip *chip = &this->mil.nand;
137
138         /* ONFI nand */
139         if (chip->onfi_version != 0)
140                 return true;
141
142         /* TOGGLE nand */
143
144         return false;
145 }
146
147 static inline int get_ecc_chunk_size(struct gpmi_nfc_data *this)
148 {
149         /* the ONFI/TOGGLE nands use 1k ecc chunk size */
150         if (is_ddr_nand(this))
151                 return 1024;
152
153         /* for historical reason */
154         return 512;
155 }
156
157 int common_nfc_set_geometry(struct gpmi_nfc_data *this)
158 {
159         struct nfc_geometry *geo = &this->nfc_geometry;
160         struct mtd_info *mtd = &this->mil.mtd;
161         unsigned int metadata_size;
162         unsigned int status_size;
163         unsigned int chunk_data_size_in_bits;
164         unsigned int chunk_ecc_size_in_bits;
165         unsigned int chunk_total_size_in_bits;
166         unsigned int block_mark_chunk_number;
167         unsigned int block_mark_chunk_bit_offset;
168         unsigned int block_mark_bit_offset;
169
170         /* We only support BCH now. */
171         geo->ecc_algorithm = "BCH";
172
173         /*
174          * We always choose a metadata size of 10. Don't try to make sense of
175          * it -- this is really only for historical compatibility.
176          */
177         geo->metadata_size_in_bytes = 10;
178
179         /* ECC chunks */
180         geo->ecc_chunk_size_in_bytes = get_ecc_chunk_size(this);
181
182         /*
183          * Compute the total number of ECC chunks in a page. This includes the
184          * slightly larger chunk at the beginning of the page, which contains
185          * both data and metadata.
186          */
187         geo->ecc_chunk_count = mtd->writesize / geo->ecc_chunk_size_in_bytes;
188
189         /*
190          * We use the same ECC strength for all chunks, including the first one.
191          */
192         geo->ecc_strength = get_ecc_strength(this);
193         if (!geo->ecc_strength) {
194                 pr_info("Page size:%d, OOB:%d\n", mtd->writesize, mtd->oobsize);
195                 return -EINVAL;
196         }
197
198         /* Compute the page size, include page and oob. */
199         geo->page_size_in_bytes = mtd->writesize + mtd->oobsize;
200
201         /*
202          * ONFI/TOGGLE nand needs GF14, so re-calculate DMA page size.
203          * The ONFI nand must do the recalculation,
204          * else it will fail in DMA in some platform(such as imx50).
205          */
206         if (is_ddr_nand(this))
207                 geo->page_size_in_bytes = mtd->writesize +
208                                 geo->metadata_size_in_bytes +
209                         (geo->ecc_strength * 14 * 8 / geo->ecc_chunk_count);
210
211         geo->payload_size_in_bytes = mtd->writesize;
212         /*
213          * In principle, computing the auxiliary buffer geometry is NFC
214          * version-specific. However, at this writing, all versions share the
215          * same model, so this code can also be shared.
216          *
217          * The auxiliary buffer contains the metadata and the ECC status. The
218          * metadata is padded to the nearest 32-bit boundary. The ECC status
219          * contains one byte for every ECC chunk, and is also padded to the
220          * nearest 32-bit boundary.
221          */
222         metadata_size = ALIGN(geo->metadata_size_in_bytes, 4);
223         status_size   = ALIGN(geo->ecc_chunk_count, 4);
224
225         geo->auxiliary_size_in_bytes = metadata_size + status_size;
226         geo->auxiliary_status_offset = metadata_size;
227
228         /* Check if we're going to do block mark swapping. */
229         if (!this->swap_block_mark)
230                 return 0;
231
232         /*
233          * If control arrives here, we're doing block mark swapping, so we need
234          * to compute the byte and bit offsets of the physical block mark within
235          * the ECC-based view of the page data. In principle, this isn't a
236          * difficult computation -- but it's very important and it's easy to get
237          * it wrong, so we do it carefully.
238          *
239          * Note that this calculation is simpler because we use the same ECC
240          * strength for all chunks, including the zero'th one, which contains
241          * the metadata. The calculation would be slightly more complicated
242          * otherwise.
243          *
244          * We start by computing the physical bit offset of the block mark. We
245          * then subtract the number of metadata and ECC bits appearing before
246          * the mark to arrive at its bit offset within the data alone.
247          */
248
249         /* Compute some important facts about chunk geometry. */
250         chunk_data_size_in_bits = geo->ecc_chunk_size_in_bytes * 8;
251
252         /* ONFI/TOGGLE nand needs GF14 */
253         if (is_ddr_nand(this))
254                 chunk_ecc_size_in_bits  = geo->ecc_strength * 14;
255         else
256                 chunk_ecc_size_in_bits  = geo->ecc_strength * 13;
257
258         chunk_total_size_in_bits =
259                         chunk_data_size_in_bits + chunk_ecc_size_in_bits;
260
261         /* Compute the bit offset of the block mark within the physical page. */
262         block_mark_bit_offset = mtd->writesize * 8;
263
264         /* Subtract the metadata bits. */
265         block_mark_bit_offset -= geo->metadata_size_in_bytes * 8;
266
267         /*
268          * Compute the chunk number (starting at zero) in which the block mark
269          * appears.
270          */
271         block_mark_chunk_number =
272                         block_mark_bit_offset / chunk_total_size_in_bits;
273
274         /*
275          * Compute the bit offset of the block mark within its chunk, and
276          * validate it.
277          */
278         block_mark_chunk_bit_offset =
279                 block_mark_bit_offset -
280                         (block_mark_chunk_number * chunk_total_size_in_bits);
281
282         if (block_mark_chunk_bit_offset > chunk_data_size_in_bits) {
283                 /*
284                  * If control arrives here, the block mark actually appears in
285                  * the ECC bits of this chunk. This wont' work.
286                  */
287                 pr_info("Unsupported page geometry : %u:%u\n",
288                                 mtd->writesize, mtd->oobsize);
289                 return -EINVAL;
290         }
291
292         /*
293          * Now that we know the chunk number in which the block mark appears,
294          * we can subtract all the ECC bits that appear before it.
295          */
296         block_mark_bit_offset -=
297                         block_mark_chunk_number * chunk_ecc_size_in_bits;
298
299         /*
300          * We now know the absolute bit offset of the block mark within the
301          * ECC-based data. We can now compute the byte offset and the bit
302          * offset within the byte.
303          */
304         geo->block_mark_byte_offset = block_mark_bit_offset / 8;
305         geo->block_mark_bit_offset  = block_mark_bit_offset % 8;
306
307         return 0;
308 }
309
310 struct dma_chan *get_dma_chan(struct gpmi_nfc_data *this)
311 {
312         int chip = this->mil.current_chip;
313
314         BUG_ON(chip < 0);
315         return this->dma_chans[chip];
316 }
317
318 /* Can we use the upper's buffer directly for DMA? */
319 void prepare_data_dma(struct gpmi_nfc_data *this, enum dma_data_direction dr)
320 {
321         struct mil *mil = &this->mil;
322         struct scatterlist *sgl = &mil->data_sgl;
323         int ret;
324
325         mil->direct_dma_map_ok = true;
326
327         /* first try to map the upper buffer directly */
328         sg_init_one(sgl, mil->upper_buf, mil->upper_len);
329         ret = dma_map_sg(this->dev, sgl, 1, dr);
330         if (ret == 0) {
331                 /* We have to use our own DMA buffer. */
332                 sg_init_one(sgl, mil->data_buffer_dma, PAGE_SIZE);
333
334                 if (dr == DMA_TO_DEVICE)
335                         memcpy(mil->data_buffer_dma, mil->upper_buf,
336                                 mil->upper_len);
337
338                 ret = dma_map_sg(this->dev, sgl, 1, dr);
339                 BUG_ON(ret == 0);
340
341                 mil->direct_dma_map_ok = false;
342         }
343 }
344
345 /* This will be called after the DMA operation is finished. */
346 static void dma_irq_callback(void *param)
347 {
348         struct gpmi_nfc_data *this = param;
349         struct nfc_hal *nfc = this->nfc;
350         struct mil *mil = &this->mil;
351
352         complete(&nfc->dma_done);
353
354         switch (this->dma_type) {
355         case DMA_FOR_COMMAND:
356                 dma_unmap_sg(this->dev, &mil->cmd_sgl, 1, DMA_TO_DEVICE);
357                 break;
358
359         case DMA_FOR_READ_DATA:
360                 dma_unmap_sg(this->dev, &mil->data_sgl, 1, DMA_FROM_DEVICE);
361                 if (mil->direct_dma_map_ok == false)
362                         memcpy(mil->upper_buf, mil->data_buffer_dma,
363                                 mil->upper_len);
364                 break;
365
366         case DMA_FOR_WRITE_DATA:
367                 dma_unmap_sg(this->dev, &mil->data_sgl, 1, DMA_TO_DEVICE);
368                 break;
369
370         case DMA_FOR_READ_ECC_PAGE:
371         case DMA_FOR_WRITE_ECC_PAGE:
372                 /* We have to wait the BCH interrupt to finish. */
373                 break;
374
375         default:
376                 BUG();
377         }
378 }
379
380 int start_dma_without_bch_irq(struct gpmi_nfc_data *this,
381                                 struct dma_async_tx_descriptor *desc)
382 {
383         struct nfc_hal *nfc = this->nfc;
384         int err;
385
386         init_completion(&nfc->dma_done);
387
388         desc->callback          = dma_irq_callback;
389         desc->callback_param    = this;
390         dmaengine_submit(desc);
391
392         /* Wait for the interrupt from the DMA block. */
393         err = wait_for_completion_timeout(&nfc->dma_done,
394                                         msecs_to_jiffies(1000));
395         err = (!err) ? -ETIMEDOUT : 0;
396         if (err)
397                 pr_info("DMA timeout!!!\n");
398         return err;
399 }
400
401 /*
402  * This function is used in BCH reading or BCH writing pages.
403  * It will wait for the BCH interrupt as long as ONE second.
404  * Actually, we must wait for two interrupts :
405  *      [1] firstly the DMA interrupt and
406  *      [2] secondly the BCH interrupt.
407  *
408  * @this:       Per-device data structure.
409  * @desc:       DMA channel
410  */
411 int start_dma_with_bch_irq(struct gpmi_nfc_data *this,
412                         struct dma_async_tx_descriptor *desc)
413 {
414         struct nfc_hal *nfc = this->nfc;
415         int err;
416
417         /* Prepare to receive an interrupt from the BCH block. */
418         init_completion(&nfc->bch_done);
419
420         /* start the DMA */
421         start_dma_without_bch_irq(this, desc);
422
423         /* Wait for the interrupt from the BCH block. */
424         err = wait_for_completion_timeout(&nfc->bch_done,
425                                         msecs_to_jiffies(1000));
426         err = (!err) ? -ETIMEDOUT : 0;
427         if (err)
428                 pr_info("bch timeout!!!\n");
429         return err;
430 }
431
432 /**
433  * ns_to_cycles - Converts time in nanoseconds to cycles.
434  *
435  * @ntime:   The time, in nanoseconds.
436  * @period:  The cycle period, in nanoseconds.
437  * @min:     The minimum allowable number of cycles.
438  */
439 static unsigned int ns_to_cycles(unsigned int time,
440                                         unsigned int period, unsigned int min)
441 {
442         unsigned int k;
443
444         /*
445          * Compute the minimum number of cycles that entirely contain the
446          * given time.
447          */
448         k = (time + period - 1) / period;
449         return max(k, min);
450 }
451
452 /**
453  * gpmi_compute_hardware_timing - Apply timing to current hardware conditions.
454  *
455  * @this:             Per-device data.
456  * @hardware_timing:  A pointer to a hardware timing structure that will receive
457  *                    the results of our calculations.
458  */
459 int gpmi_nfc_compute_hardware_timing(struct gpmi_nfc_data *this,
460                                         struct gpmi_nfc_hardware_timing *hw)
461 {
462         struct gpmi_nfc_platform_data *pdata = this->pdata;
463         struct nfc_hal *nfc = this->nfc;
464         struct nand_chip *nand = &this->mil.nand;
465         struct nand_timing target = nfc->timing;
466         bool improved_timing_is_available;
467         unsigned long clock_frequency_in_hz;
468         unsigned int clock_period_in_ns;
469         bool dll_use_half_periods;
470         unsigned int dll_delay_shift;
471         unsigned int max_sample_delay_in_ns;
472         unsigned int address_setup_in_cycles;
473         unsigned int data_setup_in_ns;
474         unsigned int data_setup_in_cycles;
475         unsigned int data_hold_in_cycles;
476         int ideal_sample_delay_in_ns;
477         unsigned int sample_delay_factor;
478         int tEYE;
479         unsigned int min_prop_delay_in_ns = pdata->min_prop_delay_in_ns;
480         unsigned int max_prop_delay_in_ns = pdata->max_prop_delay_in_ns;
481
482         /*
483          * If there are multiple chips, we need to relax the timings to allow
484          * for signal distortion due to higher capacitance.
485          */
486         if (nand->numchips > 2) {
487                 target.data_setup_in_ns    += 10;
488                 target.data_hold_in_ns     += 10;
489                 target.address_setup_in_ns += 10;
490         } else if (nand->numchips > 1) {
491                 target.data_setup_in_ns    += 5;
492                 target.data_hold_in_ns     += 5;
493                 target.address_setup_in_ns += 5;
494         }
495
496         /* Check if improved timing information is available. */
497         improved_timing_is_available =
498                 (target.tREA_in_ns  >= 0) &&
499                 (target.tRLOH_in_ns >= 0) &&
500                 (target.tRHOH_in_ns >= 0) ;
501
502         /* Inspect the clock. */
503         clock_frequency_in_hz = nfc->clock_frequency_in_hz;
504         clock_period_in_ns    = 1000000000 / clock_frequency_in_hz;
505
506         /*
507          * The NFC quantizes setup and hold parameters in terms of clock cycles.
508          * Here, we quantize the setup and hold timing parameters to the
509          * next-highest clock period to make sure we apply at least the
510          * specified times.
511          *
512          * For data setup and data hold, the hardware interprets a value of zero
513          * as the largest possible delay. This is not what's intended by a zero
514          * in the input parameter, so we impose a minimum of one cycle.
515          */
516         data_setup_in_cycles    = ns_to_cycles(target.data_setup_in_ns,
517                                                         clock_period_in_ns, 1);
518         data_hold_in_cycles     = ns_to_cycles(target.data_hold_in_ns,
519                                                         clock_period_in_ns, 1);
520         address_setup_in_cycles = ns_to_cycles(target.address_setup_in_ns,
521                                                         clock_period_in_ns, 0);
522
523         /*
524          * The clock's period affects the sample delay in a number of ways:
525          *
526          * (1) The NFC HAL tells us the maximum clock period the sample delay
527          *     DLL can tolerate. If the clock period is greater than half that
528          *     maximum, we must configure the DLL to be driven by half periods.
529          *
530          * (2) We need to convert from an ideal sample delay, in ns, to a
531          *     "sample delay factor," which the NFC uses. This factor depends on
532          *     whether we're driving the DLL with full or half periods.
533          *     Paraphrasing the reference manual:
534          *
535          *         AD = SDF x 0.125 x RP
536          *
537          * where:
538          *
539          *     AD   is the applied delay, in ns.
540          *     SDF  is the sample delay factor, which is dimensionless.
541          *     RP   is the reference period, in ns, which is a full clock period
542          *          if the DLL is being driven by full periods, or half that if
543          *          the DLL is being driven by half periods.
544          *
545          * Let's re-arrange this in a way that's more useful to us:
546          *
547          *                        8
548          *         SDF  =  AD x ----
549          *                       RP
550          *
551          * The reference period is either the clock period or half that, so this
552          * is:
553          *
554          *                        8       AD x DDF
555          *         SDF  =  AD x -----  =  --------
556          *                      f x P        P
557          *
558          * where:
559          *
560          *       f  is 1 or 1/2, depending on how we're driving the DLL.
561          *       P  is the clock period.
562          *     DDF  is the DLL Delay Factor, a dimensionless value that
563          *          incorporates all the constants in the conversion.
564          *
565          * DDF will be either 8 or 16, both of which are powers of two. We can
566          * reduce the cost of this conversion by using bit shifts instead of
567          * multiplication or division. Thus:
568          *
569          *                 AD << DDS
570          *         SDF  =  ---------
571          *                     P
572          *
573          *     or
574          *
575          *         AD  =  (SDF >> DDS) x P
576          *
577          * where:
578          *
579          *     DDS  is the DLL Delay Shift, the logarithm to base 2 of the DDF.
580          */
581         if (clock_period_in_ns > (nfc->max_dll_clock_period_in_ns >> 1)) {
582                 dll_use_half_periods = true;
583                 dll_delay_shift      = 3 + 1;
584         } else {
585                 dll_use_half_periods = false;
586                 dll_delay_shift      = 3;
587         }
588
589         /*
590          * Compute the maximum sample delay the NFC allows, under current
591          * conditions. If the clock is running too slowly, no sample delay is
592          * possible.
593          */
594         if (clock_period_in_ns > nfc->max_dll_clock_period_in_ns)
595                 max_sample_delay_in_ns = 0;
596         else {
597                 /*
598                  * Compute the delay implied by the largest sample delay factor
599                  * the NFC allows.
600                  */
601                 max_sample_delay_in_ns =
602                         (nfc->max_sample_delay_factor * clock_period_in_ns) >>
603                                                                 dll_delay_shift;
604
605                 /*
606                  * Check if the implied sample delay larger than the NFC
607                  * actually allows.
608                  */
609                 if (max_sample_delay_in_ns > nfc->max_dll_delay_in_ns)
610                         max_sample_delay_in_ns = nfc->max_dll_delay_in_ns;
611         }
612
613         /*
614          * Check if improved timing information is available. If not, we have to
615          * use a less-sophisticated algorithm.
616          */
617         if (!improved_timing_is_available) {
618                 /*
619                  * Fold the read setup time required by the NFC into the ideal
620                  * sample delay.
621                  */
622                 ideal_sample_delay_in_ns = target.gpmi_sample_delay_in_ns +
623                                                 nfc->internal_data_setup_in_ns;
624
625                 /*
626                  * The ideal sample delay may be greater than the maximum
627                  * allowed by the NFC. If so, we can trade off sample delay time
628                  * for more data setup time.
629                  *
630                  * In each iteration of the following loop, we add a cycle to
631                  * the data setup time and subtract a corresponding amount from
632                  * the sample delay until we've satisified the constraints or
633                  * can't do any better.
634                  */
635                 while ((ideal_sample_delay_in_ns > max_sample_delay_in_ns) &&
636                         (data_setup_in_cycles < nfc->max_data_setup_cycles)) {
637
638                         data_setup_in_cycles++;
639                         ideal_sample_delay_in_ns -= clock_period_in_ns;
640
641                         if (ideal_sample_delay_in_ns < 0)
642                                 ideal_sample_delay_in_ns = 0;
643
644                 }
645
646                 /*
647                  * Compute the sample delay factor that corresponds most closely
648                  * to the ideal sample delay. If the result is too large for the
649                  * NFC, use the maximum value.
650                  *
651                  * Notice that we use the ns_to_cycles function to compute the
652                  * sample delay factor. We do this because the form of the
653                  * computation is the same as that for calculating cycles.
654                  */
655                 sample_delay_factor =
656                         ns_to_cycles(
657                                 ideal_sample_delay_in_ns << dll_delay_shift,
658                                                         clock_period_in_ns, 0);
659
660                 if (sample_delay_factor > nfc->max_sample_delay_factor)
661                         sample_delay_factor = nfc->max_sample_delay_factor;
662
663                 /* Skip to the part where we return our results. */
664                 goto return_results;
665         }
666
667         /*
668          * If control arrives here, we have more detailed timing information,
669          * so we can use a better algorithm.
670          */
671
672         /*
673          * Fold the read setup time required by the NFC into the maximum
674          * propagation delay.
675          */
676         max_prop_delay_in_ns += nfc->internal_data_setup_in_ns;
677
678         /*
679          * Earlier, we computed the number of clock cycles required to satisfy
680          * the data setup time. Now, we need to know the actual nanoseconds.
681          */
682         data_setup_in_ns = clock_period_in_ns * data_setup_in_cycles;
683
684         /*
685          * Compute tEYE, the width of the data eye when reading from the NAND
686          * Flash. The eye width is fundamentally determined by the data setup
687          * time, perturbed by propagation delays and some characteristics of the
688          * NAND Flash device.
689          *
690          * start of the eye = max_prop_delay + tREA
691          * end of the eye   = min_prop_delay + tRHOH + data_setup
692          */
693         tEYE = (int)min_prop_delay_in_ns + (int)target.tRHOH_in_ns +
694                                                         (int)data_setup_in_ns;
695
696         tEYE -= (int)max_prop_delay_in_ns + (int)target.tREA_in_ns;
697
698         /*
699          * The eye must be open. If it's not, we can try to open it by
700          * increasing its main forcer, the data setup time.
701          *
702          * In each iteration of the following loop, we increase the data setup
703          * time by a single clock cycle. We do this until either the eye is
704          * open or we run into NFC limits.
705          */
706         while ((tEYE <= 0) &&
707                         (data_setup_in_cycles < nfc->max_data_setup_cycles)) {
708                 /* Give a cycle to data setup. */
709                 data_setup_in_cycles++;
710                 /* Synchronize the data setup time with the cycles. */
711                 data_setup_in_ns += clock_period_in_ns;
712                 /* Adjust tEYE accordingly. */
713                 tEYE += clock_period_in_ns;
714         }
715
716         /*
717          * When control arrives here, the eye is open. The ideal time to sample
718          * the data is in the center of the eye:
719          *
720          *     end of the eye + start of the eye
721          *     ---------------------------------  -  data_setup
722          *                    2
723          *
724          * After some algebra, this simplifies to the code immediately below.
725          */
726         ideal_sample_delay_in_ns =
727                 ((int)max_prop_delay_in_ns +
728                         (int)target.tREA_in_ns +
729                                 (int)min_prop_delay_in_ns +
730                                         (int)target.tRHOH_in_ns -
731                                                 (int)data_setup_in_ns) >> 1;
732
733         /*
734          * The following figure illustrates some aspects of a NAND Flash read:
735          *
736          *
737          *           __                   _____________________________________
738          * RDN         \_________________/
739          *
740          *                                         <---- tEYE ----->
741          *                                        /-----------------\
742          * Read Data ----------------------------<                   >---------
743          *                                        \-----------------/
744          *             ^                 ^                 ^              ^
745          *             |                 |                 |              |
746          *             |<--Data Setup -->|<--Delay Time -->|              |
747          *             |                 |                 |              |
748          *             |                 |                                |
749          *             |                 |<--   Quantized Delay Time   -->|
750          *             |                 |                                |
751          *
752          *
753          * We have some issues we must now address:
754          *
755          * (1) The *ideal* sample delay time must not be negative. If it is, we
756          *     jam it to zero.
757          *
758          * (2) The *ideal* sample delay time must not be greater than that
759          *     allowed by the NFC. If it is, we can increase the data setup
760          *     time, which will reduce the delay between the end of the data
761          *     setup and the center of the eye. It will also make the eye
762          *     larger, which might help with the next issue...
763          *
764          * (3) The *quantized* sample delay time must not fall either before the
765          *     eye opens or after it closes (the latter is the problem
766          *     illustrated in the above figure).
767          */
768
769         /* Jam a negative ideal sample delay to zero. */
770         if (ideal_sample_delay_in_ns < 0)
771                 ideal_sample_delay_in_ns = 0;
772
773         /*
774          * Extend the data setup as needed to reduce the ideal sample delay
775          * below the maximum permitted by the NFC.
776          */
777         while ((ideal_sample_delay_in_ns > max_sample_delay_in_ns) &&
778                         (data_setup_in_cycles < nfc->max_data_setup_cycles)) {
779
780                 /* Give a cycle to data setup. */
781                 data_setup_in_cycles++;
782                 /* Synchronize the data setup time with the cycles. */
783                 data_setup_in_ns += clock_period_in_ns;
784                 /* Adjust tEYE accordingly. */
785                 tEYE += clock_period_in_ns;
786
787                 /*
788                  * Decrease the ideal sample delay by one half cycle, to keep it
789                  * in the middle of the eye.
790                  */
791                 ideal_sample_delay_in_ns -= (clock_period_in_ns >> 1);
792
793                 /* Jam a negative ideal sample delay to zero. */
794                 if (ideal_sample_delay_in_ns < 0)
795                         ideal_sample_delay_in_ns = 0;
796         }
797
798         /*
799          * Compute the sample delay factor that corresponds to the ideal sample
800          * delay. If the result is too large, then use the maximum allowed
801          * value.
802          *
803          * Notice that we use the ns_to_cycles function to compute the sample
804          * delay factor. We do this because the form of the computation is the
805          * same as that for calculating cycles.
806          */
807         sample_delay_factor =
808                 ns_to_cycles(ideal_sample_delay_in_ns << dll_delay_shift,
809                                                         clock_period_in_ns, 0);
810
811         if (sample_delay_factor > nfc->max_sample_delay_factor)
812                 sample_delay_factor = nfc->max_sample_delay_factor;
813
814         /*
815          * These macros conveniently encapsulate a computation we'll use to
816          * continuously evaluate whether or not the data sample delay is inside
817          * the eye.
818          */
819         #define IDEAL_DELAY  ((int) ideal_sample_delay_in_ns)
820
821         #define QUANTIZED_DELAY  \
822                 ((int) ((sample_delay_factor * clock_period_in_ns) >> \
823                                                         dll_delay_shift))
824
825         #define DELAY_ERROR  (abs(QUANTIZED_DELAY - IDEAL_DELAY))
826
827         #define SAMPLE_IS_NOT_WITHIN_THE_EYE  (DELAY_ERROR > (tEYE >> 1))
828
829         /*
830          * While the quantized sample time falls outside the eye, reduce the
831          * sample delay or extend the data setup to move the sampling point back
832          * toward the eye. Do not allow the number of data setup cycles to
833          * exceed the maximum allowed by the NFC.
834          */
835         while (SAMPLE_IS_NOT_WITHIN_THE_EYE &&
836                         (data_setup_in_cycles < nfc->max_data_setup_cycles)) {
837                 /*
838                  * If control arrives here, the quantized sample delay falls
839                  * outside the eye. Check if it's before the eye opens, or after
840                  * the eye closes.
841                  */
842                 if (QUANTIZED_DELAY > IDEAL_DELAY) {
843                         /*
844                          * If control arrives here, the quantized sample delay
845                          * falls after the eye closes. Decrease the quantized
846                          * delay time and then go back to re-evaluate.
847                          */
848                         if (sample_delay_factor != 0)
849                                 sample_delay_factor--;
850                         continue;
851                 }
852
853                 /*
854                  * If control arrives here, the quantized sample delay falls
855                  * before the eye opens. Shift the sample point by increasing
856                  * data setup time. This will also make the eye larger.
857                  */
858
859                 /* Give a cycle to data setup. */
860                 data_setup_in_cycles++;
861                 /* Synchronize the data setup time with the cycles. */
862                 data_setup_in_ns += clock_period_in_ns;
863                 /* Adjust tEYE accordingly. */
864                 tEYE += clock_period_in_ns;
865
866                 /*
867                  * Decrease the ideal sample delay by one half cycle, to keep it
868                  * in the middle of the eye.
869                  */
870                 ideal_sample_delay_in_ns -= (clock_period_in_ns >> 1);
871
872                 /* ...and one less period for the delay time. */
873                 ideal_sample_delay_in_ns -= clock_period_in_ns;
874
875                 /* Jam a negative ideal sample delay to zero. */
876                 if (ideal_sample_delay_in_ns < 0)
877                         ideal_sample_delay_in_ns = 0;
878
879                 /*
880                  * We have a new ideal sample delay, so re-compute the quantized
881                  * delay.
882                  */
883                 sample_delay_factor =
884                         ns_to_cycles(
885                                 ideal_sample_delay_in_ns << dll_delay_shift,
886                                                         clock_period_in_ns, 0);
887
888                 if (sample_delay_factor > nfc->max_sample_delay_factor)
889                         sample_delay_factor = nfc->max_sample_delay_factor;
890         }
891
892         /* Control arrives here when we're ready to return our results. */
893 return_results:
894         hw->data_setup_in_cycles    = data_setup_in_cycles;
895         hw->data_hold_in_cycles     = data_hold_in_cycles;
896         hw->address_setup_in_cycles = address_setup_in_cycles;
897         hw->use_half_periods        = dll_use_half_periods;
898         hw->sample_delay_factor     = sample_delay_factor;
899
900         /* Return success. */
901         return 0;
902 }
903
904 static int __devinit acquire_register_block(struct gpmi_nfc_data *this,
905                         const char *resource_name, void **reg_block_base)
906 {
907         struct platform_device *pdev = this->pdev;
908         struct resource *r;
909         void *p;
910
911         r = platform_get_resource_byname(pdev, IORESOURCE_MEM, resource_name);
912         if (!r) {
913                 pr_info("Can't get resource for %s\n", resource_name);
914                 return -ENXIO;
915         }
916
917         /* remap the register block */
918         p = ioremap(r->start, resource_size(r));
919         if (!p) {
920                 pr_info("Can't remap %s\n", resource_name);
921                 return -ENOMEM;
922         }
923
924         *reg_block_base = p;
925         return 0;
926 }
927
928 static void release_register_block(struct gpmi_nfc_data *this,
929                                 void *reg_block_base)
930 {
931         iounmap(reg_block_base);
932 }
933
934 static int __devinit acquire_interrupt(struct gpmi_nfc_data *this,
935                         const char *resource_name,
936                         irq_handler_t interrupt_handler, int *lno, int *hno)
937 {
938         struct platform_device *pdev = this->pdev;
939         struct resource *r;
940         int err;
941
942         r = platform_get_resource_byname(pdev, IORESOURCE_IRQ, resource_name);
943         if (!r) {
944                 pr_info("Can't get resource for %s\n", resource_name);
945                 return -ENXIO;
946         }
947
948         BUG_ON(r->start != r->end);
949         err = request_irq(r->start, interrupt_handler, 0, resource_name, this);
950         if (err) {
951                 pr_info("Can't own %s\n", resource_name);
952                 return err;
953         }
954
955         *lno = r->start;
956         *hno = r->end;
957         return 0;
958 }
959
960 static void release_interrupt(struct gpmi_nfc_data *this,
961                         int low_interrupt_number, int high_interrupt_number)
962 {
963         int i;
964         for (i = low_interrupt_number; i <= high_interrupt_number; i++)
965                 free_irq(i, this);
966 }
967
968 static bool gpmi_dma_filter(struct dma_chan *chan, void *param)
969 {
970         struct gpmi_nfc_data *this = param;
971         struct resource *r = this->private;
972
973         if (!mxs_dma_is_apbh(chan))
974                 return false;
975         /*
976          * only catch the GPMI dma channels :
977          *      for mx23 :      MX23_DMA_GPMI0 ~ MX23_DMA_GPMI3
978          *              (These four channels share the same IRQ!)
979          *
980          *      for mx28 :      MX28_DMA_GPMI0 ~ MX28_DMA_GPMI7
981          *              (These eight channels share the same IRQ!)
982          */
983         if (r->start <= chan->chan_id && chan->chan_id <= r->end) {
984                 chan->private = &this->dma_data;
985                 return true;
986         }
987         return false;
988 }
989
990 static void release_dma_channels(struct gpmi_nfc_data *this)
991 {
992         unsigned int i;
993         for (i = 0; i < DMA_CHANS; i++)
994                 if (this->dma_chans[i]) {
995                         dma_release_channel(this->dma_chans[i]);
996                         this->dma_chans[i] = NULL;
997                 }
998 }
999
1000 static int __devinit acquire_dma_channels(struct gpmi_nfc_data *this,
1001                                 const char *resource_name,
1002                                 unsigned *low_channel, unsigned *high_channel)
1003 {
1004         struct platform_device *pdev = this->pdev;
1005         struct gpmi_nfc_platform_data *pdata = this->pdata;
1006         struct resource *r, *r_dma;
1007         unsigned int i;
1008
1009         r = platform_get_resource_byname(pdev, IORESOURCE_DMA, resource_name);
1010         r_dma = platform_get_resource_byname(pdev, IORESOURCE_IRQ,
1011                                         GPMI_NFC_DMA_INTERRUPT_RES_NAME);
1012         if (!r || !r_dma) {
1013                 pr_info("Can't get resource for DMA\n");
1014                 return -ENXIO;
1015         }
1016
1017         /* used in gpmi_dma_filter() */
1018         this->private = r;
1019
1020         for (i = r->start; i <= r->end; i++) {
1021                 dma_cap_mask_t          mask;
1022                 struct dma_chan         *dma_chan;
1023
1024                 if (i - r->start >= pdata->max_chip_count)
1025                         break;
1026
1027                 dma_cap_zero(mask);
1028                 dma_cap_set(DMA_SLAVE, mask);
1029
1030                 /* get the DMA interrupt */
1031                 this->dma_data.chan_irq = r_dma->start +
1032                         ((r_dma->start != r_dma->end) ? (i - r->start) : 0);
1033
1034                 dma_chan = dma_request_channel(mask, gpmi_dma_filter, this);
1035                 if (!dma_chan)
1036                         goto acquire_err;
1037                 /* fill the first empty item */
1038                 this->dma_chans[i - r->start] = dma_chan;
1039         }
1040
1041         *low_channel  = r->start;
1042         *high_channel = i;
1043         return 0;
1044
1045 acquire_err:
1046         pr_info("Can't acquire DMA channel %u\n", i);
1047         release_dma_channels(this);
1048         return -EINVAL;
1049 }
1050
1051 static int __devinit acquire_resources(struct gpmi_nfc_data *this)
1052 {
1053         struct resources *resources = &this->resources;
1054         int error;
1055
1056         /* Attempt to acquire the GPMI register block. */
1057         error = acquire_register_block(this,
1058                                 GPMI_NFC_GPMI_REGS_ADDR_RES_NAME,
1059                                 &resources->gpmi_regs);
1060         if (error)
1061                 goto exit_gpmi_regs;
1062
1063         /* Attempt to acquire the BCH register block. */
1064         error = acquire_register_block(this,
1065                                 GPMI_NFC_BCH_REGS_ADDR_RES_NAME,
1066                                 &resources->bch_regs);
1067         if (error)
1068                 goto exit_bch_regs;
1069
1070         /* Attempt to acquire the BCH interrupt. */
1071         error = acquire_interrupt(this,
1072                                 GPMI_NFC_BCH_INTERRUPT_RES_NAME,
1073                                 bch_irq,
1074                                 &resources->bch_low_interrupt,
1075                                 &resources->bch_high_interrupt);
1076         if (error)
1077                 goto exit_bch_interrupt;
1078
1079         /* Attempt to acquire the DMA channels. */
1080         error = acquire_dma_channels(this,
1081                                 GPMI_NFC_DMA_CHANNELS_RES_NAME,
1082                                 &resources->dma_low_channel,
1083                                 &resources->dma_high_channel);
1084         if (error)
1085                 goto exit_dma_channels;
1086
1087         /* Attempt to acquire our clock. */
1088         resources->clock = clk_get(&this->pdev->dev, NULL);
1089         if (IS_ERR(resources->clock)) {
1090                 error = -ENOENT;
1091                 pr_info("can not get the clock\n");
1092                 goto exit_clock;
1093         }
1094         return 0;
1095
1096 exit_clock:
1097         release_dma_channels(this);
1098 exit_dma_channels:
1099         release_interrupt(this, resources->bch_low_interrupt,
1100                                 resources->bch_high_interrupt);
1101 exit_bch_interrupt:
1102         release_register_block(this, resources->bch_regs);
1103 exit_bch_regs:
1104         release_register_block(this, resources->gpmi_regs);
1105 exit_gpmi_regs:
1106         return error;
1107 }
1108
1109 static void release_resources(struct gpmi_nfc_data *this)
1110 {
1111         struct resources  *resources = &this->resources;
1112
1113         clk_put(resources->clock);
1114         release_register_block(this, resources->gpmi_regs);
1115         release_register_block(this, resources->bch_regs);
1116         release_interrupt(this, resources->bch_low_interrupt,
1117                                 resources->bch_low_interrupt);
1118         release_dma_channels(this);
1119 }
1120
1121 static void exit_nfc_hal(struct gpmi_nfc_data *this)
1122 {
1123         if (this->nfc)
1124                 this->nfc->exit(this);
1125 }
1126
1127 static int __devinit set_up_nfc_hal(struct gpmi_nfc_data *this)
1128 {
1129         struct nfc_hal *nfc = NULL;
1130         int error;
1131
1132         /*
1133          * This structure contains the "safe" GPMI timing that should succeed
1134          * with any NAND Flash device
1135          * (although, with less-than-optimal performance).
1136          */
1137         static struct nand_timing  safe_timing = {
1138                 .data_setup_in_ns        = 80,
1139                 .data_hold_in_ns         = 60,
1140                 .address_setup_in_ns     = 25,
1141                 .gpmi_sample_delay_in_ns =  6,
1142                 .tREA_in_ns              = -1,
1143                 .tRLOH_in_ns             = -1,
1144                 .tRHOH_in_ns             = -1,
1145         };
1146
1147 #if defined(CONFIG_SOC_IMX23) || defined(CONFIG_SOC_IMX28)
1148         if (GPMI_IS_MX23(this) || GPMI_IS_MX28(this))
1149                 nfc = &gpmi_nfc_hal_imx23_imx28;
1150 #endif
1151 #if defined(CONFIG_SOC_IMX50)
1152         if (GPMI_IS_MX50(this))
1153                 nfc = &gpmi_nfc_hal_mx50;
1154 #endif
1155         BUG_ON(nfc == NULL);
1156         this->nfc = nfc;
1157
1158         /* Initialize the NFC HAL. */
1159         error = nfc->init(this);
1160         if (error)
1161                 return error;
1162
1163         /* Set up safe timing. */
1164         nfc->set_timing(this, &safe_timing);
1165         return 0;
1166 }
1167
1168 /* Creates/Removes sysfs files for this device.*/
1169 static void manage_sysfs_files(struct gpmi_nfc_data *this, int create)
1170 {
1171         struct device *dev = this->dev;
1172         struct device_attribute **attr;
1173         unsigned int i;
1174         int error;
1175
1176         for (i = 0, attr = device_attributes;
1177                         i < ARRAY_SIZE(device_attributes); i++, attr++) {
1178
1179                 if (create) {
1180                         error = device_create_file(dev, *attr);
1181                         if (error) {
1182                                 while (--attr >= device_attributes)
1183                                         device_remove_file(dev, *attr);
1184                                 return;
1185                         }
1186                 } else {
1187                         device_remove_file(dev, *attr);
1188                 }
1189         }
1190 }
1191
1192 static int read_page_prepare(struct gpmi_nfc_data *this,
1193                         void *destination, unsigned length,
1194                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
1195                         void **use_virt, dma_addr_t *use_phys)
1196 {
1197         struct device  *dev = this->dev;
1198         dma_addr_t destination_phys = ~0;
1199
1200         if (virt_addr_valid(destination))
1201                 destination_phys = dma_map_single(dev, destination,
1202                                                 length, DMA_FROM_DEVICE);
1203
1204         if (dma_mapping_error(dev, destination_phys)) {
1205                 if (alt_size < length) {
1206                         pr_info("Alternate buffer is too small\n");
1207                         return -ENOMEM;
1208                 }
1209
1210                 *use_virt = alt_virt;
1211                 *use_phys = alt_phys;
1212                 this->mil.direct_dma_map_ok = false;
1213         } else {
1214                 *use_virt = destination;
1215                 *use_phys = destination_phys;
1216                 this->mil.direct_dma_map_ok = true;
1217         }
1218         return 0;
1219 }
1220
1221 static void read_page_end(struct gpmi_nfc_data *this,
1222                         void *destination, unsigned length,
1223                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
1224                         void *used_virt, dma_addr_t used_phys)
1225 {
1226         if (this->mil.direct_dma_map_ok)
1227                 dma_unmap_single(this->dev, used_phys, length, DMA_FROM_DEVICE);
1228 }
1229
1230 static void read_page_swap_end(struct gpmi_nfc_data *this,
1231                         void *destination, unsigned length,
1232                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
1233                         void *used_virt, dma_addr_t used_phys)
1234 {
1235         if (!this->mil.direct_dma_map_ok)
1236                 memcpy(destination, alt_virt, length);
1237 }
1238
1239 static int send_page_prepare(struct gpmi_nfc_data *this,
1240                         const void *source, unsigned length,
1241                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
1242                         const void **use_virt, dma_addr_t *use_phys)
1243 {
1244         dma_addr_t source_phys = ~0;
1245         struct device *dev = this->dev;
1246
1247         if (virt_addr_valid(source))
1248                 source_phys = dma_map_single(dev,
1249                                 (void *)source, length, DMA_TO_DEVICE);
1250
1251         if (dma_mapping_error(dev, source_phys)) {
1252                 if (alt_size < length) {
1253                         pr_info("Alternate buffer is too small\n");
1254                         return -ENOMEM;
1255                 }
1256
1257                 /*
1258                  * Copy the contents of the source buffer into the alternate
1259                  * buffer and set up the return values accordingly.
1260                  */
1261                 memcpy(alt_virt, source, length);
1262
1263                 *use_virt = alt_virt;
1264                 *use_phys = alt_phys;
1265         } else {
1266                 *use_virt = source;
1267                 *use_phys = source_phys;
1268         }
1269         return 0;
1270 }
1271
1272 static void send_page_end(struct gpmi_nfc_data *this,
1273                         const void *source, unsigned length,
1274                         void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
1275                         const void *used_virt, dma_addr_t used_phys)
1276 {
1277         struct device *dev = this->dev;
1278         if (used_virt == source)
1279                 dma_unmap_single(dev, used_phys, length, DMA_TO_DEVICE);
1280 }
1281
1282 static void mil_free_dma_buffer(struct gpmi_nfc_data *this)
1283 {
1284         struct device *dev = this->dev;
1285         struct mil *mil = &this->mil;
1286
1287         if (mil->page_buffer_virt && virt_addr_valid(mil->page_buffer_virt))
1288                 dma_free_coherent(dev, mil->page_buffer_size,
1289                                         mil->page_buffer_virt,
1290                                         mil->page_buffer_phys);
1291         kfree(mil->cmd_buffer);
1292         kfree(mil->data_buffer_dma);
1293
1294         mil->cmd_buffer         = NULL;
1295         mil->data_buffer_dma    = NULL;
1296         mil->page_buffer_virt   = NULL;
1297         mil->page_buffer_size   =  0;
1298         mil->page_buffer_phys   = ~0;
1299 }
1300
1301 /* Allocate the DMA buffers */
1302 static int mil_alloc_dma_buffer(struct gpmi_nfc_data *this)
1303 {
1304         struct nfc_geometry *geo = &this->nfc_geometry;
1305         struct device *dev = this->dev;
1306         struct mil *mil = &this->mil;
1307
1308         /* [1] Allocate a command buffer. PAGE_SIZE is enough. */
1309         mil->cmd_buffer = kzalloc(PAGE_SIZE, GFP_DMA);
1310         if (mil->cmd_buffer == NULL)
1311                 goto error_alloc;
1312
1313         /* [2] Allocate a read/write data buffer. PAGE_SIZE is enough. */
1314         mil->data_buffer_dma = kzalloc(PAGE_SIZE, GFP_DMA);
1315         if (mil->data_buffer_dma == NULL)
1316                 goto error_alloc;
1317
1318         /*
1319          * [3] Allocate the page buffer.
1320          *
1321          * Both the payload buffer and the auxiliary buffer must appear on
1322          * 32-bit boundaries. We presume the size of the payload buffer is a
1323          * power of two and is much larger than four, which guarantees the
1324          * auxiliary buffer will appear on a 32-bit boundary.
1325          */
1326         mil->page_buffer_size = geo->payload_size_in_bytes +
1327                                 geo->auxiliary_size_in_bytes;
1328
1329         mil->page_buffer_virt = dma_alloc_coherent(dev, mil->page_buffer_size,
1330                                         &mil->page_buffer_phys, GFP_DMA);
1331         if (!mil->page_buffer_virt)
1332                 goto error_alloc;
1333
1334
1335         /* Slice up the page buffer. */
1336         mil->payload_virt = mil->page_buffer_virt;
1337         mil->payload_phys = mil->page_buffer_phys;
1338         mil->auxiliary_virt = mil->payload_virt + geo->payload_size_in_bytes;
1339         mil->auxiliary_phys = mil->payload_phys + geo->payload_size_in_bytes;
1340         return 0;
1341
1342 error_alloc:
1343         mil_free_dma_buffer(this);
1344         pr_info("allocate DMA buffer error!!\n");
1345         return -ENOMEM;
1346 }
1347
1348 static void mil_cmd_ctrl(struct mtd_info *mtd, int data, unsigned int ctrl)
1349 {
1350         struct nand_chip *nand = mtd->priv;
1351         struct gpmi_nfc_data *this = nand->priv;
1352         struct mil *mil = &this->mil;
1353         struct nfc_hal *nfc = this->nfc;
1354         int error;
1355
1356         /*
1357          * Every operation begins with a command byte and a series of zero or
1358          * more address bytes. These are distinguished by either the Address
1359          * Latch Enable (ALE) or Command Latch Enable (CLE) signals being
1360          * asserted. When MTD is ready to execute the command, it will deassert
1361          * both latch enables.
1362          *
1363          * Rather than run a separate DMA operation for every single byte, we
1364          * queue them up and run a single DMA operation for the entire series
1365          * of command and data bytes. NAND_CMD_NONE means the END of the queue.
1366          */
1367         if ((ctrl & (NAND_ALE | NAND_CLE))) {
1368                 if (data != NAND_CMD_NONE)
1369                         mil->cmd_buffer[mil->command_length++] = data;
1370                 return;
1371         }
1372
1373         if (!mil->command_length)
1374                 return;
1375
1376         error = nfc->send_command(this);
1377         if (error)
1378                 pr_info("Chip: %u, Error %d\n", mil->current_chip, error);
1379
1380         mil->command_length = 0;
1381 }
1382
1383 static int mil_dev_ready(struct mtd_info *mtd)
1384 {
1385         struct nand_chip *nand = mtd->priv;
1386         struct gpmi_nfc_data *this = nand->priv;
1387         struct nfc_hal *nfc = this->nfc;
1388         struct mil *mil = &this->mil;
1389
1390         return nfc->is_ready(this, mil->current_chip);
1391 }
1392
1393 static void mil_select_chip(struct mtd_info *mtd, int chip)
1394 {
1395         struct nand_chip *nand = mtd->priv;
1396         struct gpmi_nfc_data *this = nand->priv;
1397         struct nfc_hal *nfc = this->nfc;
1398         struct mil *mil = &this->mil;
1399
1400         if ((mil->current_chip < 0) && (chip >= 0))
1401                 nfc->begin(this);
1402         else if ((mil->current_chip >= 0) && (chip < 0))
1403                 nfc->end(this);
1404         else
1405                 ;
1406
1407         mil->current_chip = chip;
1408 }
1409
1410 static void mil_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
1411 {
1412         struct nand_chip *nand = mtd->priv;
1413         struct gpmi_nfc_data *this = nand->priv;
1414         struct nfc_hal *nfc = this->nfc;
1415         struct mil *mil = &this->mil;
1416
1417         logio(GPMI_DEBUG_READ);
1418         /* save the info in mil{} for future */
1419         mil->upper_buf  = buf;
1420         mil->upper_len  = len;
1421
1422         nfc->read_data(this);
1423 }
1424
1425 static void mil_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
1426 {
1427         struct nand_chip *nand = mtd->priv;
1428         struct gpmi_nfc_data *this = nand->priv;
1429         struct nfc_hal *nfc = this->nfc;
1430         struct mil *mil = &this->mil;
1431
1432         logio(GPMI_DEBUG_WRITE);
1433         /* save the info in mil{} for future */
1434         mil->upper_buf  = (uint8_t *)buf;
1435         mil->upper_len  = len;
1436
1437         nfc->send_data(this);
1438 }
1439
1440 static uint8_t mil_read_byte(struct mtd_info *mtd)
1441 {
1442         struct nand_chip *nand = mtd->priv;
1443         struct gpmi_nfc_data *this = nand->priv;
1444         struct mil *mil = &this->mil;
1445         uint8_t *buf = mil->data_buffer_dma;
1446
1447         mil_read_buf(mtd, buf, 1);
1448         return buf[0];
1449 }
1450
1451 /**
1452  * mil_handle_block_mark_swapping() - Handles block mark swapping.
1453  *
1454  * Note that, when this function is called, it doesn't know whether it's
1455  * swapping the block mark, or swapping it *back* -- but it doesn't matter
1456  * because the the operation is the same.
1457  *
1458  * @this:       Per-device data.
1459  * @payload:    A pointer to the payload buffer.
1460  * @auxiliary:  A pointer to the auxiliary buffer.
1461  */
1462 static void mil_handle_block_mark_swapping(struct gpmi_nfc_data *this,
1463                                                 void *payload, void *auxiliary)
1464 {
1465         struct nfc_geometry *nfc_geo = &this->nfc_geometry;
1466         unsigned char *p;
1467         unsigned char *a;
1468         unsigned int  bit;
1469         unsigned char mask;
1470         unsigned char from_data;
1471         unsigned char from_oob;
1472
1473         /* Check if we're doing block mark swapping. */
1474         if (!this->swap_block_mark)
1475                 return;
1476
1477         /*
1478          * If control arrives here, we're swapping. Make some convenience
1479          * variables.
1480          */
1481         bit = nfc_geo->block_mark_bit_offset;
1482         p   = payload + nfc_geo->block_mark_byte_offset;
1483         a   = auxiliary;
1484
1485         /*
1486          * Get the byte from the data area that overlays the block mark. Since
1487          * the ECC engine applies its own view to the bits in the page, the
1488          * physical block mark won't (in general) appear on a byte boundary in
1489          * the data.
1490          */
1491         from_data = (p[0] >> bit) | (p[1] << (8 - bit));
1492
1493         /* Get the byte from the OOB. */
1494         from_oob = a[0];
1495
1496         /* Swap them. */
1497         a[0] = from_data;
1498
1499         mask = (0x1 << bit) - 1;
1500         p[0] = (p[0] & mask) | (from_oob << bit);
1501
1502         mask = ~0 << bit;
1503         p[1] = (p[1] & mask) | (from_oob >> (8 - bit));
1504 }
1505
1506 static int mil_ecc_read_page(struct mtd_info *mtd, struct nand_chip *nand,
1507                                 uint8_t *buf, int page)
1508 {
1509         struct gpmi_nfc_data *this = nand->priv;
1510         struct nfc_hal *nfc = this->nfc;
1511         struct nfc_geometry *nfc_geo = &this->nfc_geometry;
1512         struct mil *mil = &this->mil;
1513         void          *payload_virt;
1514         dma_addr_t    payload_phys;
1515         void          *auxiliary_virt;
1516         dma_addr_t    auxiliary_phys;
1517         unsigned int  i;
1518         unsigned char *status;
1519         unsigned int  failed;
1520         unsigned int  corrected;
1521         int           error;
1522
1523         logio(GPMI_DEBUG_ECC_READ);
1524         error = read_page_prepare(this, buf, mtd->writesize,
1525                                         mil->payload_virt, mil->payload_phys,
1526                                         nfc_geo->payload_size_in_bytes,
1527                                         &payload_virt, &payload_phys);
1528         if (error) {
1529                 pr_info("Inadequate DMA buffer\n");
1530                 error = -ENOMEM;
1531                 return error;
1532         }
1533         auxiliary_virt = mil->auxiliary_virt;
1534         auxiliary_phys = mil->auxiliary_phys;
1535
1536         /* ask the NFC */
1537         error = nfc->read_page(this, payload_phys, auxiliary_phys);
1538         read_page_end(this, buf, mtd->writesize,
1539                         mil->payload_virt, mil->payload_phys,
1540                         nfc_geo->payload_size_in_bytes,
1541                         payload_virt, payload_phys);
1542         if (error) {
1543                 pr_info("Error in ECC-based read: %d\n", error);
1544                 goto exit_nfc;
1545         }
1546
1547         /* handle the block mark swapping */
1548         mil_handle_block_mark_swapping(this, payload_virt, auxiliary_virt);
1549
1550         /* Loop over status bytes, accumulating ECC status. */
1551         failed          = 0;
1552         corrected       = 0;
1553         status          = auxiliary_virt + nfc_geo->auxiliary_status_offset;
1554
1555         for (i = 0; i < nfc_geo->ecc_chunk_count; i++, status++) {
1556                 if ((*status == STATUS_GOOD) || (*status == STATUS_ERASED))
1557                         continue;
1558
1559                 if (*status == STATUS_UNCORRECTABLE) {
1560                         failed++;
1561                         continue;
1562                 }
1563                 corrected += *status;
1564         }
1565
1566         /*
1567          * Propagate ECC status to the owning MTD only when failed or
1568          * corrected times nearly reaches our ECC correction threshold.
1569          */
1570         if (failed || corrected >= (nfc_geo->ecc_strength - 1)) {
1571                 mtd->ecc_stats.failed    += failed;
1572                 mtd->ecc_stats.corrected += corrected;
1573         }
1574
1575         /*
1576          * It's time to deliver the OOB bytes. See mil_ecc_read_oob() for
1577          * details about our policy for delivering the OOB.
1578          *
1579          * We fill the caller's buffer with set bits, and then copy the block
1580          * mark to th caller's buffer. Note that, if block mark swapping was
1581          * necessary, it has already been done, so we can rely on the first
1582          * byte of the auxiliary buffer to contain the block mark.
1583          */
1584         memset(nand->oob_poi, ~0, mtd->oobsize);
1585         nand->oob_poi[0] = ((uint8_t *) auxiliary_virt)[0];
1586
1587         read_page_swap_end(this, buf, mtd->writesize,
1588                         mil->payload_virt, mil->payload_phys,
1589                         nfc_geo->payload_size_in_bytes,
1590                         payload_virt, payload_phys);
1591 exit_nfc:
1592         return error;
1593 }
1594
1595 static void mil_ecc_write_page(struct mtd_info *mtd,
1596                                 struct nand_chip *nand, const uint8_t *buf)
1597 {
1598         struct gpmi_nfc_data *this = nand->priv;
1599         struct nfc_hal *nfc =  this->nfc;
1600         struct nfc_geometry *nfc_geo = &this->nfc_geometry;
1601         struct mil *mil = &this->mil;
1602         const void *payload_virt;
1603         dma_addr_t payload_phys;
1604         const void *auxiliary_virt;
1605         dma_addr_t auxiliary_phys;
1606         int        error;
1607
1608         logio(GPMI_DEBUG_ECC_WRITE);
1609         if (this->swap_block_mark) {
1610                 /*
1611                  * If control arrives here, we're doing block mark swapping.
1612                  * Since we can't modify the caller's buffers, we must copy them
1613                  * into our own.
1614                  */
1615                 memcpy(mil->payload_virt, buf, mtd->writesize);
1616                 payload_virt = mil->payload_virt;
1617                 payload_phys = mil->payload_phys;
1618
1619                 memcpy(mil->auxiliary_virt, nand->oob_poi,
1620                                 nfc_geo->auxiliary_size_in_bytes);
1621                 auxiliary_virt = mil->auxiliary_virt;
1622                 auxiliary_phys = mil->auxiliary_phys;
1623
1624                 /* Handle block mark swapping. */
1625                 mil_handle_block_mark_swapping(this,
1626                                 (void *) payload_virt, (void *) auxiliary_virt);
1627         } else {
1628                 /*
1629                  * If control arrives here, we're not doing block mark swapping,
1630                  * so we can to try and use the caller's buffers.
1631                  */
1632                 error = send_page_prepare(this,
1633                                 buf, mtd->writesize,
1634                                 mil->payload_virt, mil->payload_phys,
1635                                 nfc_geo->payload_size_in_bytes,
1636                                 &payload_virt, &payload_phys);
1637                 if (error) {
1638                         pr_info("Inadequate payload DMA buffer\n");
1639                         return;
1640                 }
1641
1642                 error = send_page_prepare(this,
1643                                 nand->oob_poi, mtd->oobsize,
1644                                 mil->auxiliary_virt, mil->auxiliary_phys,
1645                                 nfc_geo->auxiliary_size_in_bytes,
1646                                 &auxiliary_virt, &auxiliary_phys);
1647                 if (error) {
1648                         pr_info("Inadequate auxiliary DMA buffer\n");
1649                         goto exit_auxiliary;
1650                 }
1651         }
1652
1653         /* Ask the NFC. */
1654         error = nfc->send_page(this, payload_phys, auxiliary_phys);
1655         if (error)
1656                 pr_info("Error in ECC-based write: %d\n", error);
1657
1658         if (!this->swap_block_mark) {
1659                 send_page_end(this, nand->oob_poi, mtd->oobsize,
1660                                 mil->auxiliary_virt, mil->auxiliary_phys,
1661                                 nfc_geo->auxiliary_size_in_bytes,
1662                                 auxiliary_virt, auxiliary_phys);
1663 exit_auxiliary:
1664                 send_page_end(this, buf, mtd->writesize,
1665                                 mil->payload_virt, mil->payload_phys,
1666                                 nfc_geo->payload_size_in_bytes,
1667                                 payload_virt, payload_phys);
1668         }
1669 }
1670
1671 static int mil_hook_block_markbad(struct mtd_info *mtd, loff_t ofs)
1672 {
1673         register struct nand_chip *chip = mtd->priv;
1674         struct gpmi_nfc_data *this = chip->priv;
1675         struct mil *mil = &this->mil;
1676         int ret;
1677
1678         mil->marking_a_bad_block = true;
1679         ret = mil->hooked_block_markbad(mtd, ofs);
1680         mil->marking_a_bad_block = false;
1681         return ret;
1682 }
1683
1684 /**
1685  * mil_ecc_read_oob() - MTD Interface ecc.read_oob().
1686  *
1687  * There are several places in this driver where we have to handle the OOB and
1688  * block marks. This is the function where things are the most complicated, so
1689  * this is where we try to explain it all. All the other places refer back to
1690  * here.
1691  *
1692  * These are the rules, in order of decreasing importance:
1693  *
1694  * 1) Nothing the caller does can be allowed to imperil the block mark, so all
1695  *    write operations take measures to protect it.
1696  *
1697  * 2) In read operations, the first byte of the OOB we return must reflect the
1698  *    true state of the block mark, no matter where that block mark appears in
1699  *    the physical page.
1700  *
1701  * 3) ECC-based read operations return an OOB full of set bits (since we never
1702  *    allow ECC-based writes to the OOB, it doesn't matter what ECC-based reads
1703  *    return).
1704  *
1705  * 4) "Raw" read operations return a direct view of the physical bytes in the
1706  *    page, using the conventional definition of which bytes are data and which
1707  *    are OOB. This gives the caller a way to see the actual, physical bytes
1708  *    in the page, without the distortions applied by our ECC engine.
1709  *
1710  *
1711  * What we do for this specific read operation depends on two questions:
1712  *
1713  * 1) Are we doing a "raw" read, or an ECC-based read?
1714  *
1715  * 2) Are we using block mark swapping or transcription?
1716  *
1717  * There are four cases, illustrated by the following Karnaugh map:
1718  *
1719  *                    |           Raw           |         ECC-based       |
1720  *       -------------+-------------------------+-------------------------+
1721  *                    | Read the conventional   |                         |
1722  *                    | OOB at the end of the   |                         |
1723  *       Swapping     | page and return it. It  |                         |
1724  *                    | contains exactly what   |                         |
1725  *                    | we want.                | Read the block mark and |
1726  *       -------------+-------------------------+ return it in a buffer   |
1727  *                    | Read the conventional   | full of set bits.       |
1728  *                    | OOB at the end of the   |                         |
1729  *                    | page and also the block |                         |
1730  *       Transcribing | mark in the metadata.   |                         |
1731  *                    | Copy the block mark     |                         |
1732  *                    | into the first byte of  |                         |
1733  *                    | the OOB.                |                         |
1734  *       -------------+-------------------------+-------------------------+
1735  *
1736  * Note that we break rule #4 in the Transcribing/Raw case because we're not
1737  * giving an accurate view of the actual, physical bytes in the page (we're
1738  * overwriting the block mark). That's OK because it's more important to follow
1739  * rule #2.
1740  *
1741  * It turns out that knowing whether we want an "ECC-based" or "raw" read is not
1742  * easy. When reading a page, for example, the NAND Flash MTD code calls our
1743  * ecc.read_page or ecc.read_page_raw function. Thus, the fact that MTD wants an
1744  * ECC-based or raw view of the page is implicit in which function it calls
1745  * (there is a similar pair of ECC-based/raw functions for writing).
1746  *
1747  * Since MTD assumes the OOB is not covered by ECC, there is no pair of
1748  * ECC-based/raw functions for reading or or writing the OOB. The fact that the
1749  * caller wants an ECC-based or raw view of the page is not propagated down to
1750  * this driver.
1751  *
1752  * @mtd:     A pointer to the owning MTD.
1753  * @nand:    A pointer to the owning NAND Flash MTD.
1754  * @page:    The page number to read.
1755  * @sndcmd:  Indicates this function should send a command to the chip before
1756  *           reading the out-of-band bytes. This is only false for small page
1757  *           chips that support auto-increment.
1758  */
1759 static int mil_ecc_read_oob(struct mtd_info *mtd, struct nand_chip *nand,
1760                                                         int page, int sndcmd)
1761 {
1762         struct gpmi_nfc_data *this = nand->priv;
1763
1764         /* clear the OOB buffer */
1765         memset(nand->oob_poi, ~0, mtd->oobsize);
1766
1767         /* Read out the conventional OOB. */
1768         nand->cmdfunc(mtd, NAND_CMD_READ0, mtd->writesize, page);
1769         nand->read_buf(mtd, nand->oob_poi, mtd->oobsize);
1770
1771         /*
1772          * Now, we want to make sure the block mark is correct. In the
1773          * Swapping/Raw case, we already have it. Otherwise, we need to
1774          * explicitly read it.
1775          */
1776         if (!this->swap_block_mark) {
1777                 /* Read the block mark into the first byte of the OOB buffer. */
1778                 nand->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1779                 nand->oob_poi[0] = nand->read_byte(mtd);
1780         }
1781
1782         /*
1783          * Return true, indicating that the next call to this function must send
1784          * a command.
1785          */
1786         return true;
1787 }
1788
1789 static int mil_ecc_write_oob(struct mtd_info *mtd,
1790                                 struct nand_chip *nand, int page)
1791 {
1792         struct gpmi_nfc_data *this = nand->priv;
1793         struct device *dev = this->dev;
1794         struct mil *mil = &this->mil;
1795         uint8_t *block_mark;
1796         int block_mark_column;
1797         int status;
1798         int error = 0;
1799
1800         /* Only marking a block bad is permitted to write the OOB. */
1801         if (!mil->marking_a_bad_block) {
1802                 dev_emerg(dev, "This driver doesn't support writing the OOB\n");
1803                 WARN_ON(1);
1804                 error = -EIO;
1805                 goto exit;
1806         }
1807
1808         if (this->swap_block_mark)
1809                 block_mark_column = mtd->writesize;
1810         else
1811                 block_mark_column = 0;
1812
1813         /* Write the block mark. */
1814         block_mark = mil->data_buffer_dma;
1815         block_mark[0] = 0; /* bad block marker */
1816
1817         nand->cmdfunc(mtd, NAND_CMD_SEQIN, block_mark_column, page);
1818         nand->write_buf(mtd, block_mark, 1);
1819         nand->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1820
1821         status = nand->waitfunc(mtd, nand);
1822
1823         /* Check if it worked. */
1824         if (status & NAND_STATUS_FAIL)
1825                 error = -EIO;
1826 exit:
1827         return error;
1828 }
1829
1830 /**
1831  * mil_block_bad - Claims all blocks are good.
1832  *
1833  * In principle, this function is *only* called when the NAND Flash MTD system
1834  * isn't allowed to keep an in-memory bad block table, so it is forced to ask
1835  * the driver for bad block information.
1836  *
1837  * In fact, we permit the NAND Flash MTD system to have an in-memory BBT, so
1838  * this function is *only* called when we take it away.
1839  *
1840  * We take away the in-memory BBT when the user sets the "ignorebad" parameter,
1841  * which indicates that all blocks should be reported good.
1842  *
1843  * Thus, this function is only called when we want *all* blocks to look good,
1844  * so it *always* return success.
1845  *
1846  * @mtd:      Ignored.
1847  * @ofs:      Ignored.
1848  * @getchip:  Ignored.
1849  */
1850 static int mil_block_bad(struct mtd_info *mtd, loff_t ofs, int getchip)
1851 {
1852         return 0;
1853 }
1854
1855 static int __devinit nand_boot_set_geometry(struct gpmi_nfc_data *this)
1856 {
1857         struct boot_rom_geometry *geometry = &this->rom_geometry;
1858
1859         /*
1860          * Set the boot block stride size.
1861          *
1862          * In principle, we should be reading this from the OTP bits, since
1863          * that's where the ROM is going to get it. In fact, we don't have any
1864          * way to read the OTP bits, so we go with the default and hope for the
1865          * best.
1866          */
1867         geometry->stride_size_in_pages = 64;
1868
1869         /*
1870          * Set the search area stride exponent.
1871          *
1872          * In principle, we should be reading this from the OTP bits, since
1873          * that's where the ROM is going to get it. In fact, we don't have any
1874          * way to read the OTP bits, so we go with the default and hope for the
1875          * best.
1876          */
1877         geometry->search_area_stride_exponent = 2;
1878
1879         if (gpmi_debug & GPMI_DEBUG_INIT)
1880                 pr_info("stride size in page : %d, search areas : %d\n",
1881                         geometry->stride_size_in_pages,
1882                         geometry->search_area_stride_exponent);
1883         return 0;
1884 }
1885
1886 static const char  *fingerprint = "STMP";
1887 static int __devinit mx23_check_transcription_stamp(struct gpmi_nfc_data *this)
1888 {
1889         struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1890         struct mil *mil = &this->mil;
1891         struct mtd_info *mtd = &mil->mtd;
1892         struct nand_chip *nand = &mil->nand;
1893         unsigned int search_area_size_in_strides;
1894         unsigned int stride;
1895         unsigned int page;
1896         loff_t byte;
1897         uint8_t *buffer = nand->buffers->databuf;
1898         int saved_chip_number;
1899         int found_an_ncb_fingerprint = false;
1900
1901         /* Compute the number of strides in a search area. */
1902         search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1903
1904         /* Select chip 0. */
1905         saved_chip_number = mil->current_chip;
1906         nand->select_chip(mtd, 0);
1907
1908         /*
1909          * Loop through the first search area, looking for the NCB fingerprint.
1910          */
1911         pr_info("Scanning for an NCB fingerprint...\n");
1912
1913         for (stride = 0; stride < search_area_size_in_strides; stride++) {
1914                 /* Compute the page and byte addresses. */
1915                 page = stride * rom_geo->stride_size_in_pages;
1916                 byte = page   * mtd->writesize;
1917
1918                 pr_info("  Looking for a fingerprint in page 0x%x\n", page);
1919
1920                 /*
1921                  * Read the NCB fingerprint. The fingerprint is four bytes long
1922                  * and starts in the 12th byte of the page.
1923                  */
1924                 nand->cmdfunc(mtd, NAND_CMD_READ0, 12, page);
1925                 nand->read_buf(mtd, buffer, strlen(fingerprint));
1926
1927                 /* Look for the fingerprint. */
1928                 if (!memcmp(buffer, fingerprint, strlen(fingerprint))) {
1929                         found_an_ncb_fingerprint = true;
1930                         break;
1931                 }
1932
1933         }
1934
1935         /* Deselect chip 0. */
1936         nand->select_chip(mtd, saved_chip_number);
1937
1938         if (found_an_ncb_fingerprint)
1939                 pr_info("  Found a fingerprint\n");
1940         else
1941                 pr_info("  No fingerprint found\n");
1942         return found_an_ncb_fingerprint;
1943 }
1944
1945 /* Writes a transcription stamp. */
1946 static int __devinit mx23_write_transcription_stamp(struct gpmi_nfc_data *this)
1947 {
1948         struct device *dev = this->dev;
1949         struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1950         struct mil *mil = &this->mil;
1951         struct mtd_info *mtd = &mil->mtd;
1952         struct nand_chip *nand = &mil->nand;
1953         unsigned int block_size_in_pages;
1954         unsigned int search_area_size_in_strides;
1955         unsigned int search_area_size_in_pages;
1956         unsigned int search_area_size_in_blocks;
1957         unsigned int block;
1958         unsigned int stride;
1959         unsigned int page;
1960         loff_t       byte;
1961         uint8_t      *buffer = nand->buffers->databuf;
1962         int saved_chip_number;
1963         int status;
1964
1965         /* Compute the search area geometry. */
1966         block_size_in_pages = mtd->erasesize / mtd->writesize;
1967         search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1968         search_area_size_in_pages = search_area_size_in_strides *
1969                                         rom_geo->stride_size_in_pages;
1970         search_area_size_in_blocks =
1971                   (search_area_size_in_pages + (block_size_in_pages - 1)) /
1972                                     block_size_in_pages;
1973
1974         pr_info("-------------------------------------------\n");
1975         pr_info("Search Area Geometry\n");
1976         pr_info("-------------------------------------------\n");
1977         pr_info("Search Area in Blocks : %u\n", search_area_size_in_blocks);
1978         pr_info("Search Area in Strides: %u\n", search_area_size_in_strides);
1979         pr_info("Search Area in Pages  : %u\n", search_area_size_in_pages);
1980
1981         /* Select chip 0. */
1982         saved_chip_number = mil->current_chip;
1983         nand->select_chip(mtd, 0);
1984
1985         /* Loop over blocks in the first search area, erasing them. */
1986         pr_info("Erasing the search area...\n");
1987
1988         for (block = 0; block < search_area_size_in_blocks; block++) {
1989                 /* Compute the page address. */
1990                 page = block * block_size_in_pages;
1991
1992                 /* Erase this block. */
1993                 pr_info("  Erasing block 0x%x\n", block);
1994                 nand->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1995                 nand->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1996
1997                 /* Wait for the erase to finish. */
1998                 status = nand->waitfunc(mtd, nand);
1999                 if (status & NAND_STATUS_FAIL)
2000                         dev_err(dev, "[%s] Erase failed.\n", __func__);
2001         }
2002
2003         /* Write the NCB fingerprint into the page buffer. */
2004         memset(buffer, ~0, mtd->writesize);
2005         memset(nand->oob_poi, ~0, mtd->oobsize);
2006         memcpy(buffer + 12, fingerprint, strlen(fingerprint));
2007
2008         /* Loop through the first search area, writing NCB fingerprints. */
2009         pr_info("Writing NCB fingerprints...\n");
2010         for (stride = 0; stride < search_area_size_in_strides; stride++) {
2011                 /* Compute the page and byte addresses. */
2012                 page = stride * rom_geo->stride_size_in_pages;
2013                 byte = page   * mtd->writesize;
2014
2015                 /* Write the first page of the current stride. */
2016                 pr_info("  Writing an NCB fingerprint in page 0x%x\n", page);
2017                 nand->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2018                 nand->ecc.write_page_raw(mtd, nand, buffer);
2019                 nand->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2020
2021                 /* Wait for the write to finish. */
2022                 status = nand->waitfunc(mtd, nand);
2023                 if (status & NAND_STATUS_FAIL)
2024                         dev_err(dev, "[%s] Write failed.\n", __func__);
2025         }
2026
2027         /* Deselect chip 0. */
2028         nand->select_chip(mtd, saved_chip_number);
2029         return 0;
2030 }
2031
2032 static int __devinit mx23_boot_init(struct gpmi_nfc_data  *this)
2033 {
2034         struct device *dev = this->dev;
2035         struct mil *mil = &this->mil;
2036         struct nand_chip *nand = &mil->nand;
2037         struct mtd_info *mtd = &mil->mtd;
2038         unsigned int block_count;
2039         unsigned int block;
2040         int     chip;
2041         int     page;
2042         loff_t  byte;
2043         uint8_t block_mark;
2044         int     error = 0;
2045
2046         /*
2047          * If control arrives here, we can't use block mark swapping, which
2048          * means we're forced to use transcription. First, scan for the
2049          * transcription stamp. If we find it, then we don't have to do
2050          * anything -- the block marks are already transcribed.
2051          */
2052         if (mx23_check_transcription_stamp(this))
2053                 return 0;
2054
2055         /*
2056          * If control arrives here, we couldn't find a transcription stamp, so
2057          * so we presume the block marks are in the conventional location.
2058          */
2059         pr_info("Transcribing bad block marks...\n");
2060
2061         /* Compute the number of blocks in the entire medium. */
2062         block_count = nand->chipsize >> nand->phys_erase_shift;
2063
2064         /*
2065          * Loop over all the blocks in the medium, transcribing block marks as
2066          * we go.
2067          */
2068         for (block = 0; block < block_count; block++) {
2069                 /*
2070                  * Compute the chip, page and byte addresses for this block's
2071                  * conventional mark.
2072                  */
2073                 chip = block >> (nand->chip_shift - nand->phys_erase_shift);
2074                 page = block << (nand->phys_erase_shift - nand->page_shift);
2075                 byte = block <<  nand->phys_erase_shift;
2076
2077                 /* Select the chip. */
2078                 nand->select_chip(mtd, chip);
2079
2080                 /* Send the command to read the conventional block mark. */
2081                 nand->cmdfunc(mtd, NAND_CMD_READ0, mtd->writesize, page);
2082
2083                 /* Read the conventional block mark. */
2084                 block_mark = nand->read_byte(mtd);
2085
2086                 /*
2087                  * Check if the block is marked bad. If so, we need to mark it
2088                  * again, but this time the result will be a mark in the
2089                  * location where we transcribe block marks.
2090                  *
2091                  * Notice that we have to explicitly set the marking_a_bad_block
2092                  * member before we call through the block_markbad function
2093                  * pointer in the owning struct nand_chip. If we could call
2094                  * though the block_markbad function pointer in the owning
2095                  * struct mtd_info, which we have hooked, then this would be
2096                  * taken care of for us. Unfortunately, we can't because that
2097                  * higher-level code path will do things like consulting the
2098                  * in-memory bad block table -- which doesn't even exist yet!
2099                  * So, we have to call at a lower level and handle some details
2100                  * ourselves.
2101                  */
2102                 if (block_mark != 0xff) {
2103                         pr_info("Transcribing mark in block %u\n", block);
2104                         mil->marking_a_bad_block = true;
2105                         error = nand->block_markbad(mtd, byte);
2106                         mil->marking_a_bad_block = false;
2107                         if (error)
2108                                 dev_err(dev, "Failed to mark block bad with "
2109                                                         "error %d\n", error);
2110                 }
2111
2112                 /* Deselect the chip. */
2113                 nand->select_chip(mtd, -1);
2114         }
2115
2116         /* Write the stamp that indicates we've transcribed the block marks. */
2117         mx23_write_transcription_stamp(this);
2118         return 0;
2119 }
2120
2121 static int __devinit nand_boot_init(struct gpmi_nfc_data  *this)
2122 {
2123         nand_boot_set_geometry(this);
2124
2125         /* This is ROM arch-specific initilization before the BBT scanning. */
2126         if (GPMI_IS_MX23(this))
2127                 return mx23_boot_init(this);
2128         return 0;
2129 }
2130
2131 static void show_nfc_geometry(struct nfc_geometry *geo)
2132 {
2133         pr_info("---------------------------------------\n");
2134         pr_info("       NFC Geometry (used by BCH)\n");
2135         pr_info("---------------------------------------\n");
2136         pr_info("ECC Algorithm          : %s\n", geo->ecc_algorithm);
2137         pr_info("ECC Strength           : %u\n", geo->ecc_strength);
2138         pr_info("Page Size in Bytes     : %u\n", geo->page_size_in_bytes);
2139         pr_info("Metadata Size in Bytes : %u\n", geo->metadata_size_in_bytes);
2140         pr_info("ECC Chunk Size in Bytes: %u\n", geo->ecc_chunk_size_in_bytes);
2141         pr_info("ECC Chunk Count        : %u\n", geo->ecc_chunk_count);
2142         pr_info("Payload Size in Bytes  : %u\n", geo->payload_size_in_bytes);
2143         pr_info("Auxiliary Size in Bytes: %u\n", geo->auxiliary_size_in_bytes);
2144         pr_info("Auxiliary Status Offset: %u\n", geo->auxiliary_status_offset);
2145         pr_info("Block Mark Byte Offset : %u\n", geo->block_mark_byte_offset);
2146         pr_info("Block Mark Bit Offset  : %u\n", geo->block_mark_bit_offset);
2147 }
2148
2149 static int __devinit mil_set_geometry(struct gpmi_nfc_data *this)
2150 {
2151         struct nfc_hal *nfc = this->nfc;
2152         struct nfc_geometry *geo = &this->nfc_geometry;
2153         int error;
2154
2155         /* Free the temporary DMA memory for read ID case */
2156         mil_free_dma_buffer(this);
2157
2158         /* Set up the NFC geometry which is used by BCH. */
2159         error = nfc->set_geometry(this);
2160         if (error != 0) {
2161                 pr_info("NFC set geometry error : %d\n", error);
2162                 return error;
2163         }
2164         if (gpmi_debug & GPMI_DEBUG_INIT)
2165                 show_nfc_geometry(geo);
2166
2167         /* Alloc the new DMA buffers according to the pagesize and oobsize */
2168         return mil_alloc_dma_buffer(this);
2169 }
2170
2171 static int mil_pre_bbt_scan(struct gpmi_nfc_data  *this)
2172 {
2173         struct nand_chip *nand = &this->mil.nand;
2174         struct mtd_info *mtd = &this->mil.mtd;
2175         struct nand_ecclayout *layout = nand->ecc.layout;
2176         struct nfc_hal *nfc = this->nfc;
2177         int error;
2178
2179         /* fix the ECC layout before the scanning */
2180         layout->eccbytes          = 0;
2181         layout->oobavail          = mtd->oobsize;
2182         layout->oobfree[0].offset = 0;
2183         layout->oobfree[0].length = mtd->oobsize;
2184
2185         mtd->oobavail = nand->ecc.layout->oobavail;
2186
2187         /* Set up swap block-mark, must be set before the mil_set_geometry() */
2188         if (GPMI_IS_MX23(this))
2189                 this->swap_block_mark = false;
2190         else
2191                 this->swap_block_mark = true;
2192
2193         /* Set up the medium geometry */
2194         error = mil_set_geometry(this);
2195         if (error)
2196                 return error;
2197
2198         /* extra init */
2199         if (nfc->extra_init) {
2200                 error = nfc->extra_init(this);
2201                 if (error != 0)
2202                         return error;
2203         }
2204
2205         /* NAND boot init, depends on the mil_set_geometry(). */
2206         return nand_boot_init(this);
2207 }
2208
2209 static int mil_scan_bbt(struct mtd_info *mtd)
2210 {
2211         struct nand_chip *nand = mtd->priv;
2212         struct gpmi_nfc_data *this = nand->priv;
2213         int error;
2214
2215         /* Prepare for the BBT scan. */
2216         error = mil_pre_bbt_scan(this);
2217         if (error)
2218                 return error;
2219
2220         /* use the default BBT implementation */
2221         return nand_default_bbt(mtd);
2222 }
2223
2224 static const char *cmd_parse[] = {"cmdlinepart", NULL};
2225 static int __devinit mil_partitions_init(struct gpmi_nfc_data *this)
2226 {
2227         struct gpmi_nfc_platform_data *pdata = this->pdata;
2228         struct mil *mil = &this->mil;
2229         struct mtd_info *mtd = &mil->mtd;
2230
2231         /* use the command line for simple partitions layout */
2232         mil->partition_count = parse_mtd_partitions(mtd, cmd_parse,
2233                                                 &mil->partitions, 0);
2234         if (mil->partition_count)
2235                 return add_mtd_partitions(mtd, mil->partitions,
2236                                         mil->partition_count);
2237
2238         /* The complicated partitions layout uses this. */
2239         if (pdata->partitions && pdata->partition_count > 0)
2240                 return add_mtd_partitions(mtd, pdata->partitions,
2241                                         pdata->partition_count);
2242         return add_mtd_device(mtd);
2243 }
2244
2245 static void mil_partitions_exit(struct gpmi_nfc_data *this)
2246 {
2247         struct mil *mil = &this->mil;
2248
2249         if (mil->partition_count) {
2250                 struct mtd_info *mtd = &mil->mtd;
2251
2252                 del_mtd_partitions(mtd);
2253                 kfree(mil->partitions);
2254                 mil->partition_count = 0;
2255         }
2256 }
2257
2258 /* Initializes the MTD Interface Layer */
2259 static int __devinit gpmi_nfc_mil_init(struct gpmi_nfc_data *this)
2260 {
2261         struct gpmi_nfc_platform_data *pdata = this->pdata;
2262         struct mil *mil = &this->mil;
2263         struct mtd_info  *mtd = &mil->mtd;
2264         struct nand_chip *nand = &mil->nand;
2265         int error;
2266
2267         /* Initialize MIL data */
2268         mil->current_chip       = -1;
2269         mil->command_length     =  0;
2270         mil->page_buffer_virt   =  NULL;
2271         mil->page_buffer_phys   = ~0;
2272         mil->page_buffer_size   =  0;
2273
2274         /* Initialize the MTD data structures */
2275         mtd->priv               = nand;
2276         mtd->name               = "gpmi-nfc";
2277         mtd->owner              = THIS_MODULE;
2278         nand->priv              = this;
2279
2280         /* Controls */
2281         nand->select_chip       = mil_select_chip;
2282         nand->cmd_ctrl          = mil_cmd_ctrl;
2283         nand->dev_ready         = mil_dev_ready;
2284
2285         /*
2286          * Low-level I/O :
2287          *      We don't support a 16-bit NAND Flash bus,
2288          *      so we don't implement read_word.
2289          */
2290         nand->read_byte         = mil_read_byte;
2291         nand->read_buf          = mil_read_buf;
2292         nand->write_buf         = mil_write_buf;
2293
2294         /* ECC-aware I/O */
2295         nand->ecc.read_page     = mil_ecc_read_page;
2296         nand->ecc.write_page    = mil_ecc_write_page;
2297
2298         /* High-level I/O */
2299         nand->ecc.read_oob      = mil_ecc_read_oob;
2300         nand->ecc.write_oob     = mil_ecc_write_oob;
2301
2302         /* Bad Block Management */
2303         nand->block_bad         = mil_block_bad;
2304         nand->scan_bbt          = mil_scan_bbt;
2305         nand->badblock_pattern  = &gpmi_bbt_descr;
2306
2307         /* Disallow partial page writes */
2308         nand->options           |= NAND_NO_SUBPAGE_WRITE;
2309
2310         /*
2311          * Tell the NAND Flash MTD system that we'll be handling ECC with our
2312          * own hardware. It turns out that we still have to fill in the ECC size
2313          * because the MTD code will divide by it -- even though it doesn't
2314          * actually care.
2315          */
2316         nand->ecc.mode          = NAND_ECC_HW;
2317         nand->ecc.size          = 1;
2318
2319         /* use our layout */
2320         nand->ecc.layout = &mil->oob_layout;
2321
2322         /* Allocate a temporary DMA buffer for reading ID in the nand_scan() */
2323         this->nfc_geometry.payload_size_in_bytes        = 1024;
2324         this->nfc_geometry.auxiliary_size_in_bytes      = 128;
2325         error = mil_alloc_dma_buffer(this);
2326         if (error)
2327                 goto exit_dma_allocation;
2328
2329         printk(KERN_INFO "GPMI-NFC : Scanning for NAND Flash chips...\n");
2330         error = nand_scan(mtd, pdata->max_chip_count);
2331         if (error) {
2332                 pr_info("Chip scan failed\n");
2333                 goto exit_nand_scan;
2334         }
2335
2336         /* Take over the management of the OOB */
2337         mil->hooked_block_markbad = mtd->block_markbad;
2338         mtd->block_markbad        = mil_hook_block_markbad;
2339
2340         /* Construct partitions as necessary. */
2341         error = mil_partitions_init(this);
2342         if (error)
2343                 goto exit_partitions;
2344         return 0;
2345
2346 exit_partitions:
2347         nand_release(&mil->mtd);
2348 exit_nand_scan:
2349         mil_free_dma_buffer(this);
2350 exit_dma_allocation:
2351         return error;
2352 }
2353
2354 void gpmi_nfc_mil_exit(struct gpmi_nfc_data *this)
2355 {
2356         struct mil *mil = &this->mil;
2357
2358         mil_partitions_exit(this);
2359         nand_release(&mil->mtd);
2360         mil_free_dma_buffer(this);
2361 }
2362
2363 static int __devinit gpmi_nfc_probe(struct platform_device *pdev)
2364 {
2365         struct gpmi_nfc_platform_data *pdata = pdev->dev.platform_data;
2366         struct gpmi_nfc_data *this;
2367         int error;
2368
2369         this = kzalloc(sizeof(*this), GFP_KERNEL);
2370         if (!this) {
2371                 pr_info("Failed to allocate per-device memory\n");
2372                 return -ENOMEM;
2373         }
2374
2375         /* Set up our data structures. */
2376         platform_set_drvdata(pdev, this);
2377         this->pdev  = pdev;
2378         this->dev   = &pdev->dev;
2379         this->pdata = pdata;
2380
2381         /* setup the platform */
2382         if (pdata->platform_init) {
2383                 error = pdata->platform_init();
2384                 if (error)
2385                         goto platform_init_error;
2386         }
2387
2388         /* Acquire the resources we need. */
2389         error = acquire_resources(this);
2390         if (error)
2391                 goto exit_acquire_resources;
2392
2393         /* Set up the NFC. */
2394         error = set_up_nfc_hal(this);
2395         if (error)
2396                 goto exit_nfc_init;
2397
2398         /* Initialize the MTD Interface Layer. */
2399         error = gpmi_nfc_mil_init(this);
2400         if (error)
2401                 goto exit_mil_init;
2402
2403         manage_sysfs_files(this, true);
2404         return 0;
2405
2406 exit_mil_init:
2407         exit_nfc_hal(this);
2408 exit_nfc_init:
2409         release_resources(this);
2410 platform_init_error:
2411 exit_acquire_resources:
2412         platform_set_drvdata(pdev, NULL);
2413         kfree(this);
2414         return error;
2415 }
2416
2417 static int __exit gpmi_nfc_remove(struct platform_device *pdev)
2418 {
2419         struct gpmi_nfc_data *this = platform_get_drvdata(pdev);
2420
2421         manage_sysfs_files(this, false);
2422         gpmi_nfc_mil_exit(this);
2423         exit_nfc_hal(this);
2424         release_resources(this);
2425         platform_set_drvdata(pdev, NULL);
2426         kfree(this);
2427         return 0;
2428 }
2429
2430 static const struct platform_device_id gpmi_ids[] = {
2431         {
2432                 .name = "imx23-gpmi-nfc",
2433                 .driver_data = IS_MX23,
2434         }, {
2435                 .name = "imx28-gpmi-nfc",
2436                 .driver_data = IS_MX28,
2437         }, {
2438                 .name = "imx50-gpmi-nfc",
2439                 .driver_data = IS_MX50,
2440         }, {},
2441 };
2442
2443 /* This structure represents this driver to the platform management system. */
2444 static struct platform_driver gpmi_nfc_driver = {
2445         .driver = {
2446                 .name = "gpmi-nfc",
2447         },
2448         .probe   = gpmi_nfc_probe,
2449         .remove  = __exit_p(gpmi_nfc_remove),
2450         .id_table = gpmi_ids,
2451 };
2452
2453 static int __init gpmi_nfc_init(void)
2454 {
2455         int err;
2456
2457         if (!enable_gpmi_nand)
2458                 return 0;
2459
2460         err = platform_driver_register(&gpmi_nfc_driver);
2461         if (err == 0)
2462                 printk(KERN_INFO "GPMI NFC driver registered. (IMX)\n");
2463         else
2464                 pr_err("i.MX GPMI NFC driver registration failed\n");
2465         return err;
2466 }
2467
2468 static void __exit gpmi_nfc_exit(void)
2469 {
2470         platform_driver_unregister(&gpmi_nfc_driver);
2471 }
2472
2473 static int __init gpmi_debug_setup(char *__unused)
2474 {
2475         gpmi_debug = GPMI_DEBUG_INIT;
2476         return 1;
2477 }
2478 __setup("gpmi_debug_init", gpmi_debug_setup);
2479
2480 static int __init gpmi_nand_setup(char *__unused)
2481 {
2482         enable_gpmi_nand = true;
2483         return 1;
2484 }
2485 __setup("gpmi-nfc", gpmi_nand_setup);
2486
2487 module_init(gpmi_nfc_init);
2488 module_exit(gpmi_nfc_exit);
2489
2490 MODULE_AUTHOR("Freescale Semiconductor, Inc.");
2491 MODULE_DESCRIPTION("i.MX GPMI NAND Flash Controller Driver");
2492 MODULE_LICENSE("GPL");