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