]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - drivers/mtd/nand/omap_gpmc.c
mtd: nand: gpmc: return number of corrected bits in omap_correct_data_bch()
[karo-tx-uboot.git] / drivers / mtd / nand / omap_gpmc.c
1 /*
2  * (C) Copyright 2004-2008 Texas Instruments, <www.ti.com>
3  * Rohit Choraria <rohitkc@ti.com>
4  *
5  * SPDX-License-Identifier:     GPL-2.0+
6  */
7
8 #include <common.h>
9 #include <asm/io.h>
10 #include <asm/errno.h>
11 #include <asm/arch/mem.h>
12 #include <asm/arch/cpu.h>
13 #include <asm/omap_gpmc.h>
14 #include <linux/mtd/nand_ecc.h>
15 #include <linux/bch.h>
16 #include <linux/compiler.h>
17 #include <nand.h>
18 #ifdef CONFIG_AM33XX
19 #include <asm/arch/elm.h>
20 #endif
21
22 static uint8_t cs;
23 static __maybe_unused struct nand_ecclayout hw_nand_oob =
24         GPMC_NAND_HW_ECC_LAYOUT;
25 static __maybe_unused struct nand_ecclayout hw_bch8_nand_oob =
26         GPMC_NAND_HW_BCH8_ECC_LAYOUT;
27
28 static struct gpmc __iomem *gpmc_cfg = (void __iomem *)GPMC_BASE;
29
30 #ifdef CONFIG_SYS_NAND_USE_FLASH_BBT
31 static uint8_t bbt_pattern[] = {'B', 'b', 't', '0' };
32 static uint8_t mirror_pattern[] = {'1', 't', 'b', 'B' };
33
34 static struct nand_bbt_descr bbt_main_descr = {
35         .options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE |
36                 NAND_BBT_2BIT | NAND_BBT_VERSION | NAND_BBT_PERCHIP,
37         .offs = 0, /* may be overwritten depending on ECC layout */
38         .len = 4,
39         .veroffs = 4, /* may be overwritten depending on ECC layout */
40         .maxblocks = 4,
41         .pattern = bbt_pattern,
42 };
43
44 static struct nand_bbt_descr bbt_mirror_descr = {
45         .options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE |
46                 NAND_BBT_2BIT | NAND_BBT_VERSION | NAND_BBT_PERCHIP,
47         .offs = 0, /* may be overwritten depending on ECC layout */
48         .len = 4,
49         .veroffs = 4, /* may be overwritten depending on ECC layout */
50         .maxblocks = 4,
51         .pattern = mirror_pattern,
52 };
53 #endif
54
55 #define PREFETCH_FIFOTHRESHOLD_MAX              0x40
56 #define PREFETCH_FIFOTHRESHOLD(val)             ((val) << 8)
57
58 #define PREFETCH_ENABLEOPTIMIZEDACCESS          (0x1 << 27)
59
60 #define GPMC_PREFETCH_STATUS_FIFO_CNT(val)      (((val) >> 24) & 0x7F)
61 #define GPMC_PREFETCH_STATUS_COUNT(val)         ((val) & 0x00003fff)
62
63 #define CS_NUM_SHIFT                            24
64 #define ENABLE_PREFETCH                         (0x1 << 7)
65 #define DMA_MPU_MODE                            2
66
67 #define OMAP_NAND_TIMEOUT_MS                    5000
68
69 #define PRINT_REG(x) debug("+++ %.15s (0x%08x)=0x%08x\n", #x, &gpmc_cfg->x, readl(&gpmc_cfg->x))
70
71 #ifdef CONFIG_SYS_GPMC_PREFETCH_ENABLE
72 /**
73  * gpmc_prefetch_enable - configures and starts prefetch transfer
74  * @cs: cs (chip select) number
75  * @fifo_th: fifo threshold to be used for read/ write
76  * @count: number of bytes to be transferred
77  * @is_write: prefetch read(0) or write post(1) mode
78  */
79 static inline void gpmc_prefetch_enable(int cs, int fifo_th,
80                                         unsigned int count, int is_write)
81 {
82         writel(count, &gpmc_cfg->pref_config2);
83
84         /* Set the prefetch read / post write and enable the engine.
85          * Set which cs is has requested for.
86          */
87         uint32_t val = (cs << CS_NUM_SHIFT) |
88                 PREFETCH_ENABLEOPTIMIZEDACCESS |
89                 PREFETCH_FIFOTHRESHOLD(fifo_th) |
90                 ENABLE_PREFETCH |
91                 !!is_write;
92         writel(val, &gpmc_cfg->pref_config1);
93
94         /*  Start the prefetch engine */
95         writel(0x1, &gpmc_cfg->pref_control);
96 }
97
98 /**
99  * gpmc_prefetch_reset - disables and stops the prefetch engine
100  */
101 static inline void gpmc_prefetch_reset(void)
102 {
103         /* Stop the PFPW engine */
104         writel(0x0, &gpmc_cfg->pref_control);
105
106         /* Reset/disable the PFPW engine */
107         writel(0x0, &gpmc_cfg->pref_config1);
108 }
109
110 //#define FIFO_IOADDR           (nand->IO_ADDR_R)
111 #define FIFO_IOADDR             PISMO1_NAND_BASE
112
113 /**
114  * read_buf_pref - read data from NAND controller into buffer
115  * @mtd: MTD device structure
116  * @buf: buffer to store date
117  * @len: number of bytes to read
118  */
119 static void read_buf_pref(struct mtd_info *mtd, u_char *buf, int len)
120 {
121         gpmc_prefetch_enable(cs, PREFETCH_FIFOTHRESHOLD_MAX, len, 0);
122         do {
123                 // Get number of bytes waiting in the FIFO
124                 uint32_t read_bytes = GPMC_PREFETCH_STATUS_FIFO_CNT(readl(&gpmc_cfg->pref_status));
125
126                 if (read_bytes == 0)
127                         continue;
128                 // Alignment of Destination Buffer
129                 while (read_bytes && ((unsigned int)buf & 3)) {
130                         *buf++ = readb(FIFO_IOADDR);
131                         read_bytes--;
132                         len--;
133                 }
134                 // Use maximum word size (32bit) inside this loop, because speed is limited by
135                 // GPMC bus arbitration with a maximum transfer rate of 3.000.000/sec.
136                 len -= read_bytes & ~3;
137                 while (read_bytes >= 4) {
138                         *((uint32_t*)buf) = readl(FIFO_IOADDR);
139                         buf += 4;
140                         read_bytes -= 4;
141                 }
142                 // Transfer the last (non-aligned) bytes only at the last iteration,
143                 // to maintain full speed up to the end of the transfer.
144                 if (read_bytes == len) {
145                         while (read_bytes) {
146                                 *buf++ = readb(FIFO_IOADDR);
147                                 read_bytes--;
148                         }
149                         len = 0;
150                 }
151         } while (len > 0);
152         gpmc_prefetch_reset();
153 }
154
155 /*
156  * write_buf_pref - write buffer to NAND controller
157  * @mtd: MTD device structure
158  * @buf: data buffer
159  * @len: number of bytes to write
160  */
161 static void write_buf_pref(struct mtd_info *mtd, const u_char *buf, int len)
162 {
163         /*  configure and start prefetch transfer */
164         gpmc_prefetch_enable(cs, PREFETCH_FIFOTHRESHOLD_MAX, len, 1);
165
166         while (len) {
167                 // Get number of free bytes in the FIFO
168                 uint32_t write_bytes = GPMC_PREFETCH_STATUS_FIFO_CNT(readl(&gpmc_cfg->pref_status));
169
170                 // don't write more bytes than requested
171                 if (write_bytes > len)
172                         write_bytes = len;
173
174                 // Alignment of Source Buffer
175                 while (write_bytes && ((unsigned int)buf & 3)) {
176                         writeb(*buf++, FIFO_IOADDR);
177                         write_bytes--;
178                         len--;
179                 }
180
181                 // Use maximum word size (32bit) inside this loop, because speed is limited by
182                 // GPMC bus arbitration with a maximum transfer rate of 3.000.000/sec.
183                 len -= write_bytes & ~3;
184                 while (write_bytes >= 4) {
185                         writel(*((uint32_t*)buf), FIFO_IOADDR);
186                         buf += 4;
187                         write_bytes -= 4;
188                 }
189
190                 // Transfer the last (non-aligned) bytes only at the last iteration,
191                 // to maintain full speed up to the end of the transfer.
192                 if (write_bytes == len) {
193                         while (write_bytes) {
194                                 writeb(*buf++, FIFO_IOADDR);
195                                 write_bytes--;
196                         }
197                         len = 0;
198                 }
199         }
200
201         /* wait for data to be flushed out before resetting the prefetch */
202         while ((len = GPMC_PREFETCH_STATUS_COUNT(readl(&gpmc_cfg->pref_status)))) {
203                 debug("%u bytes still in FIFO\n", PREFETCH_FIFOTHRESHOLD_MAX - len);
204                 ndelay(1);
205         }
206
207         /* disable and stop the PFPW engine */
208         gpmc_prefetch_reset();
209 }
210 #endif /* CONFIG_SYS_GPMC_PREFETCH_ENABLE */
211
212 /*
213  * omap_nand_hwcontrol - Set the address pointers corretly for the
214  *                      following address/data/command operation
215  */
216 static void omap_nand_hwcontrol(struct mtd_info *mtd, int32_t cmd,
217                                 uint32_t ctrl)
218 {
219         register struct nand_chip *this = mtd->priv;
220
221         /*
222          * Point the IO_ADDR to DATA and ADDRESS registers instead
223          * of chip address
224          */
225         switch (ctrl) {
226         case NAND_CTRL_CHANGE | NAND_CTRL_CLE:
227                 this->IO_ADDR_W = (void __iomem *)&gpmc_cfg->cs[cs].nand_cmd;
228                 break;
229         case NAND_CTRL_CHANGE | NAND_CTRL_ALE:
230                 this->IO_ADDR_W = (void __iomem *)&gpmc_cfg->cs[cs].nand_adr;
231                 break;
232         case NAND_CTRL_CHANGE | NAND_NCE:
233                 this->IO_ADDR_W = (void __iomem *)&gpmc_cfg->cs[cs].nand_dat;
234                 break;
235         }
236
237         if (cmd != NAND_CMD_NONE)
238                 writeb(cmd, this->IO_ADDR_W);
239 }
240
241 #ifdef CONFIG_SPL_BUILD
242 /* Check wait pin as dev ready indicator */
243 int omap_spl_dev_ready(struct mtd_info *mtd)
244 {
245         return readl(&gpmc_cfg->status) & (1 << 8);
246 }
247 #endif
248
249 /*
250  * omap_hwecc_init - Initialize the Hardware ECC for NAND flash in
251  *                   GPMC controller
252  * @mtd:        MTD device structure
253  *
254  */
255 static void __maybe_unused omap_hwecc_init(struct nand_chip *chip)
256 {
257         /*
258          * Init ECC Control Register
259          * Clear all ECC | Enable Reg1
260          */
261         writel(ECCCLEAR | ECCRESULTREG1, &gpmc_cfg->ecc_control);
262         writel(ECCSIZE1 | ECCSIZE0 | ECCSIZE0SEL, &gpmc_cfg->ecc_size_config);
263 }
264
265 /*
266  * gen_true_ecc - This function will generate true ECC value, which
267  * can be used when correcting data read from NAND flash memory core
268  *
269  * @ecc_buf:    buffer to store ecc code
270  *
271  * @return:     re-formatted ECC value
272  */
273 static uint32_t gen_true_ecc(uint8_t *ecc_buf)
274 {
275         return ecc_buf[0] | (ecc_buf[1] << 16) | ((ecc_buf[2] & 0xF0) << 20) |
276                 ((ecc_buf[2] & 0x0F) << 8);
277 }
278
279 /*
280  * omap_correct_data - Compares the ecc read from nand spare area with ECC
281  * registers values and corrects one bit error if it has occured
282  * Further details can be had from OMAP TRM and the following selected links:
283  * http://en.wikipedia.org/wiki/Hamming_code
284  * http://www.cs.utexas.edu/users/plaxton/c/337/05f/slides/ErrorCorrection-4.pdf
285  *
286  * @mtd:                 MTD device structure
287  * @dat:                 page data
288  * @read_ecc:            ecc read from nand flash
289  * @calc_ecc:            ecc read from ECC registers
290  *
291  * @return 0 if data is OK or corrected, else returns -1
292  */
293 static int __maybe_unused omap_correct_data(struct mtd_info *mtd, uint8_t *dat,
294                                 uint8_t *read_ecc, uint8_t *calc_ecc)
295 {
296         uint32_t orig_ecc, new_ecc, res, hm;
297         uint16_t parity_bits, byte;
298         uint8_t bit;
299
300         /* Regenerate the orginal ECC */
301         orig_ecc = gen_true_ecc(read_ecc);
302         new_ecc = gen_true_ecc(calc_ecc);
303         /* Get the XOR of real ecc */
304         res = orig_ecc ^ new_ecc;
305         if (res) {
306                 /* Get the hamming width */
307                 hm = hweight32(res);
308                 /* Single bit errors can be corrected! */
309                 if (hm == 12) {
310                         /* Correctable data! */
311                         parity_bits = res >> 16;
312                         bit = (parity_bits & 0x7);
313                         byte = (parity_bits >> 3) & 0x1FF;
314                         /* Flip the bit to correct */
315                         dat[byte] ^= (0x1 << bit);
316                 } else if (hm == 1) {
317                         printf("Error: Ecc is wrong\n");
318                         /* ECC itself is corrupted */
319                         return 2;
320                 } else {
321                         /*
322                          * hm distance != parity pairs OR one, could mean 2 bit
323                          * error OR potentially be on a blank page..
324                          * orig_ecc: contains spare area data from nand flash.
325                          * new_ecc: generated ecc while reading data area.
326                          * Note: if the ecc = 0, all data bits from which it was
327                          * generated are 0xFF.
328                          * The 3 byte(24 bits) ecc is generated per 512byte
329                          * chunk of a page. If orig_ecc(from spare area)
330                          * is 0xFF && new_ecc(computed now from data area)=0x0,
331                          * this means that data area is 0xFF and spare area is
332                          * 0xFF. A sure sign of a erased page!
333                          */
334                         if ((orig_ecc == 0x0FFF0FFF) && (new_ecc == 0x00000000))
335                                 return 0;
336                         printf("Error: Bad compare! failed\n");
337                         /* detected 2 bit error */
338                         return -1;
339                 }
340         }
341         return 0;
342 }
343
344 /*
345  *  omap_calculate_ecc - Generate non-inverted ECC bytes.
346  *
347  *  Using noninverted ECC can be considered ugly since writing a blank
348  *  page ie. padding will clear the ECC bytes. This is no problem as
349  *  long nobody is trying to write data on the seemingly unused page.
350  *  Reading an erased page will produce an ECC mismatch between
351  *  generated and read ECC bytes that has to be dealt with separately.
352  *  E.g. if page is 0xFF (fresh erased), and if HW ECC engine within GPMC
353  *  is used, the result of read will be 0x0 while the ECC offsets of the
354  *  spare area will be 0xFF which will result in an ECC mismatch.
355  *  @mtd:       MTD structure
356  *  @dat:       unused
357  *  @ecc_code:  ecc_code buffer
358  */
359 static int __maybe_unused omap_calculate_ecc(struct mtd_info *mtd,
360                 const uint8_t *dat, uint8_t *ecc_code)
361 {
362         u_int32_t val;
363
364         /* Start Reading from HW ECC1_Result = 0x200 */
365         val = readl(&gpmc_cfg->ecc1_result);
366
367         ecc_code[0] = val & 0xFF;
368         ecc_code[1] = (val >> 16) & 0xFF;
369         ecc_code[2] = ((val >> 8) & 0x0F) | ((val >> 20) & 0xF0);
370
371         /*
372          * Stop reading anymore ECC vals and clear old results
373          * enable will be called if more reads are required
374          */
375         writel(0x000, &gpmc_cfg->ecc_config);
376
377         return 0;
378 }
379
380 /*
381  * omap_enable_ecc - This function enables the hardware ecc functionality
382  * @mtd:        MTD device structure
383  * @mode:       Read/Write mode
384  */
385 static void __maybe_unused omap_enable_hwecc(struct mtd_info *mtd, int32_t mode)
386 {
387         struct nand_chip *chip = mtd->priv;
388         uint32_t val, dev_width = (chip->options & NAND_BUSWIDTH_16) >> 1;
389
390         switch (mode) {
391         case NAND_ECC_READ:
392         case NAND_ECC_WRITE:
393                 /* Clear the ecc result registers, select ecc reg as 1 */
394                 writel(ECCCLEAR | ECCRESULTREG1, &gpmc_cfg->ecc_control);
395
396                 /*
397                  * Size 0 = 0xFF, Size1 is 0xFF - both are 512 bytes
398                  * tell all regs to generate size0 sized regs
399                  * we just have a single ECC engine for all CS
400                  */
401                 writel(ECCSIZE1 | ECCSIZE0 | ECCSIZE0SEL,
402                         &gpmc_cfg->ecc_size_config);
403                 val = (dev_width << 7) | (cs << 1) | (1 << 0);
404                 writel(val, &gpmc_cfg->ecc_config);
405                 break;
406         default:
407                 printf("Error: Unrecognized Mode[%d]!\n", mode);
408         }
409 }
410
411 /*
412  * Generic BCH interface
413  */
414 struct nand_bch_priv {
415         uint8_t mode;
416         uint8_t type;
417         uint8_t nibbles;
418         struct bch_control *control;
419 };
420
421 /* bch types */
422 #define ECC_BCH4        0
423 #define ECC_BCH8        1
424 #define ECC_BCH16       2
425
426 /* GPMC ecc engine settings */
427 #define BCH_WRAPMODE_1          1       /* BCH wrap mode 1 */
428 #define BCH_WRAPMODE_6          6       /* BCH wrap mode 6 */
429
430 /* BCH nibbles for diff bch levels */
431 #define NAND_ECC_HW_BCH ((uint8_t)(NAND_ECC_HW_OOB_FIRST) + 1)
432 #define ECC_BCH4_NIBBLES        13
433 #define ECC_BCH8_NIBBLES        26
434 #define ECC_BCH16_NIBBLES       52
435
436 /*
437  * This can be a single instance cause all current users have only one NAND
438  * with nearly the same setup (BCH8, some with ELM and others with sw BCH
439  * library).
440  * When some users with other BCH strength will exists this have to change!
441  */
442 static __maybe_unused struct nand_bch_priv bch_priv = {
443         .mode = NAND_ECC_HW_BCH,
444         .type = ECC_BCH8,
445         .nibbles = ECC_BCH8_NIBBLES,
446         .control = NULL,
447 };
448
449 /*
450  * omap_hwecc_init_bch - Initialize the BCH Hardware ECC for NAND flash in
451  *                              GPMC controller
452  * @mtd:        MTD device structure
453  * @mode:       Read/Write mode
454  */
455 __maybe_unused
456 static void omap_hwecc_init_bch(struct nand_chip *chip, int32_t mode)
457 {
458         uint32_t val;
459         uint32_t dev_width = (chip->options & NAND_BUSWIDTH_16) >> 1;
460 #ifdef CONFIG_AM33XX
461         uint32_t unused_length = 0;
462 #endif
463         uint32_t wr_mode = BCH_WRAPMODE_6;
464         struct nand_bch_priv *bch = chip->priv;
465
466         /* Clear the ecc result registers, select ecc reg as 1 */
467         writel(ECCCLEAR | ECCRESULTREG1, &gpmc_cfg->ecc_control);
468
469 #ifdef CONFIG_AM33XX
470         wr_mode = BCH_WRAPMODE_1;
471
472         switch (bch->nibbles) {
473         case ECC_BCH4_NIBBLES:
474                 unused_length = 3;
475                 break;
476         case ECC_BCH8_NIBBLES:
477                 unused_length = 2;
478                 break;
479         case ECC_BCH16_NIBBLES:
480                 unused_length = 0;
481                 break;
482         }
483
484         /*
485          * This is ecc_size_config for ELM mode.
486          * Here we are using different settings for read and write access and
487          * also depending on BCH strength.
488          */
489         switch (mode) {
490         case NAND_ECC_WRITE:
491                 /* write access only setup eccsize1 config */
492                 val = ((unused_length + bch->nibbles) << 22);
493                 break;
494
495         case NAND_ECC_READ:
496         default:
497                 /*
498                  * by default eccsize0 selected for ecc1resultsize
499                  * eccsize0 config.
500                  */
501                 val  = (bch->nibbles << 12);
502                 /* eccsize1 config */
503                 val |= (unused_length << 22);
504                 break;
505         }
506 #else
507         /*
508          * This ecc_size_config setting is for BCH sw library.
509          *
510          * Note: we only support BCH8 currently with BCH sw library!
511          * Should be really easy to adopt to BCH4, however some omap3 have
512          * flaws with BCH4.
513          *
514          * Here we are using wrapping mode 6 both for reading and writing, with:
515          *  size0 = 0  (no additional protected byte in spare area)
516          *  size1 = 32 (skip 32 nibbles = 16 bytes per sector in spare area)
517          */
518         val = (32 << 22) | (0 << 12);
519 #endif
520         /* ecc size configuration */
521         writel(val, &gpmc_cfg->ecc_size_config);
522
523         /*
524          * Configure the ecc engine in gpmc
525          * We assume 512 Byte sector pages for access to NAND.
526          */
527         val  = 1 << 16;                 /* select BCH mode */
528         val |= bch->type << 12;         /* setup BCH type */
529         val |= wr_mode << 8;            /* setup wrapping mode */
530         val |= dev_width << 7;          /* setup device width (16 or 8 bit) */
531         val |= (chip->ecc.size / 512 - 1) << 4; /* set ECC size */
532         val |= cs << 1;                 /* setup chip select to work on */
533         val |= 1 << 0;                  /* enable ECC engine */
534
535         debug("set ECC_CONFIG=0x%08x\n", val);
536         writel(val, &gpmc_cfg->ecc_config);
537 }
538
539 /*
540  * omap_enable_ecc_bch - This function enables the bch h/w ecc functionality
541  * @mtd:        MTD device structure
542  * @mode:       Read/Write mode
543  */
544 __maybe_unused
545 static void omap_enable_ecc_bch(struct mtd_info *mtd, int32_t mode)
546 {
547         struct nand_chip *chip = mtd->priv;
548
549         omap_hwecc_init_bch(chip, mode);
550 }
551
552 /*
553  * omap_ecc_disable - Disable H/W ECC calculation
554  *
555  * @mtd:        MTD device structure
556  */
557 static void __maybe_unused omap_ecc_disable(struct mtd_info *mtd)
558 {
559         writel((readl(&gpmc_cfg->ecc_config) & ~0x1), &gpmc_cfg->ecc_config);
560 }
561
562 /*
563  * BCH8 support (needs ELM and thus AM33xx-only)
564  */
565 #ifdef CONFIG_AM33XX
566 /*
567  * omap_read_bch8_result - Read BCH result for BCH8 level
568  *
569  * @mtd:        MTD device structure
570  * @big_endian: When set read register 3 first
571  * @ecc_code:   Read syndrome from BCH result registers
572  */
573 static void omap_read_bch8_result(struct mtd_info *mtd, uint8_t big_endian,
574                                 uint8_t *ecc_code)
575 {
576         uint32_t *ptr;
577         int8_t i = 0, j, k;
578         struct nand_chip *chip = mtd->priv;
579         int num_steps = chip->ecc.size / 512;
580
581         for (k = 0; k < num_steps; k++) {
582                 if (big_endian) {
583                         ptr = &gpmc_cfg->bch_result_0_3[k].bch_result_x[3];
584                         ecc_code[i++] = readl(ptr) & 0xFF;
585                         ptr--;
586                         for (j = 0; j < 3; j++) {
587                                 ecc_code[i++] = (readl(ptr) >> 24) & 0xFF;
588                                 ecc_code[i++] = (readl(ptr) >> 16) & 0xFF;
589                                 ecc_code[i++] = (readl(ptr) >>  8) & 0xFF;
590                                 ecc_code[i++] = readl(ptr) & 0xFF;
591                                 ptr--;
592                         }
593                 } else {
594                         ptr = &gpmc_cfg->bch_result_0_3[k].bch_result_x[0];
595                         for (j = 0; j < 3; j++) {
596                                 ecc_code[i++] = readl(ptr) & 0xFF;
597                                 ecc_code[i++] = (readl(ptr) >>  8) & 0xFF;
598                                 ecc_code[i++] = (readl(ptr) >> 16) & 0xFF;
599                                 ecc_code[i++] = (readl(ptr) >> 24) & 0xFF;
600                                 ptr++;
601                         }
602                         ecc_code[i++] = readl(ptr) & 0xFF;
603                 }
604                 ecc_code[i++] = 0;      /* 14th byte is always zero */
605         }
606 }
607
608 /*
609  * omap_rotate_ecc_bch - Rotate the syndrome bytes
610  *
611  * @mtd:        MTD device structure
612  * @calc_ecc:   ECC read from ECC registers
613  * @syndrome:   Rotated syndrome will be returned in this array
614  *
615  */
616 static void omap_rotate_ecc_bch(struct mtd_info *mtd, uint8_t *calc_ecc,
617                 uint8_t *syndrome)
618 {
619         struct nand_chip *chip = mtd->priv;
620         struct nand_bch_priv *bch = chip->priv;
621         uint8_t n_bytes = 0;
622         int8_t i, j;
623
624         switch (bch->type) {
625         case ECC_BCH4:
626                 n_bytes = 8;
627                 break;
628
629         case ECC_BCH16:
630                 n_bytes = 28;
631                 break;
632
633         case ECC_BCH8:
634         default:
635                 n_bytes = 13;
636                 break;
637         }
638
639         for (i = 0, j = n_bytes - 1; i < n_bytes; i++, j--)
640                 syndrome[i] =  calc_ecc[j];
641 }
642
643 /*
644  *  omap_calculate_ecc_bch - Read BCH ECC result
645  *
646  *  @mtd:       MTD structure
647  *  @dat:       unused
648  *  @ecc_code:  ecc_code buffer
649  */
650 static int omap_calculate_ecc_bch(struct mtd_info *mtd, const uint8_t *dat,
651                                 uint8_t *ecc_code)
652 {
653         struct nand_chip *chip = mtd->priv;
654         struct nand_bch_priv *bch = chip->priv;
655         uint8_t big_endian = 1;
656         int8_t ret = 0;
657
658         if (bch->type == ECC_BCH8)
659                 omap_read_bch8_result(mtd, big_endian, ecc_code);
660         else /* BCH4 and BCH16 currently not supported */
661                 ret = -1;
662
663         /*
664          * Stop reading anymore ECC vals and clear old results
665          * enable will be called if more reads are required
666          */
667         omap_ecc_disable(mtd);
668
669         return ret;
670 }
671
672 /*
673  * omap_fix_errors_bch - Correct bch error in the data
674  *
675  * @mtd:        MTD device structure
676  * @data:       Data read from flash
677  * @error_count:Number of errors in data
678  * @error_loc:  Locations of errors in the data
679  *
680  */
681 static void omap_fix_errors_bch(struct mtd_info *mtd, uint8_t *data,
682                 uint32_t error_count, uint32_t *error_loc)
683 {
684         struct nand_chip *chip = mtd->priv;
685         struct nand_bch_priv *bch = chip->priv;
686         uint8_t count = 0;
687         uint32_t error_byte_pos;
688         uint32_t error_bit_mask;
689         uint32_t last_bit = (bch->nibbles * 4) - 1;
690
691         /* Flip all bits as specified by the error location array. */
692         /* FOR( each found error location flip the bit ) */
693         for (count = 0; count < error_count; count++) {
694                 if (error_loc[count] > last_bit) {
695                         /* Remove the ECC spare bits from correction. */
696                         error_loc[count] -= (last_bit + 1);
697                         /* Offset bit in data region */
698                         error_byte_pos = ((512 * 8) -
699                                         (error_loc[count]) - 1) / 8;
700                         /* Error Bit mask */
701                         error_bit_mask = 0x1 << (error_loc[count] % 8);
702                         /* Toggle the error bit to make the correction. */
703                         data[error_byte_pos] ^= error_bit_mask;
704                 }
705         }
706 }
707
708 /*
709  * omap_correct_data_bch - Compares the ecc read from nand spare area
710  * with ECC registers values and corrects one bit error if it has occured
711  *
712  * @mtd:        MTD device structure
713  * @dat:        page data
714  * @read_ecc:   ecc read from nand flash (ignored)
715  * @calc_ecc:   ecc read from ECC registers
716  *
717  * @return 0 if data is OK or corrected, else returns -1
718  */
719 static int omap_correct_data_bch(struct mtd_info *mtd, uint8_t *dat,
720                                 uint8_t *read_ecc, uint8_t *calc_ecc)
721 {
722         struct nand_chip *chip = mtd->priv;
723         struct nand_bch_priv *bch = chip->priv;
724         uint8_t syndrome[28];
725         uint32_t error_count = 0;
726         int errors = 0;
727         uint32_t error_loc[8];
728         uint32_t i, ecc_flag;
729         int k, ecc_bytes, num_steps;
730
731         num_steps = chip->ecc.size / 512;
732         ecc_bytes = chip->ecc.bytes / num_steps;
733
734         for (k = 0; k < num_steps; k++) {
735                 ecc_flag = 0;
736                 /* check if area is flashed */
737                 for (i = 0; i < chip->ecc.bytes && !ecc_flag; i++)
738                         if (read_ecc[i] != 0xff)
739                                 ecc_flag = 1;
740
741                 if (ecc_flag) {
742                         ecc_flag = 0;
743                         /* check if any ecc error */
744                         for (i = 0; (i < ecc_bytes) && !ecc_flag; i++)
745                                 if (calc_ecc[i] != 0)
746                                         ecc_flag = 1;
747                 }
748
749                 if (!ecc_flag)
750                         return 0;
751
752                 elm_reset();
753                 elm_config((enum bch_level)(bch->type));
754
755                 /*
756                  * while reading ECC result we read it in big endian.
757                  * Hence while loading to ELM we have rotate to get the right endian.
758                  */
759                 omap_rotate_ecc_bch(mtd, calc_ecc, syndrome);
760
761                 /* use elm module to check for errors */
762                 if (elm_check_error(syndrome, bch->nibbles, &error_count,
763                                         error_loc) != 0) {
764                         printf("ECC: uncorrectable.\n");
765                         return -1;
766                 }
767
768                 /* correct bch error */
769                 if (error_count > 0) {
770                         omap_fix_errors_bch(mtd, dat, error_count, error_loc);
771                         errors += error_count;
772                 }
773                 dat += 512;
774                 read_ecc += ecc_bytes;
775                 calc_ecc += ecc_bytes;
776         }
777         return errors;
778 }
779
780 /**
781  * omap_read_page_bch - hardware ecc based page read function
782  * @mtd:        mtd info structure
783  * @chip:       nand chip info structure
784  * @buf:        buffer to store read data
785  * @oob_required: caller expects OOB data read to chip->oob_poi
786  * @page:       page number to read
787  *
788  */
789 static int omap_read_page_bch(struct mtd_info *mtd, struct nand_chip *chip,
790                                 uint8_t *buf, int oob_required, int page)
791 {
792         int i, eccsize = chip->ecc.size;
793         int eccbytes = chip->ecc.bytes;
794         int eccsteps = chip->ecc.steps;
795         uint8_t *p = buf;
796         uint8_t *ecc_calc = chip->buffers->ecccalc;
797         uint8_t *ecc_code = chip->buffers->ecccode;
798         uint32_t *eccpos = chip->ecc.layout->eccpos;
799         uint8_t *oob = &chip->oob_poi[eccpos[0]];
800         uint32_t data_pos;
801         uint32_t oob_pos;
802
803         data_pos = 0;
804         /* oob area start */
805         oob_pos = (eccsize * eccsteps) + eccpos[0];
806
807         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize,
808                                 oob += eccbytes) {
809                 chip->ecc.hwctl(mtd, NAND_ECC_READ);
810                 /* read data */
811                 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_pos, page);
812                 chip->read_buf(mtd, p, eccsize);
813
814                 /* read respective ecc from oob area */
815                 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, oob_pos, page);
816                 chip->read_buf(mtd, oob, eccbytes);
817                 /* read syndrome */
818                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
819
820                 if (oob_required) {
821                         /* reread the OOB area to get the metadata */
822                         chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, page);
823                         chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
824                 }
825
826                 data_pos += eccsize;
827                 oob_pos += eccbytes;
828         }
829
830         for (i = 0; i < chip->ecc.total; i++)
831                 ecc_code[i] = chip->oob_poi[eccpos[i]];
832
833         eccsteps = chip->ecc.steps;
834         p = buf;
835
836         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
837                 int stat;
838
839                 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
840                 if (stat < 0)
841                         mtd->ecc_stats.failed++;
842                 else
843                         mtd->ecc_stats.corrected += stat;
844         }
845         return 0;
846 }
847 #endif /* CONFIG_AM33XX */
848
849 /*
850  * OMAP3 BCH8 support (with BCH library)
851  */
852 #ifdef CONFIG_NAND_OMAP_BCH8
853 /*
854  *  omap_calculate_ecc_bch - Read BCH ECC result
855  *
856  *  @mtd:       MTD device structure
857  *  @dat:       The pointer to data on which ecc is computed (unused here)
858  *  @ecc:       The ECC output buffer
859  */
860 static int omap_calculate_ecc_bch(struct mtd_info *mtd, const uint8_t *dat,
861                                 uint8_t *ecc)
862 {
863         int ret = 0;
864         size_t i;
865         unsigned long nsectors, val1, val2, val3, val4;
866
867         nsectors = ((readl(&gpmc_cfg->ecc_config) >> 4) & 0x7) + 1;
868
869         for (i = 0; i < nsectors; i++) {
870                 /* Read hw-computed remainder */
871                 val1 = readl(&gpmc_cfg->bch_result_0_3[i].bch_result_x[0]);
872                 val2 = readl(&gpmc_cfg->bch_result_0_3[i].bch_result_x[1]);
873                 val3 = readl(&gpmc_cfg->bch_result_0_3[i].bch_result_x[2]);
874                 val4 = readl(&gpmc_cfg->bch_result_0_3[i].bch_result_x[3]);
875
876                 /*
877                  * Add constant polynomial to remainder, in order to get an ecc
878                  * sequence of 0xFFs for a buffer filled with 0xFFs.
879                  */
880                 *ecc++ = 0xef ^ (val4 & 0xFF);
881                 *ecc++ = 0x51 ^ ((val3 >> 24) & 0xFF);
882                 *ecc++ = 0x2e ^ ((val3 >> 16) & 0xFF);
883                 *ecc++ = 0x09 ^ ((val3 >> 8) & 0xFF);
884                 *ecc++ = 0xed ^ (val3 & 0xFF);
885                 *ecc++ = 0x93 ^ ((val2 >> 24) & 0xFF);
886                 *ecc++ = 0x9a ^ ((val2 >> 16) & 0xFF);
887                 *ecc++ = 0xc2 ^ ((val2 >> 8) & 0xFF);
888                 *ecc++ = 0x97 ^ (val2 & 0xFF);
889                 *ecc++ = 0x79 ^ ((val1 >> 24) & 0xFF);
890                 *ecc++ = 0xe5 ^ ((val1 >> 16) & 0xFF);
891                 *ecc++ = 0x24 ^ ((val1 >> 8) & 0xFF);
892                 *ecc++ = 0xb5 ^ (val1 & 0xFF);
893         }
894
895         /*
896          * Stop reading anymore ECC vals and clear old results
897          * enable will be called if more reads are required
898          */
899         omap_ecc_disable(mtd);
900
901         return ret;
902 }
903
904 /**
905  * omap_correct_data_bch - Decode received data and correct errors
906  * @mtd: MTD device structure
907  * @data: page data
908  * @read_ecc: ecc read from nand flash
909  * @calc_ecc: ecc read from HW ECC registers
910  */
911 static int omap_correct_data_bch(struct mtd_info *mtd, u_char *data,
912                                  u_char *read_ecc, u_char *calc_ecc)
913 {
914         int i, count;
915         /* cannot correct more than 8 errors */
916         unsigned int errloc[8];
917         struct nand_chip *chip = mtd->priv;
918         struct nand_bch_priv *chip_priv = chip->priv;
919         struct bch_control *bch = chip_priv->control;
920
921         count = decode_bch(bch, NULL, 512, read_ecc, calc_ecc, NULL, errloc);
922         if (count > 0) {
923                 /* correct errors */
924                 for (i = 0; i < count; i++) {
925                         /* correct data only, not ecc bytes */
926                         if (errloc[i] < 8*512)
927                                 data[errloc[i]/8] ^= 1 << (errloc[i] & 7);
928                         printf("corrected bitflip %u\n", errloc[i]);
929 #ifdef DEBUG
930                         printf("read_ecc: ");
931                         /*
932                          * BCH8 have 13 bytes of ECC; BCH4 needs adoption
933                          * here!
934                          */
935                         for (i = 0; i < 13; i++)
936                                 printf("%02x ", read_ecc[i]);
937                         printf("\n");
938                         printf("calc_ecc: ");
939                         for (i = 0; i < 13; i++)
940                                 printf("%02x ", calc_ecc[i]);
941                         printf("\n");
942 #endif
943                 }
944         } else if (count < 0) {
945                 printf("ecc unrecoverable error\n");
946         }
947         return count;
948 }
949
950 /**
951  * omap_free_bch - Release BCH ecc resources
952  * @mtd: MTD device structure
953  */
954 static void __maybe_unused omap_free_bch(struct mtd_info *mtd)
955 {
956         struct nand_chip *chip = mtd->priv;
957         struct nand_bch_priv *chip_priv = chip->priv;
958         struct bch_control *bch = NULL;
959
960         if (chip_priv)
961                 bch = chip_priv->control;
962
963         if (bch) {
964                 free_bch(bch);
965                 chip_priv->control = NULL;
966         }
967 }
968 #endif /* CONFIG_NAND_OMAP_BCH8 */
969
970 #ifndef CONFIG_SPL_BUILD
971 /*
972  * omap_nand_switch_ecc - switch the ECC operation between different engines
973  * (h/w and s/w) and different algorithms (hamming and BCHx)
974  *
975  * @hardware            - true if one of the HW engines should be used
976  * @eccstrength         - the number of bits that could be corrected
977  *                        (1 - hamming, 4 - BCH4, 8 - BCH8, 16 - BCH16)
978  */
979 void omap_nand_switch_ecc(uint32_t hardware, uint32_t eccstrength)
980 {
981         struct nand_chip *nand;
982         struct mtd_info *mtd;
983
984         if (nand_curr_device < 0 ||
985             nand_curr_device >= CONFIG_SYS_MAX_NAND_DEVICE ||
986             !nand_info[nand_curr_device].name) {
987                 printf("Error: Can't switch ecc, no devices available\n");
988                 return;
989         }
990
991         mtd = &nand_info[nand_curr_device];
992         nand = mtd->priv;
993
994         nand->options |= NAND_OWN_BUFFERS;
995
996         /* Reset ecc interface */
997         nand->ecc.mode = NAND_ECC_NONE;
998         nand->ecc.read_page = NULL;
999         nand->ecc.write_page = NULL;
1000         nand->ecc.read_oob = NULL;
1001         nand->ecc.write_oob = NULL;
1002         nand->ecc.hwctl = NULL;
1003         nand->ecc.correct = NULL;
1004         nand->ecc.calculate = NULL;
1005         nand->ecc.strength = eccstrength;
1006
1007         /* Setup the ecc configurations again */
1008         if (hardware) {
1009                 if (eccstrength == 1) {
1010                         nand->ecc.mode = NAND_ECC_HW;
1011                         nand->ecc.layout = &hw_nand_oob;
1012                         nand->ecc.size = 512;
1013                         nand->ecc.bytes = 3;
1014                         nand->ecc.hwctl = omap_enable_hwecc;
1015                         nand->ecc.correct = omap_correct_data;
1016                         nand->ecc.calculate = omap_calculate_ecc;
1017                         omap_hwecc_init(nand);
1018                         printf("1-bit hamming HW ECC selected\n");
1019                 }
1020 #if defined(CONFIG_AM33XX) || defined(CONFIG_NAND_OMAP_BCH8)
1021                 else if (eccstrength == 8) {
1022                         nand->ecc.mode = NAND_ECC_HW;
1023                         nand->ecc.layout = &hw_bch8_nand_oob;
1024                         nand->ecc.size = 512;
1025 #ifdef CONFIG_AM33XX
1026                         nand->ecc.bytes = 14;
1027                         nand->ecc.read_page = omap_read_page_bch;
1028 #else
1029                         nand->ecc.bytes = 13;
1030 #endif
1031                         nand->ecc.hwctl = omap_enable_ecc_bch;
1032                         nand->ecc.correct = omap_correct_data_bch;
1033                         nand->ecc.calculate = omap_calculate_ecc_bch;
1034                         omap_hwecc_init_bch(nand, NAND_ECC_READ);
1035                         printf("8-bit BCH HW ECC selected\n");
1036                 }
1037 #endif
1038         } else {
1039                 nand->ecc.mode = NAND_ECC_SOFT;
1040                 /* Use mtd default settings */
1041                 nand->ecc.layout = NULL;
1042                 nand->ecc.size = 0;
1043                 printf("SW ECC selected\n");
1044         }
1045
1046         /* Update NAND handling after ECC mode switch */
1047         nand_scan_tail(mtd);
1048
1049         nand->options &= ~NAND_OWN_BUFFERS;
1050 }
1051 #endif /* CONFIG_SPL_BUILD */
1052
1053 /*
1054  * Board-specific NAND initialization. The following members of the
1055  * argument are board-specific:
1056  * - IO_ADDR_R: address to read the 8 I/O lines of the flash device
1057  * - IO_ADDR_W: address to write the 8 I/O lines of the flash device
1058  * - cmd_ctrl: hardwarespecific function for accesing control-lines
1059  * - waitfunc: hardwarespecific function for accesing device ready/busy line
1060  * - ecc.hwctl: function to enable (reset) hardware ecc generator
1061  * - ecc.mode: mode of ecc, see defines
1062  * - chip_delay: chip dependent delay for transfering data from array to
1063  *   read regs (tR)
1064  * - options: various chip options. They can partly be set to inform
1065  *   nand_scan about special functionality. See the defines for further
1066  *   explanation
1067  */
1068 int board_nand_init(struct nand_chip *nand)
1069 {
1070         int32_t gpmc_config = 0;
1071         cs = 0;
1072
1073         /*
1074          * xloader/Uboot's gpmc configuration would have configured GPMC for
1075          * nand type of memory. The following logic scans and latches on to the
1076          * first CS with NAND type memory.
1077          * TBD: need to make this logic generic to handle multiple CS NAND
1078          * devices.
1079          */
1080         while (cs < GPMC_MAX_CS) {
1081                 /* Check if NAND type is set */
1082                 if ((readl(&gpmc_cfg->cs[cs].config1) & 0xC00) == 0x800) {
1083                         /* Found it!! */
1084                         break;
1085                 }
1086                 cs++;
1087         }
1088         if (cs >= GPMC_MAX_CS) {
1089                 printf("NAND: Unable to find NAND settings in "
1090                         "GPMC Configuration - quitting\n");
1091                 return -ENODEV;
1092         }
1093
1094         gpmc_config = readl(&gpmc_cfg->config);
1095         /* Disable Write protect */
1096         gpmc_config |= 0x10;
1097         writel(gpmc_config, &gpmc_cfg->config);
1098
1099         nand->IO_ADDR_R = (void __iomem *)&gpmc_cfg->cs[cs].nand_dat;
1100         nand->IO_ADDR_W = (void __iomem *)&gpmc_cfg->cs[cs].nand_cmd;
1101
1102         nand->cmd_ctrl = omap_nand_hwcontrol;
1103         nand->options = NAND_NO_PADDING | NAND_CACHEPRG | NAND_NO_SUBPAGE_WRITE;
1104         /* If we are 16 bit dev, our gpmc config tells us that */
1105         if ((readl(&gpmc_cfg->cs[cs].config1) & 0x3000) == 0x1000)
1106                 nand->options |= NAND_BUSWIDTH_16;
1107
1108         nand->chip_delay = 100;
1109
1110 #if defined(CONFIG_AM33XX) || defined(CONFIG_NAND_OMAP_BCH8)
1111 #ifdef CONFIG_AM33XX
1112         /* AM33xx uses the ELM */
1113         /* required in case of BCH */
1114         elm_init();
1115 #else
1116         /*
1117          * Whereas other OMAP based SoC do not have the ELM, they use the BCH
1118          * SW library.
1119          */
1120         bch_priv.control = init_bch(13, 8, 0x201b /* hw polynominal */);
1121         if (!bch_priv.control) {
1122                 printf("Failed to initialize BCH engine\n");
1123                 return -ENODEV;
1124         }
1125 #endif
1126         /* BCH info that will be correct for SPL or overridden otherwise. */
1127         nand->priv = &bch_priv;
1128 #endif
1129
1130         /* Default ECC mode */
1131 #if defined(CONFIG_AM33XX) || defined(CONFIG_NAND_OMAP_BCH8)
1132         nand->ecc.mode = NAND_ECC_HW;
1133         nand->ecc.layout = &hw_bch8_nand_oob;
1134         nand->ecc.size = CONFIG_SYS_NAND_ECCSIZE;
1135         nand->ecc.bytes = CONFIG_SYS_NAND_ECCBYTES;
1136         nand->ecc.strength = 8;
1137         nand->ecc.hwctl = omap_enable_ecc_bch;
1138         nand->ecc.correct = omap_correct_data_bch;
1139         nand->ecc.calculate = omap_calculate_ecc_bch;
1140 #ifdef CONFIG_AM33XX
1141         nand->ecc.read_page = omap_read_page_bch;
1142 #endif
1143         omap_hwecc_init_bch(nand, NAND_ECC_READ);
1144 #else
1145 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_NAND_SOFTECC)
1146         nand->ecc.mode = NAND_ECC_SOFT;
1147 #else
1148         nand->ecc.mode = NAND_ECC_HW;
1149         nand->ecc.layout = &hw_nand_oob;
1150         nand->ecc.size = CONFIG_SYS_NAND_ECCSIZE;
1151         nand->ecc.bytes = CONFIG_SYS_NAND_ECCBYTES;
1152         nand->ecc.hwctl = omap_enable_hwecc;
1153         nand->ecc.correct = omap_correct_data;
1154         nand->ecc.calculate = omap_calculate_ecc;
1155         nand->ecc.strength = 1;
1156         omap_hwecc_init(nand);
1157 #endif
1158 #endif
1159 #ifdef CONFIG_SYS_NAND_USE_FLASH_BBT
1160         if (nand->ecc.layout) {
1161                 bbt_main_descr.offs = nand->ecc.layout->oobfree[0].offset;
1162                 bbt_main_descr.veroffs = bbt_main_descr.offs +
1163                         sizeof(bbt_pattern);
1164
1165                 bbt_mirror_descr.offs = nand->ecc.layout->oobfree[0].offset;
1166                 bbt_mirror_descr.veroffs = bbt_mirror_descr.offs +
1167                         sizeof(mirror_pattern);
1168         }
1169
1170         nand->bbt_options |= NAND_BBT_USE_FLASH;
1171         nand->bbt_td = &bbt_main_descr;
1172         nand->bbt_md = &bbt_mirror_descr;
1173 #endif
1174
1175 #ifdef CONFIG_SPL_BUILD
1176         if (nand->options & NAND_BUSWIDTH_16)
1177                 nand->read_buf = nand_read_buf16;
1178         else
1179                 nand->read_buf = nand_read_buf;
1180         nand->dev_ready = omap_spl_dev_ready;
1181 #else
1182 #ifdef CONFIG_SYS_GPMC_PREFETCH_ENABLE
1183         nand->write_buf = write_buf_pref;
1184         nand->read_buf = read_buf_pref;
1185 #endif /* CONFIG_SYS_GPMC_PREFETCH_ENABLE */
1186 #endif /* CONFIG_SPL_BUILD */
1187
1188         return 0;
1189 }