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