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