]> git.karo-electronics.de Git - linux-beck.git/blob - drivers/mtd/nand/atmel_nand.c
mtd: atmel_nand: Support variable RB_EDGE interrupts
[linux-beck.git] / drivers / mtd / nand / atmel_nand.c
1 /*
2  *  Copyright © 2003 Rick Bronson
3  *
4  *  Derived from drivers/mtd/nand/autcpu12.c
5  *       Copyright © 2001 Thomas Gleixner (gleixner@autronix.de)
6  *
7  *  Derived from drivers/mtd/spia.c
8  *       Copyright © 2000 Steven J. Hill (sjhill@cotw.com)
9  *
10  *
11  *  Add Hardware ECC support for AT91SAM9260 / AT91SAM9263
12  *     Richard Genoud (richard.genoud@gmail.com), Adeneo Copyright © 2007
13  *
14  *     Derived from Das U-Boot source code
15  *              (u-boot-1.1.5/board/atmel/at91sam9263ek/nand.c)
16  *     © Copyright 2006 ATMEL Rousset, Lacressonniere Nicolas
17  *
18  *  Add Programmable Multibit ECC support for various AT91 SoC
19  *     © Copyright 2012 ATMEL, Hong Xu
20  *
21  *  Add Nand Flash Controller support for SAMA5 SoC
22  *     © Copyright 2013 ATMEL, Josh Wu (josh.wu@atmel.com)
23  *
24  * This program is free software; you can redistribute it and/or modify
25  * it under the terms of the GNU General Public License version 2 as
26  * published by the Free Software Foundation.
27  *
28  */
29
30 #include <linux/clk.h>
31 #include <linux/dma-mapping.h>
32 #include <linux/slab.h>
33 #include <linux/module.h>
34 #include <linux/moduleparam.h>
35 #include <linux/platform_device.h>
36 #include <linux/of.h>
37 #include <linux/of_device.h>
38 #include <linux/of_gpio.h>
39 #include <linux/of_mtd.h>
40 #include <linux/mtd/mtd.h>
41 #include <linux/mtd/nand.h>
42 #include <linux/mtd/partitions.h>
43
44 #include <linux/delay.h>
45 #include <linux/dmaengine.h>
46 #include <linux/gpio.h>
47 #include <linux/interrupt.h>
48 #include <linux/io.h>
49 #include <linux/platform_data/atmel.h>
50
51 static int use_dma = 1;
52 module_param(use_dma, int, 0);
53
54 static int on_flash_bbt = 0;
55 module_param(on_flash_bbt, int, 0);
56
57 /* Register access macros */
58 #define ecc_readl(add, reg)                             \
59         __raw_readl(add + ATMEL_ECC_##reg)
60 #define ecc_writel(add, reg, value)                     \
61         __raw_writel((value), add + ATMEL_ECC_##reg)
62
63 #include "atmel_nand_ecc.h"     /* Hardware ECC registers */
64 #include "atmel_nand_nfc.h"     /* Nand Flash Controller definition */
65
66 struct atmel_nand_caps {
67         bool pmecc_correct_erase_page;
68 };
69
70 struct atmel_nand_nfc_caps {
71         uint32_t rb_mask;
72 };
73
74 /* oob layout for large page size
75  * bad block info is on bytes 0 and 1
76  * the bytes have to be consecutives to avoid
77  * several NAND_CMD_RNDOUT during read
78  */
79 static struct nand_ecclayout atmel_oobinfo_large = {
80         .eccbytes = 4,
81         .eccpos = {60, 61, 62, 63},
82         .oobfree = {
83                 {2, 58}
84         },
85 };
86
87 /* oob layout for small page size
88  * bad block info is on bytes 4 and 5
89  * the bytes have to be consecutives to avoid
90  * several NAND_CMD_RNDOUT during read
91  */
92 static struct nand_ecclayout atmel_oobinfo_small = {
93         .eccbytes = 4,
94         .eccpos = {0, 1, 2, 3},
95         .oobfree = {
96                 {6, 10}
97         },
98 };
99
100 struct atmel_nfc {
101         void __iomem            *base_cmd_regs;
102         void __iomem            *hsmc_regs;
103         void                    *sram_bank0;
104         dma_addr_t              sram_bank0_phys;
105         bool                    use_nfc_sram;
106         bool                    write_by_sram;
107
108         struct clk              *clk;
109
110         bool                    is_initialized;
111         struct completion       comp_ready;
112         struct completion       comp_cmd_done;
113         struct completion       comp_xfer_done;
114
115         /* Point to the sram bank which include readed data via NFC */
116         void                    *data_in_sram;
117         bool                    will_write_sram;
118         const struct atmel_nand_nfc_caps *caps;
119 };
120 static struct atmel_nfc nand_nfc;
121
122 struct atmel_nand_host {
123         struct nand_chip        nand_chip;
124         void __iomem            *io_base;
125         dma_addr_t              io_phys;
126         struct atmel_nand_data  board;
127         struct device           *dev;
128         void __iomem            *ecc;
129
130         struct completion       comp;
131         struct dma_chan         *dma_chan;
132
133         struct atmel_nfc        *nfc;
134
135         const struct atmel_nand_caps    *caps;
136         bool                    has_pmecc;
137         u8                      pmecc_corr_cap;
138         u16                     pmecc_sector_size;
139         bool                    has_no_lookup_table;
140         u32                     pmecc_lookup_table_offset;
141         u32                     pmecc_lookup_table_offset_512;
142         u32                     pmecc_lookup_table_offset_1024;
143
144         int                     pmecc_degree;   /* Degree of remainders */
145         int                     pmecc_cw_len;   /* Length of codeword */
146
147         void __iomem            *pmerrloc_base;
148         void __iomem            *pmecc_rom_base;
149
150         /* lookup table for alpha_to and index_of */
151         void __iomem            *pmecc_alpha_to;
152         void __iomem            *pmecc_index_of;
153
154         /* data for pmecc computation */
155         int16_t                 *pmecc_partial_syn;
156         int16_t                 *pmecc_si;
157         int16_t                 *pmecc_smu;     /* Sigma table */
158         int16_t                 *pmecc_lmu;     /* polynomal order */
159         int                     *pmecc_mu;
160         int                     *pmecc_dmu;
161         int                     *pmecc_delta;
162 };
163
164 static struct nand_ecclayout atmel_pmecc_oobinfo;
165
166 /*
167  * Enable NAND.
168  */
169 static void atmel_nand_enable(struct atmel_nand_host *host)
170 {
171         if (gpio_is_valid(host->board.enable_pin))
172                 gpio_set_value(host->board.enable_pin, 0);
173 }
174
175 /*
176  * Disable NAND.
177  */
178 static void atmel_nand_disable(struct atmel_nand_host *host)
179 {
180         if (gpio_is_valid(host->board.enable_pin))
181                 gpio_set_value(host->board.enable_pin, 1);
182 }
183
184 /*
185  * Hardware specific access to control-lines
186  */
187 static void atmel_nand_cmd_ctrl(struct mtd_info *mtd, int cmd, unsigned int ctrl)
188 {
189         struct nand_chip *nand_chip = mtd_to_nand(mtd);
190         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
191
192         if (ctrl & NAND_CTRL_CHANGE) {
193                 if (ctrl & NAND_NCE)
194                         atmel_nand_enable(host);
195                 else
196                         atmel_nand_disable(host);
197         }
198         if (cmd == NAND_CMD_NONE)
199                 return;
200
201         if (ctrl & NAND_CLE)
202                 writeb(cmd, host->io_base + (1 << host->board.cle));
203         else
204                 writeb(cmd, host->io_base + (1 << host->board.ale));
205 }
206
207 /*
208  * Read the Device Ready pin.
209  */
210 static int atmel_nand_device_ready(struct mtd_info *mtd)
211 {
212         struct nand_chip *nand_chip = mtd_to_nand(mtd);
213         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
214
215         return gpio_get_value(host->board.rdy_pin) ^
216                 !!host->board.rdy_pin_active_low;
217 }
218
219 /* Set up for hardware ready pin and enable pin. */
220 static int atmel_nand_set_enable_ready_pins(struct mtd_info *mtd)
221 {
222         struct nand_chip *chip = mtd_to_nand(mtd);
223         struct atmel_nand_host *host = nand_get_controller_data(chip);
224         int res = 0;
225
226         if (gpio_is_valid(host->board.rdy_pin)) {
227                 res = devm_gpio_request(host->dev,
228                                 host->board.rdy_pin, "nand_rdy");
229                 if (res < 0) {
230                         dev_err(host->dev,
231                                 "can't request rdy gpio %d\n",
232                                 host->board.rdy_pin);
233                         return res;
234                 }
235
236                 res = gpio_direction_input(host->board.rdy_pin);
237                 if (res < 0) {
238                         dev_err(host->dev,
239                                 "can't request input direction rdy gpio %d\n",
240                                 host->board.rdy_pin);
241                         return res;
242                 }
243
244                 chip->dev_ready = atmel_nand_device_ready;
245         }
246
247         if (gpio_is_valid(host->board.enable_pin)) {
248                 res = devm_gpio_request(host->dev,
249                                 host->board.enable_pin, "nand_enable");
250                 if (res < 0) {
251                         dev_err(host->dev,
252                                 "can't request enable gpio %d\n",
253                                 host->board.enable_pin);
254                         return res;
255                 }
256
257                 res = gpio_direction_output(host->board.enable_pin, 1);
258                 if (res < 0) {
259                         dev_err(host->dev,
260                                 "can't request output direction enable gpio %d\n",
261                                 host->board.enable_pin);
262                         return res;
263                 }
264         }
265
266         return res;
267 }
268
269 /*
270  * Minimal-overhead PIO for data access.
271  */
272 static void atmel_read_buf8(struct mtd_info *mtd, u8 *buf, int len)
273 {
274         struct nand_chip        *nand_chip = mtd_to_nand(mtd);
275         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
276
277         if (host->nfc && host->nfc->use_nfc_sram && host->nfc->data_in_sram) {
278                 memcpy(buf, host->nfc->data_in_sram, len);
279                 host->nfc->data_in_sram += len;
280         } else {
281                 __raw_readsb(nand_chip->IO_ADDR_R, buf, len);
282         }
283 }
284
285 static void atmel_read_buf16(struct mtd_info *mtd, u8 *buf, int len)
286 {
287         struct nand_chip        *nand_chip = mtd_to_nand(mtd);
288         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
289
290         if (host->nfc && host->nfc->use_nfc_sram && host->nfc->data_in_sram) {
291                 memcpy(buf, host->nfc->data_in_sram, len);
292                 host->nfc->data_in_sram += len;
293         } else {
294                 __raw_readsw(nand_chip->IO_ADDR_R, buf, len / 2);
295         }
296 }
297
298 static void atmel_write_buf8(struct mtd_info *mtd, const u8 *buf, int len)
299 {
300         struct nand_chip        *nand_chip = mtd_to_nand(mtd);
301
302         __raw_writesb(nand_chip->IO_ADDR_W, buf, len);
303 }
304
305 static void atmel_write_buf16(struct mtd_info *mtd, const u8 *buf, int len)
306 {
307         struct nand_chip        *nand_chip = mtd_to_nand(mtd);
308
309         __raw_writesw(nand_chip->IO_ADDR_W, buf, len / 2);
310 }
311
312 static void dma_complete_func(void *completion)
313 {
314         complete(completion);
315 }
316
317 static int nfc_set_sram_bank(struct atmel_nand_host *host, unsigned int bank)
318 {
319         /* NFC only has two banks. Must be 0 or 1 */
320         if (bank > 1)
321                 return -EINVAL;
322
323         if (bank) {
324                 struct mtd_info *mtd = nand_to_mtd(&host->nand_chip);
325
326                 /* Only for a 2k-page or lower flash, NFC can handle 2 banks */
327                 if (mtd->writesize > 2048)
328                         return -EINVAL;
329                 nfc_writel(host->nfc->hsmc_regs, BANK, ATMEL_HSMC_NFC_BANK1);
330         } else {
331                 nfc_writel(host->nfc->hsmc_regs, BANK, ATMEL_HSMC_NFC_BANK0);
332         }
333
334         return 0;
335 }
336
337 static uint nfc_get_sram_off(struct atmel_nand_host *host)
338 {
339         if (nfc_readl(host->nfc->hsmc_regs, BANK) & ATMEL_HSMC_NFC_BANK1)
340                 return NFC_SRAM_BANK1_OFFSET;
341         else
342                 return 0;
343 }
344
345 static dma_addr_t nfc_sram_phys(struct atmel_nand_host *host)
346 {
347         if (nfc_readl(host->nfc->hsmc_regs, BANK) & ATMEL_HSMC_NFC_BANK1)
348                 return host->nfc->sram_bank0_phys + NFC_SRAM_BANK1_OFFSET;
349         else
350                 return host->nfc->sram_bank0_phys;
351 }
352
353 static int atmel_nand_dma_op(struct mtd_info *mtd, void *buf, int len,
354                                int is_read)
355 {
356         struct dma_device *dma_dev;
357         enum dma_ctrl_flags flags;
358         dma_addr_t dma_src_addr, dma_dst_addr, phys_addr;
359         struct dma_async_tx_descriptor *tx = NULL;
360         dma_cookie_t cookie;
361         struct nand_chip *chip = mtd_to_nand(mtd);
362         struct atmel_nand_host *host = nand_get_controller_data(chip);
363         void *p = buf;
364         int err = -EIO;
365         enum dma_data_direction dir = is_read ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
366         struct atmel_nfc *nfc = host->nfc;
367
368         if (buf >= high_memory)
369                 goto err_buf;
370
371         dma_dev = host->dma_chan->device;
372
373         flags = DMA_CTRL_ACK | DMA_PREP_INTERRUPT;
374
375         phys_addr = dma_map_single(dma_dev->dev, p, len, dir);
376         if (dma_mapping_error(dma_dev->dev, phys_addr)) {
377                 dev_err(host->dev, "Failed to dma_map_single\n");
378                 goto err_buf;
379         }
380
381         if (is_read) {
382                 if (nfc && nfc->data_in_sram)
383                         dma_src_addr = nfc_sram_phys(host) + (nfc->data_in_sram
384                                 - (nfc->sram_bank0 + nfc_get_sram_off(host)));
385                 else
386                         dma_src_addr = host->io_phys;
387
388                 dma_dst_addr = phys_addr;
389         } else {
390                 dma_src_addr = phys_addr;
391
392                 if (nfc && nfc->write_by_sram)
393                         dma_dst_addr = nfc_sram_phys(host);
394                 else
395                         dma_dst_addr = host->io_phys;
396         }
397
398         tx = dma_dev->device_prep_dma_memcpy(host->dma_chan, dma_dst_addr,
399                                              dma_src_addr, len, flags);
400         if (!tx) {
401                 dev_err(host->dev, "Failed to prepare DMA memcpy\n");
402                 goto err_dma;
403         }
404
405         init_completion(&host->comp);
406         tx->callback = dma_complete_func;
407         tx->callback_param = &host->comp;
408
409         cookie = tx->tx_submit(tx);
410         if (dma_submit_error(cookie)) {
411                 dev_err(host->dev, "Failed to do DMA tx_submit\n");
412                 goto err_dma;
413         }
414
415         dma_async_issue_pending(host->dma_chan);
416         wait_for_completion(&host->comp);
417
418         if (is_read && nfc && nfc->data_in_sram)
419                 /* After read data from SRAM, need to increase the position */
420                 nfc->data_in_sram += len;
421
422         err = 0;
423
424 err_dma:
425         dma_unmap_single(dma_dev->dev, phys_addr, len, dir);
426 err_buf:
427         if (err != 0)
428                 dev_dbg(host->dev, "Fall back to CPU I/O\n");
429         return err;
430 }
431
432 static void atmel_read_buf(struct mtd_info *mtd, u8 *buf, int len)
433 {
434         struct nand_chip *chip = mtd_to_nand(mtd);
435         struct atmel_nand_host *host = nand_get_controller_data(chip);
436
437         if (use_dma && len > mtd->oobsize)
438                 /* only use DMA for bigger than oob size: better performances */
439                 if (atmel_nand_dma_op(mtd, buf, len, 1) == 0)
440                         return;
441
442         if (host->board.bus_width_16)
443                 atmel_read_buf16(mtd, buf, len);
444         else
445                 atmel_read_buf8(mtd, buf, len);
446 }
447
448 static void atmel_write_buf(struct mtd_info *mtd, const u8 *buf, int len)
449 {
450         struct nand_chip *chip = mtd_to_nand(mtd);
451         struct atmel_nand_host *host = nand_get_controller_data(chip);
452
453         if (use_dma && len > mtd->oobsize)
454                 /* only use DMA for bigger than oob size: better performances */
455                 if (atmel_nand_dma_op(mtd, (void *)buf, len, 0) == 0)
456                         return;
457
458         if (host->board.bus_width_16)
459                 atmel_write_buf16(mtd, buf, len);
460         else
461                 atmel_write_buf8(mtd, buf, len);
462 }
463
464 /*
465  * Return number of ecc bytes per sector according to sector size and
466  * correction capability
467  *
468  * Following table shows what at91 PMECC supported:
469  * Correction Capability        Sector_512_bytes        Sector_1024_bytes
470  * =====================        ================        =================
471  *                2-bits                 4-bytes                  4-bytes
472  *                4-bits                 7-bytes                  7-bytes
473  *                8-bits                13-bytes                 14-bytes
474  *               12-bits                20-bytes                 21-bytes
475  *               24-bits                39-bytes                 42-bytes
476  */
477 static int pmecc_get_ecc_bytes(int cap, int sector_size)
478 {
479         int m = 12 + sector_size / 512;
480         return (m * cap + 7) / 8;
481 }
482
483 static void pmecc_config_ecc_layout(struct nand_ecclayout *layout,
484                                     int oobsize, int ecc_len)
485 {
486         int i;
487
488         layout->eccbytes = ecc_len;
489
490         /* ECC will occupy the last ecc_len bytes continuously */
491         for (i = 0; i < ecc_len; i++)
492                 layout->eccpos[i] = oobsize - ecc_len + i;
493
494         layout->oobfree[0].offset = PMECC_OOB_RESERVED_BYTES;
495         layout->oobfree[0].length =
496                 oobsize - ecc_len - layout->oobfree[0].offset;
497 }
498
499 static void __iomem *pmecc_get_alpha_to(struct atmel_nand_host *host)
500 {
501         int table_size;
502
503         table_size = host->pmecc_sector_size == 512 ?
504                 PMECC_LOOKUP_TABLE_SIZE_512 : PMECC_LOOKUP_TABLE_SIZE_1024;
505
506         return host->pmecc_rom_base + host->pmecc_lookup_table_offset +
507                         table_size * sizeof(int16_t);
508 }
509
510 static int pmecc_data_alloc(struct atmel_nand_host *host)
511 {
512         const int cap = host->pmecc_corr_cap;
513         int size;
514
515         size = (2 * cap + 1) * sizeof(int16_t);
516         host->pmecc_partial_syn = devm_kzalloc(host->dev, size, GFP_KERNEL);
517         host->pmecc_si = devm_kzalloc(host->dev, size, GFP_KERNEL);
518         host->pmecc_lmu = devm_kzalloc(host->dev,
519                         (cap + 1) * sizeof(int16_t), GFP_KERNEL);
520         host->pmecc_smu = devm_kzalloc(host->dev,
521                         (cap + 2) * size, GFP_KERNEL);
522
523         size = (cap + 1) * sizeof(int);
524         host->pmecc_mu = devm_kzalloc(host->dev, size, GFP_KERNEL);
525         host->pmecc_dmu = devm_kzalloc(host->dev, size, GFP_KERNEL);
526         host->pmecc_delta = devm_kzalloc(host->dev, size, GFP_KERNEL);
527
528         if (!host->pmecc_partial_syn ||
529                 !host->pmecc_si ||
530                 !host->pmecc_lmu ||
531                 !host->pmecc_smu ||
532                 !host->pmecc_mu ||
533                 !host->pmecc_dmu ||
534                 !host->pmecc_delta)
535                 return -ENOMEM;
536
537         return 0;
538 }
539
540 static void pmecc_gen_syndrome(struct mtd_info *mtd, int sector)
541 {
542         struct nand_chip *nand_chip = mtd_to_nand(mtd);
543         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
544         int i;
545         uint32_t value;
546
547         /* Fill odd syndromes */
548         for (i = 0; i < host->pmecc_corr_cap; i++) {
549                 value = pmecc_readl_rem_relaxed(host->ecc, sector, i / 2);
550                 if (i & 1)
551                         value >>= 16;
552                 value &= 0xffff;
553                 host->pmecc_partial_syn[(2 * i) + 1] = (int16_t)value;
554         }
555 }
556
557 static void pmecc_substitute(struct mtd_info *mtd)
558 {
559         struct nand_chip *nand_chip = mtd_to_nand(mtd);
560         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
561         int16_t __iomem *alpha_to = host->pmecc_alpha_to;
562         int16_t __iomem *index_of = host->pmecc_index_of;
563         int16_t *partial_syn = host->pmecc_partial_syn;
564         const int cap = host->pmecc_corr_cap;
565         int16_t *si;
566         int i, j;
567
568         /* si[] is a table that holds the current syndrome value,
569          * an element of that table belongs to the field
570          */
571         si = host->pmecc_si;
572
573         memset(&si[1], 0, sizeof(int16_t) * (2 * cap - 1));
574
575         /* Computation 2t syndromes based on S(x) */
576         /* Odd syndromes */
577         for (i = 1; i < 2 * cap; i += 2) {
578                 for (j = 0; j < host->pmecc_degree; j++) {
579                         if (partial_syn[i] & ((unsigned short)0x1 << j))
580                                 si[i] = readw_relaxed(alpha_to + i * j) ^ si[i];
581                 }
582         }
583         /* Even syndrome = (Odd syndrome) ** 2 */
584         for (i = 2, j = 1; j <= cap; i = ++j << 1) {
585                 if (si[j] == 0) {
586                         si[i] = 0;
587                 } else {
588                         int16_t tmp;
589
590                         tmp = readw_relaxed(index_of + si[j]);
591                         tmp = (tmp * 2) % host->pmecc_cw_len;
592                         si[i] = readw_relaxed(alpha_to + tmp);
593                 }
594         }
595
596         return;
597 }
598
599 static void pmecc_get_sigma(struct mtd_info *mtd)
600 {
601         struct nand_chip *nand_chip = mtd_to_nand(mtd);
602         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
603
604         int16_t *lmu = host->pmecc_lmu;
605         int16_t *si = host->pmecc_si;
606         int *mu = host->pmecc_mu;
607         int *dmu = host->pmecc_dmu;     /* Discrepancy */
608         int *delta = host->pmecc_delta; /* Delta order */
609         int cw_len = host->pmecc_cw_len;
610         const int16_t cap = host->pmecc_corr_cap;
611         const int num = 2 * cap + 1;
612         int16_t __iomem *index_of = host->pmecc_index_of;
613         int16_t __iomem *alpha_to = host->pmecc_alpha_to;
614         int i, j, k;
615         uint32_t dmu_0_count, tmp;
616         int16_t *smu = host->pmecc_smu;
617
618         /* index of largest delta */
619         int ro;
620         int largest;
621         int diff;
622
623         dmu_0_count = 0;
624
625         /* First Row */
626
627         /* Mu */
628         mu[0] = -1;
629
630         memset(smu, 0, sizeof(int16_t) * num);
631         smu[0] = 1;
632
633         /* discrepancy set to 1 */
634         dmu[0] = 1;
635         /* polynom order set to 0 */
636         lmu[0] = 0;
637         delta[0] = (mu[0] * 2 - lmu[0]) >> 1;
638
639         /* Second Row */
640
641         /* Mu */
642         mu[1] = 0;
643         /* Sigma(x) set to 1 */
644         memset(&smu[num], 0, sizeof(int16_t) * num);
645         smu[num] = 1;
646
647         /* discrepancy set to S1 */
648         dmu[1] = si[1];
649
650         /* polynom order set to 0 */
651         lmu[1] = 0;
652
653         delta[1] = (mu[1] * 2 - lmu[1]) >> 1;
654
655         /* Init the Sigma(x) last row */
656         memset(&smu[(cap + 1) * num], 0, sizeof(int16_t) * num);
657
658         for (i = 1; i <= cap; i++) {
659                 mu[i + 1] = i << 1;
660                 /* Begin Computing Sigma (Mu+1) and L(mu) */
661                 /* check if discrepancy is set to 0 */
662                 if (dmu[i] == 0) {
663                         dmu_0_count++;
664
665                         tmp = ((cap - (lmu[i] >> 1) - 1) / 2);
666                         if ((cap - (lmu[i] >> 1) - 1) & 0x1)
667                                 tmp += 2;
668                         else
669                                 tmp += 1;
670
671                         if (dmu_0_count == tmp) {
672                                 for (j = 0; j <= (lmu[i] >> 1) + 1; j++)
673                                         smu[(cap + 1) * num + j] =
674                                                         smu[i * num + j];
675
676                                 lmu[cap + 1] = lmu[i];
677                                 return;
678                         }
679
680                         /* copy polynom */
681                         for (j = 0; j <= lmu[i] >> 1; j++)
682                                 smu[(i + 1) * num + j] = smu[i * num + j];
683
684                         /* copy previous polynom order to the next */
685                         lmu[i + 1] = lmu[i];
686                 } else {
687                         ro = 0;
688                         largest = -1;
689                         /* find largest delta with dmu != 0 */
690                         for (j = 0; j < i; j++) {
691                                 if ((dmu[j]) && (delta[j] > largest)) {
692                                         largest = delta[j];
693                                         ro = j;
694                                 }
695                         }
696
697                         /* compute difference */
698                         diff = (mu[i] - mu[ro]);
699
700                         /* Compute degree of the new smu polynomial */
701                         if ((lmu[i] >> 1) > ((lmu[ro] >> 1) + diff))
702                                 lmu[i + 1] = lmu[i];
703                         else
704                                 lmu[i + 1] = ((lmu[ro] >> 1) + diff) * 2;
705
706                         /* Init smu[i+1] with 0 */
707                         for (k = 0; k < num; k++)
708                                 smu[(i + 1) * num + k] = 0;
709
710                         /* Compute smu[i+1] */
711                         for (k = 0; k <= lmu[ro] >> 1; k++) {
712                                 int16_t a, b, c;
713
714                                 if (!(smu[ro * num + k] && dmu[i]))
715                                         continue;
716                                 a = readw_relaxed(index_of + dmu[i]);
717                                 b = readw_relaxed(index_of + dmu[ro]);
718                                 c = readw_relaxed(index_of + smu[ro * num + k]);
719                                 tmp = a + (cw_len - b) + c;
720                                 a = readw_relaxed(alpha_to + tmp % cw_len);
721                                 smu[(i + 1) * num + (k + diff)] = a;
722                         }
723
724                         for (k = 0; k <= lmu[i] >> 1; k++)
725                                 smu[(i + 1) * num + k] ^= smu[i * num + k];
726                 }
727
728                 /* End Computing Sigma (Mu+1) and L(mu) */
729                 /* In either case compute delta */
730                 delta[i + 1] = (mu[i + 1] * 2 - lmu[i + 1]) >> 1;
731
732                 /* Do not compute discrepancy for the last iteration */
733                 if (i >= cap)
734                         continue;
735
736                 for (k = 0; k <= (lmu[i + 1] >> 1); k++) {
737                         tmp = 2 * (i - 1);
738                         if (k == 0) {
739                                 dmu[i + 1] = si[tmp + 3];
740                         } else if (smu[(i + 1) * num + k] && si[tmp + 3 - k]) {
741                                 int16_t a, b, c;
742                                 a = readw_relaxed(index_of +
743                                                 smu[(i + 1) * num + k]);
744                                 b = si[2 * (i - 1) + 3 - k];
745                                 c = readw_relaxed(index_of + b);
746                                 tmp = a + c;
747                                 tmp %= cw_len;
748                                 dmu[i + 1] = readw_relaxed(alpha_to + tmp) ^
749                                         dmu[i + 1];
750                         }
751                 }
752         }
753
754         return;
755 }
756
757 static int pmecc_err_location(struct mtd_info *mtd)
758 {
759         struct nand_chip *nand_chip = mtd_to_nand(mtd);
760         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
761         unsigned long end_time;
762         const int cap = host->pmecc_corr_cap;
763         const int num = 2 * cap + 1;
764         int sector_size = host->pmecc_sector_size;
765         int err_nbr = 0;        /* number of error */
766         int roots_nbr;          /* number of roots */
767         int i;
768         uint32_t val;
769         int16_t *smu = host->pmecc_smu;
770
771         pmerrloc_writel(host->pmerrloc_base, ELDIS, PMERRLOC_DISABLE);
772
773         for (i = 0; i <= host->pmecc_lmu[cap + 1] >> 1; i++) {
774                 pmerrloc_writel_sigma_relaxed(host->pmerrloc_base, i,
775                                       smu[(cap + 1) * num + i]);
776                 err_nbr++;
777         }
778
779         val = (err_nbr - 1) << 16;
780         if (sector_size == 1024)
781                 val |= 1;
782
783         pmerrloc_writel(host->pmerrloc_base, ELCFG, val);
784         pmerrloc_writel(host->pmerrloc_base, ELEN,
785                         sector_size * 8 + host->pmecc_degree * cap);
786
787         end_time = jiffies + msecs_to_jiffies(PMECC_MAX_TIMEOUT_MS);
788         while (!(pmerrloc_readl_relaxed(host->pmerrloc_base, ELISR)
789                  & PMERRLOC_CALC_DONE)) {
790                 if (unlikely(time_after(jiffies, end_time))) {
791                         dev_err(host->dev, "PMECC: Timeout to calculate error location.\n");
792                         return -1;
793                 }
794                 cpu_relax();
795         }
796
797         roots_nbr = (pmerrloc_readl_relaxed(host->pmerrloc_base, ELISR)
798                 & PMERRLOC_ERR_NUM_MASK) >> 8;
799         /* Number of roots == degree of smu hence <= cap */
800         if (roots_nbr == host->pmecc_lmu[cap + 1] >> 1)
801                 return err_nbr - 1;
802
803         /* Number of roots does not match the degree of smu
804          * unable to correct error */
805         return -1;
806 }
807
808 static void pmecc_correct_data(struct mtd_info *mtd, uint8_t *buf, uint8_t *ecc,
809                 int sector_num, int extra_bytes, int err_nbr)
810 {
811         struct nand_chip *nand_chip = mtd_to_nand(mtd);
812         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
813         int i = 0;
814         int byte_pos, bit_pos, sector_size, pos;
815         uint32_t tmp;
816         uint8_t err_byte;
817
818         sector_size = host->pmecc_sector_size;
819
820         while (err_nbr) {
821                 tmp = pmerrloc_readl_el_relaxed(host->pmerrloc_base, i) - 1;
822                 byte_pos = tmp / 8;
823                 bit_pos  = tmp % 8;
824
825                 if (byte_pos >= (sector_size + extra_bytes))
826                         BUG();  /* should never happen */
827
828                 if (byte_pos < sector_size) {
829                         err_byte = *(buf + byte_pos);
830                         *(buf + byte_pos) ^= (1 << bit_pos);
831
832                         pos = sector_num * host->pmecc_sector_size + byte_pos;
833                         dev_dbg(host->dev, "Bit flip in data area, byte_pos: %d, bit_pos: %d, 0x%02x -> 0x%02x\n",
834                                 pos, bit_pos, err_byte, *(buf + byte_pos));
835                 } else {
836                         /* Bit flip in OOB area */
837                         tmp = sector_num * nand_chip->ecc.bytes
838                                         + (byte_pos - sector_size);
839                         err_byte = ecc[tmp];
840                         ecc[tmp] ^= (1 << bit_pos);
841
842                         pos = tmp + nand_chip->ecc.layout->eccpos[0];
843                         dev_dbg(host->dev, "Bit flip in OOB, oob_byte_pos: %d, bit_pos: %d, 0x%02x -> 0x%02x\n",
844                                 pos, bit_pos, err_byte, ecc[tmp]);
845                 }
846
847                 i++;
848                 err_nbr--;
849         }
850
851         return;
852 }
853
854 static int pmecc_correction(struct mtd_info *mtd, u32 pmecc_stat, uint8_t *buf,
855         u8 *ecc)
856 {
857         struct nand_chip *nand_chip = mtd_to_nand(mtd);
858         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
859         int i, err_nbr;
860         uint8_t *buf_pos;
861         int max_bitflips = 0;
862
863         /* If can correct bitfilps from erased page, do the normal check */
864         if (host->caps->pmecc_correct_erase_page)
865                 goto normal_check;
866
867         for (i = 0; i < nand_chip->ecc.total; i++)
868                 if (ecc[i] != 0xff)
869                         goto normal_check;
870         /* Erased page, return OK */
871         return 0;
872
873 normal_check:
874         for (i = 0; i < nand_chip->ecc.steps; i++) {
875                 err_nbr = 0;
876                 if (pmecc_stat & 0x1) {
877                         buf_pos = buf + i * host->pmecc_sector_size;
878
879                         pmecc_gen_syndrome(mtd, i);
880                         pmecc_substitute(mtd);
881                         pmecc_get_sigma(mtd);
882
883                         err_nbr = pmecc_err_location(mtd);
884                         if (err_nbr == -1) {
885                                 dev_err(host->dev, "PMECC: Too many errors\n");
886                                 mtd->ecc_stats.failed++;
887                                 return -EIO;
888                         } else {
889                                 pmecc_correct_data(mtd, buf_pos, ecc, i,
890                                         nand_chip->ecc.bytes, err_nbr);
891                                 mtd->ecc_stats.corrected += err_nbr;
892                                 max_bitflips = max_t(int, max_bitflips, err_nbr);
893                         }
894                 }
895                 pmecc_stat >>= 1;
896         }
897
898         return max_bitflips;
899 }
900
901 static void pmecc_enable(struct atmel_nand_host *host, int ecc_op)
902 {
903         u32 val;
904
905         if (ecc_op != NAND_ECC_READ && ecc_op != NAND_ECC_WRITE) {
906                 dev_err(host->dev, "atmel_nand: wrong pmecc operation type!");
907                 return;
908         }
909
910         pmecc_writel(host->ecc, CTRL, PMECC_CTRL_RST);
911         pmecc_writel(host->ecc, CTRL, PMECC_CTRL_DISABLE);
912         val = pmecc_readl_relaxed(host->ecc, CFG);
913
914         if (ecc_op == NAND_ECC_READ)
915                 pmecc_writel(host->ecc, CFG, (val & ~PMECC_CFG_WRITE_OP)
916                         | PMECC_CFG_AUTO_ENABLE);
917         else
918                 pmecc_writel(host->ecc, CFG, (val | PMECC_CFG_WRITE_OP)
919                         & ~PMECC_CFG_AUTO_ENABLE);
920
921         pmecc_writel(host->ecc, CTRL, PMECC_CTRL_ENABLE);
922         pmecc_writel(host->ecc, CTRL, PMECC_CTRL_DATA);
923 }
924
925 static int atmel_nand_pmecc_read_page(struct mtd_info *mtd,
926         struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
927 {
928         struct atmel_nand_host *host = nand_get_controller_data(chip);
929         int eccsize = chip->ecc.size * chip->ecc.steps;
930         uint8_t *oob = chip->oob_poi;
931         uint32_t *eccpos = chip->ecc.layout->eccpos;
932         uint32_t stat;
933         unsigned long end_time;
934         int bitflips = 0;
935
936         if (!host->nfc || !host->nfc->use_nfc_sram)
937                 pmecc_enable(host, NAND_ECC_READ);
938
939         chip->read_buf(mtd, buf, eccsize);
940         chip->read_buf(mtd, oob, mtd->oobsize);
941
942         end_time = jiffies + msecs_to_jiffies(PMECC_MAX_TIMEOUT_MS);
943         while ((pmecc_readl_relaxed(host->ecc, SR) & PMECC_SR_BUSY)) {
944                 if (unlikely(time_after(jiffies, end_time))) {
945                         dev_err(host->dev, "PMECC: Timeout to get error status.\n");
946                         return -EIO;
947                 }
948                 cpu_relax();
949         }
950
951         stat = pmecc_readl_relaxed(host->ecc, ISR);
952         if (stat != 0) {
953                 bitflips = pmecc_correction(mtd, stat, buf, &oob[eccpos[0]]);
954                 if (bitflips < 0)
955                         /* uncorrectable errors */
956                         return 0;
957         }
958
959         return bitflips;
960 }
961
962 static int atmel_nand_pmecc_write_page(struct mtd_info *mtd,
963                 struct nand_chip *chip, const uint8_t *buf, int oob_required,
964                 int page)
965 {
966         struct atmel_nand_host *host = nand_get_controller_data(chip);
967         uint32_t *eccpos = chip->ecc.layout->eccpos;
968         int i, j;
969         unsigned long end_time;
970
971         if (!host->nfc || !host->nfc->write_by_sram) {
972                 pmecc_enable(host, NAND_ECC_WRITE);
973                 chip->write_buf(mtd, (u8 *)buf, mtd->writesize);
974         }
975
976         end_time = jiffies + msecs_to_jiffies(PMECC_MAX_TIMEOUT_MS);
977         while ((pmecc_readl_relaxed(host->ecc, SR) & PMECC_SR_BUSY)) {
978                 if (unlikely(time_after(jiffies, end_time))) {
979                         dev_err(host->dev, "PMECC: Timeout to get ECC value.\n");
980                         return -EIO;
981                 }
982                 cpu_relax();
983         }
984
985         for (i = 0; i < chip->ecc.steps; i++) {
986                 for (j = 0; j < chip->ecc.bytes; j++) {
987                         int pos;
988
989                         pos = i * chip->ecc.bytes + j;
990                         chip->oob_poi[eccpos[pos]] =
991                                 pmecc_readb_ecc_relaxed(host->ecc, i, j);
992                 }
993         }
994         chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
995
996         return 0;
997 }
998
999 static void atmel_pmecc_core_init(struct mtd_info *mtd)
1000 {
1001         struct nand_chip *nand_chip = mtd_to_nand(mtd);
1002         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
1003         uint32_t val = 0;
1004         struct nand_ecclayout *ecc_layout;
1005
1006         pmecc_writel(host->ecc, CTRL, PMECC_CTRL_RST);
1007         pmecc_writel(host->ecc, CTRL, PMECC_CTRL_DISABLE);
1008
1009         switch (host->pmecc_corr_cap) {
1010         case 2:
1011                 val = PMECC_CFG_BCH_ERR2;
1012                 break;
1013         case 4:
1014                 val = PMECC_CFG_BCH_ERR4;
1015                 break;
1016         case 8:
1017                 val = PMECC_CFG_BCH_ERR8;
1018                 break;
1019         case 12:
1020                 val = PMECC_CFG_BCH_ERR12;
1021                 break;
1022         case 24:
1023                 val = PMECC_CFG_BCH_ERR24;
1024                 break;
1025         }
1026
1027         if (host->pmecc_sector_size == 512)
1028                 val |= PMECC_CFG_SECTOR512;
1029         else if (host->pmecc_sector_size == 1024)
1030                 val |= PMECC_CFG_SECTOR1024;
1031
1032         switch (nand_chip->ecc.steps) {
1033         case 1:
1034                 val |= PMECC_CFG_PAGE_1SECTOR;
1035                 break;
1036         case 2:
1037                 val |= PMECC_CFG_PAGE_2SECTORS;
1038                 break;
1039         case 4:
1040                 val |= PMECC_CFG_PAGE_4SECTORS;
1041                 break;
1042         case 8:
1043                 val |= PMECC_CFG_PAGE_8SECTORS;
1044                 break;
1045         }
1046
1047         val |= (PMECC_CFG_READ_OP | PMECC_CFG_SPARE_DISABLE
1048                 | PMECC_CFG_AUTO_DISABLE);
1049         pmecc_writel(host->ecc, CFG, val);
1050
1051         ecc_layout = nand_chip->ecc.layout;
1052         pmecc_writel(host->ecc, SAREA, mtd->oobsize - 1);
1053         pmecc_writel(host->ecc, SADDR, ecc_layout->eccpos[0]);
1054         pmecc_writel(host->ecc, EADDR,
1055                         ecc_layout->eccpos[ecc_layout->eccbytes - 1]);
1056         /* See datasheet about PMECC Clock Control Register */
1057         pmecc_writel(host->ecc, CLK, 2);
1058         pmecc_writel(host->ecc, IDR, 0xff);
1059         pmecc_writel(host->ecc, CTRL, PMECC_CTRL_ENABLE);
1060 }
1061
1062 /*
1063  * Get minimum ecc requirements from NAND.
1064  * If pmecc-cap, pmecc-sector-size in DTS are not specified, this function
1065  * will set them according to minimum ecc requirement. Otherwise, use the
1066  * value in DTS file.
1067  * return 0 if success. otherwise return error code.
1068  */
1069 static int pmecc_choose_ecc(struct atmel_nand_host *host,
1070                 int *cap, int *sector_size)
1071 {
1072         /* Get minimum ECC requirements */
1073         if (host->nand_chip.ecc_strength_ds) {
1074                 *cap = host->nand_chip.ecc_strength_ds;
1075                 *sector_size = host->nand_chip.ecc_step_ds;
1076                 dev_info(host->dev, "minimum ECC: %d bits in %d bytes\n",
1077                                 *cap, *sector_size);
1078         } else {
1079                 *cap = 2;
1080                 *sector_size = 512;
1081                 dev_info(host->dev, "can't detect min. ECC, assume 2 bits in 512 bytes\n");
1082         }
1083
1084         /* If device tree doesn't specify, use NAND's minimum ECC parameters */
1085         if (host->pmecc_corr_cap == 0) {
1086                 /* use the most fitable ecc bits (the near bigger one ) */
1087                 if (*cap <= 2)
1088                         host->pmecc_corr_cap = 2;
1089                 else if (*cap <= 4)
1090                         host->pmecc_corr_cap = 4;
1091                 else if (*cap <= 8)
1092                         host->pmecc_corr_cap = 8;
1093                 else if (*cap <= 12)
1094                         host->pmecc_corr_cap = 12;
1095                 else if (*cap <= 24)
1096                         host->pmecc_corr_cap = 24;
1097                 else
1098                         return -EINVAL;
1099         }
1100         if (host->pmecc_sector_size == 0) {
1101                 /* use the most fitable sector size (the near smaller one ) */
1102                 if (*sector_size >= 1024)
1103                         host->pmecc_sector_size = 1024;
1104                 else if (*sector_size >= 512)
1105                         host->pmecc_sector_size = 512;
1106                 else
1107                         return -EINVAL;
1108         }
1109         return 0;
1110 }
1111
1112 static inline int deg(unsigned int poly)
1113 {
1114         /* polynomial degree is the most-significant bit index */
1115         return fls(poly) - 1;
1116 }
1117
1118 static int build_gf_tables(int mm, unsigned int poly,
1119                 int16_t *index_of, int16_t *alpha_to)
1120 {
1121         unsigned int i, x = 1;
1122         const unsigned int k = 1 << deg(poly);
1123         unsigned int nn = (1 << mm) - 1;
1124
1125         /* primitive polynomial must be of degree m */
1126         if (k != (1u << mm))
1127                 return -EINVAL;
1128
1129         for (i = 0; i < nn; i++) {
1130                 alpha_to[i] = x;
1131                 index_of[x] = i;
1132                 if (i && (x == 1))
1133                         /* polynomial is not primitive (a^i=1 with 0<i<2^m-1) */
1134                         return -EINVAL;
1135                 x <<= 1;
1136                 if (x & k)
1137                         x ^= poly;
1138         }
1139         alpha_to[nn] = 1;
1140         index_of[0] = 0;
1141
1142         return 0;
1143 }
1144
1145 static uint16_t *create_lookup_table(struct device *dev, int sector_size)
1146 {
1147         int degree = (sector_size == 512) ?
1148                         PMECC_GF_DIMENSION_13 :
1149                         PMECC_GF_DIMENSION_14;
1150         unsigned int poly = (sector_size == 512) ?
1151                         PMECC_GF_13_PRIMITIVE_POLY :
1152                         PMECC_GF_14_PRIMITIVE_POLY;
1153         int table_size = (sector_size == 512) ?
1154                         PMECC_LOOKUP_TABLE_SIZE_512 :
1155                         PMECC_LOOKUP_TABLE_SIZE_1024;
1156
1157         int16_t *addr = devm_kzalloc(dev, 2 * table_size * sizeof(uint16_t),
1158                         GFP_KERNEL);
1159         if (addr && build_gf_tables(degree, poly, addr, addr + table_size))
1160                 return NULL;
1161
1162         return addr;
1163 }
1164
1165 static int atmel_pmecc_nand_init_params(struct platform_device *pdev,
1166                                          struct atmel_nand_host *host)
1167 {
1168         struct nand_chip *nand_chip = &host->nand_chip;
1169         struct mtd_info *mtd = nand_to_mtd(nand_chip);
1170         struct resource *regs, *regs_pmerr, *regs_rom;
1171         uint16_t *galois_table;
1172         int cap, sector_size, err_no;
1173
1174         err_no = pmecc_choose_ecc(host, &cap, &sector_size);
1175         if (err_no) {
1176                 dev_err(host->dev, "The NAND flash's ECC requirement are not support!");
1177                 return err_no;
1178         }
1179
1180         if (cap > host->pmecc_corr_cap ||
1181                         sector_size != host->pmecc_sector_size)
1182                 dev_info(host->dev, "WARNING: Be Caution! Using different PMECC parameters from Nand ONFI ECC reqirement.\n");
1183
1184         cap = host->pmecc_corr_cap;
1185         sector_size = host->pmecc_sector_size;
1186         host->pmecc_lookup_table_offset = (sector_size == 512) ?
1187                         host->pmecc_lookup_table_offset_512 :
1188                         host->pmecc_lookup_table_offset_1024;
1189
1190         dev_info(host->dev, "Initialize PMECC params, cap: %d, sector: %d\n",
1191                  cap, sector_size);
1192
1193         regs = platform_get_resource(pdev, IORESOURCE_MEM, 1);
1194         if (!regs) {
1195                 dev_warn(host->dev,
1196                         "Can't get I/O resource regs for PMECC controller, rolling back on software ECC\n");
1197                 nand_chip->ecc.mode = NAND_ECC_SOFT;
1198                 return 0;
1199         }
1200
1201         host->ecc = devm_ioremap_resource(&pdev->dev, regs);
1202         if (IS_ERR(host->ecc)) {
1203                 err_no = PTR_ERR(host->ecc);
1204                 goto err;
1205         }
1206
1207         regs_pmerr = platform_get_resource(pdev, IORESOURCE_MEM, 2);
1208         host->pmerrloc_base = devm_ioremap_resource(&pdev->dev, regs_pmerr);
1209         if (IS_ERR(host->pmerrloc_base)) {
1210                 err_no = PTR_ERR(host->pmerrloc_base);
1211                 goto err;
1212         }
1213
1214         if (!host->has_no_lookup_table) {
1215                 regs_rom = platform_get_resource(pdev, IORESOURCE_MEM, 3);
1216                 host->pmecc_rom_base = devm_ioremap_resource(&pdev->dev,
1217                                                                 regs_rom);
1218                 if (IS_ERR(host->pmecc_rom_base)) {
1219                         dev_err(host->dev, "Can not get I/O resource for ROM, will build a lookup table in runtime!\n");
1220                         host->has_no_lookup_table = true;
1221                 }
1222         }
1223
1224         if (host->has_no_lookup_table) {
1225                 /* Build the look-up table in runtime */
1226                 galois_table = create_lookup_table(host->dev, sector_size);
1227                 if (!galois_table) {
1228                         dev_err(host->dev, "Failed to build a lookup table in runtime!\n");
1229                         err_no = -EINVAL;
1230                         goto err;
1231                 }
1232
1233                 host->pmecc_rom_base = (void __iomem *)galois_table;
1234                 host->pmecc_lookup_table_offset = 0;
1235         }
1236
1237         nand_chip->ecc.size = sector_size;
1238
1239         /* set ECC page size and oob layout */
1240         switch (mtd->writesize) {
1241         case 512:
1242         case 1024:
1243         case 2048:
1244         case 4096:
1245         case 8192:
1246                 if (sector_size > mtd->writesize) {
1247                         dev_err(host->dev, "pmecc sector size is bigger than the page size!\n");
1248                         err_no = -EINVAL;
1249                         goto err;
1250                 }
1251
1252                 host->pmecc_degree = (sector_size == 512) ?
1253                         PMECC_GF_DIMENSION_13 : PMECC_GF_DIMENSION_14;
1254                 host->pmecc_cw_len = (1 << host->pmecc_degree) - 1;
1255                 host->pmecc_alpha_to = pmecc_get_alpha_to(host);
1256                 host->pmecc_index_of = host->pmecc_rom_base +
1257                         host->pmecc_lookup_table_offset;
1258
1259                 nand_chip->ecc.strength = cap;
1260                 nand_chip->ecc.bytes = pmecc_get_ecc_bytes(cap, sector_size);
1261                 nand_chip->ecc.steps = mtd->writesize / sector_size;
1262                 nand_chip->ecc.total = nand_chip->ecc.bytes *
1263                         nand_chip->ecc.steps;
1264                 if (nand_chip->ecc.total >
1265                                 mtd->oobsize - PMECC_OOB_RESERVED_BYTES) {
1266                         dev_err(host->dev, "No room for ECC bytes\n");
1267                         err_no = -EINVAL;
1268                         goto err;
1269                 }
1270                 pmecc_config_ecc_layout(&atmel_pmecc_oobinfo,
1271                                         mtd->oobsize,
1272                                         nand_chip->ecc.total);
1273
1274                 nand_chip->ecc.layout = &atmel_pmecc_oobinfo;
1275                 break;
1276         default:
1277                 dev_warn(host->dev,
1278                         "Unsupported page size for PMECC, use Software ECC\n");
1279                 /* page size not handled by HW ECC */
1280                 /* switching back to soft ECC */
1281                 nand_chip->ecc.mode = NAND_ECC_SOFT;
1282                 return 0;
1283         }
1284
1285         /* Allocate data for PMECC computation */
1286         err_no = pmecc_data_alloc(host);
1287         if (err_no) {
1288                 dev_err(host->dev,
1289                                 "Cannot allocate memory for PMECC computation!\n");
1290                 goto err;
1291         }
1292
1293         nand_chip->options |= NAND_NO_SUBPAGE_WRITE;
1294         nand_chip->ecc.read_page = atmel_nand_pmecc_read_page;
1295         nand_chip->ecc.write_page = atmel_nand_pmecc_write_page;
1296
1297         atmel_pmecc_core_init(mtd);
1298
1299         return 0;
1300
1301 err:
1302         return err_no;
1303 }
1304
1305 /*
1306  * Calculate HW ECC
1307  *
1308  * function called after a write
1309  *
1310  * mtd:        MTD block structure
1311  * dat:        raw data (unused)
1312  * ecc_code:   buffer for ECC
1313  */
1314 static int atmel_nand_calculate(struct mtd_info *mtd,
1315                 const u_char *dat, unsigned char *ecc_code)
1316 {
1317         struct nand_chip *nand_chip = mtd_to_nand(mtd);
1318         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
1319         unsigned int ecc_value;
1320
1321         /* get the first 2 ECC bytes */
1322         ecc_value = ecc_readl(host->ecc, PR);
1323
1324         ecc_code[0] = ecc_value & 0xFF;
1325         ecc_code[1] = (ecc_value >> 8) & 0xFF;
1326
1327         /* get the last 2 ECC bytes */
1328         ecc_value = ecc_readl(host->ecc, NPR) & ATMEL_ECC_NPARITY;
1329
1330         ecc_code[2] = ecc_value & 0xFF;
1331         ecc_code[3] = (ecc_value >> 8) & 0xFF;
1332
1333         return 0;
1334 }
1335
1336 /*
1337  * HW ECC read page function
1338  *
1339  * mtd:        mtd info structure
1340  * chip:       nand chip info structure
1341  * buf:        buffer to store read data
1342  * oob_required:    caller expects OOB data read to chip->oob_poi
1343  */
1344 static int atmel_nand_read_page(struct mtd_info *mtd, struct nand_chip *chip,
1345                                 uint8_t *buf, int oob_required, int page)
1346 {
1347         int eccsize = chip->ecc.size;
1348         int eccbytes = chip->ecc.bytes;
1349         uint32_t *eccpos = chip->ecc.layout->eccpos;
1350         uint8_t *p = buf;
1351         uint8_t *oob = chip->oob_poi;
1352         uint8_t *ecc_pos;
1353         int stat;
1354         unsigned int max_bitflips = 0;
1355
1356         /*
1357          * Errata: ALE is incorrectly wired up to the ECC controller
1358          * on the AP7000, so it will include the address cycles in the
1359          * ECC calculation.
1360          *
1361          * Workaround: Reset the parity registers before reading the
1362          * actual data.
1363          */
1364         struct atmel_nand_host *host = nand_get_controller_data(chip);
1365         if (host->board.need_reset_workaround)
1366                 ecc_writel(host->ecc, CR, ATMEL_ECC_RST);
1367
1368         /* read the page */
1369         chip->read_buf(mtd, p, eccsize);
1370
1371         /* move to ECC position if needed */
1372         if (eccpos[0] != 0) {
1373                 /* This only works on large pages
1374                  * because the ECC controller waits for
1375                  * NAND_CMD_RNDOUTSTART after the
1376                  * NAND_CMD_RNDOUT.
1377                  * anyway, for small pages, the eccpos[0] == 0
1378                  */
1379                 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1380                                 mtd->writesize + eccpos[0], -1);
1381         }
1382
1383         /* the ECC controller needs to read the ECC just after the data */
1384         ecc_pos = oob + eccpos[0];
1385         chip->read_buf(mtd, ecc_pos, eccbytes);
1386
1387         /* check if there's an error */
1388         stat = chip->ecc.correct(mtd, p, oob, NULL);
1389
1390         if (stat < 0) {
1391                 mtd->ecc_stats.failed++;
1392         } else {
1393                 mtd->ecc_stats.corrected += stat;
1394                 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1395         }
1396
1397         /* get back to oob start (end of page) */
1398         chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1399
1400         /* read the oob */
1401         chip->read_buf(mtd, oob, mtd->oobsize);
1402
1403         return max_bitflips;
1404 }
1405
1406 /*
1407  * HW ECC Correction
1408  *
1409  * function called after a read
1410  *
1411  * mtd:        MTD block structure
1412  * dat:        raw data read from the chip
1413  * read_ecc:   ECC from the chip (unused)
1414  * isnull:     unused
1415  *
1416  * Detect and correct a 1 bit error for a page
1417  */
1418 static int atmel_nand_correct(struct mtd_info *mtd, u_char *dat,
1419                 u_char *read_ecc, u_char *isnull)
1420 {
1421         struct nand_chip *nand_chip = mtd_to_nand(mtd);
1422         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
1423         unsigned int ecc_status;
1424         unsigned int ecc_word, ecc_bit;
1425
1426         /* get the status from the Status Register */
1427         ecc_status = ecc_readl(host->ecc, SR);
1428
1429         /* if there's no error */
1430         if (likely(!(ecc_status & ATMEL_ECC_RECERR)))
1431                 return 0;
1432
1433         /* get error bit offset (4 bits) */
1434         ecc_bit = ecc_readl(host->ecc, PR) & ATMEL_ECC_BITADDR;
1435         /* get word address (12 bits) */
1436         ecc_word = ecc_readl(host->ecc, PR) & ATMEL_ECC_WORDADDR;
1437         ecc_word >>= 4;
1438
1439         /* if there are multiple errors */
1440         if (ecc_status & ATMEL_ECC_MULERR) {
1441                 /* check if it is a freshly erased block
1442                  * (filled with 0xff) */
1443                 if ((ecc_bit == ATMEL_ECC_BITADDR)
1444                                 && (ecc_word == (ATMEL_ECC_WORDADDR >> 4))) {
1445                         /* the block has just been erased, return OK */
1446                         return 0;
1447                 }
1448                 /* it doesn't seems to be a freshly
1449                  * erased block.
1450                  * We can't correct so many errors */
1451                 dev_dbg(host->dev, "atmel_nand : multiple errors detected."
1452                                 " Unable to correct.\n");
1453                 return -EBADMSG;
1454         }
1455
1456         /* if there's a single bit error : we can correct it */
1457         if (ecc_status & ATMEL_ECC_ECCERR) {
1458                 /* there's nothing much to do here.
1459                  * the bit error is on the ECC itself.
1460                  */
1461                 dev_dbg(host->dev, "atmel_nand : one bit error on ECC code."
1462                                 " Nothing to correct\n");
1463                 return 0;
1464         }
1465
1466         dev_dbg(host->dev, "atmel_nand : one bit error on data."
1467                         " (word offset in the page :"
1468                         " 0x%x bit offset : 0x%x)\n",
1469                         ecc_word, ecc_bit);
1470         /* correct the error */
1471         if (nand_chip->options & NAND_BUSWIDTH_16) {
1472                 /* 16 bits words */
1473                 ((unsigned short *) dat)[ecc_word] ^= (1 << ecc_bit);
1474         } else {
1475                 /* 8 bits words */
1476                 dat[ecc_word] ^= (1 << ecc_bit);
1477         }
1478         dev_dbg(host->dev, "atmel_nand : error corrected\n");
1479         return 1;
1480 }
1481
1482 /*
1483  * Enable HW ECC : unused on most chips
1484  */
1485 static void atmel_nand_hwctl(struct mtd_info *mtd, int mode)
1486 {
1487         struct nand_chip *nand_chip = mtd_to_nand(mtd);
1488         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
1489
1490         if (host->board.need_reset_workaround)
1491                 ecc_writel(host->ecc, CR, ATMEL_ECC_RST);
1492 }
1493
1494 static int atmel_of_init_port(struct atmel_nand_host *host,
1495                               struct device_node *np)
1496 {
1497         u32 val;
1498         u32 offset[2];
1499         int ecc_mode;
1500         struct atmel_nand_data *board = &host->board;
1501         enum of_gpio_flags flags = 0;
1502
1503         host->caps = (struct atmel_nand_caps *)
1504                 of_device_get_match_data(host->dev);
1505
1506         if (of_property_read_u32(np, "atmel,nand-addr-offset", &val) == 0) {
1507                 if (val >= 32) {
1508                         dev_err(host->dev, "invalid addr-offset %u\n", val);
1509                         return -EINVAL;
1510                 }
1511                 board->ale = val;
1512         }
1513
1514         if (of_property_read_u32(np, "atmel,nand-cmd-offset", &val) == 0) {
1515                 if (val >= 32) {
1516                         dev_err(host->dev, "invalid cmd-offset %u\n", val);
1517                         return -EINVAL;
1518                 }
1519                 board->cle = val;
1520         }
1521
1522         ecc_mode = of_get_nand_ecc_mode(np);
1523
1524         board->ecc_mode = ecc_mode < 0 ? NAND_ECC_SOFT : ecc_mode;
1525
1526         board->on_flash_bbt = of_get_nand_on_flash_bbt(np);
1527
1528         board->has_dma = of_property_read_bool(np, "atmel,nand-has-dma");
1529
1530         if (of_get_nand_bus_width(np) == 16)
1531                 board->bus_width_16 = 1;
1532
1533         board->rdy_pin = of_get_gpio_flags(np, 0, &flags);
1534         board->rdy_pin_active_low = (flags == OF_GPIO_ACTIVE_LOW);
1535
1536         board->enable_pin = of_get_gpio(np, 1);
1537         board->det_pin = of_get_gpio(np, 2);
1538
1539         host->has_pmecc = of_property_read_bool(np, "atmel,has-pmecc");
1540
1541         /* load the nfc driver if there is */
1542         of_platform_populate(np, NULL, NULL, host->dev);
1543
1544         if (!(board->ecc_mode == NAND_ECC_HW) || !host->has_pmecc)
1545                 return 0;       /* Not using PMECC */
1546
1547         /* use PMECC, get correction capability, sector size and lookup
1548          * table offset.
1549          * If correction bits and sector size are not specified, then find
1550          * them from NAND ONFI parameters.
1551          */
1552         if (of_property_read_u32(np, "atmel,pmecc-cap", &val) == 0) {
1553                 if ((val != 2) && (val != 4) && (val != 8) && (val != 12) &&
1554                                 (val != 24)) {
1555                         dev_err(host->dev,
1556                                 "Required ECC strength not supported: %u\n",
1557                                 val);
1558                         return -EINVAL;
1559                 }
1560                 host->pmecc_corr_cap = (u8)val;
1561         }
1562
1563         if (of_property_read_u32(np, "atmel,pmecc-sector-size", &val) == 0) {
1564                 if ((val != 512) && (val != 1024)) {
1565                         dev_err(host->dev,
1566                                 "Required ECC sector size not supported: %u\n",
1567                                 val);
1568                         return -EINVAL;
1569                 }
1570                 host->pmecc_sector_size = (u16)val;
1571         }
1572
1573         if (of_property_read_u32_array(np, "atmel,pmecc-lookup-table-offset",
1574                         offset, 2) != 0) {
1575                 dev_err(host->dev, "Cannot get PMECC lookup table offset, will build a lookup table in runtime.\n");
1576                 host->has_no_lookup_table = true;
1577                 /* Will build a lookup table and initialize the offset later */
1578                 return 0;
1579         }
1580         if (!offset[0] && !offset[1]) {
1581                 dev_err(host->dev, "Invalid PMECC lookup table offset\n");
1582                 return -EINVAL;
1583         }
1584         host->pmecc_lookup_table_offset_512 = offset[0];
1585         host->pmecc_lookup_table_offset_1024 = offset[1];
1586
1587         return 0;
1588 }
1589
1590 static int atmel_hw_nand_init_params(struct platform_device *pdev,
1591                                          struct atmel_nand_host *host)
1592 {
1593         struct nand_chip *nand_chip = &host->nand_chip;
1594         struct mtd_info *mtd = nand_to_mtd(nand_chip);
1595         struct resource         *regs;
1596
1597         regs = platform_get_resource(pdev, IORESOURCE_MEM, 1);
1598         if (!regs) {
1599                 dev_err(host->dev,
1600                         "Can't get I/O resource regs, use software ECC\n");
1601                 nand_chip->ecc.mode = NAND_ECC_SOFT;
1602                 return 0;
1603         }
1604
1605         host->ecc = devm_ioremap_resource(&pdev->dev, regs);
1606         if (IS_ERR(host->ecc))
1607                 return PTR_ERR(host->ecc);
1608
1609         /* ECC is calculated for the whole page (1 step) */
1610         nand_chip->ecc.size = mtd->writesize;
1611
1612         /* set ECC page size and oob layout */
1613         switch (mtd->writesize) {
1614         case 512:
1615                 nand_chip->ecc.layout = &atmel_oobinfo_small;
1616                 ecc_writel(host->ecc, MR, ATMEL_ECC_PAGESIZE_528);
1617                 break;
1618         case 1024:
1619                 nand_chip->ecc.layout = &atmel_oobinfo_large;
1620                 ecc_writel(host->ecc, MR, ATMEL_ECC_PAGESIZE_1056);
1621                 break;
1622         case 2048:
1623                 nand_chip->ecc.layout = &atmel_oobinfo_large;
1624                 ecc_writel(host->ecc, MR, ATMEL_ECC_PAGESIZE_2112);
1625                 break;
1626         case 4096:
1627                 nand_chip->ecc.layout = &atmel_oobinfo_large;
1628                 ecc_writel(host->ecc, MR, ATMEL_ECC_PAGESIZE_4224);
1629                 break;
1630         default:
1631                 /* page size not handled by HW ECC */
1632                 /* switching back to soft ECC */
1633                 nand_chip->ecc.mode = NAND_ECC_SOFT;
1634                 return 0;
1635         }
1636
1637         /* set up for HW ECC */
1638         nand_chip->ecc.calculate = atmel_nand_calculate;
1639         nand_chip->ecc.correct = atmel_nand_correct;
1640         nand_chip->ecc.hwctl = atmel_nand_hwctl;
1641         nand_chip->ecc.read_page = atmel_nand_read_page;
1642         nand_chip->ecc.bytes = 4;
1643         nand_chip->ecc.strength = 1;
1644
1645         return 0;
1646 }
1647
1648 static inline u32 nfc_read_status(struct atmel_nand_host *host)
1649 {
1650         u32 err_flags = NFC_SR_DTOE | NFC_SR_UNDEF | NFC_SR_AWB | NFC_SR_ASE;
1651         u32 nfc_status = nfc_readl(host->nfc->hsmc_regs, SR);
1652
1653         if (unlikely(nfc_status & err_flags)) {
1654                 if (nfc_status & NFC_SR_DTOE)
1655                         dev_err(host->dev, "NFC: Waiting Nand R/B Timeout Error\n");
1656                 else if (nfc_status & NFC_SR_UNDEF)
1657                         dev_err(host->dev, "NFC: Access Undefined Area Error\n");
1658                 else if (nfc_status & NFC_SR_AWB)
1659                         dev_err(host->dev, "NFC: Access memory While NFC is busy\n");
1660                 else if (nfc_status & NFC_SR_ASE)
1661                         dev_err(host->dev, "NFC: Access memory Size Error\n");
1662         }
1663
1664         return nfc_status;
1665 }
1666
1667 /* SMC interrupt service routine */
1668 static irqreturn_t hsmc_interrupt(int irq, void *dev_id)
1669 {
1670         struct atmel_nand_host *host = dev_id;
1671         u32 status, mask, pending;
1672         irqreturn_t ret = IRQ_NONE;
1673
1674         status = nfc_read_status(host);
1675         mask = nfc_readl(host->nfc->hsmc_regs, IMR);
1676         pending = status & mask;
1677
1678         if (pending & NFC_SR_XFR_DONE) {
1679                 complete(&host->nfc->comp_xfer_done);
1680                 nfc_writel(host->nfc->hsmc_regs, IDR, NFC_SR_XFR_DONE);
1681                 ret = IRQ_HANDLED;
1682         }
1683         if (pending & host->nfc->caps->rb_mask) {
1684                 complete(&host->nfc->comp_ready);
1685                 nfc_writel(host->nfc->hsmc_regs, IDR, host->nfc->caps->rb_mask);
1686                 ret = IRQ_HANDLED;
1687         }
1688         if (pending & NFC_SR_CMD_DONE) {
1689                 complete(&host->nfc->comp_cmd_done);
1690                 nfc_writel(host->nfc->hsmc_regs, IDR, NFC_SR_CMD_DONE);
1691                 ret = IRQ_HANDLED;
1692         }
1693
1694         return ret;
1695 }
1696
1697 /* NFC(Nand Flash Controller) related functions */
1698 static void nfc_prepare_interrupt(struct atmel_nand_host *host, u32 flag)
1699 {
1700         if (flag & NFC_SR_XFR_DONE)
1701                 init_completion(&host->nfc->comp_xfer_done);
1702
1703         if (flag & host->nfc->caps->rb_mask)
1704                 init_completion(&host->nfc->comp_ready);
1705
1706         if (flag & NFC_SR_CMD_DONE)
1707                 init_completion(&host->nfc->comp_cmd_done);
1708
1709         /* Enable interrupt that need to wait for */
1710         nfc_writel(host->nfc->hsmc_regs, IER, flag);
1711 }
1712
1713 static int nfc_wait_interrupt(struct atmel_nand_host *host, u32 flag)
1714 {
1715         int i, index = 0;
1716         struct completion *comp[3];     /* Support 3 interrupt completion */
1717
1718         if (flag & NFC_SR_XFR_DONE)
1719                 comp[index++] = &host->nfc->comp_xfer_done;
1720
1721         if (flag & host->nfc->caps->rb_mask)
1722                 comp[index++] = &host->nfc->comp_ready;
1723
1724         if (flag & NFC_SR_CMD_DONE)
1725                 comp[index++] = &host->nfc->comp_cmd_done;
1726
1727         if (index == 0) {
1728                 dev_err(host->dev, "Unknown interrupt flag: 0x%08x\n", flag);
1729                 return -EINVAL;
1730         }
1731
1732         for (i = 0; i < index; i++) {
1733                 if (wait_for_completion_timeout(comp[i],
1734                                 msecs_to_jiffies(NFC_TIME_OUT_MS)))
1735                         continue;       /* wait for next completion */
1736                 else
1737                         goto err_timeout;
1738         }
1739
1740         return 0;
1741
1742 err_timeout:
1743         dev_err(host->dev, "Time out to wait for interrupt: 0x%08x\n", flag);
1744         /* Disable the interrupt as it is not handled by interrupt handler */
1745         nfc_writel(host->nfc->hsmc_regs, IDR, flag);
1746         return -ETIMEDOUT;
1747 }
1748
1749 static int nfc_send_command(struct atmel_nand_host *host,
1750         unsigned int cmd, unsigned int addr, unsigned char cycle0)
1751 {
1752         unsigned long timeout;
1753         u32 flag = NFC_SR_CMD_DONE;
1754         flag |= cmd & NFCADDR_CMD_DATAEN ? NFC_SR_XFR_DONE : 0;
1755
1756         dev_dbg(host->dev,
1757                 "nfc_cmd: 0x%08x, addr1234: 0x%08x, cycle0: 0x%02x\n",
1758                 cmd, addr, cycle0);
1759
1760         timeout = jiffies + msecs_to_jiffies(NFC_TIME_OUT_MS);
1761         while (nfc_readl(host->nfc->hsmc_regs, SR) & NFC_SR_BUSY) {
1762                 if (time_after(jiffies, timeout)) {
1763                         dev_err(host->dev,
1764                                 "Time out to wait for NFC ready!\n");
1765                         return -ETIMEDOUT;
1766                 }
1767         }
1768
1769         nfc_prepare_interrupt(host, flag);
1770         nfc_writel(host->nfc->hsmc_regs, CYCLE0, cycle0);
1771         nfc_cmd_addr1234_writel(cmd, addr, host->nfc->base_cmd_regs);
1772         return nfc_wait_interrupt(host, flag);
1773 }
1774
1775 static int nfc_device_ready(struct mtd_info *mtd)
1776 {
1777         u32 status, mask;
1778         struct nand_chip *nand_chip = mtd_to_nand(mtd);
1779         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
1780
1781         status = nfc_read_status(host);
1782         mask = nfc_readl(host->nfc->hsmc_regs, IMR);
1783
1784         /* The mask should be 0. If not we may lost interrupts */
1785         if (unlikely(mask & status))
1786                 dev_err(host->dev, "Lost the interrupt flags: 0x%08x\n",
1787                                 mask & status);
1788
1789         return status & host->nfc->caps->rb_mask;
1790 }
1791
1792 static void nfc_select_chip(struct mtd_info *mtd, int chip)
1793 {
1794         struct nand_chip *nand_chip = mtd_to_nand(mtd);
1795         struct atmel_nand_host *host = nand_get_controller_data(nand_chip);
1796
1797         if (chip == -1)
1798                 nfc_writel(host->nfc->hsmc_regs, CTRL, NFC_CTRL_DISABLE);
1799         else
1800                 nfc_writel(host->nfc->hsmc_regs, CTRL, NFC_CTRL_ENABLE);
1801 }
1802
1803 static int nfc_make_addr(struct mtd_info *mtd, int command, int column,
1804                 int page_addr, unsigned int *addr1234, unsigned int *cycle0)
1805 {
1806         struct nand_chip *chip = mtd_to_nand(mtd);
1807
1808         int acycle = 0;
1809         unsigned char addr_bytes[8];
1810         int index = 0, bit_shift;
1811
1812         BUG_ON(addr1234 == NULL || cycle0 == NULL);
1813
1814         *cycle0 = 0;
1815         *addr1234 = 0;
1816
1817         if (column != -1) {
1818                 if (chip->options & NAND_BUSWIDTH_16 &&
1819                                 !nand_opcode_8bits(command))
1820                         column >>= 1;
1821                 addr_bytes[acycle++] = column & 0xff;
1822                 if (mtd->writesize > 512)
1823                         addr_bytes[acycle++] = (column >> 8) & 0xff;
1824         }
1825
1826         if (page_addr != -1) {
1827                 addr_bytes[acycle++] = page_addr & 0xff;
1828                 addr_bytes[acycle++] = (page_addr >> 8) & 0xff;
1829                 if (chip->chipsize > (128 << 20))
1830                         addr_bytes[acycle++] = (page_addr >> 16) & 0xff;
1831         }
1832
1833         if (acycle > 4)
1834                 *cycle0 = addr_bytes[index++];
1835
1836         for (bit_shift = 0; index < acycle; bit_shift += 8)
1837                 *addr1234 += addr_bytes[index++] << bit_shift;
1838
1839         /* return acycle in cmd register */
1840         return acycle << NFCADDR_CMD_ACYCLE_BIT_POS;
1841 }
1842
1843 static void nfc_nand_command(struct mtd_info *mtd, unsigned int command,
1844                                 int column, int page_addr)
1845 {
1846         struct nand_chip *chip = mtd_to_nand(mtd);
1847         struct atmel_nand_host *host = nand_get_controller_data(chip);
1848         unsigned long timeout;
1849         unsigned int nfc_addr_cmd = 0;
1850
1851         unsigned int cmd1 = command << NFCADDR_CMD_CMD1_BIT_POS;
1852
1853         /* Set default settings: no cmd2, no addr cycle. read from nand */
1854         unsigned int cmd2 = 0;
1855         unsigned int vcmd2 = 0;
1856         int acycle = NFCADDR_CMD_ACYCLE_NONE;
1857         int csid = NFCADDR_CMD_CSID_3;
1858         int dataen = NFCADDR_CMD_DATADIS;
1859         int nfcwr = NFCADDR_CMD_NFCRD;
1860         unsigned int addr1234 = 0;
1861         unsigned int cycle0 = 0;
1862         bool do_addr = true;
1863         host->nfc->data_in_sram = NULL;
1864
1865         dev_dbg(host->dev, "%s: cmd = 0x%02x, col = 0x%08x, page = 0x%08x\n",
1866              __func__, command, column, page_addr);
1867
1868         switch (command) {
1869         case NAND_CMD_RESET:
1870                 nfc_addr_cmd = cmd1 | acycle | csid | dataen | nfcwr;
1871                 nfc_send_command(host, nfc_addr_cmd, addr1234, cycle0);
1872                 udelay(chip->chip_delay);
1873
1874                 nfc_nand_command(mtd, NAND_CMD_STATUS, -1, -1);
1875                 timeout = jiffies + msecs_to_jiffies(NFC_TIME_OUT_MS);
1876                 while (!(chip->read_byte(mtd) & NAND_STATUS_READY)) {
1877                         if (time_after(jiffies, timeout)) {
1878                                 dev_err(host->dev,
1879                                         "Time out to wait status ready!\n");
1880                                 break;
1881                         }
1882                 }
1883                 return;
1884         case NAND_CMD_STATUS:
1885                 do_addr = false;
1886                 break;
1887         case NAND_CMD_PARAM:
1888         case NAND_CMD_READID:
1889                 do_addr = false;
1890                 acycle = NFCADDR_CMD_ACYCLE_1;
1891                 if (column != -1)
1892                         addr1234 = column;
1893                 break;
1894         case NAND_CMD_RNDOUT:
1895                 cmd2 = NAND_CMD_RNDOUTSTART << NFCADDR_CMD_CMD2_BIT_POS;
1896                 vcmd2 = NFCADDR_CMD_VCMD2;
1897                 break;
1898         case NAND_CMD_READ0:
1899         case NAND_CMD_READOOB:
1900                 if (command == NAND_CMD_READOOB) {
1901                         column += mtd->writesize;
1902                         command = NAND_CMD_READ0; /* only READ0 is valid */
1903                         cmd1 = command << NFCADDR_CMD_CMD1_BIT_POS;
1904                 }
1905                 if (host->nfc->use_nfc_sram) {
1906                         /* Enable Data transfer to sram */
1907                         dataen = NFCADDR_CMD_DATAEN;
1908
1909                         /* Need enable PMECC now, since NFC will transfer
1910                          * data in bus after sending nfc read command.
1911                          */
1912                         if (chip->ecc.mode == NAND_ECC_HW && host->has_pmecc)
1913                                 pmecc_enable(host, NAND_ECC_READ);
1914                 }
1915
1916                 cmd2 = NAND_CMD_READSTART << NFCADDR_CMD_CMD2_BIT_POS;
1917                 vcmd2 = NFCADDR_CMD_VCMD2;
1918                 break;
1919         /* For prgramming command, the cmd need set to write enable */
1920         case NAND_CMD_PAGEPROG:
1921         case NAND_CMD_SEQIN:
1922         case NAND_CMD_RNDIN:
1923                 nfcwr = NFCADDR_CMD_NFCWR;
1924                 if (host->nfc->will_write_sram && command == NAND_CMD_SEQIN)
1925                         dataen = NFCADDR_CMD_DATAEN;
1926                 break;
1927         default:
1928                 break;
1929         }
1930
1931         if (do_addr)
1932                 acycle = nfc_make_addr(mtd, command, column, page_addr,
1933                                 &addr1234, &cycle0);
1934
1935         nfc_addr_cmd = cmd1 | cmd2 | vcmd2 | acycle | csid | dataen | nfcwr;
1936         nfc_send_command(host, nfc_addr_cmd, addr1234, cycle0);
1937
1938         /*
1939          * Program and erase have their own busy handlers status, sequential
1940          * in, and deplete1 need no delay.
1941          */
1942         switch (command) {
1943         case NAND_CMD_CACHEDPROG:
1944         case NAND_CMD_PAGEPROG:
1945         case NAND_CMD_ERASE1:
1946         case NAND_CMD_ERASE2:
1947         case NAND_CMD_RNDIN:
1948         case NAND_CMD_STATUS:
1949         case NAND_CMD_RNDOUT:
1950         case NAND_CMD_SEQIN:
1951         case NAND_CMD_READID:
1952                 return;
1953
1954         case NAND_CMD_READ0:
1955                 if (dataen == NFCADDR_CMD_DATAEN) {
1956                         host->nfc->data_in_sram = host->nfc->sram_bank0 +
1957                                 nfc_get_sram_off(host);
1958                         return;
1959                 }
1960                 /* fall through */
1961         default:
1962                 nfc_prepare_interrupt(host, host->nfc->caps->rb_mask);
1963                 nfc_wait_interrupt(host, host->nfc->caps->rb_mask);
1964         }
1965 }
1966
1967 static int nfc_sram_write_page(struct mtd_info *mtd, struct nand_chip *chip,
1968                         uint32_t offset, int data_len, const uint8_t *buf,
1969                         int oob_required, int page, int cached, int raw)
1970 {
1971         int cfg, len;
1972         int status = 0;
1973         struct atmel_nand_host *host = nand_get_controller_data(chip);
1974         void *sram = host->nfc->sram_bank0 + nfc_get_sram_off(host);
1975
1976         /* Subpage write is not supported */
1977         if (offset || (data_len < mtd->writesize))
1978                 return -EINVAL;
1979
1980         len = mtd->writesize;
1981         /* Copy page data to sram that will write to nand via NFC */
1982         if (use_dma) {
1983                 if (atmel_nand_dma_op(mtd, (void *)buf, len, 0) != 0)
1984                         /* Fall back to use cpu copy */
1985                         memcpy(sram, buf, len);
1986         } else {
1987                 memcpy(sram, buf, len);
1988         }
1989
1990         cfg = nfc_readl(host->nfc->hsmc_regs, CFG);
1991         if (unlikely(raw) && oob_required) {
1992                 memcpy(sram + len, chip->oob_poi, mtd->oobsize);
1993                 len += mtd->oobsize;
1994                 nfc_writel(host->nfc->hsmc_regs, CFG, cfg | NFC_CFG_WSPARE);
1995         } else {
1996                 nfc_writel(host->nfc->hsmc_regs, CFG, cfg & ~NFC_CFG_WSPARE);
1997         }
1998
1999         if (chip->ecc.mode == NAND_ECC_HW && host->has_pmecc)
2000                 /*
2001                  * When use NFC sram, need set up PMECC before send
2002                  * NAND_CMD_SEQIN command. Since when the nand command
2003                  * is sent, nfc will do transfer from sram and nand.
2004                  */
2005                 pmecc_enable(host, NAND_ECC_WRITE);
2006
2007         host->nfc->will_write_sram = true;
2008         chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2009         host->nfc->will_write_sram = false;
2010
2011         if (likely(!raw))
2012                 /* Need to write ecc into oob */
2013                 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2014                                               page);
2015
2016         if (status < 0)
2017                 return status;
2018
2019         chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2020         status = chip->waitfunc(mtd, chip);
2021
2022         if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2023                 status = chip->errstat(mtd, chip, FL_WRITING, status, page);
2024
2025         if (status & NAND_STATUS_FAIL)
2026                 return -EIO;
2027
2028         return 0;
2029 }
2030
2031 static int nfc_sram_init(struct mtd_info *mtd)
2032 {
2033         struct nand_chip *chip = mtd_to_nand(mtd);
2034         struct atmel_nand_host *host = nand_get_controller_data(chip);
2035         int res = 0;
2036
2037         /* Initialize the NFC CFG register */
2038         unsigned int cfg_nfc = 0;
2039
2040         /* set page size and oob layout */
2041         switch (mtd->writesize) {
2042         case 512:
2043                 cfg_nfc = NFC_CFG_PAGESIZE_512;
2044                 break;
2045         case 1024:
2046                 cfg_nfc = NFC_CFG_PAGESIZE_1024;
2047                 break;
2048         case 2048:
2049                 cfg_nfc = NFC_CFG_PAGESIZE_2048;
2050                 break;
2051         case 4096:
2052                 cfg_nfc = NFC_CFG_PAGESIZE_4096;
2053                 break;
2054         case 8192:
2055                 cfg_nfc = NFC_CFG_PAGESIZE_8192;
2056                 break;
2057         default:
2058                 dev_err(host->dev, "Unsupported page size for NFC.\n");
2059                 res = -ENXIO;
2060                 return res;
2061         }
2062
2063         /* oob bytes size = (NFCSPARESIZE + 1) * 4
2064          * Max support spare size is 512 bytes. */
2065         cfg_nfc |= (((mtd->oobsize / 4) - 1) << NFC_CFG_NFC_SPARESIZE_BIT_POS
2066                 & NFC_CFG_NFC_SPARESIZE);
2067         /* default set a max timeout */
2068         cfg_nfc |= NFC_CFG_RSPARE |
2069                         NFC_CFG_NFC_DTOCYC | NFC_CFG_NFC_DTOMUL;
2070
2071         nfc_writel(host->nfc->hsmc_regs, CFG, cfg_nfc);
2072
2073         host->nfc->will_write_sram = false;
2074         nfc_set_sram_bank(host, 0);
2075
2076         /* Use Write page with NFC SRAM only for PMECC or ECC NONE. */
2077         if (host->nfc->write_by_sram) {
2078                 if ((chip->ecc.mode == NAND_ECC_HW && host->has_pmecc) ||
2079                                 chip->ecc.mode == NAND_ECC_NONE)
2080                         chip->write_page = nfc_sram_write_page;
2081                 else
2082                         host->nfc->write_by_sram = false;
2083         }
2084
2085         dev_info(host->dev, "Using NFC Sram read %s\n",
2086                         host->nfc->write_by_sram ? "and write" : "");
2087         return 0;
2088 }
2089
2090 static struct platform_driver atmel_nand_nfc_driver;
2091 /*
2092  * Probe for the NAND device.
2093  */
2094 static int atmel_nand_probe(struct platform_device *pdev)
2095 {
2096         struct atmel_nand_host *host;
2097         struct mtd_info *mtd;
2098         struct nand_chip *nand_chip;
2099         struct resource *mem;
2100         int res, irq;
2101
2102         /* Allocate memory for the device structure (and zero it) */
2103         host = devm_kzalloc(&pdev->dev, sizeof(*host), GFP_KERNEL);
2104         if (!host)
2105                 return -ENOMEM;
2106
2107         res = platform_driver_register(&atmel_nand_nfc_driver);
2108         if (res)
2109                 dev_err(&pdev->dev, "atmel_nand: can't register NFC driver\n");
2110
2111         mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2112         host->io_base = devm_ioremap_resource(&pdev->dev, mem);
2113         if (IS_ERR(host->io_base)) {
2114                 res = PTR_ERR(host->io_base);
2115                 goto err_nand_ioremap;
2116         }
2117         host->io_phys = (dma_addr_t)mem->start;
2118
2119         nand_chip = &host->nand_chip;
2120         mtd = nand_to_mtd(nand_chip);
2121         host->dev = &pdev->dev;
2122         if (IS_ENABLED(CONFIG_OF) && pdev->dev.of_node) {
2123                 nand_set_flash_node(nand_chip, pdev->dev.of_node);
2124                 /* Only when CONFIG_OF is enabled of_node can be parsed */
2125                 res = atmel_of_init_port(host, pdev->dev.of_node);
2126                 if (res)
2127                         goto err_nand_ioremap;
2128         } else {
2129                 memcpy(&host->board, dev_get_platdata(&pdev->dev),
2130                        sizeof(struct atmel_nand_data));
2131         }
2132
2133          /* link the private data structures */
2134         nand_set_controller_data(nand_chip, host);
2135         mtd->dev.parent = &pdev->dev;
2136
2137         /* Set address of NAND IO lines */
2138         nand_chip->IO_ADDR_R = host->io_base;
2139         nand_chip->IO_ADDR_W = host->io_base;
2140
2141         if (nand_nfc.is_initialized) {
2142                 /* NFC driver is probed and initialized */
2143                 host->nfc = &nand_nfc;
2144
2145                 nand_chip->select_chip = nfc_select_chip;
2146                 nand_chip->dev_ready = nfc_device_ready;
2147                 nand_chip->cmdfunc = nfc_nand_command;
2148
2149                 /* Initialize the interrupt for NFC */
2150                 irq = platform_get_irq(pdev, 0);
2151                 if (irq < 0) {
2152                         dev_err(host->dev, "Cannot get HSMC irq!\n");
2153                         res = irq;
2154                         goto err_nand_ioremap;
2155                 }
2156
2157                 res = devm_request_irq(&pdev->dev, irq, hsmc_interrupt,
2158                                 0, "hsmc", host);
2159                 if (res) {
2160                         dev_err(&pdev->dev, "Unable to request HSMC irq %d\n",
2161                                 irq);
2162                         goto err_nand_ioremap;
2163                 }
2164         } else {
2165                 res = atmel_nand_set_enable_ready_pins(mtd);
2166                 if (res)
2167                         goto err_nand_ioremap;
2168
2169                 nand_chip->cmd_ctrl = atmel_nand_cmd_ctrl;
2170         }
2171
2172         nand_chip->ecc.mode = host->board.ecc_mode;
2173         nand_chip->chip_delay = 40;             /* 40us command delay time */
2174
2175         if (host->board.bus_width_16)   /* 16-bit bus width */
2176                 nand_chip->options |= NAND_BUSWIDTH_16;
2177
2178         nand_chip->read_buf = atmel_read_buf;
2179         nand_chip->write_buf = atmel_write_buf;
2180
2181         platform_set_drvdata(pdev, host);
2182         atmel_nand_enable(host);
2183
2184         if (gpio_is_valid(host->board.det_pin)) {
2185                 res = devm_gpio_request(&pdev->dev,
2186                                 host->board.det_pin, "nand_det");
2187                 if (res < 0) {
2188                         dev_err(&pdev->dev,
2189                                 "can't request det gpio %d\n",
2190                                 host->board.det_pin);
2191                         goto err_no_card;
2192                 }
2193
2194                 res = gpio_direction_input(host->board.det_pin);
2195                 if (res < 0) {
2196                         dev_err(&pdev->dev,
2197                                 "can't request input direction det gpio %d\n",
2198                                 host->board.det_pin);
2199                         goto err_no_card;
2200                 }
2201
2202                 if (gpio_get_value(host->board.det_pin)) {
2203                         dev_info(&pdev->dev, "No SmartMedia card inserted.\n");
2204                         res = -ENXIO;
2205                         goto err_no_card;
2206                 }
2207         }
2208
2209         if (host->board.on_flash_bbt || on_flash_bbt) {
2210                 dev_info(&pdev->dev, "Use On Flash BBT\n");
2211                 nand_chip->bbt_options |= NAND_BBT_USE_FLASH;
2212         }
2213
2214         if (!host->board.has_dma)
2215                 use_dma = 0;
2216
2217         if (use_dma) {
2218                 dma_cap_mask_t mask;
2219
2220                 dma_cap_zero(mask);
2221                 dma_cap_set(DMA_MEMCPY, mask);
2222                 host->dma_chan = dma_request_channel(mask, NULL, NULL);
2223                 if (!host->dma_chan) {
2224                         dev_err(host->dev, "Failed to request DMA channel\n");
2225                         use_dma = 0;
2226                 }
2227         }
2228         if (use_dma)
2229                 dev_info(host->dev, "Using %s for DMA transfers.\n",
2230                                         dma_chan_name(host->dma_chan));
2231         else
2232                 dev_info(host->dev, "No DMA support for NAND access.\n");
2233
2234         /* first scan to find the device and get the page size */
2235         if (nand_scan_ident(mtd, 1, NULL)) {
2236                 res = -ENXIO;
2237                 goto err_scan_ident;
2238         }
2239
2240         if (nand_chip->ecc.mode == NAND_ECC_HW) {
2241                 if (host->has_pmecc)
2242                         res = atmel_pmecc_nand_init_params(pdev, host);
2243                 else
2244                         res = atmel_hw_nand_init_params(pdev, host);
2245
2246                 if (res != 0)
2247                         goto err_hw_ecc;
2248         }
2249
2250         /* initialize the nfc configuration register */
2251         if (host->nfc && host->nfc->use_nfc_sram) {
2252                 res = nfc_sram_init(mtd);
2253                 if (res) {
2254                         host->nfc->use_nfc_sram = false;
2255                         dev_err(host->dev, "Disable use nfc sram for data transfer.\n");
2256                 }
2257         }
2258
2259         /* second phase scan */
2260         if (nand_scan_tail(mtd)) {
2261                 res = -ENXIO;
2262                 goto err_scan_tail;
2263         }
2264
2265         mtd->name = "atmel_nand";
2266         res = mtd_device_register(mtd, host->board.parts,
2267                                   host->board.num_parts);
2268         if (!res)
2269                 return res;
2270
2271 err_scan_tail:
2272         if (host->has_pmecc && host->nand_chip.ecc.mode == NAND_ECC_HW)
2273                 pmecc_writel(host->ecc, CTRL, PMECC_CTRL_DISABLE);
2274 err_hw_ecc:
2275 err_scan_ident:
2276 err_no_card:
2277         atmel_nand_disable(host);
2278         if (host->dma_chan)
2279                 dma_release_channel(host->dma_chan);
2280 err_nand_ioremap:
2281         return res;
2282 }
2283
2284 /*
2285  * Remove a NAND device.
2286  */
2287 static int atmel_nand_remove(struct platform_device *pdev)
2288 {
2289         struct atmel_nand_host *host = platform_get_drvdata(pdev);
2290         struct mtd_info *mtd = nand_to_mtd(&host->nand_chip);
2291
2292         nand_release(mtd);
2293
2294         atmel_nand_disable(host);
2295
2296         if (host->has_pmecc && host->nand_chip.ecc.mode == NAND_ECC_HW) {
2297                 pmecc_writel(host->ecc, CTRL, PMECC_CTRL_DISABLE);
2298                 pmerrloc_writel(host->pmerrloc_base, ELDIS,
2299                                 PMERRLOC_DISABLE);
2300         }
2301
2302         if (host->dma_chan)
2303                 dma_release_channel(host->dma_chan);
2304
2305         platform_driver_unregister(&atmel_nand_nfc_driver);
2306
2307         return 0;
2308 }
2309
2310 static const struct atmel_nand_caps at91rm9200_caps = {
2311         .pmecc_correct_erase_page = false,
2312 };
2313
2314 static const struct atmel_nand_caps sama5d4_caps = {
2315         .pmecc_correct_erase_page = true,
2316 };
2317
2318 static const struct of_device_id atmel_nand_dt_ids[] = {
2319         { .compatible = "atmel,at91rm9200-nand", .data = &at91rm9200_caps },
2320         { .compatible = "atmel,sama5d4-nand", .data = &sama5d4_caps },
2321         { /* sentinel */ }
2322 };
2323
2324 MODULE_DEVICE_TABLE(of, atmel_nand_dt_ids);
2325
2326 static int atmel_nand_nfc_probe(struct platform_device *pdev)
2327 {
2328         struct atmel_nfc *nfc = &nand_nfc;
2329         struct resource *nfc_cmd_regs, *nfc_hsmc_regs, *nfc_sram;
2330         int ret;
2331
2332         nfc_cmd_regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2333         nfc->base_cmd_regs = devm_ioremap_resource(&pdev->dev, nfc_cmd_regs);
2334         if (IS_ERR(nfc->base_cmd_regs))
2335                 return PTR_ERR(nfc->base_cmd_regs);
2336
2337         nfc_hsmc_regs = platform_get_resource(pdev, IORESOURCE_MEM, 1);
2338         nfc->hsmc_regs = devm_ioremap_resource(&pdev->dev, nfc_hsmc_regs);
2339         if (IS_ERR(nfc->hsmc_regs))
2340                 return PTR_ERR(nfc->hsmc_regs);
2341
2342         nfc_sram = platform_get_resource(pdev, IORESOURCE_MEM, 2);
2343         if (nfc_sram) {
2344                 nfc->sram_bank0 = (void * __force)
2345                                 devm_ioremap_resource(&pdev->dev, nfc_sram);
2346                 if (IS_ERR(nfc->sram_bank0)) {
2347                         dev_warn(&pdev->dev, "Fail to ioremap the NFC sram with error: %ld. So disable NFC sram.\n",
2348                                         PTR_ERR(nfc->sram_bank0));
2349                 } else {
2350                         nfc->use_nfc_sram = true;
2351                         nfc->sram_bank0_phys = (dma_addr_t)nfc_sram->start;
2352
2353                         if (pdev->dev.of_node)
2354                                 nfc->write_by_sram = of_property_read_bool(
2355                                                 pdev->dev.of_node,
2356                                                 "atmel,write-by-sram");
2357                 }
2358         }
2359
2360         nfc->caps = (const struct atmel_nand_nfc_caps *)
2361                 of_device_get_match_data(&pdev->dev);
2362         if (!nfc->caps)
2363                 return -ENODEV;
2364
2365         nfc_writel(nfc->hsmc_regs, IDR, 0xffffffff);
2366         nfc_readl(nfc->hsmc_regs, SR);  /* clear the NFC_SR */
2367
2368         nfc->clk = devm_clk_get(&pdev->dev, NULL);
2369         if (!IS_ERR(nfc->clk)) {
2370                 ret = clk_prepare_enable(nfc->clk);
2371                 if (ret)
2372                         return ret;
2373         } else {
2374                 dev_warn(&pdev->dev, "NFC clock missing, update your Device Tree");
2375         }
2376
2377         nfc->is_initialized = true;
2378         dev_info(&pdev->dev, "NFC is probed.\n");
2379
2380         return 0;
2381 }
2382
2383 static int atmel_nand_nfc_remove(struct platform_device *pdev)
2384 {
2385         struct atmel_nfc *nfc = &nand_nfc;
2386
2387         if (!IS_ERR(nfc->clk))
2388                 clk_disable_unprepare(nfc->clk);
2389
2390         return 0;
2391 }
2392
2393 static const struct atmel_nand_nfc_caps sama5d3_nfc_caps = {
2394         .rb_mask = NFC_SR_RB_EDGE0,
2395 };
2396
2397 static const struct atmel_nand_nfc_caps sama5d4_nfc_caps = {
2398         .rb_mask = NFC_SR_RB_EDGE3,
2399 };
2400
2401 static const struct of_device_id atmel_nand_nfc_match[] = {
2402         { .compatible = "atmel,sama5d3-nfc", .data = &sama5d3_nfc_caps },
2403         { .compatible = "atmel,sama5d4-nfc", .data = &sama5d4_nfc_caps },
2404         { /* sentinel */ }
2405 };
2406 MODULE_DEVICE_TABLE(of, atmel_nand_nfc_match);
2407
2408 static struct platform_driver atmel_nand_nfc_driver = {
2409         .driver = {
2410                 .name = "atmel_nand_nfc",
2411                 .of_match_table = of_match_ptr(atmel_nand_nfc_match),
2412         },
2413         .probe = atmel_nand_nfc_probe,
2414         .remove = atmel_nand_nfc_remove,
2415 };
2416
2417 static struct platform_driver atmel_nand_driver = {
2418         .probe          = atmel_nand_probe,
2419         .remove         = atmel_nand_remove,
2420         .driver         = {
2421                 .name   = "atmel_nand",
2422                 .of_match_table = of_match_ptr(atmel_nand_dt_ids),
2423         },
2424 };
2425
2426 module_platform_driver(atmel_nand_driver);
2427
2428 MODULE_LICENSE("GPL");
2429 MODULE_AUTHOR("Rick Bronson");
2430 MODULE_DESCRIPTION("NAND/SmartMedia driver for AT91 / AVR32");
2431 MODULE_ALIAS("platform:atmel_nand");