mtd: rawnand: Allow selection of ECC byte ordering at runtime
[linux-2.6-microblaze.git] / drivers / mtd / nand / raw / fsmc_nand.c
1 /*
2  * ST Microelectronics
3  * Flexible Static Memory Controller (FSMC)
4  * Driver for NAND portions
5  *
6  * Copyright © 2010 ST Microelectronics
7  * Vipin Kumar <vipin.kumar@st.com>
8  * Ashish Priyadarshi
9  *
10  * Based on drivers/mtd/nand/nomadik_nand.c (removed in v3.8)
11  *  Copyright © 2007 STMicroelectronics Pvt. Ltd.
12  *  Copyright © 2009 Alessandro Rubini
13  *
14  * This file is licensed under the terms of the GNU General Public
15  * License version 2. This program is licensed "as is" without any
16  * warranty of any kind, whether express or implied.
17  */
18
19 #include <linux/clk.h>
20 #include <linux/completion.h>
21 #include <linux/dmaengine.h>
22 #include <linux/dma-direction.h>
23 #include <linux/dma-mapping.h>
24 #include <linux/err.h>
25 #include <linux/init.h>
26 #include <linux/module.h>
27 #include <linux/resource.h>
28 #include <linux/sched.h>
29 #include <linux/types.h>
30 #include <linux/mtd/mtd.h>
31 #include <linux/mtd/rawnand.h>
32 #include <linux/mtd/nand_ecc.h>
33 #include <linux/platform_device.h>
34 #include <linux/of.h>
35 #include <linux/mtd/partitions.h>
36 #include <linux/io.h>
37 #include <linux/slab.h>
38 #include <linux/amba/bus.h>
39 #include <mtd/mtd-abi.h>
40
41 /* fsmc controller registers for NOR flash */
42 #define CTRL                    0x0
43         /* ctrl register definitions */
44         #define BANK_ENABLE             (1 << 0)
45         #define MUXED                   (1 << 1)
46         #define NOR_DEV                 (2 << 2)
47         #define WIDTH_8                 (0 << 4)
48         #define WIDTH_16                (1 << 4)
49         #define RSTPWRDWN               (1 << 6)
50         #define WPROT                   (1 << 7)
51         #define WRT_ENABLE              (1 << 12)
52         #define WAIT_ENB                (1 << 13)
53
54 #define CTRL_TIM                0x4
55         /* ctrl_tim register definitions */
56
57 #define FSMC_NOR_BANK_SZ        0x8
58 #define FSMC_NOR_REG_SIZE       0x40
59
60 #define FSMC_NOR_REG(base, bank, reg)           (base + \
61                                                 FSMC_NOR_BANK_SZ * (bank) + \
62                                                 reg)
63
64 /* fsmc controller registers for NAND flash */
65 #define FSMC_PC                 0x00
66         /* pc register definitions */
67         #define FSMC_RESET              (1 << 0)
68         #define FSMC_WAITON             (1 << 1)
69         #define FSMC_ENABLE             (1 << 2)
70         #define FSMC_DEVTYPE_NAND       (1 << 3)
71         #define FSMC_DEVWID_8           (0 << 4)
72         #define FSMC_DEVWID_16          (1 << 4)
73         #define FSMC_ECCEN              (1 << 6)
74         #define FSMC_ECCPLEN_512        (0 << 7)
75         #define FSMC_ECCPLEN_256        (1 << 7)
76         #define FSMC_TCLR_1             (1)
77         #define FSMC_TCLR_SHIFT         (9)
78         #define FSMC_TCLR_MASK          (0xF)
79         #define FSMC_TAR_1              (1)
80         #define FSMC_TAR_SHIFT          (13)
81         #define FSMC_TAR_MASK           (0xF)
82 #define STS                     0x04
83         /* sts register definitions */
84         #define FSMC_CODE_RDY           (1 << 15)
85 #define COMM                    0x08
86         /* comm register definitions */
87         #define FSMC_TSET_0             0
88         #define FSMC_TSET_SHIFT         0
89         #define FSMC_TSET_MASK          0xFF
90         #define FSMC_TWAIT_6            6
91         #define FSMC_TWAIT_SHIFT        8
92         #define FSMC_TWAIT_MASK         0xFF
93         #define FSMC_THOLD_4            4
94         #define FSMC_THOLD_SHIFT        16
95         #define FSMC_THOLD_MASK         0xFF
96         #define FSMC_THIZ_1             1
97         #define FSMC_THIZ_SHIFT         24
98         #define FSMC_THIZ_MASK          0xFF
99 #define ATTRIB                  0x0C
100 #define IOATA                   0x10
101 #define ECC1                    0x14
102 #define ECC2                    0x18
103 #define ECC3                    0x1C
104 #define FSMC_NAND_BANK_SZ       0x20
105
106 #define FSMC_BUSY_WAIT_TIMEOUT  (1 * HZ)
107
108 struct fsmc_nand_timings {
109         uint8_t tclr;
110         uint8_t tar;
111         uint8_t thiz;
112         uint8_t thold;
113         uint8_t twait;
114         uint8_t tset;
115 };
116
117 enum access_mode {
118         USE_DMA_ACCESS = 1,
119         USE_WORD_ACCESS,
120 };
121
122 /**
123  * struct fsmc_nand_data - structure for FSMC NAND device state
124  *
125  * @pid:                Part ID on the AMBA PrimeCell format
126  * @mtd:                MTD info for a NAND flash.
127  * @nand:               Chip related info for a NAND flash.
128  * @partitions:         Partition info for a NAND Flash.
129  * @nr_partitions:      Total number of partition of a NAND flash.
130  *
131  * @bank:               Bank number for probed device.
132  * @clk:                Clock structure for FSMC.
133  *
134  * @read_dma_chan:      DMA channel for read access
135  * @write_dma_chan:     DMA channel for write access to NAND
136  * @dma_access_complete: Completion structure
137  *
138  * @data_pa:            NAND Physical port for Data.
139  * @data_va:            NAND port for Data.
140  * @cmd_va:             NAND port for Command.
141  * @addr_va:            NAND port for Address.
142  * @regs_va:            Registers base address for a given bank.
143  */
144 struct fsmc_nand_data {
145         u32                     pid;
146         struct nand_chip        nand;
147
148         unsigned int            bank;
149         struct device           *dev;
150         enum access_mode        mode;
151         struct clk              *clk;
152
153         /* DMA related objects */
154         struct dma_chan         *read_dma_chan;
155         struct dma_chan         *write_dma_chan;
156         struct completion       dma_access_complete;
157
158         struct fsmc_nand_timings *dev_timings;
159
160         dma_addr_t              data_pa;
161         void __iomem            *data_va;
162         void __iomem            *cmd_va;
163         void __iomem            *addr_va;
164         void __iomem            *regs_va;
165 };
166
167 static int fsmc_ecc1_ooblayout_ecc(struct mtd_info *mtd, int section,
168                                    struct mtd_oob_region *oobregion)
169 {
170         struct nand_chip *chip = mtd_to_nand(mtd);
171
172         if (section >= chip->ecc.steps)
173                 return -ERANGE;
174
175         oobregion->offset = (section * 16) + 2;
176         oobregion->length = 3;
177
178         return 0;
179 }
180
181 static int fsmc_ecc1_ooblayout_free(struct mtd_info *mtd, int section,
182                                     struct mtd_oob_region *oobregion)
183 {
184         struct nand_chip *chip = mtd_to_nand(mtd);
185
186         if (section >= chip->ecc.steps)
187                 return -ERANGE;
188
189         oobregion->offset = (section * 16) + 8;
190
191         if (section < chip->ecc.steps - 1)
192                 oobregion->length = 8;
193         else
194                 oobregion->length = mtd->oobsize - oobregion->offset;
195
196         return 0;
197 }
198
199 static const struct mtd_ooblayout_ops fsmc_ecc1_ooblayout_ops = {
200         .ecc = fsmc_ecc1_ooblayout_ecc,
201         .free = fsmc_ecc1_ooblayout_free,
202 };
203
204 /*
205  * ECC placement definitions in oobfree type format.
206  * There are 13 bytes of ecc for every 512 byte block and it has to be read
207  * consecutively and immediately after the 512 byte data block for hardware to
208  * generate the error bit offsets in 512 byte data.
209  */
210 static int fsmc_ecc4_ooblayout_ecc(struct mtd_info *mtd, int section,
211                                    struct mtd_oob_region *oobregion)
212 {
213         struct nand_chip *chip = mtd_to_nand(mtd);
214
215         if (section >= chip->ecc.steps)
216                 return -ERANGE;
217
218         oobregion->length = chip->ecc.bytes;
219
220         if (!section && mtd->writesize <= 512)
221                 oobregion->offset = 0;
222         else
223                 oobregion->offset = (section * 16) + 2;
224
225         return 0;
226 }
227
228 static int fsmc_ecc4_ooblayout_free(struct mtd_info *mtd, int section,
229                                     struct mtd_oob_region *oobregion)
230 {
231         struct nand_chip *chip = mtd_to_nand(mtd);
232
233         if (section >= chip->ecc.steps)
234                 return -ERANGE;
235
236         oobregion->offset = (section * 16) + 15;
237
238         if (section < chip->ecc.steps - 1)
239                 oobregion->length = 3;
240         else
241                 oobregion->length = mtd->oobsize - oobregion->offset;
242
243         return 0;
244 }
245
246 static const struct mtd_ooblayout_ops fsmc_ecc4_ooblayout_ops = {
247         .ecc = fsmc_ecc4_ooblayout_ecc,
248         .free = fsmc_ecc4_ooblayout_free,
249 };
250
251 static inline struct fsmc_nand_data *mtd_to_fsmc(struct mtd_info *mtd)
252 {
253         return container_of(mtd_to_nand(mtd), struct fsmc_nand_data, nand);
254 }
255
256 /*
257  * fsmc_nand_setup - FSMC (Flexible Static Memory Controller) init routine
258  *
259  * This routine initializes timing parameters related to NAND memory access in
260  * FSMC registers
261  */
262 static void fsmc_nand_setup(struct fsmc_nand_data *host,
263                             struct fsmc_nand_timings *tims)
264 {
265         uint32_t value = FSMC_DEVTYPE_NAND | FSMC_ENABLE | FSMC_WAITON;
266         uint32_t tclr, tar, thiz, thold, twait, tset;
267
268         tclr = (tims->tclr & FSMC_TCLR_MASK) << FSMC_TCLR_SHIFT;
269         tar = (tims->tar & FSMC_TAR_MASK) << FSMC_TAR_SHIFT;
270         thiz = (tims->thiz & FSMC_THIZ_MASK) << FSMC_THIZ_SHIFT;
271         thold = (tims->thold & FSMC_THOLD_MASK) << FSMC_THOLD_SHIFT;
272         twait = (tims->twait & FSMC_TWAIT_MASK) << FSMC_TWAIT_SHIFT;
273         tset = (tims->tset & FSMC_TSET_MASK) << FSMC_TSET_SHIFT;
274
275         if (host->nand.options & NAND_BUSWIDTH_16)
276                 writel_relaxed(value | FSMC_DEVWID_16,
277                                host->regs_va + FSMC_PC);
278         else
279                 writel_relaxed(value | FSMC_DEVWID_8, host->regs_va + FSMC_PC);
280
281         writel_relaxed(readl(host->regs_va + FSMC_PC) | tclr | tar,
282                        host->regs_va + FSMC_PC);
283         writel_relaxed(thiz | thold | twait | tset, host->regs_va + COMM);
284         writel_relaxed(thiz | thold | twait | tset, host->regs_va + ATTRIB);
285 }
286
287 static int fsmc_calc_timings(struct fsmc_nand_data *host,
288                              const struct nand_sdr_timings *sdrt,
289                              struct fsmc_nand_timings *tims)
290 {
291         unsigned long hclk = clk_get_rate(host->clk);
292         unsigned long hclkn = NSEC_PER_SEC / hclk;
293         uint32_t thiz, thold, twait, tset;
294
295         if (sdrt->tRC_min < 30000)
296                 return -EOPNOTSUPP;
297
298         tims->tar = DIV_ROUND_UP(sdrt->tAR_min / 1000, hclkn) - 1;
299         if (tims->tar > FSMC_TAR_MASK)
300                 tims->tar = FSMC_TAR_MASK;
301         tims->tclr = DIV_ROUND_UP(sdrt->tCLR_min / 1000, hclkn) - 1;
302         if (tims->tclr > FSMC_TCLR_MASK)
303                 tims->tclr = FSMC_TCLR_MASK;
304
305         thiz = sdrt->tCS_min - sdrt->tWP_min;
306         tims->thiz = DIV_ROUND_UP(thiz / 1000, hclkn);
307
308         thold = sdrt->tDH_min;
309         if (thold < sdrt->tCH_min)
310                 thold = sdrt->tCH_min;
311         if (thold < sdrt->tCLH_min)
312                 thold = sdrt->tCLH_min;
313         if (thold < sdrt->tWH_min)
314                 thold = sdrt->tWH_min;
315         if (thold < sdrt->tALH_min)
316                 thold = sdrt->tALH_min;
317         if (thold < sdrt->tREH_min)
318                 thold = sdrt->tREH_min;
319         tims->thold = DIV_ROUND_UP(thold / 1000, hclkn);
320         if (tims->thold == 0)
321                 tims->thold = 1;
322         else if (tims->thold > FSMC_THOLD_MASK)
323                 tims->thold = FSMC_THOLD_MASK;
324
325         twait = max(sdrt->tRP_min, sdrt->tWP_min);
326         tims->twait = DIV_ROUND_UP(twait / 1000, hclkn) - 1;
327         if (tims->twait == 0)
328                 tims->twait = 1;
329         else if (tims->twait > FSMC_TWAIT_MASK)
330                 tims->twait = FSMC_TWAIT_MASK;
331
332         tset = max(sdrt->tCS_min - sdrt->tWP_min,
333                    sdrt->tCEA_max - sdrt->tREA_max);
334         tims->tset = DIV_ROUND_UP(tset / 1000, hclkn) - 1;
335         if (tims->tset == 0)
336                 tims->tset = 1;
337         else if (tims->tset > FSMC_TSET_MASK)
338                 tims->tset = FSMC_TSET_MASK;
339
340         return 0;
341 }
342
343 static int fsmc_setup_data_interface(struct nand_chip *nand, int csline,
344                                      const struct nand_data_interface *conf)
345 {
346         struct fsmc_nand_data *host = nand_get_controller_data(nand);
347         struct fsmc_nand_timings tims;
348         const struct nand_sdr_timings *sdrt;
349         int ret;
350
351         sdrt = nand_get_sdr_timings(conf);
352         if (IS_ERR(sdrt))
353                 return PTR_ERR(sdrt);
354
355         ret = fsmc_calc_timings(host, sdrt, &tims);
356         if (ret)
357                 return ret;
358
359         if (csline == NAND_DATA_IFACE_CHECK_ONLY)
360                 return 0;
361
362         fsmc_nand_setup(host, &tims);
363
364         return 0;
365 }
366
367 /*
368  * fsmc_enable_hwecc - Enables Hardware ECC through FSMC registers
369  */
370 static void fsmc_enable_hwecc(struct nand_chip *chip, int mode)
371 {
372         struct fsmc_nand_data *host = mtd_to_fsmc(nand_to_mtd(chip));
373
374         writel_relaxed(readl(host->regs_va + FSMC_PC) & ~FSMC_ECCPLEN_256,
375                        host->regs_va + FSMC_PC);
376         writel_relaxed(readl(host->regs_va + FSMC_PC) & ~FSMC_ECCEN,
377                        host->regs_va + FSMC_PC);
378         writel_relaxed(readl(host->regs_va + FSMC_PC) | FSMC_ECCEN,
379                        host->regs_va + FSMC_PC);
380 }
381
382 /*
383  * fsmc_read_hwecc_ecc4 - Hardware ECC calculator for ecc4 option supported by
384  * FSMC. ECC is 13 bytes for 512 bytes of data (supports error correction up to
385  * max of 8-bits)
386  */
387 static int fsmc_read_hwecc_ecc4(struct nand_chip *chip, const uint8_t *data,
388                                 uint8_t *ecc)
389 {
390         struct fsmc_nand_data *host = mtd_to_fsmc(nand_to_mtd(chip));
391         uint32_t ecc_tmp;
392         unsigned long deadline = jiffies + FSMC_BUSY_WAIT_TIMEOUT;
393
394         do {
395                 if (readl_relaxed(host->regs_va + STS) & FSMC_CODE_RDY)
396                         break;
397                 else
398                         cond_resched();
399         } while (!time_after_eq(jiffies, deadline));
400
401         if (time_after_eq(jiffies, deadline)) {
402                 dev_err(host->dev, "calculate ecc timed out\n");
403                 return -ETIMEDOUT;
404         }
405
406         ecc_tmp = readl_relaxed(host->regs_va + ECC1);
407         ecc[0] = (uint8_t) (ecc_tmp >> 0);
408         ecc[1] = (uint8_t) (ecc_tmp >> 8);
409         ecc[2] = (uint8_t) (ecc_tmp >> 16);
410         ecc[3] = (uint8_t) (ecc_tmp >> 24);
411
412         ecc_tmp = readl_relaxed(host->regs_va + ECC2);
413         ecc[4] = (uint8_t) (ecc_tmp >> 0);
414         ecc[5] = (uint8_t) (ecc_tmp >> 8);
415         ecc[6] = (uint8_t) (ecc_tmp >> 16);
416         ecc[7] = (uint8_t) (ecc_tmp >> 24);
417
418         ecc_tmp = readl_relaxed(host->regs_va + ECC3);
419         ecc[8] = (uint8_t) (ecc_tmp >> 0);
420         ecc[9] = (uint8_t) (ecc_tmp >> 8);
421         ecc[10] = (uint8_t) (ecc_tmp >> 16);
422         ecc[11] = (uint8_t) (ecc_tmp >> 24);
423
424         ecc_tmp = readl_relaxed(host->regs_va + STS);
425         ecc[12] = (uint8_t) (ecc_tmp >> 16);
426
427         return 0;
428 }
429
430 /*
431  * fsmc_read_hwecc_ecc1 - Hardware ECC calculator for ecc1 option supported by
432  * FSMC. ECC is 3 bytes for 512 bytes of data (supports error correction up to
433  * max of 1-bit)
434  */
435 static int fsmc_read_hwecc_ecc1(struct nand_chip *chip, const uint8_t *data,
436                                 uint8_t *ecc)
437 {
438         struct fsmc_nand_data *host = mtd_to_fsmc(nand_to_mtd(chip));
439         uint32_t ecc_tmp;
440
441         ecc_tmp = readl_relaxed(host->regs_va + ECC1);
442         ecc[0] = (uint8_t) (ecc_tmp >> 0);
443         ecc[1] = (uint8_t) (ecc_tmp >> 8);
444         ecc[2] = (uint8_t) (ecc_tmp >> 16);
445
446         return 0;
447 }
448
449 /* Count the number of 0's in buff upto a max of max_bits */
450 static int count_written_bits(uint8_t *buff, int size, int max_bits)
451 {
452         int k, written_bits = 0;
453
454         for (k = 0; k < size; k++) {
455                 written_bits += hweight8(~buff[k]);
456                 if (written_bits > max_bits)
457                         break;
458         }
459
460         return written_bits;
461 }
462
463 static void dma_complete(void *param)
464 {
465         struct fsmc_nand_data *host = param;
466
467         complete(&host->dma_access_complete);
468 }
469
470 static int dma_xfer(struct fsmc_nand_data *host, void *buffer, int len,
471                 enum dma_data_direction direction)
472 {
473         struct dma_chan *chan;
474         struct dma_device *dma_dev;
475         struct dma_async_tx_descriptor *tx;
476         dma_addr_t dma_dst, dma_src, dma_addr;
477         dma_cookie_t cookie;
478         unsigned long flags = DMA_CTRL_ACK | DMA_PREP_INTERRUPT;
479         int ret;
480         unsigned long time_left;
481
482         if (direction == DMA_TO_DEVICE)
483                 chan = host->write_dma_chan;
484         else if (direction == DMA_FROM_DEVICE)
485                 chan = host->read_dma_chan;
486         else
487                 return -EINVAL;
488
489         dma_dev = chan->device;
490         dma_addr = dma_map_single(dma_dev->dev, buffer, len, direction);
491
492         if (direction == DMA_TO_DEVICE) {
493                 dma_src = dma_addr;
494                 dma_dst = host->data_pa;
495         } else {
496                 dma_src = host->data_pa;
497                 dma_dst = dma_addr;
498         }
499
500         tx = dma_dev->device_prep_dma_memcpy(chan, dma_dst, dma_src,
501                         len, flags);
502         if (!tx) {
503                 dev_err(host->dev, "device_prep_dma_memcpy error\n");
504                 ret = -EIO;
505                 goto unmap_dma;
506         }
507
508         tx->callback = dma_complete;
509         tx->callback_param = host;
510         cookie = tx->tx_submit(tx);
511
512         ret = dma_submit_error(cookie);
513         if (ret) {
514                 dev_err(host->dev, "dma_submit_error %d\n", cookie);
515                 goto unmap_dma;
516         }
517
518         dma_async_issue_pending(chan);
519
520         time_left =
521         wait_for_completion_timeout(&host->dma_access_complete,
522                                 msecs_to_jiffies(3000));
523         if (time_left == 0) {
524                 dmaengine_terminate_all(chan);
525                 dev_err(host->dev, "wait_for_completion_timeout\n");
526                 ret = -ETIMEDOUT;
527                 goto unmap_dma;
528         }
529
530         ret = 0;
531
532 unmap_dma:
533         dma_unmap_single(dma_dev->dev, dma_addr, len, direction);
534
535         return ret;
536 }
537
538 /*
539  * fsmc_write_buf - write buffer to chip
540  * @mtd:        MTD device structure
541  * @buf:        data buffer
542  * @len:        number of bytes to write
543  */
544 static void fsmc_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
545 {
546         struct fsmc_nand_data *host  = mtd_to_fsmc(mtd);
547         int i;
548
549         if (IS_ALIGNED((uintptr_t)buf, sizeof(uint32_t)) &&
550                         IS_ALIGNED(len, sizeof(uint32_t))) {
551                 uint32_t *p = (uint32_t *)buf;
552                 len = len >> 2;
553                 for (i = 0; i < len; i++)
554                         writel_relaxed(p[i], host->data_va);
555         } else {
556                 for (i = 0; i < len; i++)
557                         writeb_relaxed(buf[i], host->data_va);
558         }
559 }
560
561 /*
562  * fsmc_read_buf - read chip data into buffer
563  * @mtd:        MTD device structure
564  * @buf:        buffer to store date
565  * @len:        number of bytes to read
566  */
567 static void fsmc_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
568 {
569         struct fsmc_nand_data *host  = mtd_to_fsmc(mtd);
570         int i;
571
572         if (IS_ALIGNED((uintptr_t)buf, sizeof(uint32_t)) &&
573                         IS_ALIGNED(len, sizeof(uint32_t))) {
574                 uint32_t *p = (uint32_t *)buf;
575                 len = len >> 2;
576                 for (i = 0; i < len; i++)
577                         p[i] = readl_relaxed(host->data_va);
578         } else {
579                 for (i = 0; i < len; i++)
580                         buf[i] = readb_relaxed(host->data_va);
581         }
582 }
583
584 /*
585  * fsmc_read_buf_dma - read chip data into buffer
586  * @mtd:        MTD device structure
587  * @buf:        buffer to store date
588  * @len:        number of bytes to read
589  */
590 static void fsmc_read_buf_dma(struct mtd_info *mtd, uint8_t *buf, int len)
591 {
592         struct fsmc_nand_data *host  = mtd_to_fsmc(mtd);
593
594         dma_xfer(host, buf, len, DMA_FROM_DEVICE);
595 }
596
597 /*
598  * fsmc_write_buf_dma - write buffer to chip
599  * @mtd:        MTD device structure
600  * @buf:        data buffer
601  * @len:        number of bytes to write
602  */
603 static void fsmc_write_buf_dma(struct mtd_info *mtd, const uint8_t *buf,
604                 int len)
605 {
606         struct fsmc_nand_data *host = mtd_to_fsmc(mtd);
607
608         dma_xfer(host, (void *)buf, len, DMA_TO_DEVICE);
609 }
610
611 /* fsmc_select_chip - assert or deassert nCE */
612 static void fsmc_select_chip(struct nand_chip *chip, int chipnr)
613 {
614         struct fsmc_nand_data *host = mtd_to_fsmc(nand_to_mtd(chip));
615         u32 pc;
616
617         /* Support only one CS */
618         if (chipnr > 0)
619                 return;
620
621         pc = readl(host->regs_va + FSMC_PC);
622         if (chipnr < 0)
623                 writel_relaxed(pc & ~FSMC_ENABLE, host->regs_va + FSMC_PC);
624         else
625                 writel_relaxed(pc | FSMC_ENABLE, host->regs_va + FSMC_PC);
626
627         /* nCE line must be asserted before starting any operation */
628         mb();
629 }
630
631 /*
632  * fsmc_exec_op - hook called by the core to execute NAND operations
633  *
634  * This controller is simple enough and thus does not need to use the parser
635  * provided by the core, instead, handle every situation here.
636  */
637 static int fsmc_exec_op(struct nand_chip *chip, const struct nand_operation *op,
638                         bool check_only)
639 {
640         struct mtd_info *mtd = nand_to_mtd(chip);
641         struct fsmc_nand_data *host = mtd_to_fsmc(mtd);
642         const struct nand_op_instr *instr = NULL;
643         int ret = 0;
644         unsigned int op_id;
645         int i;
646
647         pr_debug("Executing operation [%d instructions]:\n", op->ninstrs);
648         for (op_id = 0; op_id < op->ninstrs; op_id++) {
649                 instr = &op->instrs[op_id];
650
651                 switch (instr->type) {
652                 case NAND_OP_CMD_INSTR:
653                         pr_debug("  ->CMD      [0x%02x]\n",
654                                  instr->ctx.cmd.opcode);
655
656                         writeb_relaxed(instr->ctx.cmd.opcode, host->cmd_va);
657                         break;
658
659                 case NAND_OP_ADDR_INSTR:
660                         pr_debug("  ->ADDR     [%d cyc]",
661                                  instr->ctx.addr.naddrs);
662
663                         for (i = 0; i < instr->ctx.addr.naddrs; i++)
664                                 writeb_relaxed(instr->ctx.addr.addrs[i],
665                                                host->addr_va);
666                         break;
667
668                 case NAND_OP_DATA_IN_INSTR:
669                         pr_debug("  ->DATA_IN  [%d B%s]\n", instr->ctx.data.len,
670                                  instr->ctx.data.force_8bit ?
671                                  ", force 8-bit" : "");
672
673                         if (host->mode == USE_DMA_ACCESS)
674                                 fsmc_read_buf_dma(mtd, instr->ctx.data.buf.in,
675                                                   instr->ctx.data.len);
676                         else
677                                 fsmc_read_buf(mtd, instr->ctx.data.buf.in,
678                                               instr->ctx.data.len);
679                         break;
680
681                 case NAND_OP_DATA_OUT_INSTR:
682                         pr_debug("  ->DATA_OUT [%d B%s]\n", instr->ctx.data.len,
683                                  instr->ctx.data.force_8bit ?
684                                  ", force 8-bit" : "");
685
686                         if (host->mode == USE_DMA_ACCESS)
687                                 fsmc_write_buf_dma(mtd, instr->ctx.data.buf.out,
688                                                    instr->ctx.data.len);
689                         else
690                                 fsmc_write_buf(mtd, instr->ctx.data.buf.out,
691                                                instr->ctx.data.len);
692                         break;
693
694                 case NAND_OP_WAITRDY_INSTR:
695                         pr_debug("  ->WAITRDY  [max %d ms]\n",
696                                  instr->ctx.waitrdy.timeout_ms);
697
698                         ret = nand_soft_waitrdy(chip,
699                                                 instr->ctx.waitrdy.timeout_ms);
700                         break;
701                 }
702         }
703
704         return ret;
705 }
706
707 /*
708  * fsmc_read_page_hwecc
709  * @chip:       nand chip info structure
710  * @buf:        buffer to store read data
711  * @oob_required:       caller expects OOB data read to chip->oob_poi
712  * @page:       page number to read
713  *
714  * This routine is needed for fsmc version 8 as reading from NAND chip has to be
715  * performed in a strict sequence as follows:
716  * data(512 byte) -> ecc(13 byte)
717  * After this read, fsmc hardware generates and reports error data bits(up to a
718  * max of 8 bits)
719  */
720 static int fsmc_read_page_hwecc(struct nand_chip *chip, uint8_t *buf,
721                                 int oob_required, int page)
722 {
723         struct mtd_info *mtd = nand_to_mtd(chip);
724         int i, j, s, stat, eccsize = chip->ecc.size;
725         int eccbytes = chip->ecc.bytes;
726         int eccsteps = chip->ecc.steps;
727         uint8_t *p = buf;
728         uint8_t *ecc_calc = chip->ecc.calc_buf;
729         uint8_t *ecc_code = chip->ecc.code_buf;
730         int off, len, group = 0;
731         /*
732          * ecc_oob is intentionally taken as uint16_t. In 16bit devices, we
733          * end up reading 14 bytes (7 words) from oob. The local array is
734          * to maintain word alignment
735          */
736         uint16_t ecc_oob[7];
737         uint8_t *oob = (uint8_t *)&ecc_oob[0];
738         unsigned int max_bitflips = 0;
739
740         for (i = 0, s = 0; s < eccsteps; s++, i += eccbytes, p += eccsize) {
741                 nand_read_page_op(chip, page, s * eccsize, NULL, 0);
742                 chip->ecc.hwctl(chip, NAND_ECC_READ);
743                 nand_read_data_op(chip, p, eccsize, false);
744
745                 for (j = 0; j < eccbytes;) {
746                         struct mtd_oob_region oobregion;
747                         int ret;
748
749                         ret = mtd_ooblayout_ecc(mtd, group++, &oobregion);
750                         if (ret)
751                                 return ret;
752
753                         off = oobregion.offset;
754                         len = oobregion.length;
755
756                         /*
757                          * length is intentionally kept a higher multiple of 2
758                          * to read at least 13 bytes even in case of 16 bit NAND
759                          * devices
760                          */
761                         if (chip->options & NAND_BUSWIDTH_16)
762                                 len = roundup(len, 2);
763
764                         nand_read_oob_op(chip, page, off, oob + j, len);
765                         j += len;
766                 }
767
768                 memcpy(&ecc_code[i], oob, chip->ecc.bytes);
769                 chip->ecc.calculate(chip, p, &ecc_calc[i]);
770
771                 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
772                 if (stat < 0) {
773                         mtd->ecc_stats.failed++;
774                 } else {
775                         mtd->ecc_stats.corrected += stat;
776                         max_bitflips = max_t(unsigned int, max_bitflips, stat);
777                 }
778         }
779
780         return max_bitflips;
781 }
782
783 /*
784  * fsmc_bch8_correct_data
785  * @mtd:        mtd info structure
786  * @dat:        buffer of read data
787  * @read_ecc:   ecc read from device spare area
788  * @calc_ecc:   ecc calculated from read data
789  *
790  * calc_ecc is a 104 bit information containing maximum of 8 error
791  * offset informations of 13 bits each in 512 bytes of read data.
792  */
793 static int fsmc_bch8_correct_data(struct nand_chip *chip, uint8_t *dat,
794                                   uint8_t *read_ecc, uint8_t *calc_ecc)
795 {
796         struct fsmc_nand_data *host = mtd_to_fsmc(nand_to_mtd(chip));
797         uint32_t err_idx[8];
798         uint32_t num_err, i;
799         uint32_t ecc1, ecc2, ecc3, ecc4;
800
801         num_err = (readl_relaxed(host->regs_va + STS) >> 10) & 0xF;
802
803         /* no bit flipping */
804         if (likely(num_err == 0))
805                 return 0;
806
807         /* too many errors */
808         if (unlikely(num_err > 8)) {
809                 /*
810                  * This is a temporary erase check. A newly erased page read
811                  * would result in an ecc error because the oob data is also
812                  * erased to FF and the calculated ecc for an FF data is not
813                  * FF..FF.
814                  * This is a workaround to skip performing correction in case
815                  * data is FF..FF
816                  *
817                  * Logic:
818                  * For every page, each bit written as 0 is counted until these
819                  * number of bits are greater than 8 (the maximum correction
820                  * capability of FSMC for each 512 + 13 bytes)
821                  */
822
823                 int bits_ecc = count_written_bits(read_ecc, chip->ecc.bytes, 8);
824                 int bits_data = count_written_bits(dat, chip->ecc.size, 8);
825
826                 if ((bits_ecc + bits_data) <= 8) {
827                         if (bits_data)
828                                 memset(dat, 0xff, chip->ecc.size);
829                         return bits_data;
830                 }
831
832                 return -EBADMSG;
833         }
834
835         /*
836          * ------------------- calc_ecc[] bit wise -----------|--13 bits--|
837          * |---idx[7]--|--.....-----|---idx[2]--||---idx[1]--||---idx[0]--|
838          *
839          * calc_ecc is a 104 bit information containing maximum of 8 error
840          * offset informations of 13 bits each. calc_ecc is copied into a
841          * uint64_t array and error offset indexes are populated in err_idx
842          * array
843          */
844         ecc1 = readl_relaxed(host->regs_va + ECC1);
845         ecc2 = readl_relaxed(host->regs_va + ECC2);
846         ecc3 = readl_relaxed(host->regs_va + ECC3);
847         ecc4 = readl_relaxed(host->regs_va + STS);
848
849         err_idx[0] = (ecc1 >> 0) & 0x1FFF;
850         err_idx[1] = (ecc1 >> 13) & 0x1FFF;
851         err_idx[2] = (((ecc2 >> 0) & 0x7F) << 6) | ((ecc1 >> 26) & 0x3F);
852         err_idx[3] = (ecc2 >> 7) & 0x1FFF;
853         err_idx[4] = (((ecc3 >> 0) & 0x1) << 12) | ((ecc2 >> 20) & 0xFFF);
854         err_idx[5] = (ecc3 >> 1) & 0x1FFF;
855         err_idx[6] = (ecc3 >> 14) & 0x1FFF;
856         err_idx[7] = (((ecc4 >> 16) & 0xFF) << 5) | ((ecc3 >> 27) & 0x1F);
857
858         i = 0;
859         while (num_err--) {
860                 change_bit(0, (unsigned long *)&err_idx[i]);
861                 change_bit(1, (unsigned long *)&err_idx[i]);
862
863                 if (err_idx[i] < chip->ecc.size * 8) {
864                         change_bit(err_idx[i], (unsigned long *)dat);
865                         i++;
866                 }
867         }
868         return i;
869 }
870
871 static bool filter(struct dma_chan *chan, void *slave)
872 {
873         chan->private = slave;
874         return true;
875 }
876
877 static int fsmc_nand_probe_config_dt(struct platform_device *pdev,
878                                      struct fsmc_nand_data *host,
879                                      struct nand_chip *nand)
880 {
881         struct device_node *np = pdev->dev.of_node;
882         u32 val;
883         int ret;
884
885         nand->options = 0;
886
887         if (!of_property_read_u32(np, "bank-width", &val)) {
888                 if (val == 2) {
889                         nand->options |= NAND_BUSWIDTH_16;
890                 } else if (val != 1) {
891                         dev_err(&pdev->dev, "invalid bank-width %u\n", val);
892                         return -EINVAL;
893                 }
894         }
895
896         if (of_get_property(np, "nand-skip-bbtscan", NULL))
897                 nand->options |= NAND_SKIP_BBTSCAN;
898
899         host->dev_timings = devm_kzalloc(&pdev->dev,
900                                 sizeof(*host->dev_timings), GFP_KERNEL);
901         if (!host->dev_timings)
902                 return -ENOMEM;
903         ret = of_property_read_u8_array(np, "timings", (u8 *)host->dev_timings,
904                                                 sizeof(*host->dev_timings));
905         if (ret)
906                 host->dev_timings = NULL;
907
908         /* Set default NAND bank to 0 */
909         host->bank = 0;
910         if (!of_property_read_u32(np, "bank", &val)) {
911                 if (val > 3) {
912                         dev_err(&pdev->dev, "invalid bank %u\n", val);
913                         return -EINVAL;
914                 }
915                 host->bank = val;
916         }
917         return 0;
918 }
919
920 static int fsmc_nand_attach_chip(struct nand_chip *nand)
921 {
922         struct mtd_info *mtd = nand_to_mtd(nand);
923         struct fsmc_nand_data *host = mtd_to_fsmc(mtd);
924
925         if (AMBA_REV_BITS(host->pid) >= 8) {
926                 switch (mtd->oobsize) {
927                 case 16:
928                 case 64:
929                 case 128:
930                 case 224:
931                 case 256:
932                         break;
933                 default:
934                         dev_warn(host->dev,
935                                  "No oob scheme defined for oobsize %d\n",
936                                  mtd->oobsize);
937                         return -EINVAL;
938                 }
939
940                 mtd_set_ooblayout(mtd, &fsmc_ecc4_ooblayout_ops);
941
942                 return 0;
943         }
944
945         switch (nand->ecc.mode) {
946         case NAND_ECC_HW:
947                 dev_info(host->dev, "Using 1-bit HW ECC scheme\n");
948                 nand->ecc.calculate = fsmc_read_hwecc_ecc1;
949                 nand->ecc.correct = nand_correct_data;
950                 nand->ecc.bytes = 3;
951                 nand->ecc.strength = 1;
952                 nand->ecc.options |= NAND_ECC_SOFT_HAMMING_SM_ORDER;
953                 break;
954
955         case NAND_ECC_SOFT:
956                 if (nand->ecc.algo == NAND_ECC_BCH) {
957                         dev_info(host->dev,
958                                  "Using 4-bit SW BCH ECC scheme\n");
959                         break;
960                 }
961
962         case NAND_ECC_ON_DIE:
963                 break;
964
965         default:
966                 dev_err(host->dev, "Unsupported ECC mode!\n");
967                 return -ENOTSUPP;
968         }
969
970         /*
971          * Don't set layout for BCH4 SW ECC. This will be
972          * generated later in nand_bch_init() later.
973          */
974         if (nand->ecc.mode == NAND_ECC_HW) {
975                 switch (mtd->oobsize) {
976                 case 16:
977                 case 64:
978                 case 128:
979                         mtd_set_ooblayout(mtd,
980                                           &fsmc_ecc1_ooblayout_ops);
981                         break;
982                 default:
983                         dev_warn(host->dev,
984                                  "No oob scheme defined for oobsize %d\n",
985                                  mtd->oobsize);
986                         return -EINVAL;
987                 }
988         }
989
990         return 0;
991 }
992
993 static const struct nand_controller_ops fsmc_nand_controller_ops = {
994         .attach_chip = fsmc_nand_attach_chip,
995 };
996
997 /*
998  * fsmc_nand_probe - Probe function
999  * @pdev:       platform device structure
1000  */
1001 static int __init fsmc_nand_probe(struct platform_device *pdev)
1002 {
1003         struct fsmc_nand_data *host;
1004         struct mtd_info *mtd;
1005         struct nand_chip *nand;
1006         struct resource *res;
1007         void __iomem *base;
1008         dma_cap_mask_t mask;
1009         int ret = 0;
1010         u32 pid;
1011         int i;
1012
1013         /* Allocate memory for the device structure (and zero it) */
1014         host = devm_kzalloc(&pdev->dev, sizeof(*host), GFP_KERNEL);
1015         if (!host)
1016                 return -ENOMEM;
1017
1018         nand = &host->nand;
1019
1020         ret = fsmc_nand_probe_config_dt(pdev, host, nand);
1021         if (ret)
1022                 return ret;
1023
1024         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "nand_data");
1025         host->data_va = devm_ioremap_resource(&pdev->dev, res);
1026         if (IS_ERR(host->data_va))
1027                 return PTR_ERR(host->data_va);
1028
1029         host->data_pa = (dma_addr_t)res->start;
1030
1031         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "nand_addr");
1032         host->addr_va = devm_ioremap_resource(&pdev->dev, res);
1033         if (IS_ERR(host->addr_va))
1034                 return PTR_ERR(host->addr_va);
1035
1036         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "nand_cmd");
1037         host->cmd_va = devm_ioremap_resource(&pdev->dev, res);
1038         if (IS_ERR(host->cmd_va))
1039                 return PTR_ERR(host->cmd_va);
1040
1041         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "fsmc_regs");
1042         base = devm_ioremap_resource(&pdev->dev, res);
1043         if (IS_ERR(base))
1044                 return PTR_ERR(base);
1045
1046         host->regs_va = base + FSMC_NOR_REG_SIZE +
1047                 (host->bank * FSMC_NAND_BANK_SZ);
1048
1049         host->clk = devm_clk_get(&pdev->dev, NULL);
1050         if (IS_ERR(host->clk)) {
1051                 dev_err(&pdev->dev, "failed to fetch block clock\n");
1052                 return PTR_ERR(host->clk);
1053         }
1054
1055         ret = clk_prepare_enable(host->clk);
1056         if (ret)
1057                 return ret;
1058
1059         /*
1060          * This device ID is actually a common AMBA ID as used on the
1061          * AMBA PrimeCell bus. However it is not a PrimeCell.
1062          */
1063         for (pid = 0, i = 0; i < 4; i++)
1064                 pid |= (readl(base + resource_size(res) - 0x20 + 4 * i) & 255) << (i * 8);
1065         host->pid = pid;
1066         dev_info(&pdev->dev, "FSMC device partno %03x, manufacturer %02x, "
1067                  "revision %02x, config %02x\n",
1068                  AMBA_PART_BITS(pid), AMBA_MANF_BITS(pid),
1069                  AMBA_REV_BITS(pid), AMBA_CONFIG_BITS(pid));
1070
1071         host->dev = &pdev->dev;
1072
1073         if (host->mode == USE_DMA_ACCESS)
1074                 init_completion(&host->dma_access_complete);
1075
1076         /* Link all private pointers */
1077         mtd = nand_to_mtd(&host->nand);
1078         nand_set_controller_data(nand, host);
1079         nand_set_flash_node(nand, pdev->dev.of_node);
1080
1081         mtd->dev.parent = &pdev->dev;
1082         nand->exec_op = fsmc_exec_op;
1083         nand->select_chip = fsmc_select_chip;
1084
1085         /*
1086          * Setup default ECC mode. nand_dt_init() called from nand_scan_ident()
1087          * can overwrite this value if the DT provides a different value.
1088          */
1089         nand->ecc.mode = NAND_ECC_HW;
1090         nand->ecc.hwctl = fsmc_enable_hwecc;
1091         nand->ecc.size = 512;
1092         nand->badblockbits = 7;
1093
1094         if (host->mode == USE_DMA_ACCESS) {
1095                 dma_cap_zero(mask);
1096                 dma_cap_set(DMA_MEMCPY, mask);
1097                 host->read_dma_chan = dma_request_channel(mask, filter, NULL);
1098                 if (!host->read_dma_chan) {
1099                         dev_err(&pdev->dev, "Unable to get read dma channel\n");
1100                         goto disable_clk;
1101                 }
1102                 host->write_dma_chan = dma_request_channel(mask, filter, NULL);
1103                 if (!host->write_dma_chan) {
1104                         dev_err(&pdev->dev, "Unable to get write dma channel\n");
1105                         goto release_dma_read_chan;
1106                 }
1107         }
1108
1109         if (host->dev_timings)
1110                 fsmc_nand_setup(host, host->dev_timings);
1111         else
1112                 nand->setup_data_interface = fsmc_setup_data_interface;
1113
1114         if (AMBA_REV_BITS(host->pid) >= 8) {
1115                 nand->ecc.read_page = fsmc_read_page_hwecc;
1116                 nand->ecc.calculate = fsmc_read_hwecc_ecc4;
1117                 nand->ecc.correct = fsmc_bch8_correct_data;
1118                 nand->ecc.bytes = 13;
1119                 nand->ecc.strength = 8;
1120         }
1121
1122         /*
1123          * Scan to find existence of the device
1124          */
1125         nand->dummy_controller.ops = &fsmc_nand_controller_ops;
1126         ret = nand_scan(nand, 1);
1127         if (ret)
1128                 goto release_dma_write_chan;
1129
1130         mtd->name = "nand";
1131         ret = mtd_device_register(mtd, NULL, 0);
1132         if (ret)
1133                 goto cleanup_nand;
1134
1135         platform_set_drvdata(pdev, host);
1136         dev_info(&pdev->dev, "FSMC NAND driver registration successful\n");
1137
1138         return 0;
1139
1140 cleanup_nand:
1141         nand_cleanup(nand);
1142 release_dma_write_chan:
1143         if (host->mode == USE_DMA_ACCESS)
1144                 dma_release_channel(host->write_dma_chan);
1145 release_dma_read_chan:
1146         if (host->mode == USE_DMA_ACCESS)
1147                 dma_release_channel(host->read_dma_chan);
1148 disable_clk:
1149         clk_disable_unprepare(host->clk);
1150
1151         return ret;
1152 }
1153
1154 /*
1155  * Clean up routine
1156  */
1157 static int fsmc_nand_remove(struct platform_device *pdev)
1158 {
1159         struct fsmc_nand_data *host = platform_get_drvdata(pdev);
1160
1161         if (host) {
1162                 nand_release(&host->nand);
1163
1164                 if (host->mode == USE_DMA_ACCESS) {
1165                         dma_release_channel(host->write_dma_chan);
1166                         dma_release_channel(host->read_dma_chan);
1167                 }
1168                 clk_disable_unprepare(host->clk);
1169         }
1170
1171         return 0;
1172 }
1173
1174 #ifdef CONFIG_PM_SLEEP
1175 static int fsmc_nand_suspend(struct device *dev)
1176 {
1177         struct fsmc_nand_data *host = dev_get_drvdata(dev);
1178         if (host)
1179                 clk_disable_unprepare(host->clk);
1180         return 0;
1181 }
1182
1183 static int fsmc_nand_resume(struct device *dev)
1184 {
1185         struct fsmc_nand_data *host = dev_get_drvdata(dev);
1186         if (host) {
1187                 clk_prepare_enable(host->clk);
1188                 if (host->dev_timings)
1189                         fsmc_nand_setup(host, host->dev_timings);
1190         }
1191         return 0;
1192 }
1193 #endif
1194
1195 static SIMPLE_DEV_PM_OPS(fsmc_nand_pm_ops, fsmc_nand_suspend, fsmc_nand_resume);
1196
1197 static const struct of_device_id fsmc_nand_id_table[] = {
1198         { .compatible = "st,spear600-fsmc-nand" },
1199         { .compatible = "stericsson,fsmc-nand" },
1200         {}
1201 };
1202 MODULE_DEVICE_TABLE(of, fsmc_nand_id_table);
1203
1204 static struct platform_driver fsmc_nand_driver = {
1205         .remove = fsmc_nand_remove,
1206         .driver = {
1207                 .name = "fsmc-nand",
1208                 .of_match_table = fsmc_nand_id_table,
1209                 .pm = &fsmc_nand_pm_ops,
1210         },
1211 };
1212
1213 module_platform_driver_probe(fsmc_nand_driver, fsmc_nand_probe);
1214
1215 MODULE_LICENSE("GPL");
1216 MODULE_AUTHOR("Vipin Kumar <vipin.kumar@st.com>, Ashish Priyadarshi");
1217 MODULE_DESCRIPTION("NAND driver for SPEAr Platforms");