GNU Linux-libre 4.4.284-gnu1
[releases.git] / drivers / mtd / nand / gpmi-nand / gpmi-lib.c
1 /*
2  * Freescale GPMI NAND Flash Driver
3  *
4  * Copyright (C) 2008-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/delay.h>
22 #include <linux/clk.h>
23 #include <linux/slab.h>
24
25 #include "gpmi-nand.h"
26 #include "gpmi-regs.h"
27 #include "bch-regs.h"
28
29 static struct timing_threshod timing_default_threshold = {
30         .max_data_setup_cycles       = (BM_GPMI_TIMING0_DATA_SETUP >>
31                                                 BP_GPMI_TIMING0_DATA_SETUP),
32         .internal_data_setup_in_ns   = 0,
33         .max_sample_delay_factor     = (BM_GPMI_CTRL1_RDN_DELAY >>
34                                                 BP_GPMI_CTRL1_RDN_DELAY),
35         .max_dll_clock_period_in_ns  = 32,
36         .max_dll_delay_in_ns         = 16,
37 };
38
39 #define MXS_SET_ADDR            0x4
40 #define MXS_CLR_ADDR            0x8
41 /*
42  * Clear the bit and poll it cleared.  This is usually called with
43  * a reset address and mask being either SFTRST(bit 31) or CLKGATE
44  * (bit 30).
45  */
46 static int clear_poll_bit(void __iomem *addr, u32 mask)
47 {
48         int timeout = 0x400;
49
50         /* clear the bit */
51         writel(mask, addr + MXS_CLR_ADDR);
52
53         /*
54          * SFTRST needs 3 GPMI clocks to settle, the reference manual
55          * recommends to wait 1us.
56          */
57         udelay(1);
58
59         /* poll the bit becoming clear */
60         while ((readl(addr) & mask) && --timeout)
61                 /* nothing */;
62
63         return !timeout;
64 }
65
66 #define MODULE_CLKGATE          (1 << 30)
67 #define MODULE_SFTRST           (1 << 31)
68 /*
69  * The current mxs_reset_block() will do two things:
70  *  [1] enable the module.
71  *  [2] reset the module.
72  *
73  * In most of the cases, it's ok.
74  * But in MX23, there is a hardware bug in the BCH block (see erratum #2847).
75  * If you try to soft reset the BCH block, it becomes unusable until
76  * the next hard reset. This case occurs in the NAND boot mode. When the board
77  * boots by NAND, the ROM of the chip will initialize the BCH blocks itself.
78  * So If the driver tries to reset the BCH again, the BCH will not work anymore.
79  * You will see a DMA timeout in this case. The bug has been fixed
80  * in the following chips, such as MX28.
81  *
82  * To avoid this bug, just add a new parameter `just_enable` for
83  * the mxs_reset_block(), and rewrite it here.
84  */
85 static int gpmi_reset_block(void __iomem *reset_addr, bool just_enable)
86 {
87         int ret;
88         int timeout = 0x400;
89
90         /* clear and poll SFTRST */
91         ret = clear_poll_bit(reset_addr, MODULE_SFTRST);
92         if (unlikely(ret))
93                 goto error;
94
95         /* clear CLKGATE */
96         writel(MODULE_CLKGATE, reset_addr + MXS_CLR_ADDR);
97
98         if (!just_enable) {
99                 /* set SFTRST to reset the block */
100                 writel(MODULE_SFTRST, reset_addr + MXS_SET_ADDR);
101                 udelay(1);
102
103                 /* poll CLKGATE becoming set */
104                 while ((!(readl(reset_addr) & MODULE_CLKGATE)) && --timeout)
105                         /* nothing */;
106                 if (unlikely(!timeout))
107                         goto error;
108         }
109
110         /* clear and poll SFTRST */
111         ret = clear_poll_bit(reset_addr, MODULE_SFTRST);
112         if (unlikely(ret))
113                 goto error;
114
115         /* clear and poll CLKGATE */
116         ret = clear_poll_bit(reset_addr, MODULE_CLKGATE);
117         if (unlikely(ret))
118                 goto error;
119
120         return 0;
121
122 error:
123         pr_err("%s(%p): module reset timeout\n", __func__, reset_addr);
124         return -ETIMEDOUT;
125 }
126
127 static int __gpmi_enable_clk(struct gpmi_nand_data *this, bool v)
128 {
129         struct clk *clk;
130         int ret;
131         int i;
132
133         for (i = 0; i < GPMI_CLK_MAX; i++) {
134                 clk = this->resources.clock[i];
135                 if (!clk)
136                         break;
137
138                 if (v) {
139                         ret = clk_prepare_enable(clk);
140                         if (ret)
141                                 goto err_clk;
142                 } else {
143                         clk_disable_unprepare(clk);
144                 }
145         }
146         return 0;
147
148 err_clk:
149         for (; i > 0; i--)
150                 clk_disable_unprepare(this->resources.clock[i - 1]);
151         return ret;
152 }
153
154 #define gpmi_enable_clk(x) __gpmi_enable_clk(x, true)
155 #define gpmi_disable_clk(x) __gpmi_enable_clk(x, false)
156
157 int gpmi_init(struct gpmi_nand_data *this)
158 {
159         struct resources *r = &this->resources;
160         int ret;
161
162         ret = gpmi_enable_clk(this);
163         if (ret)
164                 goto err_out;
165         ret = gpmi_reset_block(r->gpmi_regs, false);
166         if (ret)
167                 goto err_out;
168
169         /*
170          * Reset BCH here, too. We got failures otherwise :(
171          * See later BCH reset for explanation of MX23 and MX28 handling
172          */
173         ret = gpmi_reset_block(r->bch_regs,
174                                GPMI_IS_MX23(this) || GPMI_IS_MX28(this));
175         if (ret)
176                 goto err_out;
177
178
179         /* Choose NAND mode. */
180         writel(BM_GPMI_CTRL1_GPMI_MODE, r->gpmi_regs + HW_GPMI_CTRL1_CLR);
181
182         /* Set the IRQ polarity. */
183         writel(BM_GPMI_CTRL1_ATA_IRQRDY_POLARITY,
184                                 r->gpmi_regs + HW_GPMI_CTRL1_SET);
185
186         /* Disable Write-Protection. */
187         writel(BM_GPMI_CTRL1_DEV_RESET, r->gpmi_regs + HW_GPMI_CTRL1_SET);
188
189         /* Select BCH ECC. */
190         writel(BM_GPMI_CTRL1_BCH_MODE, r->gpmi_regs + HW_GPMI_CTRL1_SET);
191
192         /*
193          * Decouple the chip select from dma channel. We use dma0 for all
194          * the chips.
195          */
196         writel(BM_GPMI_CTRL1_DECOUPLE_CS, r->gpmi_regs + HW_GPMI_CTRL1_SET);
197
198         gpmi_disable_clk(this);
199         return 0;
200 err_out:
201         return ret;
202 }
203
204 /* This function is very useful. It is called only when the bug occur. */
205 void gpmi_dump_info(struct gpmi_nand_data *this)
206 {
207         struct resources *r = &this->resources;
208         struct bch_geometry *geo = &this->bch_geometry;
209         u32 reg;
210         int i;
211
212         dev_err(this->dev, "Show GPMI registers :\n");
213         for (i = 0; i <= HW_GPMI_DEBUG / 0x10 + 1; i++) {
214                 reg = readl(r->gpmi_regs + i * 0x10);
215                 dev_err(this->dev, "offset 0x%.3x : 0x%.8x\n", i * 0x10, reg);
216         }
217
218         /* start to print out the BCH info */
219         dev_err(this->dev, "Show BCH registers :\n");
220         for (i = 0; i <= HW_BCH_VERSION / 0x10 + 1; i++) {
221                 reg = readl(r->bch_regs + i * 0x10);
222                 dev_err(this->dev, "offset 0x%.3x : 0x%.8x\n", i * 0x10, reg);
223         }
224         dev_err(this->dev, "BCH Geometry :\n"
225                 "GF length              : %u\n"
226                 "ECC Strength           : %u\n"
227                 "Page Size in Bytes     : %u\n"
228                 "Metadata Size in Bytes : %u\n"
229                 "ECC Chunk Size in Bytes: %u\n"
230                 "ECC Chunk Count        : %u\n"
231                 "Payload Size in Bytes  : %u\n"
232                 "Auxiliary Size in Bytes: %u\n"
233                 "Auxiliary Status Offset: %u\n"
234                 "Block Mark Byte Offset : %u\n"
235                 "Block Mark Bit Offset  : %u\n",
236                 geo->gf_len,
237                 geo->ecc_strength,
238                 geo->page_size,
239                 geo->metadata_size,
240                 geo->ecc_chunk_size,
241                 geo->ecc_chunk_count,
242                 geo->payload_size,
243                 geo->auxiliary_size,
244                 geo->auxiliary_status_offset,
245                 geo->block_mark_byte_offset,
246                 geo->block_mark_bit_offset);
247 }
248
249 /* Configures the geometry for BCH.  */
250 int bch_set_geometry(struct gpmi_nand_data *this)
251 {
252         struct resources *r = &this->resources;
253         struct bch_geometry *bch_geo = &this->bch_geometry;
254         unsigned int block_count;
255         unsigned int block_size;
256         unsigned int metadata_size;
257         unsigned int ecc_strength;
258         unsigned int page_size;
259         unsigned int gf_len;
260         int ret;
261
262         if (common_nfc_set_geometry(this))
263                 return !0;
264
265         block_count   = bch_geo->ecc_chunk_count - 1;
266         block_size    = bch_geo->ecc_chunk_size;
267         metadata_size = bch_geo->metadata_size;
268         ecc_strength  = bch_geo->ecc_strength >> 1;
269         page_size     = bch_geo->page_size;
270         gf_len        = bch_geo->gf_len;
271
272         ret = gpmi_enable_clk(this);
273         if (ret)
274                 goto err_out;
275
276         /*
277         * Due to erratum #2847 of the MX23, the BCH cannot be soft reset on this
278         * chip, otherwise it will lock up. So we skip resetting BCH on the MX23
279         * and MX28.
280         */
281         ret = gpmi_reset_block(r->bch_regs,
282                                GPMI_IS_MX23(this) || GPMI_IS_MX28(this));
283         if (ret)
284                 goto err_out;
285
286         /* Configure layout 0. */
287         writel(BF_BCH_FLASH0LAYOUT0_NBLOCKS(block_count)
288                         | BF_BCH_FLASH0LAYOUT0_META_SIZE(metadata_size)
289                         | BF_BCH_FLASH0LAYOUT0_ECC0(ecc_strength, this)
290                         | BF_BCH_FLASH0LAYOUT0_GF(gf_len, this)
291                         | BF_BCH_FLASH0LAYOUT0_DATA0_SIZE(block_size, this),
292                         r->bch_regs + HW_BCH_FLASH0LAYOUT0);
293
294         writel(BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(page_size)
295                         | BF_BCH_FLASH0LAYOUT1_ECCN(ecc_strength, this)
296                         | BF_BCH_FLASH0LAYOUT1_GF(gf_len, this)
297                         | BF_BCH_FLASH0LAYOUT1_DATAN_SIZE(block_size, this),
298                         r->bch_regs + HW_BCH_FLASH0LAYOUT1);
299
300         /* Set *all* chip selects to use layout 0. */
301         writel(0, r->bch_regs + HW_BCH_LAYOUTSELECT);
302
303         /* Enable interrupts. */
304         writel(BM_BCH_CTRL_COMPLETE_IRQ_EN,
305                                 r->bch_regs + HW_BCH_CTRL_SET);
306
307         gpmi_disable_clk(this);
308         return 0;
309 err_out:
310         return ret;
311 }
312
313 /* Converts time in nanoseconds to cycles. */
314 static unsigned int ns_to_cycles(unsigned int time,
315                         unsigned int period, unsigned int min)
316 {
317         unsigned int k;
318
319         k = (time + period - 1) / period;
320         return max(k, min);
321 }
322
323 #define DEF_MIN_PROP_DELAY      5
324 #define DEF_MAX_PROP_DELAY      9
325 /* Apply timing to current hardware conditions. */
326 static int gpmi_nfc_compute_hardware_timing(struct gpmi_nand_data *this,
327                                         struct gpmi_nfc_hardware_timing *hw)
328 {
329         struct timing_threshod *nfc = &timing_default_threshold;
330         struct resources *r = &this->resources;
331         struct nand_chip *nand = &this->nand;
332         struct nand_timing target = this->timing;
333         bool improved_timing_is_available;
334         unsigned long clock_frequency_in_hz;
335         unsigned int clock_period_in_ns;
336         bool dll_use_half_periods;
337         unsigned int dll_delay_shift;
338         unsigned int max_sample_delay_in_ns;
339         unsigned int address_setup_in_cycles;
340         unsigned int data_setup_in_ns;
341         unsigned int data_setup_in_cycles;
342         unsigned int data_hold_in_cycles;
343         int ideal_sample_delay_in_ns;
344         unsigned int sample_delay_factor;
345         int tEYE;
346         unsigned int min_prop_delay_in_ns = DEF_MIN_PROP_DELAY;
347         unsigned int max_prop_delay_in_ns = DEF_MAX_PROP_DELAY;
348
349         /*
350          * If there are multiple chips, we need to relax the timings to allow
351          * for signal distortion due to higher capacitance.
352          */
353         if (nand->numchips > 2) {
354                 target.data_setup_in_ns    += 10;
355                 target.data_hold_in_ns     += 10;
356                 target.address_setup_in_ns += 10;
357         } else if (nand->numchips > 1) {
358                 target.data_setup_in_ns    += 5;
359                 target.data_hold_in_ns     += 5;
360                 target.address_setup_in_ns += 5;
361         }
362
363         /* Check if improved timing information is available. */
364         improved_timing_is_available =
365                 (target.tREA_in_ns  >= 0) &&
366                 (target.tRLOH_in_ns >= 0) &&
367                 (target.tRHOH_in_ns >= 0);
368
369         /* Inspect the clock. */
370         nfc->clock_frequency_in_hz = clk_get_rate(r->clock[0]);
371         clock_frequency_in_hz = nfc->clock_frequency_in_hz;
372         clock_period_in_ns    = NSEC_PER_SEC / clock_frequency_in_hz;
373
374         /*
375          * The NFC quantizes setup and hold parameters in terms of clock cycles.
376          * Here, we quantize the setup and hold timing parameters to the
377          * next-highest clock period to make sure we apply at least the
378          * specified times.
379          *
380          * For data setup and data hold, the hardware interprets a value of zero
381          * as the largest possible delay. This is not what's intended by a zero
382          * in the input parameter, so we impose a minimum of one cycle.
383          */
384         data_setup_in_cycles    = ns_to_cycles(target.data_setup_in_ns,
385                                                         clock_period_in_ns, 1);
386         data_hold_in_cycles     = ns_to_cycles(target.data_hold_in_ns,
387                                                         clock_period_in_ns, 1);
388         address_setup_in_cycles = ns_to_cycles(target.address_setup_in_ns,
389                                                         clock_period_in_ns, 0);
390
391         /*
392          * The clock's period affects the sample delay in a number of ways:
393          *
394          * (1) The NFC HAL tells us the maximum clock period the sample delay
395          *     DLL can tolerate. If the clock period is greater than half that
396          *     maximum, we must configure the DLL to be driven by half periods.
397          *
398          * (2) We need to convert from an ideal sample delay, in ns, to a
399          *     "sample delay factor," which the NFC uses. This factor depends on
400          *     whether we're driving the DLL with full or half periods.
401          *     Paraphrasing the reference manual:
402          *
403          *         AD = SDF x 0.125 x RP
404          *
405          * where:
406          *
407          *     AD   is the applied delay, in ns.
408          *     SDF  is the sample delay factor, which is dimensionless.
409          *     RP   is the reference period, in ns, which is a full clock period
410          *          if the DLL is being driven by full periods, or half that if
411          *          the DLL is being driven by half periods.
412          *
413          * Let's re-arrange this in a way that's more useful to us:
414          *
415          *                        8
416          *         SDF  =  AD x ----
417          *                       RP
418          *
419          * The reference period is either the clock period or half that, so this
420          * is:
421          *
422          *                        8       AD x DDF
423          *         SDF  =  AD x -----  =  --------
424          *                      f x P        P
425          *
426          * where:
427          *
428          *       f  is 1 or 1/2, depending on how we're driving the DLL.
429          *       P  is the clock period.
430          *     DDF  is the DLL Delay Factor, a dimensionless value that
431          *          incorporates all the constants in the conversion.
432          *
433          * DDF will be either 8 or 16, both of which are powers of two. We can
434          * reduce the cost of this conversion by using bit shifts instead of
435          * multiplication or division. Thus:
436          *
437          *                 AD << DDS
438          *         SDF  =  ---------
439          *                     P
440          *
441          *     or
442          *
443          *         AD  =  (SDF >> DDS) x P
444          *
445          * where:
446          *
447          *     DDS  is the DLL Delay Shift, the logarithm to base 2 of the DDF.
448          */
449         if (clock_period_in_ns > (nfc->max_dll_clock_period_in_ns >> 1)) {
450                 dll_use_half_periods = true;
451                 dll_delay_shift      = 3 + 1;
452         } else {
453                 dll_use_half_periods = false;
454                 dll_delay_shift      = 3;
455         }
456
457         /*
458          * Compute the maximum sample delay the NFC allows, under current
459          * conditions. If the clock is running too slowly, no sample delay is
460          * possible.
461          */
462         if (clock_period_in_ns > nfc->max_dll_clock_period_in_ns)
463                 max_sample_delay_in_ns = 0;
464         else {
465                 /*
466                  * Compute the delay implied by the largest sample delay factor
467                  * the NFC allows.
468                  */
469                 max_sample_delay_in_ns =
470                         (nfc->max_sample_delay_factor * clock_period_in_ns) >>
471                                                                 dll_delay_shift;
472
473                 /*
474                  * Check if the implied sample delay larger than the NFC
475                  * actually allows.
476                  */
477                 if (max_sample_delay_in_ns > nfc->max_dll_delay_in_ns)
478                         max_sample_delay_in_ns = nfc->max_dll_delay_in_ns;
479         }
480
481         /*
482          * Check if improved timing information is available. If not, we have to
483          * use a less-sophisticated algorithm.
484          */
485         if (!improved_timing_is_available) {
486                 /*
487                  * Fold the read setup time required by the NFC into the ideal
488                  * sample delay.
489                  */
490                 ideal_sample_delay_in_ns = target.gpmi_sample_delay_in_ns +
491                                                 nfc->internal_data_setup_in_ns;
492
493                 /*
494                  * The ideal sample delay may be greater than the maximum
495                  * allowed by the NFC. If so, we can trade off sample delay time
496                  * for more data setup time.
497                  *
498                  * In each iteration of the following loop, we add a cycle to
499                  * the data setup time and subtract a corresponding amount from
500                  * the sample delay until we've satisified the constraints or
501                  * can't do any better.
502                  */
503                 while ((ideal_sample_delay_in_ns > max_sample_delay_in_ns) &&
504                         (data_setup_in_cycles < nfc->max_data_setup_cycles)) {
505
506                         data_setup_in_cycles++;
507                         ideal_sample_delay_in_ns -= clock_period_in_ns;
508
509                         if (ideal_sample_delay_in_ns < 0)
510                                 ideal_sample_delay_in_ns = 0;
511
512                 }
513
514                 /*
515                  * Compute the sample delay factor that corresponds most closely
516                  * to the ideal sample delay. If the result is too large for the
517                  * NFC, use the maximum value.
518                  *
519                  * Notice that we use the ns_to_cycles function to compute the
520                  * sample delay factor. We do this because the form of the
521                  * computation is the same as that for calculating cycles.
522                  */
523                 sample_delay_factor =
524                         ns_to_cycles(
525                                 ideal_sample_delay_in_ns << dll_delay_shift,
526                                                         clock_period_in_ns, 0);
527
528                 if (sample_delay_factor > nfc->max_sample_delay_factor)
529                         sample_delay_factor = nfc->max_sample_delay_factor;
530
531                 /* Skip to the part where we return our results. */
532                 goto return_results;
533         }
534
535         /*
536          * If control arrives here, we have more detailed timing information,
537          * so we can use a better algorithm.
538          */
539
540         /*
541          * Fold the read setup time required by the NFC into the maximum
542          * propagation delay.
543          */
544         max_prop_delay_in_ns += nfc->internal_data_setup_in_ns;
545
546         /*
547          * Earlier, we computed the number of clock cycles required to satisfy
548          * the data setup time. Now, we need to know the actual nanoseconds.
549          */
550         data_setup_in_ns = clock_period_in_ns * data_setup_in_cycles;
551
552         /*
553          * Compute tEYE, the width of the data eye when reading from the NAND
554          * Flash. The eye width is fundamentally determined by the data setup
555          * time, perturbed by propagation delays and some characteristics of the
556          * NAND Flash device.
557          *
558          * start of the eye = max_prop_delay + tREA
559          * end of the eye   = min_prop_delay + tRHOH + data_setup
560          */
561         tEYE = (int)min_prop_delay_in_ns + (int)target.tRHOH_in_ns +
562                                                         (int)data_setup_in_ns;
563
564         tEYE -= (int)max_prop_delay_in_ns + (int)target.tREA_in_ns;
565
566         /*
567          * The eye must be open. If it's not, we can try to open it by
568          * increasing its main forcer, the data setup time.
569          *
570          * In each iteration of the following loop, we increase the data setup
571          * time by a single clock cycle. We do this until either the eye is
572          * open or we run into NFC limits.
573          */
574         while ((tEYE <= 0) &&
575                         (data_setup_in_cycles < nfc->max_data_setup_cycles)) {
576                 /* Give a cycle to data setup. */
577                 data_setup_in_cycles++;
578                 /* Synchronize the data setup time with the cycles. */
579                 data_setup_in_ns += clock_period_in_ns;
580                 /* Adjust tEYE accordingly. */
581                 tEYE += clock_period_in_ns;
582         }
583
584         /*
585          * When control arrives here, the eye is open. The ideal time to sample
586          * the data is in the center of the eye:
587          *
588          *     end of the eye + start of the eye
589          *     ---------------------------------  -  data_setup
590          *                    2
591          *
592          * After some algebra, this simplifies to the code immediately below.
593          */
594         ideal_sample_delay_in_ns =
595                 ((int)max_prop_delay_in_ns +
596                         (int)target.tREA_in_ns +
597                                 (int)min_prop_delay_in_ns +
598                                         (int)target.tRHOH_in_ns -
599                                                 (int)data_setup_in_ns) >> 1;
600
601         /*
602          * The following figure illustrates some aspects of a NAND Flash read:
603          *
604          *
605          *           __                   _____________________________________
606          * RDN         \_________________/
607          *
608          *                                         <---- tEYE ----->
609          *                                        /-----------------\
610          * Read Data ----------------------------<                   >---------
611          *                                        \-----------------/
612          *             ^                 ^                 ^              ^
613          *             |                 |                 |              |
614          *             |<--Data Setup -->|<--Delay Time -->|              |
615          *             |                 |                 |              |
616          *             |                 |                                |
617          *             |                 |<--   Quantized Delay Time   -->|
618          *             |                 |                                |
619          *
620          *
621          * We have some issues we must now address:
622          *
623          * (1) The *ideal* sample delay time must not be negative. If it is, we
624          *     jam it to zero.
625          *
626          * (2) The *ideal* sample delay time must not be greater than that
627          *     allowed by the NFC. If it is, we can increase the data setup
628          *     time, which will reduce the delay between the end of the data
629          *     setup and the center of the eye. It will also make the eye
630          *     larger, which might help with the next issue...
631          *
632          * (3) The *quantized* sample delay time must not fall either before the
633          *     eye opens or after it closes (the latter is the problem
634          *     illustrated in the above figure).
635          */
636
637         /* Jam a negative ideal sample delay to zero. */
638         if (ideal_sample_delay_in_ns < 0)
639                 ideal_sample_delay_in_ns = 0;
640
641         /*
642          * Extend the data setup as needed to reduce the ideal sample delay
643          * below the maximum permitted by the NFC.
644          */
645         while ((ideal_sample_delay_in_ns > max_sample_delay_in_ns) &&
646                         (data_setup_in_cycles < nfc->max_data_setup_cycles)) {
647
648                 /* Give a cycle to data setup. */
649                 data_setup_in_cycles++;
650                 /* Synchronize the data setup time with the cycles. */
651                 data_setup_in_ns += clock_period_in_ns;
652                 /* Adjust tEYE accordingly. */
653                 tEYE += clock_period_in_ns;
654
655                 /*
656                  * Decrease the ideal sample delay by one half cycle, to keep it
657                  * in the middle of the eye.
658                  */
659                 ideal_sample_delay_in_ns -= (clock_period_in_ns >> 1);
660
661                 /* Jam a negative ideal sample delay to zero. */
662                 if (ideal_sample_delay_in_ns < 0)
663                         ideal_sample_delay_in_ns = 0;
664         }
665
666         /*
667          * Compute the sample delay factor that corresponds to the ideal sample
668          * delay. If the result is too large, then use the maximum allowed
669          * value.
670          *
671          * Notice that we use the ns_to_cycles function to compute the sample
672          * delay factor. We do this because the form of the computation is the
673          * same as that for calculating cycles.
674          */
675         sample_delay_factor =
676                 ns_to_cycles(ideal_sample_delay_in_ns << dll_delay_shift,
677                                                         clock_period_in_ns, 0);
678
679         if (sample_delay_factor > nfc->max_sample_delay_factor)
680                 sample_delay_factor = nfc->max_sample_delay_factor;
681
682         /*
683          * These macros conveniently encapsulate a computation we'll use to
684          * continuously evaluate whether or not the data sample delay is inside
685          * the eye.
686          */
687         #define IDEAL_DELAY  ((int) ideal_sample_delay_in_ns)
688
689         #define QUANTIZED_DELAY  \
690                 ((int) ((sample_delay_factor * clock_period_in_ns) >> \
691                                                         dll_delay_shift))
692
693         #define DELAY_ERROR  (abs(QUANTIZED_DELAY - IDEAL_DELAY))
694
695         #define SAMPLE_IS_NOT_WITHIN_THE_EYE  (DELAY_ERROR > (tEYE >> 1))
696
697         /*
698          * While the quantized sample time falls outside the eye, reduce the
699          * sample delay or extend the data setup to move the sampling point back
700          * toward the eye. Do not allow the number of data setup cycles to
701          * exceed the maximum allowed by the NFC.
702          */
703         while (SAMPLE_IS_NOT_WITHIN_THE_EYE &&
704                         (data_setup_in_cycles < nfc->max_data_setup_cycles)) {
705                 /*
706                  * If control arrives here, the quantized sample delay falls
707                  * outside the eye. Check if it's before the eye opens, or after
708                  * the eye closes.
709                  */
710                 if (QUANTIZED_DELAY > IDEAL_DELAY) {
711                         /*
712                          * If control arrives here, the quantized sample delay
713                          * falls after the eye closes. Decrease the quantized
714                          * delay time and then go back to re-evaluate.
715                          */
716                         if (sample_delay_factor != 0)
717                                 sample_delay_factor--;
718                         continue;
719                 }
720
721                 /*
722                  * If control arrives here, the quantized sample delay falls
723                  * before the eye opens. Shift the sample point by increasing
724                  * data setup time. This will also make the eye larger.
725                  */
726
727                 /* Give a cycle to data setup. */
728                 data_setup_in_cycles++;
729                 /* Synchronize the data setup time with the cycles. */
730                 data_setup_in_ns += clock_period_in_ns;
731                 /* Adjust tEYE accordingly. */
732                 tEYE += clock_period_in_ns;
733
734                 /*
735                  * Decrease the ideal sample delay by one half cycle, to keep it
736                  * in the middle of the eye.
737                  */
738                 ideal_sample_delay_in_ns -= (clock_period_in_ns >> 1);
739
740                 /* ...and one less period for the delay time. */
741                 ideal_sample_delay_in_ns -= clock_period_in_ns;
742
743                 /* Jam a negative ideal sample delay to zero. */
744                 if (ideal_sample_delay_in_ns < 0)
745                         ideal_sample_delay_in_ns = 0;
746
747                 /*
748                  * We have a new ideal sample delay, so re-compute the quantized
749                  * delay.
750                  */
751                 sample_delay_factor =
752                         ns_to_cycles(
753                                 ideal_sample_delay_in_ns << dll_delay_shift,
754                                                         clock_period_in_ns, 0);
755
756                 if (sample_delay_factor > nfc->max_sample_delay_factor)
757                         sample_delay_factor = nfc->max_sample_delay_factor;
758         }
759
760         /* Control arrives here when we're ready to return our results. */
761 return_results:
762         hw->data_setup_in_cycles    = data_setup_in_cycles;
763         hw->data_hold_in_cycles     = data_hold_in_cycles;
764         hw->address_setup_in_cycles = address_setup_in_cycles;
765         hw->use_half_periods        = dll_use_half_periods;
766         hw->sample_delay_factor     = sample_delay_factor;
767         hw->device_busy_timeout     = GPMI_DEFAULT_BUSY_TIMEOUT;
768         hw->wrn_dly_sel             = BV_GPMI_CTRL1_WRN_DLY_SEL_4_TO_8NS;
769
770         /* Return success. */
771         return 0;
772 }
773
774 /*
775  * <1> Firstly, we should know what's the GPMI-clock means.
776  *     The GPMI-clock is the internal clock in the gpmi nand controller.
777  *     If you set 100MHz to gpmi nand controller, the GPMI-clock's period
778  *     is 10ns. Mark the GPMI-clock's period as GPMI-clock-period.
779  *
780  * <2> Secondly, we should know what's the frequency on the nand chip pins.
781  *     The frequency on the nand chip pins is derived from the GPMI-clock.
782  *     We can get it from the following equation:
783  *
784  *         F = G / (DS + DH)
785  *
786  *         F  : the frequency on the nand chip pins.
787  *         G  : the GPMI clock, such as 100MHz.
788  *         DS : GPMI_HW_GPMI_TIMING0:DATA_SETUP
789  *         DH : GPMI_HW_GPMI_TIMING0:DATA_HOLD
790  *
791  * <3> Thirdly, when the frequency on the nand chip pins is above 33MHz,
792  *     the nand EDO(extended Data Out) timing could be applied.
793  *     The GPMI implements a feedback read strobe to sample the read data.
794  *     The feedback read strobe can be delayed to support the nand EDO timing
795  *     where the read strobe may deasserts before the read data is valid, and
796  *     read data is valid for some time after read strobe.
797  *
798  *     The following figure illustrates some aspects of a NAND Flash read:
799  *
800  *                   |<---tREA---->|
801  *                   |             |
802  *                   |         |   |
803  *                   |<--tRP-->|   |
804  *                   |         |   |
805  *                  __          ___|__________________________________
806  *     RDN            \________/   |
807  *                                 |
808  *                                 /---------\
809  *     Read Data    --------------<           >---------
810  *                                 \---------/
811  *                                |     |
812  *                                |<-D->|
813  *     FeedbackRDN  ________             ____________
814  *                          \___________/
815  *
816  *          D stands for delay, set in the HW_GPMI_CTRL1:RDN_DELAY.
817  *
818  *
819  * <4> Now, we begin to describe how to compute the right RDN_DELAY.
820  *
821  *  4.1) From the aspect of the nand chip pins:
822  *        Delay = (tREA + C - tRP)               {1}
823  *
824  *        tREA : the maximum read access time. From the ONFI nand standards,
825  *               we know that tREA is 16ns in mode 5, tREA is 20ns is mode 4.
826  *               Please check it in : www.onfi.org
827  *        C    : a constant for adjust the delay. default is 4.
828  *        tRP  : the read pulse width.
829  *               Specified by the HW_GPMI_TIMING0:DATA_SETUP:
830  *                    tRP = (GPMI-clock-period) * DATA_SETUP
831  *
832  *  4.2) From the aspect of the GPMI nand controller:
833  *         Delay = RDN_DELAY * 0.125 * RP        {2}
834  *
835  *         RP   : the DLL reference period.
836  *            if (GPMI-clock-period > DLL_THRETHOLD)
837  *                   RP = GPMI-clock-period / 2;
838  *            else
839  *                   RP = GPMI-clock-period;
840  *
841  *            Set the HW_GPMI_CTRL1:HALF_PERIOD if GPMI-clock-period
842  *            is greater DLL_THRETHOLD. In other SOCs, the DLL_THRETHOLD
843  *            is 16ns, but in mx6q, we use 12ns.
844  *
845  *  4.3) since {1} equals {2}, we get:
846  *
847  *                    (tREA + 4 - tRP) * 8
848  *         RDN_DELAY = ---------------------     {3}
849  *                           RP
850  *
851  *  4.4) We only support the fastest asynchronous mode of ONFI nand.
852  *       For some ONFI nand, the mode 4 is the fastest mode;
853  *       while for some ONFI nand, the mode 5 is the fastest mode.
854  *       So we only support the mode 4 and mode 5. It is no need to
855  *       support other modes.
856  */
857 static void gpmi_compute_edo_timing(struct gpmi_nand_data *this,
858                         struct gpmi_nfc_hardware_timing *hw)
859 {
860         struct resources *r = &this->resources;
861         unsigned long rate = clk_get_rate(r->clock[0]);
862         int mode = this->timing_mode;
863         int dll_threshold = this->devdata->max_chain_delay;
864         unsigned long delay;
865         unsigned long clk_period;
866         int t_rea;
867         int c = 4;
868         int t_rp;
869         int rp;
870
871         /*
872          * [1] for GPMI_HW_GPMI_TIMING0:
873          *     The async mode requires 40MHz for mode 4, 50MHz for mode 5.
874          *     The GPMI can support 100MHz at most. So if we want to
875          *     get the 40MHz or 50MHz, we have to set DS=1, DH=1.
876          *     Set the ADDRESS_SETUP to 0 in mode 4.
877          */
878         hw->data_setup_in_cycles = 1;
879         hw->data_hold_in_cycles = 1;
880         hw->address_setup_in_cycles = ((mode == 5) ? 1 : 0);
881
882         /* [2] for GPMI_HW_GPMI_TIMING1 */
883         hw->device_busy_timeout = 0x9000;
884
885         /* [3] for GPMI_HW_GPMI_CTRL1 */
886         hw->wrn_dly_sel = BV_GPMI_CTRL1_WRN_DLY_SEL_NO_DELAY;
887
888         /*
889          * Enlarge 10 times for the numerator and denominator in {3}.
890          * This make us to get more accurate result.
891          */
892         clk_period = NSEC_PER_SEC / (rate / 10);
893         dll_threshold *= 10;
894         t_rea = ((mode == 5) ? 16 : 20) * 10;
895         c *= 10;
896
897         t_rp = clk_period * 1; /* DATA_SETUP is 1 */
898
899         if (clk_period > dll_threshold) {
900                 hw->use_half_periods = 1;
901                 rp = clk_period / 2;
902         } else {
903                 hw->use_half_periods = 0;
904                 rp = clk_period;
905         }
906
907         /*
908          * Multiply the numerator with 10, we could do a round off:
909          *      7.8 round up to 8; 7.4 round down to 7.
910          */
911         delay  = (((t_rea + c - t_rp) * 8) * 10) / rp;
912         delay = (delay + 5) / 10;
913
914         hw->sample_delay_factor = delay;
915 }
916
917 static int enable_edo_mode(struct gpmi_nand_data *this, int mode)
918 {
919         struct resources  *r = &this->resources;
920         struct nand_chip *nand = &this->nand;
921         struct mtd_info  *mtd = &this->mtd;
922         uint8_t *feature;
923         unsigned long rate;
924         int ret;
925
926         feature = kzalloc(ONFI_SUBFEATURE_PARAM_LEN, GFP_KERNEL);
927         if (!feature)
928                 return -ENOMEM;
929
930         nand->select_chip(mtd, 0);
931
932         /* [1] send SET FEATURE commond to NAND */
933         feature[0] = mode;
934         ret = nand->onfi_set_features(mtd, nand,
935                                 ONFI_FEATURE_ADDR_TIMING_MODE, feature);
936         if (ret)
937                 goto err_out;
938
939         /* [2] send GET FEATURE command to double-check the timing mode */
940         memset(feature, 0, ONFI_SUBFEATURE_PARAM_LEN);
941         ret = nand->onfi_get_features(mtd, nand,
942                                 ONFI_FEATURE_ADDR_TIMING_MODE, feature);
943         if (ret || feature[0] != mode)
944                 goto err_out;
945
946         nand->select_chip(mtd, -1);
947
948         /* [3] set the main IO clock, 100MHz for mode 5, 80MHz for mode 4. */
949         rate = (mode == 5) ? 100000000 : 80000000;
950         clk_set_rate(r->clock[0], rate);
951
952         /* Let the gpmi_begin() re-compute the timing again. */
953         this->flags &= ~GPMI_TIMING_INIT_OK;
954
955         this->flags |= GPMI_ASYNC_EDO_ENABLED;
956         this->timing_mode = mode;
957         kfree(feature);
958         dev_info(this->dev, "enable the asynchronous EDO mode %d\n", mode);
959         return 0;
960
961 err_out:
962         nand->select_chip(mtd, -1);
963         kfree(feature);
964         dev_err(this->dev, "mode:%d ,failed in set feature.\n", mode);
965         return -EINVAL;
966 }
967
968 int gpmi_extra_init(struct gpmi_nand_data *this)
969 {
970         struct nand_chip *chip = &this->nand;
971
972         /* Enable the asynchronous EDO feature. */
973         if (GPMI_IS_MX6(this) && chip->onfi_version) {
974                 int mode = onfi_get_async_timing_mode(chip);
975
976                 /* We only support the timing mode 4 and mode 5. */
977                 if (mode & ONFI_TIMING_MODE_5)
978                         mode = 5;
979                 else if (mode & ONFI_TIMING_MODE_4)
980                         mode = 4;
981                 else
982                         return 0;
983
984                 return enable_edo_mode(this, mode);
985         }
986         return 0;
987 }
988
989 /* Begin the I/O */
990 void gpmi_begin(struct gpmi_nand_data *this)
991 {
992         struct resources *r = &this->resources;
993         void __iomem *gpmi_regs = r->gpmi_regs;
994         unsigned int   clock_period_in_ns;
995         uint32_t       reg;
996         unsigned int   dll_wait_time_in_us;
997         struct gpmi_nfc_hardware_timing  hw;
998         int ret;
999
1000         /* Enable the clock. */
1001         ret = gpmi_enable_clk(this);
1002         if (ret) {
1003                 dev_err(this->dev, "We failed in enable the clk\n");
1004                 goto err_out;
1005         }
1006
1007         /* Only initialize the timing once */
1008         if (this->flags & GPMI_TIMING_INIT_OK)
1009                 return;
1010         this->flags |= GPMI_TIMING_INIT_OK;
1011
1012         if (this->flags & GPMI_ASYNC_EDO_ENABLED)
1013                 gpmi_compute_edo_timing(this, &hw);
1014         else
1015                 gpmi_nfc_compute_hardware_timing(this, &hw);
1016
1017         /* [1] Set HW_GPMI_TIMING0 */
1018         reg = BF_GPMI_TIMING0_ADDRESS_SETUP(hw.address_setup_in_cycles) |
1019                 BF_GPMI_TIMING0_DATA_HOLD(hw.data_hold_in_cycles)         |
1020                 BF_GPMI_TIMING0_DATA_SETUP(hw.data_setup_in_cycles);
1021
1022         writel(reg, gpmi_regs + HW_GPMI_TIMING0);
1023
1024         /* [2] Set HW_GPMI_TIMING1 */
1025         writel(BF_GPMI_TIMING1_BUSY_TIMEOUT(hw.device_busy_timeout),
1026                 gpmi_regs + HW_GPMI_TIMING1);
1027
1028         /* [3] The following code is to set the HW_GPMI_CTRL1. */
1029
1030         /* Set the WRN_DLY_SEL */
1031         writel(BM_GPMI_CTRL1_WRN_DLY_SEL, gpmi_regs + HW_GPMI_CTRL1_CLR);
1032         writel(BF_GPMI_CTRL1_WRN_DLY_SEL(hw.wrn_dly_sel),
1033                                         gpmi_regs + HW_GPMI_CTRL1_SET);
1034
1035         /* DLL_ENABLE must be set to 0 when setting RDN_DELAY or HALF_PERIOD. */
1036         writel(BM_GPMI_CTRL1_DLL_ENABLE, gpmi_regs + HW_GPMI_CTRL1_CLR);
1037
1038         /* Clear out the DLL control fields. */
1039         reg = BM_GPMI_CTRL1_RDN_DELAY | BM_GPMI_CTRL1_HALF_PERIOD;
1040         writel(reg, gpmi_regs + HW_GPMI_CTRL1_CLR);
1041
1042         /* If no sample delay is called for, return immediately. */
1043         if (!hw.sample_delay_factor)
1044                 return;
1045
1046         /* Set RDN_DELAY or HALF_PERIOD. */
1047         reg = ((hw.use_half_periods) ? BM_GPMI_CTRL1_HALF_PERIOD : 0)
1048                 | BF_GPMI_CTRL1_RDN_DELAY(hw.sample_delay_factor);
1049
1050         writel(reg, gpmi_regs + HW_GPMI_CTRL1_SET);
1051
1052         /* At last, we enable the DLL. */
1053         writel(BM_GPMI_CTRL1_DLL_ENABLE, gpmi_regs + HW_GPMI_CTRL1_SET);
1054
1055         /*
1056          * After we enable the GPMI DLL, we have to wait 64 clock cycles before
1057          * we can use the GPMI. Calculate the amount of time we need to wait,
1058          * in microseconds.
1059          */
1060         clock_period_in_ns = NSEC_PER_SEC / clk_get_rate(r->clock[0]);
1061         dll_wait_time_in_us = (clock_period_in_ns * 64) / 1000;
1062
1063         if (!dll_wait_time_in_us)
1064                 dll_wait_time_in_us = 1;
1065
1066         /* Wait for the DLL to settle. */
1067         udelay(dll_wait_time_in_us);
1068
1069 err_out:
1070         return;
1071 }
1072
1073 void gpmi_end(struct gpmi_nand_data *this)
1074 {
1075         gpmi_disable_clk(this);
1076 }
1077
1078 /* Clears a BCH interrupt. */
1079 void gpmi_clear_bch(struct gpmi_nand_data *this)
1080 {
1081         struct resources *r = &this->resources;
1082         writel(BM_BCH_CTRL_COMPLETE_IRQ, r->bch_regs + HW_BCH_CTRL_CLR);
1083 }
1084
1085 /* Returns the Ready/Busy status of the given chip. */
1086 int gpmi_is_ready(struct gpmi_nand_data *this, unsigned chip)
1087 {
1088         struct resources *r = &this->resources;
1089         uint32_t mask = 0;
1090         uint32_t reg = 0;
1091
1092         if (GPMI_IS_MX23(this)) {
1093                 mask = MX23_BM_GPMI_DEBUG_READY0 << chip;
1094                 reg = readl(r->gpmi_regs + HW_GPMI_DEBUG);
1095         } else if (GPMI_IS_MX28(this) || GPMI_IS_MX6(this)) {
1096                 /*
1097                  * In the imx6, all the ready/busy pins are bound
1098                  * together. So we only need to check chip 0.
1099                  */
1100                 if (GPMI_IS_MX6(this))
1101                         chip = 0;
1102
1103                 /* MX28 shares the same R/B register as MX6Q. */
1104                 mask = MX28_BF_GPMI_STAT_READY_BUSY(1 << chip);
1105                 reg = readl(r->gpmi_regs + HW_GPMI_STAT);
1106         } else
1107                 dev_err(this->dev, "unknown arch.\n");
1108         return reg & mask;
1109 }
1110
1111 static inline void set_dma_type(struct gpmi_nand_data *this,
1112                                         enum dma_ops_type type)
1113 {
1114         this->last_dma_type = this->dma_type;
1115         this->dma_type = type;
1116 }
1117
1118 int gpmi_send_command(struct gpmi_nand_data *this)
1119 {
1120         struct dma_chan *channel = get_dma_chan(this);
1121         struct dma_async_tx_descriptor *desc;
1122         struct scatterlist *sgl;
1123         int chip = this->current_chip;
1124         u32 pio[3];
1125
1126         /* [1] send out the PIO words */
1127         pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__WRITE)
1128                 | BM_GPMI_CTRL0_WORD_LENGTH
1129                 | BF_GPMI_CTRL0_CS(chip, this)
1130                 | BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
1131                 | BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_CLE)
1132                 | BM_GPMI_CTRL0_ADDRESS_INCREMENT
1133                 | BF_GPMI_CTRL0_XFER_COUNT(this->command_length);
1134         pio[1] = pio[2] = 0;
1135         desc = dmaengine_prep_slave_sg(channel,
1136                                         (struct scatterlist *)pio,
1137                                         ARRAY_SIZE(pio), DMA_TRANS_NONE, 0);
1138         if (!desc)
1139                 return -EINVAL;
1140
1141         /* [2] send out the COMMAND + ADDRESS string stored in @buffer */
1142         sgl = &this->cmd_sgl;
1143
1144         sg_init_one(sgl, this->cmd_buffer, this->command_length);
1145         dma_map_sg(this->dev, sgl, 1, DMA_TO_DEVICE);
1146         desc = dmaengine_prep_slave_sg(channel,
1147                                 sgl, 1, DMA_MEM_TO_DEV,
1148                                 DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
1149         if (!desc)
1150                 return -EINVAL;
1151
1152         /* [3] submit the DMA */
1153         set_dma_type(this, DMA_FOR_COMMAND);
1154         return start_dma_without_bch_irq(this, desc);
1155 }
1156
1157 int gpmi_send_data(struct gpmi_nand_data *this)
1158 {
1159         struct dma_async_tx_descriptor *desc;
1160         struct dma_chan *channel = get_dma_chan(this);
1161         int chip = this->current_chip;
1162         uint32_t command_mode;
1163         uint32_t address;
1164         u32 pio[2];
1165
1166         /* [1] PIO */
1167         command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WRITE;
1168         address      = BV_GPMI_CTRL0_ADDRESS__NAND_DATA;
1169
1170         pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(command_mode)
1171                 | BM_GPMI_CTRL0_WORD_LENGTH
1172                 | BF_GPMI_CTRL0_CS(chip, this)
1173                 | BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
1174                 | BF_GPMI_CTRL0_ADDRESS(address)
1175                 | BF_GPMI_CTRL0_XFER_COUNT(this->upper_len);
1176         pio[1] = 0;
1177         desc = dmaengine_prep_slave_sg(channel, (struct scatterlist *)pio,
1178                                         ARRAY_SIZE(pio), DMA_TRANS_NONE, 0);
1179         if (!desc)
1180                 return -EINVAL;
1181
1182         /* [2] send DMA request */
1183         prepare_data_dma(this, DMA_TO_DEVICE);
1184         desc = dmaengine_prep_slave_sg(channel, &this->data_sgl,
1185                                         1, DMA_MEM_TO_DEV,
1186                                         DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
1187         if (!desc)
1188                 return -EINVAL;
1189
1190         /* [3] submit the DMA */
1191         set_dma_type(this, DMA_FOR_WRITE_DATA);
1192         return start_dma_without_bch_irq(this, desc);
1193 }
1194
1195 int gpmi_read_data(struct gpmi_nand_data *this)
1196 {
1197         struct dma_async_tx_descriptor *desc;
1198         struct dma_chan *channel = get_dma_chan(this);
1199         int chip = this->current_chip;
1200         u32 pio[2];
1201
1202         /* [1] : send PIO */
1203         pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__READ)
1204                 | BM_GPMI_CTRL0_WORD_LENGTH
1205                 | BF_GPMI_CTRL0_CS(chip, this)
1206                 | BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
1207                 | BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_DATA)
1208                 | BF_GPMI_CTRL0_XFER_COUNT(this->upper_len);
1209         pio[1] = 0;
1210         desc = dmaengine_prep_slave_sg(channel,
1211                                         (struct scatterlist *)pio,
1212                                         ARRAY_SIZE(pio), DMA_TRANS_NONE, 0);
1213         if (!desc)
1214                 return -EINVAL;
1215
1216         /* [2] : send DMA request */
1217         prepare_data_dma(this, DMA_FROM_DEVICE);
1218         desc = dmaengine_prep_slave_sg(channel, &this->data_sgl,
1219                                         1, DMA_DEV_TO_MEM,
1220                                         DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
1221         if (!desc)
1222                 return -EINVAL;
1223
1224         /* [3] : submit the DMA */
1225         set_dma_type(this, DMA_FOR_READ_DATA);
1226         return start_dma_without_bch_irq(this, desc);
1227 }
1228
1229 int gpmi_send_page(struct gpmi_nand_data *this,
1230                         dma_addr_t payload, dma_addr_t auxiliary)
1231 {
1232         struct bch_geometry *geo = &this->bch_geometry;
1233         uint32_t command_mode;
1234         uint32_t address;
1235         uint32_t ecc_command;
1236         uint32_t buffer_mask;
1237         struct dma_async_tx_descriptor *desc;
1238         struct dma_chan *channel = get_dma_chan(this);
1239         int chip = this->current_chip;
1240         u32 pio[6];
1241
1242         /* A DMA descriptor that does an ECC page read. */
1243         command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WRITE;
1244         address      = BV_GPMI_CTRL0_ADDRESS__NAND_DATA;
1245         ecc_command  = BV_GPMI_ECCCTRL_ECC_CMD__BCH_ENCODE;
1246         buffer_mask  = BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE |
1247                                 BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY;
1248
1249         pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(command_mode)
1250                 | BM_GPMI_CTRL0_WORD_LENGTH
1251                 | BF_GPMI_CTRL0_CS(chip, this)
1252                 | BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
1253                 | BF_GPMI_CTRL0_ADDRESS(address)
1254                 | BF_GPMI_CTRL0_XFER_COUNT(0);
1255         pio[1] = 0;
1256         pio[2] = BM_GPMI_ECCCTRL_ENABLE_ECC
1257                 | BF_GPMI_ECCCTRL_ECC_CMD(ecc_command)
1258                 | BF_GPMI_ECCCTRL_BUFFER_MASK(buffer_mask);
1259         pio[3] = geo->page_size;
1260         pio[4] = payload;
1261         pio[5] = auxiliary;
1262
1263         desc = dmaengine_prep_slave_sg(channel,
1264                                         (struct scatterlist *)pio,
1265                                         ARRAY_SIZE(pio), DMA_TRANS_NONE,
1266                                         DMA_CTRL_ACK);
1267         if (!desc)
1268                 return -EINVAL;
1269
1270         set_dma_type(this, DMA_FOR_WRITE_ECC_PAGE);
1271         return start_dma_with_bch_irq(this, desc);
1272 }
1273
1274 int gpmi_read_page(struct gpmi_nand_data *this,
1275                                 dma_addr_t payload, dma_addr_t auxiliary)
1276 {
1277         struct bch_geometry *geo = &this->bch_geometry;
1278         uint32_t command_mode;
1279         uint32_t address;
1280         uint32_t ecc_command;
1281         uint32_t buffer_mask;
1282         struct dma_async_tx_descriptor *desc;
1283         struct dma_chan *channel = get_dma_chan(this);
1284         int chip = this->current_chip;
1285         u32 pio[6];
1286
1287         /* [1] Wait for the chip to report ready. */
1288         command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY;
1289         address      = BV_GPMI_CTRL0_ADDRESS__NAND_DATA;
1290
1291         pio[0] =  BF_GPMI_CTRL0_COMMAND_MODE(command_mode)
1292                 | BM_GPMI_CTRL0_WORD_LENGTH
1293                 | BF_GPMI_CTRL0_CS(chip, this)
1294                 | BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
1295                 | BF_GPMI_CTRL0_ADDRESS(address)
1296                 | BF_GPMI_CTRL0_XFER_COUNT(0);
1297         pio[1] = 0;
1298         desc = dmaengine_prep_slave_sg(channel,
1299                                 (struct scatterlist *)pio, 2,
1300                                 DMA_TRANS_NONE, 0);
1301         if (!desc)
1302                 return -EINVAL;
1303
1304         /* [2] Enable the BCH block and read. */
1305         command_mode = BV_GPMI_CTRL0_COMMAND_MODE__READ;
1306         address      = BV_GPMI_CTRL0_ADDRESS__NAND_DATA;
1307         ecc_command  = BV_GPMI_ECCCTRL_ECC_CMD__BCH_DECODE;
1308         buffer_mask  = BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE
1309                         | BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY;
1310
1311         pio[0] =  BF_GPMI_CTRL0_COMMAND_MODE(command_mode)
1312                 | BM_GPMI_CTRL0_WORD_LENGTH
1313                 | BF_GPMI_CTRL0_CS(chip, this)
1314                 | BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
1315                 | BF_GPMI_CTRL0_ADDRESS(address)
1316                 | BF_GPMI_CTRL0_XFER_COUNT(geo->page_size);
1317
1318         pio[1] = 0;
1319         pio[2] =  BM_GPMI_ECCCTRL_ENABLE_ECC
1320                 | BF_GPMI_ECCCTRL_ECC_CMD(ecc_command)
1321                 | BF_GPMI_ECCCTRL_BUFFER_MASK(buffer_mask);
1322         pio[3] = geo->page_size;
1323         pio[4] = payload;
1324         pio[5] = auxiliary;
1325         desc = dmaengine_prep_slave_sg(channel,
1326                                         (struct scatterlist *)pio,
1327                                         ARRAY_SIZE(pio), DMA_TRANS_NONE,
1328                                         DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
1329         if (!desc)
1330                 return -EINVAL;
1331
1332         /* [3] Disable the BCH block */
1333         command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY;
1334         address      = BV_GPMI_CTRL0_ADDRESS__NAND_DATA;
1335
1336         pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(command_mode)
1337                 | BM_GPMI_CTRL0_WORD_LENGTH
1338                 | BF_GPMI_CTRL0_CS(chip, this)
1339                 | BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
1340                 | BF_GPMI_CTRL0_ADDRESS(address)
1341                 | BF_GPMI_CTRL0_XFER_COUNT(geo->page_size);
1342         pio[1] = 0;
1343         pio[2] = 0; /* clear GPMI_HW_GPMI_ECCCTRL, disable the BCH. */
1344         desc = dmaengine_prep_slave_sg(channel,
1345                                 (struct scatterlist *)pio, 3,
1346                                 DMA_TRANS_NONE,
1347                                 DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
1348         if (!desc)
1349                 return -EINVAL;
1350
1351         /* [4] submit the DMA */
1352         set_dma_type(this, DMA_FOR_READ_ECC_PAGE);
1353         return start_dma_with_bch_irq(this, desc);
1354 }
1355
1356 /**
1357  * gpmi_copy_bits - copy bits from one memory region to another
1358  * @dst: destination buffer
1359  * @dst_bit_off: bit offset we're starting to write at
1360  * @src: source buffer
1361  * @src_bit_off: bit offset we're starting to read from
1362  * @nbits: number of bits to copy
1363  *
1364  * This functions copies bits from one memory region to another, and is used by
1365  * the GPMI driver to copy ECC sections which are not guaranteed to be byte
1366  * aligned.
1367  *
1368  * src and dst should not overlap.
1369  *
1370  */
1371 void gpmi_copy_bits(u8 *dst, size_t dst_bit_off,
1372                     const u8 *src, size_t src_bit_off,
1373                     size_t nbits)
1374 {
1375         size_t i;
1376         size_t nbytes;
1377         u32 src_buffer = 0;
1378         size_t bits_in_src_buffer = 0;
1379
1380         if (!nbits)
1381                 return;
1382
1383         /*
1384          * Move src and dst pointers to the closest byte pointer and store bit
1385          * offsets within a byte.
1386          */
1387         src += src_bit_off / 8;
1388         src_bit_off %= 8;
1389
1390         dst += dst_bit_off / 8;
1391         dst_bit_off %= 8;
1392
1393         /*
1394          * Initialize the src_buffer value with bits available in the first
1395          * byte of data so that we end up with a byte aligned src pointer.
1396          */
1397         if (src_bit_off) {
1398                 src_buffer = src[0] >> src_bit_off;
1399                 if (nbits >= (8 - src_bit_off)) {
1400                         bits_in_src_buffer += 8 - src_bit_off;
1401                 } else {
1402                         src_buffer &= GENMASK(nbits - 1, 0);
1403                         bits_in_src_buffer += nbits;
1404                 }
1405                 nbits -= bits_in_src_buffer;
1406                 src++;
1407         }
1408
1409         /* Calculate the number of bytes that can be copied from src to dst. */
1410         nbytes = nbits / 8;
1411
1412         /* Try to align dst to a byte boundary. */
1413         if (dst_bit_off) {
1414                 if (bits_in_src_buffer < (8 - dst_bit_off) && nbytes) {
1415                         src_buffer |= src[0] << bits_in_src_buffer;
1416                         bits_in_src_buffer += 8;
1417                         src++;
1418                         nbytes--;
1419                 }
1420
1421                 if (bits_in_src_buffer >= (8 - dst_bit_off)) {
1422                         dst[0] &= GENMASK(dst_bit_off - 1, 0);
1423                         dst[0] |= src_buffer << dst_bit_off;
1424                         src_buffer >>= (8 - dst_bit_off);
1425                         bits_in_src_buffer -= (8 - dst_bit_off);
1426                         dst_bit_off = 0;
1427                         dst++;
1428                         if (bits_in_src_buffer > 7) {
1429                                 bits_in_src_buffer -= 8;
1430                                 dst[0] = src_buffer;
1431                                 dst++;
1432                                 src_buffer >>= 8;
1433                         }
1434                 }
1435         }
1436
1437         if (!bits_in_src_buffer && !dst_bit_off) {
1438                 /*
1439                  * Both src and dst pointers are byte aligned, thus we can
1440                  * just use the optimized memcpy function.
1441                  */
1442                 if (nbytes)
1443                         memcpy(dst, src, nbytes);
1444         } else {
1445                 /*
1446                  * src buffer is not byte aligned, hence we have to copy each
1447                  * src byte to the src_buffer variable before extracting a byte
1448                  * to store in dst.
1449                  */
1450                 for (i = 0; i < nbytes; i++) {
1451                         src_buffer |= src[i] << bits_in_src_buffer;
1452                         dst[i] = src_buffer;
1453                         src_buffer >>= 8;
1454                 }
1455         }
1456         /* Update dst and src pointers */
1457         dst += nbytes;
1458         src += nbytes;
1459
1460         /*
1461          * nbits is the number of remaining bits. It should not exceed 8 as
1462          * we've already copied as much bytes as possible.
1463          */
1464         nbits %= 8;
1465
1466         /*
1467          * If there's no more bits to copy to the destination and src buffer
1468          * was already byte aligned, then we're done.
1469          */
1470         if (!nbits && !bits_in_src_buffer)
1471                 return;
1472
1473         /* Copy the remaining bits to src_buffer */
1474         if (nbits)
1475                 src_buffer |= (*src & GENMASK(nbits - 1, 0)) <<
1476                               bits_in_src_buffer;
1477         bits_in_src_buffer += nbits;
1478
1479         /*
1480          * In case there were not enough bits to get a byte aligned dst buffer
1481          * prepare the src_buffer variable to match the dst organization (shift
1482          * src_buffer by dst_bit_off and retrieve the least significant bits
1483          * from dst).
1484          */
1485         if (dst_bit_off)
1486                 src_buffer = (src_buffer << dst_bit_off) |
1487                              (*dst & GENMASK(dst_bit_off - 1, 0));
1488         bits_in_src_buffer += dst_bit_off;
1489
1490         /*
1491          * Keep most significant bits from dst if we end up with an unaligned
1492          * number of bits.
1493          */
1494         nbytes = bits_in_src_buffer / 8;
1495         if (bits_in_src_buffer % 8) {
1496                 src_buffer |= (dst[nbytes] &
1497                                GENMASK(7, bits_in_src_buffer % 8)) <<
1498                               (nbytes * 8);
1499                 nbytes++;
1500         }
1501
1502         /* Copy the remaining bytes to dst */
1503         for (i = 0; i < nbytes; i++) {
1504                 dst[i] = src_buffer;
1505                 src_buffer >>= 8;
1506         }
1507 }