970ba1ec8b439c1e87a1eca2e6ad9fc45c7415b0
[platform/kernel/linux-starfive.git] / drivers / mtd / nand / raw / marvell_nand.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Marvell NAND flash controller driver
4  *
5  * Copyright (C) 2017 Marvell
6  * Author: Miquel RAYNAL <miquel.raynal@free-electrons.com>
7  *
8  *
9  * This NAND controller driver handles two versions of the hardware,
10  * one is called NFCv1 and is available on PXA SoCs and the other is
11  * called NFCv2 and is available on Armada SoCs.
12  *
13  * The main visible difference is that NFCv1 only has Hamming ECC
14  * capabilities, while NFCv2 also embeds a BCH ECC engine. Also, DMA
15  * is not used with NFCv2.
16  *
17  * The ECC layouts are depicted in details in Marvell AN-379, but here
18  * is a brief description.
19  *
20  * When using Hamming, the data is split in 512B chunks (either 1, 2
21  * or 4) and each chunk will have its own ECC "digest" of 6B at the
22  * beginning of the OOB area and eventually the remaining free OOB
23  * bytes (also called "spare" bytes in the driver). This engine
24  * corrects up to 1 bit per chunk and detects reliably an error if
25  * there are at most 2 bitflips. Here is the page layout used by the
26  * controller when Hamming is chosen:
27  *
28  * +-------------------------------------------------------------+
29  * | Data 1 | ... | Data N | ECC 1 | ... | ECCN | Free OOB bytes |
30  * +-------------------------------------------------------------+
31  *
32  * When using the BCH engine, there are N identical (data + free OOB +
33  * ECC) sections and potentially an extra one to deal with
34  * configurations where the chosen (data + free OOB + ECC) sizes do
35  * not align with the page (data + OOB) size. ECC bytes are always
36  * 30B per ECC chunk. Here is the page layout used by the controller
37  * when BCH is chosen:
38  *
39  * +-----------------------------------------
40  * | Data 1 | Free OOB bytes 1 | ECC 1 | ...
41  * +-----------------------------------------
42  *
43  *      -------------------------------------------
44  *       ... | Data N | Free OOB bytes N | ECC N |
45  *      -------------------------------------------
46  *
47  *           --------------------------------------------+
48  *            Last Data | Last Free OOB bytes | Last ECC |
49  *           --------------------------------------------+
50  *
51  * In both cases, the layout seen by the user is always: all data
52  * first, then all free OOB bytes and finally all ECC bytes. With BCH,
53  * ECC bytes are 30B long and are padded with 0xFF to align on 32
54  * bytes.
55  *
56  * The controller has certain limitations that are handled by the
57  * driver:
58  *   - It can only read 2k at a time. To overcome this limitation, the
59  *     driver issues data cycles on the bus, without issuing new
60  *     CMD + ADDR cycles. The Marvell term is "naked" operations.
61  *   - The ECC strength in BCH mode cannot be tuned. It is fixed 16
62  *     bits. What can be tuned is the ECC block size as long as it
63  *     stays between 512B and 2kiB. It's usually chosen based on the
64  *     chip ECC requirements. For instance, using 2kiB ECC chunks
65  *     provides 4b/512B correctability.
66  *   - The controller will always treat data bytes, free OOB bytes
67  *     and ECC bytes in that order, no matter what the real layout is
68  *     (which is usually all data then all OOB bytes). The
69  *     marvell_nfc_layouts array below contains the currently
70  *     supported layouts.
71  *   - Because of these weird layouts, the Bad Block Markers can be
72  *     located in data section. In this case, the NAND_BBT_NO_OOB_BBM
73  *     option must be set to prevent scanning/writing bad block
74  *     markers.
75  */
76
77 #include <linux/module.h>
78 #include <linux/clk.h>
79 #include <linux/mtd/rawnand.h>
80 #include <linux/of_platform.h>
81 #include <linux/iopoll.h>
82 #include <linux/interrupt.h>
83 #include <linux/slab.h>
84 #include <linux/mfd/syscon.h>
85 #include <linux/regmap.h>
86 #include <asm/unaligned.h>
87
88 #include <linux/dmaengine.h>
89 #include <linux/dma-mapping.h>
90 #include <linux/dma/pxa-dma.h>
91 #include <linux/platform_data/mtd-nand-pxa3xx.h>
92
93 /* Data FIFO granularity, FIFO reads/writes must be a multiple of this length */
94 #define FIFO_DEPTH              8
95 #define FIFO_REP(x)             (x / sizeof(u32))
96 #define BCH_SEQ_READS           (32 / FIFO_DEPTH)
97 /* NFC does not support transfers of larger chunks at a time */
98 #define MAX_CHUNK_SIZE          2112
99 /* NFCv1 cannot read more that 7 bytes of ID */
100 #define NFCV1_READID_LEN        7
101 /* Polling is done at a pace of POLL_PERIOD us until POLL_TIMEOUT is reached */
102 #define POLL_PERIOD             0
103 #define POLL_TIMEOUT            100000
104 /* Interrupt maximum wait period in ms */
105 #define IRQ_TIMEOUT             1000
106 /* Latency in clock cycles between SoC pins and NFC logic */
107 #define MIN_RD_DEL_CNT          3
108 /* Maximum number of contiguous address cycles */
109 #define MAX_ADDRESS_CYC_NFCV1   5
110 #define MAX_ADDRESS_CYC_NFCV2   7
111 /* System control registers/bits to enable the NAND controller on some SoCs */
112 #define GENCONF_SOC_DEVICE_MUX  0x208
113 #define GENCONF_SOC_DEVICE_MUX_NFC_EN BIT(0)
114 #define GENCONF_SOC_DEVICE_MUX_ECC_CLK_RST BIT(20)
115 #define GENCONF_SOC_DEVICE_MUX_ECC_CORE_RST BIT(21)
116 #define GENCONF_SOC_DEVICE_MUX_NFC_INT_EN BIT(25)
117 #define GENCONF_CLK_GATING_CTRL 0x220
118 #define GENCONF_CLK_GATING_CTRL_ND_GATE BIT(2)
119 #define GENCONF_ND_CLK_CTRL     0x700
120 #define GENCONF_ND_CLK_CTRL_EN  BIT(0)
121
122 /* NAND controller data flash control register */
123 #define NDCR                    0x00
124 #define NDCR_ALL_INT            GENMASK(11, 0)
125 #define NDCR_CS1_CMDDM          BIT(7)
126 #define NDCR_CS0_CMDDM          BIT(8)
127 #define NDCR_RDYM               BIT(11)
128 #define NDCR_ND_ARB_EN          BIT(12)
129 #define NDCR_RA_START           BIT(15)
130 #define NDCR_RD_ID_CNT(x)       (min_t(unsigned int, x, 0x7) << 16)
131 #define NDCR_PAGE_SZ(x)         (x >= 2048 ? BIT(24) : 0)
132 #define NDCR_DWIDTH_M           BIT(26)
133 #define NDCR_DWIDTH_C           BIT(27)
134 #define NDCR_ND_RUN             BIT(28)
135 #define NDCR_DMA_EN             BIT(29)
136 #define NDCR_ECC_EN             BIT(30)
137 #define NDCR_SPARE_EN           BIT(31)
138 #define NDCR_GENERIC_FIELDS_MASK (~(NDCR_RA_START | NDCR_PAGE_SZ(2048) | \
139                                     NDCR_DWIDTH_M | NDCR_DWIDTH_C))
140
141 /* NAND interface timing parameter 0 register */
142 #define NDTR0                   0x04
143 #define NDTR0_TRP(x)            ((min_t(unsigned int, x, 0xF) & 0x7) << 0)
144 #define NDTR0_TRH(x)            (min_t(unsigned int, x, 0x7) << 3)
145 #define NDTR0_ETRP(x)           ((min_t(unsigned int, x, 0xF) & 0x8) << 3)
146 #define NDTR0_SEL_NRE_EDGE      BIT(7)
147 #define NDTR0_TWP(x)            (min_t(unsigned int, x, 0x7) << 8)
148 #define NDTR0_TWH(x)            (min_t(unsigned int, x, 0x7) << 11)
149 #define NDTR0_TCS(x)            (min_t(unsigned int, x, 0x7) << 16)
150 #define NDTR0_TCH(x)            (min_t(unsigned int, x, 0x7) << 19)
151 #define NDTR0_RD_CNT_DEL(x)     (min_t(unsigned int, x, 0xF) << 22)
152 #define NDTR0_SELCNTR           BIT(26)
153 #define NDTR0_TADL(x)           (min_t(unsigned int, x, 0x1F) << 27)
154
155 /* NAND interface timing parameter 1 register */
156 #define NDTR1                   0x0C
157 #define NDTR1_TAR(x)            (min_t(unsigned int, x, 0xF) << 0)
158 #define NDTR1_TWHR(x)           (min_t(unsigned int, x, 0xF) << 4)
159 #define NDTR1_TRHW(x)           (min_t(unsigned int, x / 16, 0x3) << 8)
160 #define NDTR1_PRESCALE          BIT(14)
161 #define NDTR1_WAIT_MODE         BIT(15)
162 #define NDTR1_TR(x)             (min_t(unsigned int, x, 0xFFFF) << 16)
163
164 /* NAND controller status register */
165 #define NDSR                    0x14
166 #define NDSR_WRCMDREQ           BIT(0)
167 #define NDSR_RDDREQ             BIT(1)
168 #define NDSR_WRDREQ             BIT(2)
169 #define NDSR_CORERR             BIT(3)
170 #define NDSR_UNCERR             BIT(4)
171 #define NDSR_CMDD(cs)           BIT(8 - cs)
172 #define NDSR_RDY(rb)            BIT(11 + rb)
173 #define NDSR_ERRCNT(x)          ((x >> 16) & 0x1F)
174
175 /* NAND ECC control register */
176 #define NDECCCTRL               0x28
177 #define NDECCCTRL_BCH_EN        BIT(0)
178
179 /* NAND controller data buffer register */
180 #define NDDB                    0x40
181
182 /* NAND controller command buffer 0 register */
183 #define NDCB0                   0x48
184 #define NDCB0_CMD1(x)           ((x & 0xFF) << 0)
185 #define NDCB0_CMD2(x)           ((x & 0xFF) << 8)
186 #define NDCB0_ADDR_CYC(x)       ((x & 0x7) << 16)
187 #define NDCB0_ADDR_GET_NUM_CYC(x) (((x) >> 16) & 0x7)
188 #define NDCB0_DBC               BIT(19)
189 #define NDCB0_CMD_TYPE(x)       ((x & 0x7) << 21)
190 #define NDCB0_CSEL              BIT(24)
191 #define NDCB0_RDY_BYP           BIT(27)
192 #define NDCB0_LEN_OVRD          BIT(28)
193 #define NDCB0_CMD_XTYPE(x)      ((x & 0x7) << 29)
194
195 /* NAND controller command buffer 1 register */
196 #define NDCB1                   0x4C
197 #define NDCB1_COLS(x)           ((x & 0xFFFF) << 0)
198 #define NDCB1_ADDRS_PAGE(x)     (x << 16)
199
200 /* NAND controller command buffer 2 register */
201 #define NDCB2                   0x50
202 #define NDCB2_ADDR5_PAGE(x)     (((x >> 16) & 0xFF) << 0)
203 #define NDCB2_ADDR5_CYC(x)      ((x & 0xFF) << 0)
204
205 /* NAND controller command buffer 3 register */
206 #define NDCB3                   0x54
207 #define NDCB3_ADDR6_CYC(x)      ((x & 0xFF) << 16)
208 #define NDCB3_ADDR7_CYC(x)      ((x & 0xFF) << 24)
209
210 /* NAND controller command buffer 0 register 'type' and 'xtype' fields */
211 #define TYPE_READ               0
212 #define TYPE_WRITE              1
213 #define TYPE_ERASE              2
214 #define TYPE_READ_ID            3
215 #define TYPE_STATUS             4
216 #define TYPE_RESET              5
217 #define TYPE_NAKED_CMD          6
218 #define TYPE_NAKED_ADDR         7
219 #define TYPE_MASK               7
220 #define XTYPE_MONOLITHIC_RW     0
221 #define XTYPE_LAST_NAKED_RW     1
222 #define XTYPE_FINAL_COMMAND     3
223 #define XTYPE_READ              4
224 #define XTYPE_WRITE_DISPATCH    4
225 #define XTYPE_NAKED_RW          5
226 #define XTYPE_COMMAND_DISPATCH  6
227 #define XTYPE_MASK              7
228
229 /**
230  * Marvell ECC engine works differently than the others, in order to limit the
231  * size of the IP, hardware engineers chose to set a fixed strength at 16 bits
232  * per subpage, and depending on a the desired strength needed by the NAND chip,
233  * a particular layout mixing data/spare/ecc is defined, with a possible last
234  * chunk smaller that the others.
235  *
236  * @writesize:          Full page size on which the layout applies
237  * @chunk:              Desired ECC chunk size on which the layout applies
238  * @strength:           Desired ECC strength (per chunk size bytes) on which the
239  *                      layout applies
240  * @nchunks:            Total number of chunks
241  * @full_chunk_cnt:     Number of full-sized chunks, which is the number of
242  *                      repetitions of the pattern:
243  *                      (data_bytes + spare_bytes + ecc_bytes).
244  * @data_bytes:         Number of data bytes per chunk
245  * @spare_bytes:        Number of spare bytes per chunk
246  * @ecc_bytes:          Number of ecc bytes per chunk
247  * @last_data_bytes:    Number of data bytes in the last chunk
248  * @last_spare_bytes:   Number of spare bytes in the last chunk
249  * @last_ecc_bytes:     Number of ecc bytes in the last chunk
250  */
251 struct marvell_hw_ecc_layout {
252         /* Constraints */
253         int writesize;
254         int chunk;
255         int strength;
256         /* Corresponding layout */
257         int nchunks;
258         int full_chunk_cnt;
259         int data_bytes;
260         int spare_bytes;
261         int ecc_bytes;
262         int last_data_bytes;
263         int last_spare_bytes;
264         int last_ecc_bytes;
265 };
266
267 #define MARVELL_LAYOUT(ws, dc, ds, nc, fcc, db, sb, eb, ldb, lsb, leb)  \
268         {                                                               \
269                 .writesize = ws,                                        \
270                 .chunk = dc,                                            \
271                 .strength = ds,                                         \
272                 .nchunks = nc,                                          \
273                 .full_chunk_cnt = fcc,                                  \
274                 .data_bytes = db,                                       \
275                 .spare_bytes = sb,                                      \
276                 .ecc_bytes = eb,                                        \
277                 .last_data_bytes = ldb,                                 \
278                 .last_spare_bytes = lsb,                                \
279                 .last_ecc_bytes = leb,                                  \
280         }
281
282 /* Layouts explained in AN-379_Marvell_SoC_NFC_ECC */
283 static const struct marvell_hw_ecc_layout marvell_nfc_layouts[] = {
284         MARVELL_LAYOUT(  512,   512,  1,  1,  1,  512,  8,  8,  0,  0,  0),
285         MARVELL_LAYOUT( 2048,   512,  1,  1,  1, 2048, 40, 24,  0,  0,  0),
286         MARVELL_LAYOUT( 2048,   512,  4,  1,  1, 2048, 32, 30,  0,  0,  0),
287         MARVELL_LAYOUT( 2048,   512,  8,  2,  1, 1024,  0, 30,1024,32, 30),
288         MARVELL_LAYOUT( 4096,   512,  4,  2,  2, 2048, 32, 30,  0,  0,  0),
289         MARVELL_LAYOUT( 4096,   512,  8,  5,  4, 1024,  0, 30,  0, 64, 30),
290         MARVELL_LAYOUT( 8192,   512,  4,  4,  4, 2048,  0, 30,  0,  0,  0),
291         MARVELL_LAYOUT( 8192,   512,  8,  9,  8, 1024,  0, 30,  0, 160, 30),
292 };
293
294 /**
295  * The Nand Flash Controller has up to 4 CE and 2 RB pins. The CE selection
296  * is made by a field in NDCB0 register, and in another field in NDCB2 register.
297  * The datasheet describes the logic with an error: ADDR5 field is once
298  * declared at the beginning of NDCB2, and another time at its end. Because the
299  * ADDR5 field of NDCB2 may be used by other bytes, it would be more logical
300  * to use the last bit of this field instead of the first ones.
301  *
302  * @cs:                 Wanted CE lane.
303  * @ndcb0_csel:         Value of the NDCB0 register with or without the flag
304  *                      selecting the wanted CE lane. This is set once when
305  *                      the Device Tree is probed.
306  * @rb:                 Ready/Busy pin for the flash chip
307  */
308 struct marvell_nand_chip_sel {
309         unsigned int cs;
310         u32 ndcb0_csel;
311         unsigned int rb;
312 };
313
314 /**
315  * NAND chip structure: stores NAND chip device related information
316  *
317  * @chip:               Base NAND chip structure
318  * @node:               Used to store NAND chips into a list
319  * @layout              NAND layout when using hardware ECC
320  * @ndcr:               Controller register value for this NAND chip
321  * @ndtr0:              Timing registers 0 value for this NAND chip
322  * @ndtr1:              Timing registers 1 value for this NAND chip
323  * @selected_die:       Current active CS
324  * @nsels:              Number of CS lines required by the NAND chip
325  * @sels:               Array of CS lines descriptions
326  */
327 struct marvell_nand_chip {
328         struct nand_chip chip;
329         struct list_head node;
330         const struct marvell_hw_ecc_layout *layout;
331         u32 ndcr;
332         u32 ndtr0;
333         u32 ndtr1;
334         int addr_cyc;
335         int selected_die;
336         unsigned int nsels;
337         struct marvell_nand_chip_sel sels[];
338 };
339
340 static inline struct marvell_nand_chip *to_marvell_nand(struct nand_chip *chip)
341 {
342         return container_of(chip, struct marvell_nand_chip, chip);
343 }
344
345 static inline struct marvell_nand_chip_sel *to_nand_sel(struct marvell_nand_chip
346                                                         *nand)
347 {
348         return &nand->sels[nand->selected_die];
349 }
350
351 /**
352  * NAND controller capabilities for distinction between compatible strings
353  *
354  * @max_cs_nb:          Number of Chip Select lines available
355  * @max_rb_nb:          Number of Ready/Busy lines available
356  * @need_system_controller: Indicates if the SoC needs to have access to the
357  *                      system controller (ie. to enable the NAND controller)
358  * @legacy_of_bindings: Indicates if DT parsing must be done using the old
359  *                      fashion way
360  * @is_nfcv2:           NFCv2 has numerous enhancements compared to NFCv1, ie.
361  *                      BCH error detection and correction algorithm,
362  *                      NDCB3 register has been added
363  * @use_dma:            Use dma for data transfers
364  */
365 struct marvell_nfc_caps {
366         unsigned int max_cs_nb;
367         unsigned int max_rb_nb;
368         bool need_system_controller;
369         bool legacy_of_bindings;
370         bool is_nfcv2;
371         bool use_dma;
372 };
373
374 /**
375  * NAND controller structure: stores Marvell NAND controller information
376  *
377  * @controller:         Base controller structure
378  * @dev:                Parent device (used to print error messages)
379  * @regs:               NAND controller registers
380  * @core_clk:           Core clock
381  * @reg_clk:            Registers clock
382  * @complete:           Completion object to wait for NAND controller events
383  * @assigned_cs:        Bitmask describing already assigned CS lines
384  * @chips:              List containing all the NAND chips attached to
385  *                      this NAND controller
386  * @caps:               NAND controller capabilities for each compatible string
387  * @dma_chan:           DMA channel (NFCv1 only)
388  * @dma_buf:            32-bit aligned buffer for DMA transfers (NFCv1 only)
389  */
390 struct marvell_nfc {
391         struct nand_controller controller;
392         struct device *dev;
393         void __iomem *regs;
394         struct clk *core_clk;
395         struct clk *reg_clk;
396         struct completion complete;
397         unsigned long assigned_cs;
398         struct list_head chips;
399         struct nand_chip *selected_chip;
400         const struct marvell_nfc_caps *caps;
401
402         /* DMA (NFCv1 only) */
403         bool use_dma;
404         struct dma_chan *dma_chan;
405         u8 *dma_buf;
406 };
407
408 static inline struct marvell_nfc *to_marvell_nfc(struct nand_controller *ctrl)
409 {
410         return container_of(ctrl, struct marvell_nfc, controller);
411 }
412
413 /**
414  * NAND controller timings expressed in NAND Controller clock cycles
415  *
416  * @tRP:                ND_nRE pulse width
417  * @tRH:                ND_nRE high duration
418  * @tWP:                ND_nWE pulse time
419  * @tWH:                ND_nWE high duration
420  * @tCS:                Enable signal setup time
421  * @tCH:                Enable signal hold time
422  * @tADL:               Address to write data delay
423  * @tAR:                ND_ALE low to ND_nRE low delay
424  * @tWHR:               ND_nWE high to ND_nRE low for status read
425  * @tRHW:               ND_nRE high duration, read to write delay
426  * @tR:                 ND_nWE high to ND_nRE low for read
427  */
428 struct marvell_nfc_timings {
429         /* NDTR0 fields */
430         unsigned int tRP;
431         unsigned int tRH;
432         unsigned int tWP;
433         unsigned int tWH;
434         unsigned int tCS;
435         unsigned int tCH;
436         unsigned int tADL;
437         /* NDTR1 fields */
438         unsigned int tAR;
439         unsigned int tWHR;
440         unsigned int tRHW;
441         unsigned int tR;
442 };
443
444 /**
445  * Derives a duration in numbers of clock cycles.
446  *
447  * @ps: Duration in pico-seconds
448  * @period_ns:  Clock period in nano-seconds
449  *
450  * Convert the duration in nano-seconds, then divide by the period and
451  * return the number of clock periods.
452  */
453 #define TO_CYCLES(ps, period_ns) (DIV_ROUND_UP(ps / 1000, period_ns))
454 #define TO_CYCLES64(ps, period_ns) (DIV_ROUND_UP_ULL(div_u64(ps, 1000), \
455                                                      period_ns))
456
457 /**
458  * NAND driver structure filled during the parsing of the ->exec_op() subop
459  * subset of instructions.
460  *
461  * @ndcb:               Array of values written to NDCBx registers
462  * @cle_ale_delay_ns:   Optional delay after the last CMD or ADDR cycle
463  * @rdy_timeout_ms:     Timeout for waits on Ready/Busy pin
464  * @rdy_delay_ns:       Optional delay after waiting for the RB pin
465  * @data_delay_ns:      Optional delay after the data xfer
466  * @data_instr_idx:     Index of the data instruction in the subop
467  * @data_instr:         Pointer to the data instruction in the subop
468  */
469 struct marvell_nfc_op {
470         u32 ndcb[4];
471         unsigned int cle_ale_delay_ns;
472         unsigned int rdy_timeout_ms;
473         unsigned int rdy_delay_ns;
474         unsigned int data_delay_ns;
475         unsigned int data_instr_idx;
476         const struct nand_op_instr *data_instr;
477 };
478
479 /*
480  * Internal helper to conditionnally apply a delay (from the above structure,
481  * most of the time).
482  */
483 static void cond_delay(unsigned int ns)
484 {
485         if (!ns)
486                 return;
487
488         if (ns < 10000)
489                 ndelay(ns);
490         else
491                 udelay(DIV_ROUND_UP(ns, 1000));
492 }
493
494 /*
495  * The controller has many flags that could generate interrupts, most of them
496  * are disabled and polling is used. For the very slow signals, using interrupts
497  * may relax the CPU charge.
498  */
499 static void marvell_nfc_disable_int(struct marvell_nfc *nfc, u32 int_mask)
500 {
501         u32 reg;
502
503         /* Writing 1 disables the interrupt */
504         reg = readl_relaxed(nfc->regs + NDCR);
505         writel_relaxed(reg | int_mask, nfc->regs + NDCR);
506 }
507
508 static void marvell_nfc_enable_int(struct marvell_nfc *nfc, u32 int_mask)
509 {
510         u32 reg;
511
512         /* Writing 0 enables the interrupt */
513         reg = readl_relaxed(nfc->regs + NDCR);
514         writel_relaxed(reg & ~int_mask, nfc->regs + NDCR);
515 }
516
517 static u32 marvell_nfc_clear_int(struct marvell_nfc *nfc, u32 int_mask)
518 {
519         u32 reg;
520
521         reg = readl_relaxed(nfc->regs + NDSR);
522         writel_relaxed(int_mask, nfc->regs + NDSR);
523
524         return reg & int_mask;
525 }
526
527 static void marvell_nfc_force_byte_access(struct nand_chip *chip,
528                                           bool force_8bit)
529 {
530         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
531         u32 ndcr;
532
533         /*
534          * Callers of this function do not verify if the NAND is using a 16-bit
535          * an 8-bit bus for normal operations, so we need to take care of that
536          * here by leaving the configuration unchanged if the NAND does not have
537          * the NAND_BUSWIDTH_16 flag set.
538          */
539         if (!(chip->options & NAND_BUSWIDTH_16))
540                 return;
541
542         ndcr = readl_relaxed(nfc->regs + NDCR);
543
544         if (force_8bit)
545                 ndcr &= ~(NDCR_DWIDTH_M | NDCR_DWIDTH_C);
546         else
547                 ndcr |= NDCR_DWIDTH_M | NDCR_DWIDTH_C;
548
549         writel_relaxed(ndcr, nfc->regs + NDCR);
550 }
551
552 static int marvell_nfc_wait_ndrun(struct nand_chip *chip)
553 {
554         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
555         u32 val;
556         int ret;
557
558         /*
559          * The command is being processed, wait for the ND_RUN bit to be
560          * cleared by the NFC. If not, we must clear it by hand.
561          */
562         ret = readl_relaxed_poll_timeout(nfc->regs + NDCR, val,
563                                          (val & NDCR_ND_RUN) == 0,
564                                          POLL_PERIOD, POLL_TIMEOUT);
565         if (ret) {
566                 dev_err(nfc->dev, "Timeout on NAND controller run mode\n");
567                 writel_relaxed(readl(nfc->regs + NDCR) & ~NDCR_ND_RUN,
568                                nfc->regs + NDCR);
569                 return ret;
570         }
571
572         return 0;
573 }
574
575 /*
576  * Any time a command has to be sent to the controller, the following sequence
577  * has to be followed:
578  * - call marvell_nfc_prepare_cmd()
579  *      -> activate the ND_RUN bit that will kind of 'start a job'
580  *      -> wait the signal indicating the NFC is waiting for a command
581  * - send the command (cmd and address cycles)
582  * - enventually send or receive the data
583  * - call marvell_nfc_end_cmd() with the corresponding flag
584  *      -> wait the flag to be triggered or cancel the job with a timeout
585  *
586  * The following helpers are here to factorize the code a bit so that
587  * specialized functions responsible for executing the actual NAND
588  * operations do not have to replicate the same code blocks.
589  */
590 static int marvell_nfc_prepare_cmd(struct nand_chip *chip)
591 {
592         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
593         u32 ndcr, val;
594         int ret;
595
596         /* Poll ND_RUN and clear NDSR before issuing any command */
597         ret = marvell_nfc_wait_ndrun(chip);
598         if (ret) {
599                 dev_err(nfc->dev, "Last operation did not succeed\n");
600                 return ret;
601         }
602
603         ndcr = readl_relaxed(nfc->regs + NDCR);
604         writel_relaxed(readl(nfc->regs + NDSR), nfc->regs + NDSR);
605
606         /* Assert ND_RUN bit and wait the NFC to be ready */
607         writel_relaxed(ndcr | NDCR_ND_RUN, nfc->regs + NDCR);
608         ret = readl_relaxed_poll_timeout(nfc->regs + NDSR, val,
609                                          val & NDSR_WRCMDREQ,
610                                          POLL_PERIOD, POLL_TIMEOUT);
611         if (ret) {
612                 dev_err(nfc->dev, "Timeout on WRCMDRE\n");
613                 return -ETIMEDOUT;
614         }
615
616         /* Command may be written, clear WRCMDREQ status bit */
617         writel_relaxed(NDSR_WRCMDREQ, nfc->regs + NDSR);
618
619         return 0;
620 }
621
622 static void marvell_nfc_send_cmd(struct nand_chip *chip,
623                                  struct marvell_nfc_op *nfc_op)
624 {
625         struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
626         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
627
628         dev_dbg(nfc->dev, "\nNDCR:  0x%08x\n"
629                 "NDCB0: 0x%08x\nNDCB1: 0x%08x\nNDCB2: 0x%08x\nNDCB3: 0x%08x\n",
630                 (u32)readl_relaxed(nfc->regs + NDCR), nfc_op->ndcb[0],
631                 nfc_op->ndcb[1], nfc_op->ndcb[2], nfc_op->ndcb[3]);
632
633         writel_relaxed(to_nand_sel(marvell_nand)->ndcb0_csel | nfc_op->ndcb[0],
634                        nfc->regs + NDCB0);
635         writel_relaxed(nfc_op->ndcb[1], nfc->regs + NDCB0);
636         writel(nfc_op->ndcb[2], nfc->regs + NDCB0);
637
638         /*
639          * Write NDCB0 four times only if LEN_OVRD is set or if ADDR6 or ADDR7
640          * fields are used (only available on NFCv2).
641          */
642         if (nfc_op->ndcb[0] & NDCB0_LEN_OVRD ||
643             NDCB0_ADDR_GET_NUM_CYC(nfc_op->ndcb[0]) >= 6) {
644                 if (!WARN_ON_ONCE(!nfc->caps->is_nfcv2))
645                         writel(nfc_op->ndcb[3], nfc->regs + NDCB0);
646         }
647 }
648
649 static int marvell_nfc_end_cmd(struct nand_chip *chip, int flag,
650                                const char *label)
651 {
652         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
653         u32 val;
654         int ret;
655
656         ret = readl_relaxed_poll_timeout(nfc->regs + NDSR, val,
657                                          val & flag,
658                                          POLL_PERIOD, POLL_TIMEOUT);
659
660         if (ret) {
661                 dev_err(nfc->dev, "Timeout on %s (NDSR: 0x%08x)\n",
662                         label, val);
663                 if (nfc->dma_chan)
664                         dmaengine_terminate_all(nfc->dma_chan);
665                 return ret;
666         }
667
668         /*
669          * DMA function uses this helper to poll on CMDD bits without wanting
670          * them to be cleared.
671          */
672         if (nfc->use_dma && (readl_relaxed(nfc->regs + NDCR) & NDCR_DMA_EN))
673                 return 0;
674
675         writel_relaxed(flag, nfc->regs + NDSR);
676
677         return 0;
678 }
679
680 static int marvell_nfc_wait_cmdd(struct nand_chip *chip)
681 {
682         struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
683         int cs_flag = NDSR_CMDD(to_nand_sel(marvell_nand)->ndcb0_csel);
684
685         return marvell_nfc_end_cmd(chip, cs_flag, "CMDD");
686 }
687
688 static int marvell_nfc_poll_status(struct marvell_nfc *nfc, u32 mask,
689                                    u32 expected_val, unsigned long timeout_ms)
690 {
691         unsigned long limit;
692         u32 st;
693
694         limit = jiffies + msecs_to_jiffies(timeout_ms);
695         do {
696                 st = readl_relaxed(nfc->regs + NDSR);
697                 if (st & NDSR_RDY(1))
698                         st |= NDSR_RDY(0);
699
700                 if ((st & mask) == expected_val)
701                         return 0;
702
703                 cpu_relax();
704         } while (time_after(limit, jiffies));
705
706         return -ETIMEDOUT;
707 }
708
709 static int marvell_nfc_wait_op(struct nand_chip *chip, unsigned int timeout_ms)
710 {
711         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
712         struct mtd_info *mtd = nand_to_mtd(chip);
713         u32 pending;
714         int ret;
715
716         /* Timeout is expressed in ms */
717         if (!timeout_ms)
718                 timeout_ms = IRQ_TIMEOUT;
719
720         if (mtd->oops_panic_write) {
721                 ret = marvell_nfc_poll_status(nfc, NDSR_RDY(0),
722                                               NDSR_RDY(0),
723                                               timeout_ms);
724         } else {
725                 init_completion(&nfc->complete);
726
727                 marvell_nfc_enable_int(nfc, NDCR_RDYM);
728                 ret = wait_for_completion_timeout(&nfc->complete,
729                                                   msecs_to_jiffies(timeout_ms));
730                 marvell_nfc_disable_int(nfc, NDCR_RDYM);
731         }
732         pending = marvell_nfc_clear_int(nfc, NDSR_RDY(0) | NDSR_RDY(1));
733
734         /*
735          * In case the interrupt was not served in the required time frame,
736          * check if the ISR was not served or if something went actually wrong.
737          */
738         if (!ret && !pending) {
739                 dev_err(nfc->dev, "Timeout waiting for RB signal\n");
740                 return -ETIMEDOUT;
741         }
742
743         return 0;
744 }
745
746 static void marvell_nfc_select_target(struct nand_chip *chip,
747                                       unsigned int die_nr)
748 {
749         struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
750         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
751         u32 ndcr_generic;
752
753         /*
754          * Reset the NDCR register to a clean state for this particular chip,
755          * also clear ND_RUN bit.
756          */
757         ndcr_generic = readl_relaxed(nfc->regs + NDCR) &
758                        NDCR_GENERIC_FIELDS_MASK & ~NDCR_ND_RUN;
759         writel_relaxed(ndcr_generic | marvell_nand->ndcr, nfc->regs + NDCR);
760
761         /* Also reset the interrupt status register */
762         marvell_nfc_clear_int(nfc, NDCR_ALL_INT);
763
764         if (chip == nfc->selected_chip && die_nr == marvell_nand->selected_die)
765                 return;
766
767         writel_relaxed(marvell_nand->ndtr0, nfc->regs + NDTR0);
768         writel_relaxed(marvell_nand->ndtr1, nfc->regs + NDTR1);
769
770         nfc->selected_chip = chip;
771         marvell_nand->selected_die = die_nr;
772 }
773
774 static irqreturn_t marvell_nfc_isr(int irq, void *dev_id)
775 {
776         struct marvell_nfc *nfc = dev_id;
777         u32 st = readl_relaxed(nfc->regs + NDSR);
778         u32 ien = (~readl_relaxed(nfc->regs + NDCR)) & NDCR_ALL_INT;
779
780         /*
781          * RDY interrupt mask is one bit in NDCR while there are two status
782          * bit in NDSR (RDY[cs0/cs2] and RDY[cs1/cs3]).
783          */
784         if (st & NDSR_RDY(1))
785                 st |= NDSR_RDY(0);
786
787         if (!(st & ien))
788                 return IRQ_NONE;
789
790         marvell_nfc_disable_int(nfc, st & NDCR_ALL_INT);
791
792         if (st & (NDSR_RDY(0) | NDSR_RDY(1)))
793                 complete(&nfc->complete);
794
795         return IRQ_HANDLED;
796 }
797
798 /* HW ECC related functions */
799 static void marvell_nfc_enable_hw_ecc(struct nand_chip *chip)
800 {
801         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
802         u32 ndcr = readl_relaxed(nfc->regs + NDCR);
803
804         if (!(ndcr & NDCR_ECC_EN)) {
805                 writel_relaxed(ndcr | NDCR_ECC_EN, nfc->regs + NDCR);
806
807                 /*
808                  * When enabling BCH, set threshold to 0 to always know the
809                  * number of corrected bitflips.
810                  */
811                 if (chip->ecc.algo == NAND_ECC_ALGO_BCH)
812                         writel_relaxed(NDECCCTRL_BCH_EN, nfc->regs + NDECCCTRL);
813         }
814 }
815
816 static void marvell_nfc_disable_hw_ecc(struct nand_chip *chip)
817 {
818         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
819         u32 ndcr = readl_relaxed(nfc->regs + NDCR);
820
821         if (ndcr & NDCR_ECC_EN) {
822                 writel_relaxed(ndcr & ~NDCR_ECC_EN, nfc->regs + NDCR);
823                 if (chip->ecc.algo == NAND_ECC_ALGO_BCH)
824                         writel_relaxed(0, nfc->regs + NDECCCTRL);
825         }
826 }
827
828 /* DMA related helpers */
829 static void marvell_nfc_enable_dma(struct marvell_nfc *nfc)
830 {
831         u32 reg;
832
833         reg = readl_relaxed(nfc->regs + NDCR);
834         writel_relaxed(reg | NDCR_DMA_EN, nfc->regs + NDCR);
835 }
836
837 static void marvell_nfc_disable_dma(struct marvell_nfc *nfc)
838 {
839         u32 reg;
840
841         reg = readl_relaxed(nfc->regs + NDCR);
842         writel_relaxed(reg & ~NDCR_DMA_EN, nfc->regs + NDCR);
843 }
844
845 /* Read/write PIO/DMA accessors */
846 static int marvell_nfc_xfer_data_dma(struct marvell_nfc *nfc,
847                                      enum dma_data_direction direction,
848                                      unsigned int len)
849 {
850         unsigned int dma_len = min_t(int, ALIGN(len, 32), MAX_CHUNK_SIZE);
851         struct dma_async_tx_descriptor *tx;
852         struct scatterlist sg;
853         dma_cookie_t cookie;
854         int ret;
855
856         marvell_nfc_enable_dma(nfc);
857         /* Prepare the DMA transfer */
858         sg_init_one(&sg, nfc->dma_buf, dma_len);
859         dma_map_sg(nfc->dma_chan->device->dev, &sg, 1, direction);
860         tx = dmaengine_prep_slave_sg(nfc->dma_chan, &sg, 1,
861                                      direction == DMA_FROM_DEVICE ?
862                                      DMA_DEV_TO_MEM : DMA_MEM_TO_DEV,
863                                      DMA_PREP_INTERRUPT);
864         if (!tx) {
865                 dev_err(nfc->dev, "Could not prepare DMA S/G list\n");
866                 return -ENXIO;
867         }
868
869         /* Do the task and wait for it to finish */
870         cookie = dmaengine_submit(tx);
871         ret = dma_submit_error(cookie);
872         if (ret)
873                 return -EIO;
874
875         dma_async_issue_pending(nfc->dma_chan);
876         ret = marvell_nfc_wait_cmdd(nfc->selected_chip);
877         dma_unmap_sg(nfc->dma_chan->device->dev, &sg, 1, direction);
878         marvell_nfc_disable_dma(nfc);
879         if (ret) {
880                 dev_err(nfc->dev, "Timeout waiting for DMA (status: %d)\n",
881                         dmaengine_tx_status(nfc->dma_chan, cookie, NULL));
882                 dmaengine_terminate_all(nfc->dma_chan);
883                 return -ETIMEDOUT;
884         }
885
886         return 0;
887 }
888
889 static int marvell_nfc_xfer_data_in_pio(struct marvell_nfc *nfc, u8 *in,
890                                         unsigned int len)
891 {
892         unsigned int last_len = len % FIFO_DEPTH;
893         unsigned int last_full_offset = round_down(len, FIFO_DEPTH);
894         int i;
895
896         for (i = 0; i < last_full_offset; i += FIFO_DEPTH)
897                 ioread32_rep(nfc->regs + NDDB, in + i, FIFO_REP(FIFO_DEPTH));
898
899         if (last_len) {
900                 u8 tmp_buf[FIFO_DEPTH];
901
902                 ioread32_rep(nfc->regs + NDDB, tmp_buf, FIFO_REP(FIFO_DEPTH));
903                 memcpy(in + last_full_offset, tmp_buf, last_len);
904         }
905
906         return 0;
907 }
908
909 static int marvell_nfc_xfer_data_out_pio(struct marvell_nfc *nfc, const u8 *out,
910                                          unsigned int len)
911 {
912         unsigned int last_len = len % FIFO_DEPTH;
913         unsigned int last_full_offset = round_down(len, FIFO_DEPTH);
914         int i;
915
916         for (i = 0; i < last_full_offset; i += FIFO_DEPTH)
917                 iowrite32_rep(nfc->regs + NDDB, out + i, FIFO_REP(FIFO_DEPTH));
918
919         if (last_len) {
920                 u8 tmp_buf[FIFO_DEPTH];
921
922                 memcpy(tmp_buf, out + last_full_offset, last_len);
923                 iowrite32_rep(nfc->regs + NDDB, tmp_buf, FIFO_REP(FIFO_DEPTH));
924         }
925
926         return 0;
927 }
928
929 static void marvell_nfc_check_empty_chunk(struct nand_chip *chip,
930                                           u8 *data, int data_len,
931                                           u8 *spare, int spare_len,
932                                           u8 *ecc, int ecc_len,
933                                           unsigned int *max_bitflips)
934 {
935         struct mtd_info *mtd = nand_to_mtd(chip);
936         int bf;
937
938         /*
939          * Blank pages (all 0xFF) that have not been written may be recognized
940          * as bad if bitflips occur, so whenever an uncorrectable error occurs,
941          * check if the entire page (with ECC bytes) is actually blank or not.
942          */
943         if (!data)
944                 data_len = 0;
945         if (!spare)
946                 spare_len = 0;
947         if (!ecc)
948                 ecc_len = 0;
949
950         bf = nand_check_erased_ecc_chunk(data, data_len, ecc, ecc_len,
951                                          spare, spare_len, chip->ecc.strength);
952         if (bf < 0) {
953                 mtd->ecc_stats.failed++;
954                 return;
955         }
956
957         /* Update the stats and max_bitflips */
958         mtd->ecc_stats.corrected += bf;
959         *max_bitflips = max_t(unsigned int, *max_bitflips, bf);
960 }
961
962 /*
963  * Check if a chunk is correct or not according to the hardware ECC engine.
964  * mtd->ecc_stats.corrected is updated, as well as max_bitflips, however
965  * mtd->ecc_stats.failure is not, the function will instead return a non-zero
966  * value indicating that a check on the emptyness of the subpage must be
967  * performed before actually declaring the subpage as "corrupted".
968  */
969 static int marvell_nfc_hw_ecc_check_bitflips(struct nand_chip *chip,
970                                              unsigned int *max_bitflips)
971 {
972         struct mtd_info *mtd = nand_to_mtd(chip);
973         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
974         int bf = 0;
975         u32 ndsr;
976
977         ndsr = readl_relaxed(nfc->regs + NDSR);
978
979         /* Check uncorrectable error flag */
980         if (ndsr & NDSR_UNCERR) {
981                 writel_relaxed(ndsr, nfc->regs + NDSR);
982
983                 /*
984                  * Do not increment ->ecc_stats.failed now, instead, return a
985                  * non-zero value to indicate that this chunk was apparently
986                  * bad, and it should be check to see if it empty or not. If
987                  * the chunk (with ECC bytes) is not declared empty, the calling
988                  * function must increment the failure count.
989                  */
990                 return -EBADMSG;
991         }
992
993         /* Check correctable error flag */
994         if (ndsr & NDSR_CORERR) {
995                 writel_relaxed(ndsr, nfc->regs + NDSR);
996
997                 if (chip->ecc.algo == NAND_ECC_ALGO_BCH)
998                         bf = NDSR_ERRCNT(ndsr);
999                 else
1000                         bf = 1;
1001         }
1002
1003         /* Update the stats and max_bitflips */
1004         mtd->ecc_stats.corrected += bf;
1005         *max_bitflips = max_t(unsigned int, *max_bitflips, bf);
1006
1007         return 0;
1008 }
1009
1010 /* Hamming read helpers */
1011 static int marvell_nfc_hw_ecc_hmg_do_read_page(struct nand_chip *chip,
1012                                                u8 *data_buf, u8 *oob_buf,
1013                                                bool raw, int page)
1014 {
1015         struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
1016         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1017         const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1018         struct marvell_nfc_op nfc_op = {
1019                 .ndcb[0] = NDCB0_CMD_TYPE(TYPE_READ) |
1020                            NDCB0_ADDR_CYC(marvell_nand->addr_cyc) |
1021                            NDCB0_DBC |
1022                            NDCB0_CMD1(NAND_CMD_READ0) |
1023                            NDCB0_CMD2(NAND_CMD_READSTART),
1024                 .ndcb[1] = NDCB1_ADDRS_PAGE(page),
1025                 .ndcb[2] = NDCB2_ADDR5_PAGE(page),
1026         };
1027         unsigned int oob_bytes = lt->spare_bytes + (raw ? lt->ecc_bytes : 0);
1028         int ret;
1029
1030         /* NFCv2 needs more information about the operation being executed */
1031         if (nfc->caps->is_nfcv2)
1032                 nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_MONOLITHIC_RW);
1033
1034         ret = marvell_nfc_prepare_cmd(chip);
1035         if (ret)
1036                 return ret;
1037
1038         marvell_nfc_send_cmd(chip, &nfc_op);
1039         ret = marvell_nfc_end_cmd(chip, NDSR_RDDREQ,
1040                                   "RDDREQ while draining FIFO (data/oob)");
1041         if (ret)
1042                 return ret;
1043
1044         /*
1045          * Read the page then the OOB area. Unlike what is shown in current
1046          * documentation, spare bytes are protected by the ECC engine, and must
1047          * be at the beginning of the OOB area or running this driver on legacy
1048          * systems will prevent the discovery of the BBM/BBT.
1049          */
1050         if (nfc->use_dma) {
1051                 marvell_nfc_xfer_data_dma(nfc, DMA_FROM_DEVICE,
1052                                           lt->data_bytes + oob_bytes);
1053                 memcpy(data_buf, nfc->dma_buf, lt->data_bytes);
1054                 memcpy(oob_buf, nfc->dma_buf + lt->data_bytes, oob_bytes);
1055         } else {
1056                 marvell_nfc_xfer_data_in_pio(nfc, data_buf, lt->data_bytes);
1057                 marvell_nfc_xfer_data_in_pio(nfc, oob_buf, oob_bytes);
1058         }
1059
1060         ret = marvell_nfc_wait_cmdd(chip);
1061         return ret;
1062 }
1063
1064 static int marvell_nfc_hw_ecc_hmg_read_page_raw(struct nand_chip *chip, u8 *buf,
1065                                                 int oob_required, int page)
1066 {
1067         marvell_nfc_select_target(chip, chip->cur_cs);
1068         return marvell_nfc_hw_ecc_hmg_do_read_page(chip, buf, chip->oob_poi,
1069                                                    true, page);
1070 }
1071
1072 static int marvell_nfc_hw_ecc_hmg_read_page(struct nand_chip *chip, u8 *buf,
1073                                             int oob_required, int page)
1074 {
1075         const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1076         unsigned int full_sz = lt->data_bytes + lt->spare_bytes + lt->ecc_bytes;
1077         int max_bitflips = 0, ret;
1078         u8 *raw_buf;
1079
1080         marvell_nfc_select_target(chip, chip->cur_cs);
1081         marvell_nfc_enable_hw_ecc(chip);
1082         marvell_nfc_hw_ecc_hmg_do_read_page(chip, buf, chip->oob_poi, false,
1083                                             page);
1084         ret = marvell_nfc_hw_ecc_check_bitflips(chip, &max_bitflips);
1085         marvell_nfc_disable_hw_ecc(chip);
1086
1087         if (!ret)
1088                 return max_bitflips;
1089
1090         /*
1091          * When ECC failures are detected, check if the full page has been
1092          * written or not. Ignore the failure if it is actually empty.
1093          */
1094         raw_buf = kmalloc(full_sz, GFP_KERNEL);
1095         if (!raw_buf)
1096                 return -ENOMEM;
1097
1098         marvell_nfc_hw_ecc_hmg_do_read_page(chip, raw_buf, raw_buf +
1099                                             lt->data_bytes, true, page);
1100         marvell_nfc_check_empty_chunk(chip, raw_buf, full_sz, NULL, 0, NULL, 0,
1101                                       &max_bitflips);
1102         kfree(raw_buf);
1103
1104         return max_bitflips;
1105 }
1106
1107 /*
1108  * Spare area in Hamming layouts is not protected by the ECC engine (even if
1109  * it appears before the ECC bytes when reading), the ->read_oob_raw() function
1110  * also stands for ->read_oob().
1111  */
1112 static int marvell_nfc_hw_ecc_hmg_read_oob_raw(struct nand_chip *chip, int page)
1113 {
1114         u8 *buf = nand_get_data_buf(chip);
1115
1116         marvell_nfc_select_target(chip, chip->cur_cs);
1117         return marvell_nfc_hw_ecc_hmg_do_read_page(chip, buf, chip->oob_poi,
1118                                                    true, page);
1119 }
1120
1121 /* Hamming write helpers */
1122 static int marvell_nfc_hw_ecc_hmg_do_write_page(struct nand_chip *chip,
1123                                                 const u8 *data_buf,
1124                                                 const u8 *oob_buf, bool raw,
1125                                                 int page)
1126 {
1127         const struct nand_sdr_timings *sdr =
1128                 nand_get_sdr_timings(nand_get_interface_config(chip));
1129         struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
1130         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1131         const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1132         struct marvell_nfc_op nfc_op = {
1133                 .ndcb[0] = NDCB0_CMD_TYPE(TYPE_WRITE) |
1134                            NDCB0_ADDR_CYC(marvell_nand->addr_cyc) |
1135                            NDCB0_CMD1(NAND_CMD_SEQIN) |
1136                            NDCB0_CMD2(NAND_CMD_PAGEPROG) |
1137                            NDCB0_DBC,
1138                 .ndcb[1] = NDCB1_ADDRS_PAGE(page),
1139                 .ndcb[2] = NDCB2_ADDR5_PAGE(page),
1140         };
1141         unsigned int oob_bytes = lt->spare_bytes + (raw ? lt->ecc_bytes : 0);
1142         int ret;
1143
1144         /* NFCv2 needs more information about the operation being executed */
1145         if (nfc->caps->is_nfcv2)
1146                 nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_MONOLITHIC_RW);
1147
1148         ret = marvell_nfc_prepare_cmd(chip);
1149         if (ret)
1150                 return ret;
1151
1152         marvell_nfc_send_cmd(chip, &nfc_op);
1153         ret = marvell_nfc_end_cmd(chip, NDSR_WRDREQ,
1154                                   "WRDREQ while loading FIFO (data)");
1155         if (ret)
1156                 return ret;
1157
1158         /* Write the page then the OOB area */
1159         if (nfc->use_dma) {
1160                 memcpy(nfc->dma_buf, data_buf, lt->data_bytes);
1161                 memcpy(nfc->dma_buf + lt->data_bytes, oob_buf, oob_bytes);
1162                 marvell_nfc_xfer_data_dma(nfc, DMA_TO_DEVICE, lt->data_bytes +
1163                                           lt->ecc_bytes + lt->spare_bytes);
1164         } else {
1165                 marvell_nfc_xfer_data_out_pio(nfc, data_buf, lt->data_bytes);
1166                 marvell_nfc_xfer_data_out_pio(nfc, oob_buf, oob_bytes);
1167         }
1168
1169         ret = marvell_nfc_wait_cmdd(chip);
1170         if (ret)
1171                 return ret;
1172
1173         ret = marvell_nfc_wait_op(chip,
1174                                   PSEC_TO_MSEC(sdr->tPROG_max));
1175         return ret;
1176 }
1177
1178 static int marvell_nfc_hw_ecc_hmg_write_page_raw(struct nand_chip *chip,
1179                                                  const u8 *buf,
1180                                                  int oob_required, int page)
1181 {
1182         marvell_nfc_select_target(chip, chip->cur_cs);
1183         return marvell_nfc_hw_ecc_hmg_do_write_page(chip, buf, chip->oob_poi,
1184                                                     true, page);
1185 }
1186
1187 static int marvell_nfc_hw_ecc_hmg_write_page(struct nand_chip *chip,
1188                                              const u8 *buf,
1189                                              int oob_required, int page)
1190 {
1191         int ret;
1192
1193         marvell_nfc_select_target(chip, chip->cur_cs);
1194         marvell_nfc_enable_hw_ecc(chip);
1195         ret = marvell_nfc_hw_ecc_hmg_do_write_page(chip, buf, chip->oob_poi,
1196                                                    false, page);
1197         marvell_nfc_disable_hw_ecc(chip);
1198
1199         return ret;
1200 }
1201
1202 /*
1203  * Spare area in Hamming layouts is not protected by the ECC engine (even if
1204  * it appears before the ECC bytes when reading), the ->write_oob_raw() function
1205  * also stands for ->write_oob().
1206  */
1207 static int marvell_nfc_hw_ecc_hmg_write_oob_raw(struct nand_chip *chip,
1208                                                 int page)
1209 {
1210         struct mtd_info *mtd = nand_to_mtd(chip);
1211         u8 *buf = nand_get_data_buf(chip);
1212
1213         memset(buf, 0xFF, mtd->writesize);
1214
1215         marvell_nfc_select_target(chip, chip->cur_cs);
1216         return marvell_nfc_hw_ecc_hmg_do_write_page(chip, buf, chip->oob_poi,
1217                                                     true, page);
1218 }
1219
1220 /* BCH read helpers */
1221 static int marvell_nfc_hw_ecc_bch_read_page_raw(struct nand_chip *chip, u8 *buf,
1222                                                 int oob_required, int page)
1223 {
1224         struct mtd_info *mtd = nand_to_mtd(chip);
1225         const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1226         u8 *oob = chip->oob_poi;
1227         int chunk_size = lt->data_bytes + lt->spare_bytes + lt->ecc_bytes;
1228         int ecc_offset = (lt->full_chunk_cnt * lt->spare_bytes) +
1229                 lt->last_spare_bytes;
1230         int data_len = lt->data_bytes;
1231         int spare_len = lt->spare_bytes;
1232         int ecc_len = lt->ecc_bytes;
1233         int chunk;
1234
1235         marvell_nfc_select_target(chip, chip->cur_cs);
1236
1237         if (oob_required)
1238                 memset(chip->oob_poi, 0xFF, mtd->oobsize);
1239
1240         nand_read_page_op(chip, page, 0, NULL, 0);
1241
1242         for (chunk = 0; chunk < lt->nchunks; chunk++) {
1243                 /* Update last chunk length */
1244                 if (chunk >= lt->full_chunk_cnt) {
1245                         data_len = lt->last_data_bytes;
1246                         spare_len = lt->last_spare_bytes;
1247                         ecc_len = lt->last_ecc_bytes;
1248                 }
1249
1250                 /* Read data bytes*/
1251                 nand_change_read_column_op(chip, chunk * chunk_size,
1252                                            buf + (lt->data_bytes * chunk),
1253                                            data_len, false);
1254
1255                 /* Read spare bytes */
1256                 nand_read_data_op(chip, oob + (lt->spare_bytes * chunk),
1257                                   spare_len, false, false);
1258
1259                 /* Read ECC bytes */
1260                 nand_read_data_op(chip, oob + ecc_offset +
1261                                   (ALIGN(lt->ecc_bytes, 32) * chunk),
1262                                   ecc_len, false, false);
1263         }
1264
1265         return 0;
1266 }
1267
1268 static void marvell_nfc_hw_ecc_bch_read_chunk(struct nand_chip *chip, int chunk,
1269                                               u8 *data, unsigned int data_len,
1270                                               u8 *spare, unsigned int spare_len,
1271                                               int page)
1272 {
1273         struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
1274         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1275         const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1276         int i, ret;
1277         struct marvell_nfc_op nfc_op = {
1278                 .ndcb[0] = NDCB0_CMD_TYPE(TYPE_READ) |
1279                            NDCB0_ADDR_CYC(marvell_nand->addr_cyc) |
1280                            NDCB0_LEN_OVRD,
1281                 .ndcb[1] = NDCB1_ADDRS_PAGE(page),
1282                 .ndcb[2] = NDCB2_ADDR5_PAGE(page),
1283                 .ndcb[3] = data_len + spare_len,
1284         };
1285
1286         ret = marvell_nfc_prepare_cmd(chip);
1287         if (ret)
1288                 return;
1289
1290         if (chunk == 0)
1291                 nfc_op.ndcb[0] |= NDCB0_DBC |
1292                                   NDCB0_CMD1(NAND_CMD_READ0) |
1293                                   NDCB0_CMD2(NAND_CMD_READSTART);
1294
1295         /*
1296          * Trigger the monolithic read on the first chunk, then naked read on
1297          * intermediate chunks and finally a last naked read on the last chunk.
1298          */
1299         if (chunk == 0)
1300                 nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_MONOLITHIC_RW);
1301         else if (chunk < lt->nchunks - 1)
1302                 nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_NAKED_RW);
1303         else
1304                 nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_LAST_NAKED_RW);
1305
1306         marvell_nfc_send_cmd(chip, &nfc_op);
1307
1308         /*
1309          * According to the datasheet, when reading from NDDB
1310          * with BCH enabled, after each 32 bytes reads, we
1311          * have to make sure that the NDSR.RDDREQ bit is set.
1312          *
1313          * Drain the FIFO, 8 32-bit reads at a time, and skip
1314          * the polling on the last read.
1315          *
1316          * Length is a multiple of 32 bytes, hence it is a multiple of 8 too.
1317          */
1318         for (i = 0; i < data_len; i += FIFO_DEPTH * BCH_SEQ_READS) {
1319                 marvell_nfc_end_cmd(chip, NDSR_RDDREQ,
1320                                     "RDDREQ while draining FIFO (data)");
1321                 marvell_nfc_xfer_data_in_pio(nfc, data,
1322                                              FIFO_DEPTH * BCH_SEQ_READS);
1323                 data += FIFO_DEPTH * BCH_SEQ_READS;
1324         }
1325
1326         for (i = 0; i < spare_len; i += FIFO_DEPTH * BCH_SEQ_READS) {
1327                 marvell_nfc_end_cmd(chip, NDSR_RDDREQ,
1328                                     "RDDREQ while draining FIFO (OOB)");
1329                 marvell_nfc_xfer_data_in_pio(nfc, spare,
1330                                              FIFO_DEPTH * BCH_SEQ_READS);
1331                 spare += FIFO_DEPTH * BCH_SEQ_READS;
1332         }
1333 }
1334
1335 static int marvell_nfc_hw_ecc_bch_read_page(struct nand_chip *chip,
1336                                             u8 *buf, int oob_required,
1337                                             int page)
1338 {
1339         struct mtd_info *mtd = nand_to_mtd(chip);
1340         const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1341         int data_len = lt->data_bytes, spare_len = lt->spare_bytes;
1342         u8 *data = buf, *spare = chip->oob_poi;
1343         int max_bitflips = 0;
1344         u32 failure_mask = 0;
1345         int chunk, ret;
1346
1347         marvell_nfc_select_target(chip, chip->cur_cs);
1348
1349         /*
1350          * With BCH, OOB is not fully used (and thus not read entirely), not
1351          * expected bytes could show up at the end of the OOB buffer if not
1352          * explicitly erased.
1353          */
1354         if (oob_required)
1355                 memset(chip->oob_poi, 0xFF, mtd->oobsize);
1356
1357         marvell_nfc_enable_hw_ecc(chip);
1358
1359         for (chunk = 0; chunk < lt->nchunks; chunk++) {
1360                 /* Update length for the last chunk */
1361                 if (chunk >= lt->full_chunk_cnt) {
1362                         data_len = lt->last_data_bytes;
1363                         spare_len = lt->last_spare_bytes;
1364                 }
1365
1366                 /* Read the chunk and detect number of bitflips */
1367                 marvell_nfc_hw_ecc_bch_read_chunk(chip, chunk, data, data_len,
1368                                                   spare, spare_len, page);
1369                 ret = marvell_nfc_hw_ecc_check_bitflips(chip, &max_bitflips);
1370                 if (ret)
1371                         failure_mask |= BIT(chunk);
1372
1373                 data += data_len;
1374                 spare += spare_len;
1375         }
1376
1377         marvell_nfc_disable_hw_ecc(chip);
1378
1379         if (!failure_mask)
1380                 return max_bitflips;
1381
1382         /*
1383          * Please note that dumping the ECC bytes during a normal read with OOB
1384          * area would add a significant overhead as ECC bytes are "consumed" by
1385          * the controller in normal mode and must be re-read in raw mode. To
1386          * avoid dropping the performances, we prefer not to include them. The
1387          * user should re-read the page in raw mode if ECC bytes are required.
1388          */
1389
1390         /*
1391          * In case there is any subpage read error, we usually re-read only ECC
1392          * bytes in raw mode and check if the whole page is empty. In this case,
1393          * it is normal that the ECC check failed and we just ignore the error.
1394          *
1395          * However, it has been empirically observed that for some layouts (e.g
1396          * 2k page, 8b strength per 512B chunk), the controller tries to correct
1397          * bits and may create itself bitflips in the erased area. To overcome
1398          * this strange behavior, the whole page is re-read in raw mode, not
1399          * only the ECC bytes.
1400          */
1401         for (chunk = 0; chunk < lt->nchunks; chunk++) {
1402                 int data_off_in_page, spare_off_in_page, ecc_off_in_page;
1403                 int data_off, spare_off, ecc_off;
1404                 int data_len, spare_len, ecc_len;
1405
1406                 /* No failure reported for this chunk, move to the next one */
1407                 if (!(failure_mask & BIT(chunk)))
1408                         continue;
1409
1410                 data_off_in_page = chunk * (lt->data_bytes + lt->spare_bytes +
1411                                             lt->ecc_bytes);
1412                 spare_off_in_page = data_off_in_page +
1413                         (chunk < lt->full_chunk_cnt ? lt->data_bytes :
1414                                                       lt->last_data_bytes);
1415                 ecc_off_in_page = spare_off_in_page +
1416                         (chunk < lt->full_chunk_cnt ? lt->spare_bytes :
1417                                                       lt->last_spare_bytes);
1418
1419                 data_off = chunk * lt->data_bytes;
1420                 spare_off = chunk * lt->spare_bytes;
1421                 ecc_off = (lt->full_chunk_cnt * lt->spare_bytes) +
1422                           lt->last_spare_bytes +
1423                           (chunk * (lt->ecc_bytes + 2));
1424
1425                 data_len = chunk < lt->full_chunk_cnt ? lt->data_bytes :
1426                                                         lt->last_data_bytes;
1427                 spare_len = chunk < lt->full_chunk_cnt ? lt->spare_bytes :
1428                                                          lt->last_spare_bytes;
1429                 ecc_len = chunk < lt->full_chunk_cnt ? lt->ecc_bytes :
1430                                                        lt->last_ecc_bytes;
1431
1432                 /*
1433                  * Only re-read the ECC bytes, unless we are using the 2k/8b
1434                  * layout which is buggy in the sense that the ECC engine will
1435                  * try to correct data bytes anyway, creating bitflips. In this
1436                  * case, re-read the entire page.
1437                  */
1438                 if (lt->writesize == 2048 && lt->strength == 8) {
1439                         nand_change_read_column_op(chip, data_off_in_page,
1440                                                    buf + data_off, data_len,
1441                                                    false);
1442                         nand_change_read_column_op(chip, spare_off_in_page,
1443                                                    chip->oob_poi + spare_off, spare_len,
1444                                                    false);
1445                 }
1446
1447                 nand_change_read_column_op(chip, ecc_off_in_page,
1448                                            chip->oob_poi + ecc_off, ecc_len,
1449                                            false);
1450
1451                 /* Check the entire chunk (data + spare + ecc) for emptyness */
1452                 marvell_nfc_check_empty_chunk(chip, buf + data_off, data_len,
1453                                               chip->oob_poi + spare_off, spare_len,
1454                                               chip->oob_poi + ecc_off, ecc_len,
1455                                               &max_bitflips);
1456         }
1457
1458         return max_bitflips;
1459 }
1460
1461 static int marvell_nfc_hw_ecc_bch_read_oob_raw(struct nand_chip *chip, int page)
1462 {
1463         u8 *buf = nand_get_data_buf(chip);
1464
1465         return chip->ecc.read_page_raw(chip, buf, true, page);
1466 }
1467
1468 static int marvell_nfc_hw_ecc_bch_read_oob(struct nand_chip *chip, int page)
1469 {
1470         u8 *buf = nand_get_data_buf(chip);
1471
1472         return chip->ecc.read_page(chip, buf, true, page);
1473 }
1474
1475 /* BCH write helpers */
1476 static int marvell_nfc_hw_ecc_bch_write_page_raw(struct nand_chip *chip,
1477                                                  const u8 *buf,
1478                                                  int oob_required, int page)
1479 {
1480         const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1481         int full_chunk_size = lt->data_bytes + lt->spare_bytes + lt->ecc_bytes;
1482         int data_len = lt->data_bytes;
1483         int spare_len = lt->spare_bytes;
1484         int ecc_len = lt->ecc_bytes;
1485         int spare_offset = 0;
1486         int ecc_offset = (lt->full_chunk_cnt * lt->spare_bytes) +
1487                 lt->last_spare_bytes;
1488         int chunk;
1489
1490         marvell_nfc_select_target(chip, chip->cur_cs);
1491
1492         nand_prog_page_begin_op(chip, page, 0, NULL, 0);
1493
1494         for (chunk = 0; chunk < lt->nchunks; chunk++) {
1495                 if (chunk >= lt->full_chunk_cnt) {
1496                         data_len = lt->last_data_bytes;
1497                         spare_len = lt->last_spare_bytes;
1498                         ecc_len = lt->last_ecc_bytes;
1499                 }
1500
1501                 /* Point to the column of the next chunk */
1502                 nand_change_write_column_op(chip, chunk * full_chunk_size,
1503                                             NULL, 0, false);
1504
1505                 /* Write the data */
1506                 nand_write_data_op(chip, buf + (chunk * lt->data_bytes),
1507                                    data_len, false);
1508
1509                 if (!oob_required)
1510                         continue;
1511
1512                 /* Write the spare bytes */
1513                 if (spare_len)
1514                         nand_write_data_op(chip, chip->oob_poi + spare_offset,
1515                                            spare_len, false);
1516
1517                 /* Write the ECC bytes */
1518                 if (ecc_len)
1519                         nand_write_data_op(chip, chip->oob_poi + ecc_offset,
1520                                            ecc_len, false);
1521
1522                 spare_offset += spare_len;
1523                 ecc_offset += ALIGN(ecc_len, 32);
1524         }
1525
1526         return nand_prog_page_end_op(chip);
1527 }
1528
1529 static int
1530 marvell_nfc_hw_ecc_bch_write_chunk(struct nand_chip *chip, int chunk,
1531                                    const u8 *data, unsigned int data_len,
1532                                    const u8 *spare, unsigned int spare_len,
1533                                    int page)
1534 {
1535         struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
1536         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1537         const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1538         u32 xtype;
1539         int ret;
1540         struct marvell_nfc_op nfc_op = {
1541                 .ndcb[0] = NDCB0_CMD_TYPE(TYPE_WRITE) | NDCB0_LEN_OVRD,
1542                 .ndcb[3] = data_len + spare_len,
1543         };
1544
1545         /*
1546          * First operation dispatches the CMD_SEQIN command, issue the address
1547          * cycles and asks for the first chunk of data.
1548          * All operations in the middle (if any) will issue a naked write and
1549          * also ask for data.
1550          * Last operation (if any) asks for the last chunk of data through a
1551          * last naked write.
1552          */
1553         if (chunk == 0) {
1554                 if (lt->nchunks == 1)
1555                         xtype = XTYPE_MONOLITHIC_RW;
1556                 else
1557                         xtype = XTYPE_WRITE_DISPATCH;
1558
1559                 nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(xtype) |
1560                                   NDCB0_ADDR_CYC(marvell_nand->addr_cyc) |
1561                                   NDCB0_CMD1(NAND_CMD_SEQIN);
1562                 nfc_op.ndcb[1] |= NDCB1_ADDRS_PAGE(page);
1563                 nfc_op.ndcb[2] |= NDCB2_ADDR5_PAGE(page);
1564         } else if (chunk < lt->nchunks - 1) {
1565                 nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_NAKED_RW);
1566         } else {
1567                 nfc_op.ndcb[0] |= NDCB0_CMD_XTYPE(XTYPE_LAST_NAKED_RW);
1568         }
1569
1570         /* Always dispatch the PAGEPROG command on the last chunk */
1571         if (chunk == lt->nchunks - 1)
1572                 nfc_op.ndcb[0] |= NDCB0_CMD2(NAND_CMD_PAGEPROG) | NDCB0_DBC;
1573
1574         ret = marvell_nfc_prepare_cmd(chip);
1575         if (ret)
1576                 return ret;
1577
1578         marvell_nfc_send_cmd(chip, &nfc_op);
1579         ret = marvell_nfc_end_cmd(chip, NDSR_WRDREQ,
1580                                   "WRDREQ while loading FIFO (data)");
1581         if (ret)
1582                 return ret;
1583
1584         /* Transfer the contents */
1585         iowrite32_rep(nfc->regs + NDDB, data, FIFO_REP(data_len));
1586         iowrite32_rep(nfc->regs + NDDB, spare, FIFO_REP(spare_len));
1587
1588         return 0;
1589 }
1590
1591 static int marvell_nfc_hw_ecc_bch_write_page(struct nand_chip *chip,
1592                                              const u8 *buf,
1593                                              int oob_required, int page)
1594 {
1595         const struct nand_sdr_timings *sdr =
1596                 nand_get_sdr_timings(nand_get_interface_config(chip));
1597         struct mtd_info *mtd = nand_to_mtd(chip);
1598         const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
1599         const u8 *data = buf;
1600         const u8 *spare = chip->oob_poi;
1601         int data_len = lt->data_bytes;
1602         int spare_len = lt->spare_bytes;
1603         int chunk, ret;
1604
1605         marvell_nfc_select_target(chip, chip->cur_cs);
1606
1607         /* Spare data will be written anyway, so clear it to avoid garbage */
1608         if (!oob_required)
1609                 memset(chip->oob_poi, 0xFF, mtd->oobsize);
1610
1611         marvell_nfc_enable_hw_ecc(chip);
1612
1613         for (chunk = 0; chunk < lt->nchunks; chunk++) {
1614                 if (chunk >= lt->full_chunk_cnt) {
1615                         data_len = lt->last_data_bytes;
1616                         spare_len = lt->last_spare_bytes;
1617                 }
1618
1619                 marvell_nfc_hw_ecc_bch_write_chunk(chip, chunk, data, data_len,
1620                                                    spare, spare_len, page);
1621                 data += data_len;
1622                 spare += spare_len;
1623
1624                 /*
1625                  * Waiting only for CMDD or PAGED is not enough, ECC are
1626                  * partially written. No flag is set once the operation is
1627                  * really finished but the ND_RUN bit is cleared, so wait for it
1628                  * before stepping into the next command.
1629                  */
1630                 marvell_nfc_wait_ndrun(chip);
1631         }
1632
1633         ret = marvell_nfc_wait_op(chip, PSEC_TO_MSEC(sdr->tPROG_max));
1634
1635         marvell_nfc_disable_hw_ecc(chip);
1636
1637         if (ret)
1638                 return ret;
1639
1640         return 0;
1641 }
1642
1643 static int marvell_nfc_hw_ecc_bch_write_oob_raw(struct nand_chip *chip,
1644                                                 int page)
1645 {
1646         struct mtd_info *mtd = nand_to_mtd(chip);
1647         u8 *buf = nand_get_data_buf(chip);
1648
1649         memset(buf, 0xFF, mtd->writesize);
1650
1651         return chip->ecc.write_page_raw(chip, buf, true, page);
1652 }
1653
1654 static int marvell_nfc_hw_ecc_bch_write_oob(struct nand_chip *chip, int page)
1655 {
1656         struct mtd_info *mtd = nand_to_mtd(chip);
1657         u8 *buf = nand_get_data_buf(chip);
1658
1659         memset(buf, 0xFF, mtd->writesize);
1660
1661         return chip->ecc.write_page(chip, buf, true, page);
1662 }
1663
1664 /* NAND framework ->exec_op() hooks and related helpers */
1665 static void marvell_nfc_parse_instructions(struct nand_chip *chip,
1666                                            const struct nand_subop *subop,
1667                                            struct marvell_nfc_op *nfc_op)
1668 {
1669         const struct nand_op_instr *instr = NULL;
1670         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1671         bool first_cmd = true;
1672         unsigned int op_id;
1673         int i;
1674
1675         /* Reset the input structure as most of its fields will be OR'ed */
1676         memset(nfc_op, 0, sizeof(struct marvell_nfc_op));
1677
1678         for (op_id = 0; op_id < subop->ninstrs; op_id++) {
1679                 unsigned int offset, naddrs;
1680                 const u8 *addrs;
1681                 int len;
1682
1683                 instr = &subop->instrs[op_id];
1684
1685                 switch (instr->type) {
1686                 case NAND_OP_CMD_INSTR:
1687                         if (first_cmd)
1688                                 nfc_op->ndcb[0] |=
1689                                         NDCB0_CMD1(instr->ctx.cmd.opcode);
1690                         else
1691                                 nfc_op->ndcb[0] |=
1692                                         NDCB0_CMD2(instr->ctx.cmd.opcode) |
1693                                         NDCB0_DBC;
1694
1695                         nfc_op->cle_ale_delay_ns = instr->delay_ns;
1696                         first_cmd = false;
1697                         break;
1698
1699                 case NAND_OP_ADDR_INSTR:
1700                         offset = nand_subop_get_addr_start_off(subop, op_id);
1701                         naddrs = nand_subop_get_num_addr_cyc(subop, op_id);
1702                         addrs = &instr->ctx.addr.addrs[offset];
1703
1704                         nfc_op->ndcb[0] |= NDCB0_ADDR_CYC(naddrs);
1705
1706                         for (i = 0; i < min_t(unsigned int, 4, naddrs); i++)
1707                                 nfc_op->ndcb[1] |= addrs[i] << (8 * i);
1708
1709                         if (naddrs >= 5)
1710                                 nfc_op->ndcb[2] |= NDCB2_ADDR5_CYC(addrs[4]);
1711                         if (naddrs >= 6)
1712                                 nfc_op->ndcb[3] |= NDCB3_ADDR6_CYC(addrs[5]);
1713                         if (naddrs == 7)
1714                                 nfc_op->ndcb[3] |= NDCB3_ADDR7_CYC(addrs[6]);
1715
1716                         nfc_op->cle_ale_delay_ns = instr->delay_ns;
1717                         break;
1718
1719                 case NAND_OP_DATA_IN_INSTR:
1720                         nfc_op->data_instr = instr;
1721                         nfc_op->data_instr_idx = op_id;
1722                         nfc_op->ndcb[0] |= NDCB0_CMD_TYPE(TYPE_READ);
1723                         if (nfc->caps->is_nfcv2) {
1724                                 nfc_op->ndcb[0] |=
1725                                         NDCB0_CMD_XTYPE(XTYPE_MONOLITHIC_RW) |
1726                                         NDCB0_LEN_OVRD;
1727                                 len = nand_subop_get_data_len(subop, op_id);
1728                                 nfc_op->ndcb[3] |= round_up(len, FIFO_DEPTH);
1729                         }
1730                         nfc_op->data_delay_ns = instr->delay_ns;
1731                         break;
1732
1733                 case NAND_OP_DATA_OUT_INSTR:
1734                         nfc_op->data_instr = instr;
1735                         nfc_op->data_instr_idx = op_id;
1736                         nfc_op->ndcb[0] |= NDCB0_CMD_TYPE(TYPE_WRITE);
1737                         if (nfc->caps->is_nfcv2) {
1738                                 nfc_op->ndcb[0] |=
1739                                         NDCB0_CMD_XTYPE(XTYPE_MONOLITHIC_RW) |
1740                                         NDCB0_LEN_OVRD;
1741                                 len = nand_subop_get_data_len(subop, op_id);
1742                                 nfc_op->ndcb[3] |= round_up(len, FIFO_DEPTH);
1743                         }
1744                         nfc_op->data_delay_ns = instr->delay_ns;
1745                         break;
1746
1747                 case NAND_OP_WAITRDY_INSTR:
1748                         nfc_op->rdy_timeout_ms = instr->ctx.waitrdy.timeout_ms;
1749                         nfc_op->rdy_delay_ns = instr->delay_ns;
1750                         break;
1751                 }
1752         }
1753 }
1754
1755 static int marvell_nfc_xfer_data_pio(struct nand_chip *chip,
1756                                      const struct nand_subop *subop,
1757                                      struct marvell_nfc_op *nfc_op)
1758 {
1759         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1760         const struct nand_op_instr *instr = nfc_op->data_instr;
1761         unsigned int op_id = nfc_op->data_instr_idx;
1762         unsigned int len = nand_subop_get_data_len(subop, op_id);
1763         unsigned int offset = nand_subop_get_data_start_off(subop, op_id);
1764         bool reading = (instr->type == NAND_OP_DATA_IN_INSTR);
1765         int ret;
1766
1767         if (instr->ctx.data.force_8bit)
1768                 marvell_nfc_force_byte_access(chip, true);
1769
1770         if (reading) {
1771                 u8 *in = instr->ctx.data.buf.in + offset;
1772
1773                 ret = marvell_nfc_xfer_data_in_pio(nfc, in, len);
1774         } else {
1775                 const u8 *out = instr->ctx.data.buf.out + offset;
1776
1777                 ret = marvell_nfc_xfer_data_out_pio(nfc, out, len);
1778         }
1779
1780         if (instr->ctx.data.force_8bit)
1781                 marvell_nfc_force_byte_access(chip, false);
1782
1783         return ret;
1784 }
1785
1786 static int marvell_nfc_monolithic_access_exec(struct nand_chip *chip,
1787                                               const struct nand_subop *subop)
1788 {
1789         struct marvell_nfc_op nfc_op;
1790         bool reading;
1791         int ret;
1792
1793         marvell_nfc_parse_instructions(chip, subop, &nfc_op);
1794         reading = (nfc_op.data_instr->type == NAND_OP_DATA_IN_INSTR);
1795
1796         ret = marvell_nfc_prepare_cmd(chip);
1797         if (ret)
1798                 return ret;
1799
1800         marvell_nfc_send_cmd(chip, &nfc_op);
1801         ret = marvell_nfc_end_cmd(chip, NDSR_RDDREQ | NDSR_WRDREQ,
1802                                   "RDDREQ/WRDREQ while draining raw data");
1803         if (ret)
1804                 return ret;
1805
1806         cond_delay(nfc_op.cle_ale_delay_ns);
1807
1808         if (reading) {
1809                 if (nfc_op.rdy_timeout_ms) {
1810                         ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
1811                         if (ret)
1812                                 return ret;
1813                 }
1814
1815                 cond_delay(nfc_op.rdy_delay_ns);
1816         }
1817
1818         marvell_nfc_xfer_data_pio(chip, subop, &nfc_op);
1819         ret = marvell_nfc_wait_cmdd(chip);
1820         if (ret)
1821                 return ret;
1822
1823         cond_delay(nfc_op.data_delay_ns);
1824
1825         if (!reading) {
1826                 if (nfc_op.rdy_timeout_ms) {
1827                         ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
1828                         if (ret)
1829                                 return ret;
1830                 }
1831
1832                 cond_delay(nfc_op.rdy_delay_ns);
1833         }
1834
1835         /*
1836          * NDCR ND_RUN bit should be cleared automatically at the end of each
1837          * operation but experience shows that the behavior is buggy when it
1838          * comes to writes (with LEN_OVRD). Clear it by hand in this case.
1839          */
1840         if (!reading) {
1841                 struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1842
1843                 writel_relaxed(readl(nfc->regs + NDCR) & ~NDCR_ND_RUN,
1844                                nfc->regs + NDCR);
1845         }
1846
1847         return 0;
1848 }
1849
1850 static int marvell_nfc_naked_access_exec(struct nand_chip *chip,
1851                                          const struct nand_subop *subop)
1852 {
1853         struct marvell_nfc_op nfc_op;
1854         int ret;
1855
1856         marvell_nfc_parse_instructions(chip, subop, &nfc_op);
1857
1858         /*
1859          * Naked access are different in that they need to be flagged as naked
1860          * by the controller. Reset the controller registers fields that inform
1861          * on the type and refill them according to the ongoing operation.
1862          */
1863         nfc_op.ndcb[0] &= ~(NDCB0_CMD_TYPE(TYPE_MASK) |
1864                             NDCB0_CMD_XTYPE(XTYPE_MASK));
1865         switch (subop->instrs[0].type) {
1866         case NAND_OP_CMD_INSTR:
1867                 nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_NAKED_CMD);
1868                 break;
1869         case NAND_OP_ADDR_INSTR:
1870                 nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_NAKED_ADDR);
1871                 break;
1872         case NAND_OP_DATA_IN_INSTR:
1873                 nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_READ) |
1874                                   NDCB0_CMD_XTYPE(XTYPE_LAST_NAKED_RW);
1875                 break;
1876         case NAND_OP_DATA_OUT_INSTR:
1877                 nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_WRITE) |
1878                                   NDCB0_CMD_XTYPE(XTYPE_LAST_NAKED_RW);
1879                 break;
1880         default:
1881                 /* This should never happen */
1882                 break;
1883         }
1884
1885         ret = marvell_nfc_prepare_cmd(chip);
1886         if (ret)
1887                 return ret;
1888
1889         marvell_nfc_send_cmd(chip, &nfc_op);
1890
1891         if (!nfc_op.data_instr) {
1892                 ret = marvell_nfc_wait_cmdd(chip);
1893                 cond_delay(nfc_op.cle_ale_delay_ns);
1894                 return ret;
1895         }
1896
1897         ret = marvell_nfc_end_cmd(chip, NDSR_RDDREQ | NDSR_WRDREQ,
1898                                   "RDDREQ/WRDREQ while draining raw data");
1899         if (ret)
1900                 return ret;
1901
1902         marvell_nfc_xfer_data_pio(chip, subop, &nfc_op);
1903         ret = marvell_nfc_wait_cmdd(chip);
1904         if (ret)
1905                 return ret;
1906
1907         /*
1908          * NDCR ND_RUN bit should be cleared automatically at the end of each
1909          * operation but experience shows that the behavior is buggy when it
1910          * comes to writes (with LEN_OVRD). Clear it by hand in this case.
1911          */
1912         if (subop->instrs[0].type == NAND_OP_DATA_OUT_INSTR) {
1913                 struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
1914
1915                 writel_relaxed(readl(nfc->regs + NDCR) & ~NDCR_ND_RUN,
1916                                nfc->regs + NDCR);
1917         }
1918
1919         return 0;
1920 }
1921
1922 static int marvell_nfc_naked_waitrdy_exec(struct nand_chip *chip,
1923                                           const struct nand_subop *subop)
1924 {
1925         struct marvell_nfc_op nfc_op;
1926         int ret;
1927
1928         marvell_nfc_parse_instructions(chip, subop, &nfc_op);
1929
1930         ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
1931         cond_delay(nfc_op.rdy_delay_ns);
1932
1933         return ret;
1934 }
1935
1936 static int marvell_nfc_read_id_type_exec(struct nand_chip *chip,
1937                                          const struct nand_subop *subop)
1938 {
1939         struct marvell_nfc_op nfc_op;
1940         int ret;
1941
1942         marvell_nfc_parse_instructions(chip, subop, &nfc_op);
1943         nfc_op.ndcb[0] &= ~NDCB0_CMD_TYPE(TYPE_READ);
1944         nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_READ_ID);
1945
1946         ret = marvell_nfc_prepare_cmd(chip);
1947         if (ret)
1948                 return ret;
1949
1950         marvell_nfc_send_cmd(chip, &nfc_op);
1951         ret = marvell_nfc_end_cmd(chip, NDSR_RDDREQ,
1952                                   "RDDREQ while reading ID");
1953         if (ret)
1954                 return ret;
1955
1956         cond_delay(nfc_op.cle_ale_delay_ns);
1957
1958         if (nfc_op.rdy_timeout_ms) {
1959                 ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
1960                 if (ret)
1961                         return ret;
1962         }
1963
1964         cond_delay(nfc_op.rdy_delay_ns);
1965
1966         marvell_nfc_xfer_data_pio(chip, subop, &nfc_op);
1967         ret = marvell_nfc_wait_cmdd(chip);
1968         if (ret)
1969                 return ret;
1970
1971         cond_delay(nfc_op.data_delay_ns);
1972
1973         return 0;
1974 }
1975
1976 static int marvell_nfc_read_status_exec(struct nand_chip *chip,
1977                                         const struct nand_subop *subop)
1978 {
1979         struct marvell_nfc_op nfc_op;
1980         int ret;
1981
1982         marvell_nfc_parse_instructions(chip, subop, &nfc_op);
1983         nfc_op.ndcb[0] &= ~NDCB0_CMD_TYPE(TYPE_READ);
1984         nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_STATUS);
1985
1986         ret = marvell_nfc_prepare_cmd(chip);
1987         if (ret)
1988                 return ret;
1989
1990         marvell_nfc_send_cmd(chip, &nfc_op);
1991         ret = marvell_nfc_end_cmd(chip, NDSR_RDDREQ,
1992                                   "RDDREQ while reading status");
1993         if (ret)
1994                 return ret;
1995
1996         cond_delay(nfc_op.cle_ale_delay_ns);
1997
1998         if (nfc_op.rdy_timeout_ms) {
1999                 ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
2000                 if (ret)
2001                         return ret;
2002         }
2003
2004         cond_delay(nfc_op.rdy_delay_ns);
2005
2006         marvell_nfc_xfer_data_pio(chip, subop, &nfc_op);
2007         ret = marvell_nfc_wait_cmdd(chip);
2008         if (ret)
2009                 return ret;
2010
2011         cond_delay(nfc_op.data_delay_ns);
2012
2013         return 0;
2014 }
2015
2016 static int marvell_nfc_reset_cmd_type_exec(struct nand_chip *chip,
2017                                            const struct nand_subop *subop)
2018 {
2019         struct marvell_nfc_op nfc_op;
2020         int ret;
2021
2022         marvell_nfc_parse_instructions(chip, subop, &nfc_op);
2023         nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_RESET);
2024
2025         ret = marvell_nfc_prepare_cmd(chip);
2026         if (ret)
2027                 return ret;
2028
2029         marvell_nfc_send_cmd(chip, &nfc_op);
2030         ret = marvell_nfc_wait_cmdd(chip);
2031         if (ret)
2032                 return ret;
2033
2034         cond_delay(nfc_op.cle_ale_delay_ns);
2035
2036         ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
2037         if (ret)
2038                 return ret;
2039
2040         cond_delay(nfc_op.rdy_delay_ns);
2041
2042         return 0;
2043 }
2044
2045 static int marvell_nfc_erase_cmd_type_exec(struct nand_chip *chip,
2046                                            const struct nand_subop *subop)
2047 {
2048         struct marvell_nfc_op nfc_op;
2049         int ret;
2050
2051         marvell_nfc_parse_instructions(chip, subop, &nfc_op);
2052         nfc_op.ndcb[0] |= NDCB0_CMD_TYPE(TYPE_ERASE);
2053
2054         ret = marvell_nfc_prepare_cmd(chip);
2055         if (ret)
2056                 return ret;
2057
2058         marvell_nfc_send_cmd(chip, &nfc_op);
2059         ret = marvell_nfc_wait_cmdd(chip);
2060         if (ret)
2061                 return ret;
2062
2063         cond_delay(nfc_op.cle_ale_delay_ns);
2064
2065         ret = marvell_nfc_wait_op(chip, nfc_op.rdy_timeout_ms);
2066         if (ret)
2067                 return ret;
2068
2069         cond_delay(nfc_op.rdy_delay_ns);
2070
2071         return 0;
2072 }
2073
2074 static const struct nand_op_parser marvell_nfcv2_op_parser = NAND_OP_PARSER(
2075         /* Monolithic reads/writes */
2076         NAND_OP_PARSER_PATTERN(
2077                 marvell_nfc_monolithic_access_exec,
2078                 NAND_OP_PARSER_PAT_CMD_ELEM(false),
2079                 NAND_OP_PARSER_PAT_ADDR_ELEM(true, MAX_ADDRESS_CYC_NFCV2),
2080                 NAND_OP_PARSER_PAT_CMD_ELEM(true),
2081                 NAND_OP_PARSER_PAT_WAITRDY_ELEM(true),
2082                 NAND_OP_PARSER_PAT_DATA_IN_ELEM(false, MAX_CHUNK_SIZE)),
2083         NAND_OP_PARSER_PATTERN(
2084                 marvell_nfc_monolithic_access_exec,
2085                 NAND_OP_PARSER_PAT_CMD_ELEM(false),
2086                 NAND_OP_PARSER_PAT_ADDR_ELEM(false, MAX_ADDRESS_CYC_NFCV2),
2087                 NAND_OP_PARSER_PAT_DATA_OUT_ELEM(false, MAX_CHUNK_SIZE),
2088                 NAND_OP_PARSER_PAT_CMD_ELEM(true),
2089                 NAND_OP_PARSER_PAT_WAITRDY_ELEM(true)),
2090         /* Naked commands */
2091         NAND_OP_PARSER_PATTERN(
2092                 marvell_nfc_naked_access_exec,
2093                 NAND_OP_PARSER_PAT_CMD_ELEM(false)),
2094         NAND_OP_PARSER_PATTERN(
2095                 marvell_nfc_naked_access_exec,
2096                 NAND_OP_PARSER_PAT_ADDR_ELEM(false, MAX_ADDRESS_CYC_NFCV2)),
2097         NAND_OP_PARSER_PATTERN(
2098                 marvell_nfc_naked_access_exec,
2099                 NAND_OP_PARSER_PAT_DATA_IN_ELEM(false, MAX_CHUNK_SIZE)),
2100         NAND_OP_PARSER_PATTERN(
2101                 marvell_nfc_naked_access_exec,
2102                 NAND_OP_PARSER_PAT_DATA_OUT_ELEM(false, MAX_CHUNK_SIZE)),
2103         NAND_OP_PARSER_PATTERN(
2104                 marvell_nfc_naked_waitrdy_exec,
2105                 NAND_OP_PARSER_PAT_WAITRDY_ELEM(false)),
2106         );
2107
2108 static const struct nand_op_parser marvell_nfcv1_op_parser = NAND_OP_PARSER(
2109         /* Naked commands not supported, use a function for each pattern */
2110         NAND_OP_PARSER_PATTERN(
2111                 marvell_nfc_read_id_type_exec,
2112                 NAND_OP_PARSER_PAT_CMD_ELEM(false),
2113                 NAND_OP_PARSER_PAT_ADDR_ELEM(false, MAX_ADDRESS_CYC_NFCV1),
2114                 NAND_OP_PARSER_PAT_DATA_IN_ELEM(false, 8)),
2115         NAND_OP_PARSER_PATTERN(
2116                 marvell_nfc_erase_cmd_type_exec,
2117                 NAND_OP_PARSER_PAT_CMD_ELEM(false),
2118                 NAND_OP_PARSER_PAT_ADDR_ELEM(false, MAX_ADDRESS_CYC_NFCV1),
2119                 NAND_OP_PARSER_PAT_CMD_ELEM(false),
2120                 NAND_OP_PARSER_PAT_WAITRDY_ELEM(false)),
2121         NAND_OP_PARSER_PATTERN(
2122                 marvell_nfc_read_status_exec,
2123                 NAND_OP_PARSER_PAT_CMD_ELEM(false),
2124                 NAND_OP_PARSER_PAT_DATA_IN_ELEM(false, 1)),
2125         NAND_OP_PARSER_PATTERN(
2126                 marvell_nfc_reset_cmd_type_exec,
2127                 NAND_OP_PARSER_PAT_CMD_ELEM(false),
2128                 NAND_OP_PARSER_PAT_WAITRDY_ELEM(false)),
2129         NAND_OP_PARSER_PATTERN(
2130                 marvell_nfc_naked_waitrdy_exec,
2131                 NAND_OP_PARSER_PAT_WAITRDY_ELEM(false)),
2132         );
2133
2134 static int marvell_nfc_exec_op(struct nand_chip *chip,
2135                                const struct nand_operation *op,
2136                                bool check_only)
2137 {
2138         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
2139
2140         if (!check_only)
2141                 marvell_nfc_select_target(chip, op->cs);
2142
2143         if (nfc->caps->is_nfcv2)
2144                 return nand_op_parser_exec_op(chip, &marvell_nfcv2_op_parser,
2145                                               op, check_only);
2146         else
2147                 return nand_op_parser_exec_op(chip, &marvell_nfcv1_op_parser,
2148                                               op, check_only);
2149 }
2150
2151 /*
2152  * Layouts were broken in old pxa3xx_nand driver, these are supposed to be
2153  * usable.
2154  */
2155 static int marvell_nand_ooblayout_ecc(struct mtd_info *mtd, int section,
2156                                       struct mtd_oob_region *oobregion)
2157 {
2158         struct nand_chip *chip = mtd_to_nand(mtd);
2159         const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
2160
2161         if (section)
2162                 return -ERANGE;
2163
2164         oobregion->length = (lt->full_chunk_cnt * lt->ecc_bytes) +
2165                             lt->last_ecc_bytes;
2166         oobregion->offset = mtd->oobsize - oobregion->length;
2167
2168         return 0;
2169 }
2170
2171 static int marvell_nand_ooblayout_free(struct mtd_info *mtd, int section,
2172                                        struct mtd_oob_region *oobregion)
2173 {
2174         struct nand_chip *chip = mtd_to_nand(mtd);
2175         const struct marvell_hw_ecc_layout *lt = to_marvell_nand(chip)->layout;
2176
2177         if (section)
2178                 return -ERANGE;
2179
2180         /*
2181          * Bootrom looks in bytes 0 & 5 for bad blocks for the
2182          * 4KB page / 4bit BCH combination.
2183          */
2184         if (mtd->writesize == SZ_4K && lt->data_bytes == SZ_2K)
2185                 oobregion->offset = 6;
2186         else
2187                 oobregion->offset = 2;
2188
2189         oobregion->length = (lt->full_chunk_cnt * lt->spare_bytes) +
2190                             lt->last_spare_bytes - oobregion->offset;
2191
2192         return 0;
2193 }
2194
2195 static const struct mtd_ooblayout_ops marvell_nand_ooblayout_ops = {
2196         .ecc = marvell_nand_ooblayout_ecc,
2197         .free = marvell_nand_ooblayout_free,
2198 };
2199
2200 static int marvell_nand_hw_ecc_controller_init(struct mtd_info *mtd,
2201                                                struct nand_ecc_ctrl *ecc)
2202 {
2203         struct nand_chip *chip = mtd_to_nand(mtd);
2204         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
2205         const struct marvell_hw_ecc_layout *l;
2206         int i;
2207
2208         if (!nfc->caps->is_nfcv2 &&
2209             (mtd->writesize + mtd->oobsize > MAX_CHUNK_SIZE)) {
2210                 dev_err(nfc->dev,
2211                         "NFCv1: writesize (%d) cannot be bigger than a chunk (%d)\n",
2212                         mtd->writesize, MAX_CHUNK_SIZE - mtd->oobsize);
2213                 return -ENOTSUPP;
2214         }
2215
2216         to_marvell_nand(chip)->layout = NULL;
2217         for (i = 0; i < ARRAY_SIZE(marvell_nfc_layouts); i++) {
2218                 l = &marvell_nfc_layouts[i];
2219                 if (mtd->writesize == l->writesize &&
2220                     ecc->size == l->chunk && ecc->strength == l->strength) {
2221                         to_marvell_nand(chip)->layout = l;
2222                         break;
2223                 }
2224         }
2225
2226         if (!to_marvell_nand(chip)->layout ||
2227             (!nfc->caps->is_nfcv2 && ecc->strength > 1)) {
2228                 dev_err(nfc->dev,
2229                         "ECC strength %d at page size %d is not supported\n",
2230                         ecc->strength, mtd->writesize);
2231                 return -ENOTSUPP;
2232         }
2233
2234         /* Special care for the layout 2k/8-bit/512B  */
2235         if (l->writesize == 2048 && l->strength == 8) {
2236                 if (mtd->oobsize < 128) {
2237                         dev_err(nfc->dev, "Requested layout needs at least 128 OOB bytes\n");
2238                         return -ENOTSUPP;
2239                 } else {
2240                         chip->bbt_options |= NAND_BBT_NO_OOB_BBM;
2241                 }
2242         }
2243
2244         mtd_set_ooblayout(mtd, &marvell_nand_ooblayout_ops);
2245         ecc->steps = l->nchunks;
2246         ecc->size = l->data_bytes;
2247
2248         if (ecc->strength == 1) {
2249                 chip->ecc.algo = NAND_ECC_ALGO_HAMMING;
2250                 ecc->read_page_raw = marvell_nfc_hw_ecc_hmg_read_page_raw;
2251                 ecc->read_page = marvell_nfc_hw_ecc_hmg_read_page;
2252                 ecc->read_oob_raw = marvell_nfc_hw_ecc_hmg_read_oob_raw;
2253                 ecc->read_oob = ecc->read_oob_raw;
2254                 ecc->write_page_raw = marvell_nfc_hw_ecc_hmg_write_page_raw;
2255                 ecc->write_page = marvell_nfc_hw_ecc_hmg_write_page;
2256                 ecc->write_oob_raw = marvell_nfc_hw_ecc_hmg_write_oob_raw;
2257                 ecc->write_oob = ecc->write_oob_raw;
2258         } else {
2259                 chip->ecc.algo = NAND_ECC_ALGO_BCH;
2260                 ecc->strength = 16;
2261                 ecc->read_page_raw = marvell_nfc_hw_ecc_bch_read_page_raw;
2262                 ecc->read_page = marvell_nfc_hw_ecc_bch_read_page;
2263                 ecc->read_oob_raw = marvell_nfc_hw_ecc_bch_read_oob_raw;
2264                 ecc->read_oob = marvell_nfc_hw_ecc_bch_read_oob;
2265                 ecc->write_page_raw = marvell_nfc_hw_ecc_bch_write_page_raw;
2266                 ecc->write_page = marvell_nfc_hw_ecc_bch_write_page;
2267                 ecc->write_oob_raw = marvell_nfc_hw_ecc_bch_write_oob_raw;
2268                 ecc->write_oob = marvell_nfc_hw_ecc_bch_write_oob;
2269         }
2270
2271         return 0;
2272 }
2273
2274 static int marvell_nand_ecc_init(struct mtd_info *mtd,
2275                                  struct nand_ecc_ctrl *ecc)
2276 {
2277         struct nand_chip *chip = mtd_to_nand(mtd);
2278         const struct nand_ecc_props *requirements =
2279                 nanddev_get_ecc_requirements(&chip->base);
2280         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
2281         int ret;
2282
2283         if (ecc->engine_type != NAND_ECC_ENGINE_TYPE_NONE &&
2284             (!ecc->size || !ecc->strength)) {
2285                 if (requirements->step_size && requirements->strength) {
2286                         ecc->size = requirements->step_size;
2287                         ecc->strength = requirements->strength;
2288                 } else {
2289                         dev_info(nfc->dev,
2290                                  "No minimum ECC strength, using 1b/512B\n");
2291                         ecc->size = 512;
2292                         ecc->strength = 1;
2293                 }
2294         }
2295
2296         switch (ecc->engine_type) {
2297         case NAND_ECC_ENGINE_TYPE_ON_HOST:
2298                 ret = marvell_nand_hw_ecc_controller_init(mtd, ecc);
2299                 if (ret)
2300                         return ret;
2301                 break;
2302         case NAND_ECC_ENGINE_TYPE_NONE:
2303         case NAND_ECC_ENGINE_TYPE_SOFT:
2304         case NAND_ECC_ENGINE_TYPE_ON_DIE:
2305                 if (!nfc->caps->is_nfcv2 && mtd->writesize != SZ_512 &&
2306                     mtd->writesize != SZ_2K) {
2307                         dev_err(nfc->dev, "NFCv1 cannot write %d bytes pages\n",
2308                                 mtd->writesize);
2309                         return -EINVAL;
2310                 }
2311                 break;
2312         default:
2313                 return -EINVAL;
2314         }
2315
2316         return 0;
2317 }
2318
2319 static u8 bbt_pattern[] = {'M', 'V', 'B', 'b', 't', '0' };
2320 static u8 bbt_mirror_pattern[] = {'1', 't', 'b', 'B', 'V', 'M' };
2321
2322 static struct nand_bbt_descr bbt_main_descr = {
2323         .options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE |
2324                    NAND_BBT_2BIT | NAND_BBT_VERSION,
2325         .offs = 8,
2326         .len = 6,
2327         .veroffs = 14,
2328         .maxblocks = 8, /* Last 8 blocks in each chip */
2329         .pattern = bbt_pattern
2330 };
2331
2332 static struct nand_bbt_descr bbt_mirror_descr = {
2333         .options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE |
2334                    NAND_BBT_2BIT | NAND_BBT_VERSION,
2335         .offs = 8,
2336         .len = 6,
2337         .veroffs = 14,
2338         .maxblocks = 8, /* Last 8 blocks in each chip */
2339         .pattern = bbt_mirror_pattern
2340 };
2341
2342 static int marvell_nfc_setup_interface(struct nand_chip *chip, int chipnr,
2343                                        const struct nand_interface_config *conf)
2344 {
2345         struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
2346         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
2347         unsigned int period_ns = 1000000000 / clk_get_rate(nfc->core_clk) * 2;
2348         const struct nand_sdr_timings *sdr;
2349         struct marvell_nfc_timings nfc_tmg;
2350         int read_delay;
2351
2352         sdr = nand_get_sdr_timings(conf);
2353         if (IS_ERR(sdr))
2354                 return PTR_ERR(sdr);
2355
2356         /*
2357          * SDR timings are given in pico-seconds while NFC timings must be
2358          * expressed in NAND controller clock cycles, which is half of the
2359          * frequency of the accessible ECC clock retrieved by clk_get_rate().
2360          * This is not written anywhere in the datasheet but was observed
2361          * with an oscilloscope.
2362          *
2363          * NFC datasheet gives equations from which thoses calculations
2364          * are derived, they tend to be slightly more restrictives than the
2365          * given core timings and may improve the overall speed.
2366          */
2367         nfc_tmg.tRP = TO_CYCLES(DIV_ROUND_UP(sdr->tRC_min, 2), period_ns) - 1;
2368         nfc_tmg.tRH = nfc_tmg.tRP;
2369         nfc_tmg.tWP = TO_CYCLES(DIV_ROUND_UP(sdr->tWC_min, 2), period_ns) - 1;
2370         nfc_tmg.tWH = nfc_tmg.tWP;
2371         nfc_tmg.tCS = TO_CYCLES(sdr->tCS_min, period_ns);
2372         nfc_tmg.tCH = TO_CYCLES(sdr->tCH_min, period_ns) - 1;
2373         nfc_tmg.tADL = TO_CYCLES(sdr->tADL_min, period_ns);
2374         /*
2375          * Read delay is the time of propagation from SoC pins to NFC internal
2376          * logic. With non-EDO timings, this is MIN_RD_DEL_CNT clock cycles. In
2377          * EDO mode, an additional delay of tRH must be taken into account so
2378          * the data is sampled on the falling edge instead of the rising edge.
2379          */
2380         read_delay = sdr->tRC_min >= 30000 ?
2381                 MIN_RD_DEL_CNT : MIN_RD_DEL_CNT + nfc_tmg.tRH;
2382
2383         nfc_tmg.tAR = TO_CYCLES(sdr->tAR_min, period_ns);
2384         /*
2385          * tWHR and tRHW are supposed to be read to write delays (and vice
2386          * versa) but in some cases, ie. when doing a change column, they must
2387          * be greater than that to be sure tCCS delay is respected.
2388          */
2389         nfc_tmg.tWHR = TO_CYCLES(max_t(int, sdr->tWHR_min, sdr->tCCS_min),
2390                                  period_ns) - 2,
2391         nfc_tmg.tRHW = TO_CYCLES(max_t(int, sdr->tRHW_min, sdr->tCCS_min),
2392                                  period_ns);
2393
2394         /*
2395          * NFCv2: Use WAIT_MODE (wait for RB line), do not rely only on delays.
2396          * NFCv1: No WAIT_MODE, tR must be maximal.
2397          */
2398         if (nfc->caps->is_nfcv2) {
2399                 nfc_tmg.tR = TO_CYCLES(sdr->tWB_max, period_ns);
2400         } else {
2401                 nfc_tmg.tR = TO_CYCLES64(sdr->tWB_max + sdr->tR_max,
2402                                          period_ns);
2403                 if (nfc_tmg.tR + 3 > nfc_tmg.tCH)
2404                         nfc_tmg.tR = nfc_tmg.tCH - 3;
2405                 else
2406                         nfc_tmg.tR = 0;
2407         }
2408
2409         if (chipnr < 0)
2410                 return 0;
2411
2412         marvell_nand->ndtr0 =
2413                 NDTR0_TRP(nfc_tmg.tRP) |
2414                 NDTR0_TRH(nfc_tmg.tRH) |
2415                 NDTR0_ETRP(nfc_tmg.tRP) |
2416                 NDTR0_TWP(nfc_tmg.tWP) |
2417                 NDTR0_TWH(nfc_tmg.tWH) |
2418                 NDTR0_TCS(nfc_tmg.tCS) |
2419                 NDTR0_TCH(nfc_tmg.tCH);
2420
2421         marvell_nand->ndtr1 =
2422                 NDTR1_TAR(nfc_tmg.tAR) |
2423                 NDTR1_TWHR(nfc_tmg.tWHR) |
2424                 NDTR1_TR(nfc_tmg.tR);
2425
2426         if (nfc->caps->is_nfcv2) {
2427                 marvell_nand->ndtr0 |=
2428                         NDTR0_RD_CNT_DEL(read_delay) |
2429                         NDTR0_SELCNTR |
2430                         NDTR0_TADL(nfc_tmg.tADL);
2431
2432                 marvell_nand->ndtr1 |=
2433                         NDTR1_TRHW(nfc_tmg.tRHW) |
2434                         NDTR1_WAIT_MODE;
2435         }
2436
2437         return 0;
2438 }
2439
2440 static int marvell_nand_attach_chip(struct nand_chip *chip)
2441 {
2442         struct mtd_info *mtd = nand_to_mtd(chip);
2443         struct marvell_nand_chip *marvell_nand = to_marvell_nand(chip);
2444         struct marvell_nfc *nfc = to_marvell_nfc(chip->controller);
2445         struct pxa3xx_nand_platform_data *pdata = dev_get_platdata(nfc->dev);
2446         int ret;
2447
2448         if (pdata && pdata->flash_bbt)
2449                 chip->bbt_options |= NAND_BBT_USE_FLASH;
2450
2451         if (chip->bbt_options & NAND_BBT_USE_FLASH) {
2452                 /*
2453                  * We'll use a bad block table stored in-flash and don't
2454                  * allow writing the bad block marker to the flash.
2455                  */
2456                 chip->bbt_options |= NAND_BBT_NO_OOB_BBM;
2457                 chip->bbt_td = &bbt_main_descr;
2458                 chip->bbt_md = &bbt_mirror_descr;
2459         }
2460
2461         /* Save the chip-specific fields of NDCR */
2462         marvell_nand->ndcr = NDCR_PAGE_SZ(mtd->writesize);
2463         if (chip->options & NAND_BUSWIDTH_16)
2464                 marvell_nand->ndcr |= NDCR_DWIDTH_M | NDCR_DWIDTH_C;
2465
2466         /*
2467          * On small page NANDs, only one cycle is needed to pass the
2468          * column address.
2469          */
2470         if (mtd->writesize <= 512) {
2471                 marvell_nand->addr_cyc = 1;
2472         } else {
2473                 marvell_nand->addr_cyc = 2;
2474                 marvell_nand->ndcr |= NDCR_RA_START;
2475         }
2476
2477         /*
2478          * Now add the number of cycles needed to pass the row
2479          * address.
2480          *
2481          * Addressing a chip using CS 2 or 3 should also need the third row
2482          * cycle but due to inconsistance in the documentation and lack of
2483          * hardware to test this situation, this case is not supported.
2484          */
2485         if (chip->options & NAND_ROW_ADDR_3)
2486                 marvell_nand->addr_cyc += 3;
2487         else
2488                 marvell_nand->addr_cyc += 2;
2489
2490         if (pdata) {
2491                 chip->ecc.size = pdata->ecc_step_size;
2492                 chip->ecc.strength = pdata->ecc_strength;
2493         }
2494
2495         ret = marvell_nand_ecc_init(mtd, &chip->ecc);
2496         if (ret) {
2497                 dev_err(nfc->dev, "ECC init failed: %d\n", ret);
2498                 return ret;
2499         }
2500
2501         if (chip->ecc.engine_type == NAND_ECC_ENGINE_TYPE_ON_HOST) {
2502                 /*
2503                  * Subpage write not available with hardware ECC, prohibit also
2504                  * subpage read as in userspace subpage access would still be
2505                  * allowed and subpage write, if used, would lead to numerous
2506                  * uncorrectable ECC errors.
2507                  */
2508                 chip->options |= NAND_NO_SUBPAGE_WRITE;
2509         }
2510
2511         if (pdata || nfc->caps->legacy_of_bindings) {
2512                 /*
2513                  * We keep the MTD name unchanged to avoid breaking platforms
2514                  * where the MTD cmdline parser is used and the bootloader
2515                  * has not been updated to use the new naming scheme.
2516                  */
2517                 mtd->name = "pxa3xx_nand-0";
2518         } else if (!mtd->name) {
2519                 /*
2520                  * If the new bindings are used and the bootloader has not been
2521                  * updated to pass a new mtdparts parameter on the cmdline, you
2522                  * should define the following property in your NAND node, ie:
2523                  *
2524                  *      label = "main-storage";
2525                  *
2526                  * This way, mtd->name will be set by the core when
2527                  * nand_set_flash_node() is called.
2528                  */
2529                 mtd->name = devm_kasprintf(nfc->dev, GFP_KERNEL,
2530                                            "%s:nand.%d", dev_name(nfc->dev),
2531                                            marvell_nand->sels[0].cs);
2532                 if (!mtd->name) {
2533                         dev_err(nfc->dev, "Failed to allocate mtd->name\n");
2534                         return -ENOMEM;
2535                 }
2536         }
2537
2538         return 0;
2539 }
2540
2541 static const struct nand_controller_ops marvell_nand_controller_ops = {
2542         .attach_chip = marvell_nand_attach_chip,
2543         .exec_op = marvell_nfc_exec_op,
2544         .setup_interface = marvell_nfc_setup_interface,
2545 };
2546
2547 static int marvell_nand_chip_init(struct device *dev, struct marvell_nfc *nfc,
2548                                   struct device_node *np)
2549 {
2550         struct pxa3xx_nand_platform_data *pdata = dev_get_platdata(dev);
2551         struct marvell_nand_chip *marvell_nand;
2552         struct mtd_info *mtd;
2553         struct nand_chip *chip;
2554         int nsels, ret, i;
2555         u32 cs, rb;
2556
2557         /*
2558          * The legacy "num-cs" property indicates the number of CS on the only
2559          * chip connected to the controller (legacy bindings does not support
2560          * more than one chip). The CS and RB pins are always the #0.
2561          *
2562          * When not using legacy bindings, a couple of "reg" and "nand-rb"
2563          * properties must be filled. For each chip, expressed as a subnode,
2564          * "reg" points to the CS lines and "nand-rb" to the RB line.
2565          */
2566         if (pdata || nfc->caps->legacy_of_bindings) {
2567                 nsels = 1;
2568         } else {
2569                 nsels = of_property_count_elems_of_size(np, "reg", sizeof(u32));
2570                 if (nsels <= 0) {
2571                         dev_err(dev, "missing/invalid reg property\n");
2572                         return -EINVAL;
2573                 }
2574         }
2575
2576         /* Alloc the nand chip structure */
2577         marvell_nand = devm_kzalloc(dev,
2578                                     struct_size(marvell_nand, sels, nsels),
2579                                     GFP_KERNEL);
2580         if (!marvell_nand) {
2581                 dev_err(dev, "could not allocate chip structure\n");
2582                 return -ENOMEM;
2583         }
2584
2585         marvell_nand->nsels = nsels;
2586         marvell_nand->selected_die = -1;
2587
2588         for (i = 0; i < nsels; i++) {
2589                 if (pdata || nfc->caps->legacy_of_bindings) {
2590                         /*
2591                          * Legacy bindings use the CS lines in natural
2592                          * order (0, 1, ...)
2593                          */
2594                         cs = i;
2595                 } else {
2596                         /* Retrieve CS id */
2597                         ret = of_property_read_u32_index(np, "reg", i, &cs);
2598                         if (ret) {
2599                                 dev_err(dev, "could not retrieve reg property: %d\n",
2600                                         ret);
2601                                 return ret;
2602                         }
2603                 }
2604
2605                 if (cs >= nfc->caps->max_cs_nb) {
2606                         dev_err(dev, "invalid reg value: %u (max CS = %d)\n",
2607                                 cs, nfc->caps->max_cs_nb);
2608                         return -EINVAL;
2609                 }
2610
2611                 if (test_and_set_bit(cs, &nfc->assigned_cs)) {
2612                         dev_err(dev, "CS %d already assigned\n", cs);
2613                         return -EINVAL;
2614                 }
2615
2616                 /*
2617                  * The cs variable represents the chip select id, which must be
2618                  * converted in bit fields for NDCB0 and NDCB2 to select the
2619                  * right chip. Unfortunately, due to a lack of information on
2620                  * the subject and incoherent documentation, the user should not
2621                  * use CS1 and CS3 at all as asserting them is not supported in
2622                  * a reliable way (due to multiplexing inside ADDR5 field).
2623                  */
2624                 marvell_nand->sels[i].cs = cs;
2625                 switch (cs) {
2626                 case 0:
2627                 case 2:
2628                         marvell_nand->sels[i].ndcb0_csel = 0;
2629                         break;
2630                 case 1:
2631                 case 3:
2632                         marvell_nand->sels[i].ndcb0_csel = NDCB0_CSEL;
2633                         break;
2634                 default:
2635                         return -EINVAL;
2636                 }
2637
2638                 /* Retrieve RB id */
2639                 if (pdata || nfc->caps->legacy_of_bindings) {
2640                         /* Legacy bindings always use RB #0 */
2641                         rb = 0;
2642                 } else {
2643                         ret = of_property_read_u32_index(np, "nand-rb", i,
2644                                                          &rb);
2645                         if (ret) {
2646                                 dev_err(dev,
2647                                         "could not retrieve RB property: %d\n",
2648                                         ret);
2649                                 return ret;
2650                         }
2651                 }
2652
2653                 if (rb >= nfc->caps->max_rb_nb) {
2654                         dev_err(dev, "invalid reg value: %u (max RB = %d)\n",
2655                                 rb, nfc->caps->max_rb_nb);
2656                         return -EINVAL;
2657                 }
2658
2659                 marvell_nand->sels[i].rb = rb;
2660         }
2661
2662         chip = &marvell_nand->chip;
2663         chip->controller = &nfc->controller;
2664         nand_set_flash_node(chip, np);
2665
2666         if (!of_property_read_bool(np, "marvell,nand-keep-config"))
2667                 chip->options |= NAND_KEEP_TIMINGS;
2668
2669         mtd = nand_to_mtd(chip);
2670         mtd->dev.parent = dev;
2671
2672         /*
2673          * Default to HW ECC engine mode. If the nand-ecc-mode property is given
2674          * in the DT node, this entry will be overwritten in nand_scan_ident().
2675          */
2676         chip->ecc.engine_type = NAND_ECC_ENGINE_TYPE_ON_HOST;
2677
2678         /*
2679          * Save a reference value for timing registers before
2680          * ->setup_interface() is called.
2681          */
2682         marvell_nand->ndtr0 = readl_relaxed(nfc->regs + NDTR0);
2683         marvell_nand->ndtr1 = readl_relaxed(nfc->regs + NDTR1);
2684
2685         chip->options |= NAND_BUSWIDTH_AUTO;
2686
2687         ret = nand_scan(chip, marvell_nand->nsels);
2688         if (ret) {
2689                 dev_err(dev, "could not scan the nand chip\n");
2690                 return ret;
2691         }
2692
2693         if (pdata)
2694                 /* Legacy bindings support only one chip */
2695                 ret = mtd_device_register(mtd, pdata->parts, pdata->nr_parts);
2696         else
2697                 ret = mtd_device_register(mtd, NULL, 0);
2698         if (ret) {
2699                 dev_err(dev, "failed to register mtd device: %d\n", ret);
2700                 nand_cleanup(chip);
2701                 return ret;
2702         }
2703
2704         list_add_tail(&marvell_nand->node, &nfc->chips);
2705
2706         return 0;
2707 }
2708
2709 static void marvell_nand_chips_cleanup(struct marvell_nfc *nfc)
2710 {
2711         struct marvell_nand_chip *entry, *temp;
2712         struct nand_chip *chip;
2713         int ret;
2714
2715         list_for_each_entry_safe(entry, temp, &nfc->chips, node) {
2716                 chip = &entry->chip;
2717                 ret = mtd_device_unregister(nand_to_mtd(chip));
2718                 WARN_ON(ret);
2719                 nand_cleanup(chip);
2720                 list_del(&entry->node);
2721         }
2722 }
2723
2724 static int marvell_nand_chips_init(struct device *dev, struct marvell_nfc *nfc)
2725 {
2726         struct device_node *np = dev->of_node;
2727         struct device_node *nand_np;
2728         int max_cs = nfc->caps->max_cs_nb;
2729         int nchips;
2730         int ret;
2731
2732         if (!np)
2733                 nchips = 1;
2734         else
2735                 nchips = of_get_child_count(np);
2736
2737         if (nchips > max_cs) {
2738                 dev_err(dev, "too many NAND chips: %d (max = %d CS)\n", nchips,
2739                         max_cs);
2740                 return -EINVAL;
2741         }
2742
2743         /*
2744          * Legacy bindings do not use child nodes to exhibit NAND chip
2745          * properties and layout. Instead, NAND properties are mixed with the
2746          * controller ones, and partitions are defined as direct subnodes of the
2747          * NAND controller node.
2748          */
2749         if (nfc->caps->legacy_of_bindings) {
2750                 ret = marvell_nand_chip_init(dev, nfc, np);
2751                 return ret;
2752         }
2753
2754         for_each_child_of_node(np, nand_np) {
2755                 ret = marvell_nand_chip_init(dev, nfc, nand_np);
2756                 if (ret) {
2757                         of_node_put(nand_np);
2758                         goto cleanup_chips;
2759                 }
2760         }
2761
2762         return 0;
2763
2764 cleanup_chips:
2765         marvell_nand_chips_cleanup(nfc);
2766
2767         return ret;
2768 }
2769
2770 static int marvell_nfc_init_dma(struct marvell_nfc *nfc)
2771 {
2772         struct platform_device *pdev = container_of(nfc->dev,
2773                                                     struct platform_device,
2774                                                     dev);
2775         struct dma_slave_config config = {};
2776         struct resource *r;
2777         int ret;
2778
2779         if (!IS_ENABLED(CONFIG_PXA_DMA)) {
2780                 dev_warn(nfc->dev,
2781                          "DMA not enabled in configuration\n");
2782                 return -ENOTSUPP;
2783         }
2784
2785         ret = dma_set_mask_and_coherent(nfc->dev, DMA_BIT_MASK(32));
2786         if (ret)
2787                 return ret;
2788
2789         nfc->dma_chan = dma_request_chan(nfc->dev, "data");
2790         if (IS_ERR(nfc->dma_chan)) {
2791                 ret = PTR_ERR(nfc->dma_chan);
2792                 nfc->dma_chan = NULL;
2793                 return dev_err_probe(nfc->dev, ret, "DMA channel request failed\n");
2794         }
2795
2796         r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2797         if (!r) {
2798                 ret = -ENXIO;
2799                 goto release_channel;
2800         }
2801
2802         config.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
2803         config.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
2804         config.src_addr = r->start + NDDB;
2805         config.dst_addr = r->start + NDDB;
2806         config.src_maxburst = 32;
2807         config.dst_maxburst = 32;
2808         ret = dmaengine_slave_config(nfc->dma_chan, &config);
2809         if (ret < 0) {
2810                 dev_err(nfc->dev, "Failed to configure DMA channel\n");
2811                 goto release_channel;
2812         }
2813
2814         /*
2815          * DMA must act on length multiple of 32 and this length may be
2816          * bigger than the destination buffer. Use this buffer instead
2817          * for DMA transfers and then copy the desired amount of data to
2818          * the provided buffer.
2819          */
2820         nfc->dma_buf = kmalloc(MAX_CHUNK_SIZE, GFP_KERNEL | GFP_DMA);
2821         if (!nfc->dma_buf) {
2822                 ret = -ENOMEM;
2823                 goto release_channel;
2824         }
2825
2826         nfc->use_dma = true;
2827
2828         return 0;
2829
2830 release_channel:
2831         dma_release_channel(nfc->dma_chan);
2832         nfc->dma_chan = NULL;
2833
2834         return ret;
2835 }
2836
2837 static void marvell_nfc_reset(struct marvell_nfc *nfc)
2838 {
2839         /*
2840          * ECC operations and interruptions are only enabled when specifically
2841          * needed. ECC shall not be activated in the early stages (fails probe).
2842          * Arbiter flag, even if marked as "reserved", must be set (empirical).
2843          * SPARE_EN bit must always be set or ECC bytes will not be at the same
2844          * offset in the read page and this will fail the protection.
2845          */
2846         writel_relaxed(NDCR_ALL_INT | NDCR_ND_ARB_EN | NDCR_SPARE_EN |
2847                        NDCR_RD_ID_CNT(NFCV1_READID_LEN), nfc->regs + NDCR);
2848         writel_relaxed(0xFFFFFFFF, nfc->regs + NDSR);
2849         writel_relaxed(0, nfc->regs + NDECCCTRL);
2850 }
2851
2852 static int marvell_nfc_init(struct marvell_nfc *nfc)
2853 {
2854         struct device_node *np = nfc->dev->of_node;
2855
2856         /*
2857          * Some SoCs like A7k/A8k need to enable manually the NAND
2858          * controller, gated clocks and reset bits to avoid being bootloader
2859          * dependent. This is done through the use of the System Functions
2860          * registers.
2861          */
2862         if (nfc->caps->need_system_controller) {
2863                 struct regmap *sysctrl_base =
2864                         syscon_regmap_lookup_by_phandle(np,
2865                                                         "marvell,system-controller");
2866
2867                 if (IS_ERR(sysctrl_base))
2868                         return PTR_ERR(sysctrl_base);
2869
2870                 regmap_write(sysctrl_base, GENCONF_SOC_DEVICE_MUX,
2871                              GENCONF_SOC_DEVICE_MUX_NFC_EN |
2872                              GENCONF_SOC_DEVICE_MUX_ECC_CLK_RST |
2873                              GENCONF_SOC_DEVICE_MUX_ECC_CORE_RST |
2874                              GENCONF_SOC_DEVICE_MUX_NFC_INT_EN);
2875
2876                 regmap_update_bits(sysctrl_base, GENCONF_CLK_GATING_CTRL,
2877                                    GENCONF_CLK_GATING_CTRL_ND_GATE,
2878                                    GENCONF_CLK_GATING_CTRL_ND_GATE);
2879
2880                 regmap_update_bits(sysctrl_base, GENCONF_ND_CLK_CTRL,
2881                                    GENCONF_ND_CLK_CTRL_EN,
2882                                    GENCONF_ND_CLK_CTRL_EN);
2883         }
2884
2885         /* Configure the DMA if appropriate */
2886         if (!nfc->caps->is_nfcv2)
2887                 marvell_nfc_init_dma(nfc);
2888
2889         marvell_nfc_reset(nfc);
2890
2891         return 0;
2892 }
2893
2894 static int marvell_nfc_probe(struct platform_device *pdev)
2895 {
2896         struct device *dev = &pdev->dev;
2897         struct marvell_nfc *nfc;
2898         int ret;
2899         int irq;
2900
2901         nfc = devm_kzalloc(&pdev->dev, sizeof(struct marvell_nfc),
2902                            GFP_KERNEL);
2903         if (!nfc)
2904                 return -ENOMEM;
2905
2906         nfc->dev = dev;
2907         nand_controller_init(&nfc->controller);
2908         nfc->controller.ops = &marvell_nand_controller_ops;
2909         INIT_LIST_HEAD(&nfc->chips);
2910
2911         nfc->regs = devm_platform_ioremap_resource(pdev, 0);
2912         if (IS_ERR(nfc->regs))
2913                 return PTR_ERR(nfc->regs);
2914
2915         irq = platform_get_irq(pdev, 0);
2916         if (irq < 0)
2917                 return irq;
2918
2919         nfc->core_clk = devm_clk_get(&pdev->dev, "core");
2920
2921         /* Managed the legacy case (when the first clock was not named) */
2922         if (nfc->core_clk == ERR_PTR(-ENOENT))
2923                 nfc->core_clk = devm_clk_get(&pdev->dev, NULL);
2924
2925         if (IS_ERR(nfc->core_clk))
2926                 return PTR_ERR(nfc->core_clk);
2927
2928         ret = clk_prepare_enable(nfc->core_clk);
2929         if (ret)
2930                 return ret;
2931
2932         nfc->reg_clk = devm_clk_get(&pdev->dev, "reg");
2933         if (IS_ERR(nfc->reg_clk)) {
2934                 if (PTR_ERR(nfc->reg_clk) != -ENOENT) {
2935                         ret = PTR_ERR(nfc->reg_clk);
2936                         goto unprepare_core_clk;
2937                 }
2938
2939                 nfc->reg_clk = NULL;
2940         }
2941
2942         ret = clk_prepare_enable(nfc->reg_clk);
2943         if (ret)
2944                 goto unprepare_core_clk;
2945
2946         marvell_nfc_disable_int(nfc, NDCR_ALL_INT);
2947         marvell_nfc_clear_int(nfc, NDCR_ALL_INT);
2948         ret = devm_request_irq(dev, irq, marvell_nfc_isr,
2949                                0, "marvell-nfc", nfc);
2950         if (ret)
2951                 goto unprepare_reg_clk;
2952
2953         /* Get NAND controller capabilities */
2954         if (pdev->id_entry)
2955                 nfc->caps = (void *)pdev->id_entry->driver_data;
2956         else
2957                 nfc->caps = of_device_get_match_data(&pdev->dev);
2958
2959         if (!nfc->caps) {
2960                 dev_err(dev, "Could not retrieve NFC caps\n");
2961                 ret = -EINVAL;
2962                 goto unprepare_reg_clk;
2963         }
2964
2965         /* Init the controller and then probe the chips */
2966         ret = marvell_nfc_init(nfc);
2967         if (ret)
2968                 goto unprepare_reg_clk;
2969
2970         platform_set_drvdata(pdev, nfc);
2971
2972         ret = marvell_nand_chips_init(dev, nfc);
2973         if (ret)
2974                 goto release_dma;
2975
2976         return 0;
2977
2978 release_dma:
2979         if (nfc->use_dma)
2980                 dma_release_channel(nfc->dma_chan);
2981 unprepare_reg_clk:
2982         clk_disable_unprepare(nfc->reg_clk);
2983 unprepare_core_clk:
2984         clk_disable_unprepare(nfc->core_clk);
2985
2986         return ret;
2987 }
2988
2989 static int marvell_nfc_remove(struct platform_device *pdev)
2990 {
2991         struct marvell_nfc *nfc = platform_get_drvdata(pdev);
2992
2993         marvell_nand_chips_cleanup(nfc);
2994
2995         if (nfc->use_dma) {
2996                 dmaengine_terminate_all(nfc->dma_chan);
2997                 dma_release_channel(nfc->dma_chan);
2998         }
2999
3000         clk_disable_unprepare(nfc->reg_clk);
3001         clk_disable_unprepare(nfc->core_clk);
3002
3003         return 0;
3004 }
3005
3006 static int __maybe_unused marvell_nfc_suspend(struct device *dev)
3007 {
3008         struct marvell_nfc *nfc = dev_get_drvdata(dev);
3009         struct marvell_nand_chip *chip;
3010
3011         list_for_each_entry(chip, &nfc->chips, node)
3012                 marvell_nfc_wait_ndrun(&chip->chip);
3013
3014         clk_disable_unprepare(nfc->reg_clk);
3015         clk_disable_unprepare(nfc->core_clk);
3016
3017         return 0;
3018 }
3019
3020 static int __maybe_unused marvell_nfc_resume(struct device *dev)
3021 {
3022         struct marvell_nfc *nfc = dev_get_drvdata(dev);
3023         int ret;
3024
3025         ret = clk_prepare_enable(nfc->core_clk);
3026         if (ret < 0)
3027                 return ret;
3028
3029         ret = clk_prepare_enable(nfc->reg_clk);
3030         if (ret < 0)
3031                 return ret;
3032
3033         /*
3034          * Reset nfc->selected_chip so the next command will cause the timing
3035          * registers to be restored in marvell_nfc_select_target().
3036          */
3037         nfc->selected_chip = NULL;
3038
3039         /* Reset registers that have lost their contents */
3040         marvell_nfc_reset(nfc);
3041
3042         return 0;
3043 }
3044
3045 static const struct dev_pm_ops marvell_nfc_pm_ops = {
3046         SET_SYSTEM_SLEEP_PM_OPS(marvell_nfc_suspend, marvell_nfc_resume)
3047 };
3048
3049 static const struct marvell_nfc_caps marvell_armada_8k_nfc_caps = {
3050         .max_cs_nb = 4,
3051         .max_rb_nb = 2,
3052         .need_system_controller = true,
3053         .is_nfcv2 = true,
3054 };
3055
3056 static const struct marvell_nfc_caps marvell_armada370_nfc_caps = {
3057         .max_cs_nb = 4,
3058         .max_rb_nb = 2,
3059         .is_nfcv2 = true,
3060 };
3061
3062 static const struct marvell_nfc_caps marvell_pxa3xx_nfc_caps = {
3063         .max_cs_nb = 2,
3064         .max_rb_nb = 1,
3065         .use_dma = true,
3066 };
3067
3068 static const struct marvell_nfc_caps marvell_armada_8k_nfc_legacy_caps = {
3069         .max_cs_nb = 4,
3070         .max_rb_nb = 2,
3071         .need_system_controller = true,
3072         .legacy_of_bindings = true,
3073         .is_nfcv2 = true,
3074 };
3075
3076 static const struct marvell_nfc_caps marvell_armada370_nfc_legacy_caps = {
3077         .max_cs_nb = 4,
3078         .max_rb_nb = 2,
3079         .legacy_of_bindings = true,
3080         .is_nfcv2 = true,
3081 };
3082
3083 static const struct marvell_nfc_caps marvell_pxa3xx_nfc_legacy_caps = {
3084         .max_cs_nb = 2,
3085         .max_rb_nb = 1,
3086         .legacy_of_bindings = true,
3087         .use_dma = true,
3088 };
3089
3090 static const struct platform_device_id marvell_nfc_platform_ids[] = {
3091         {
3092                 .name = "pxa3xx-nand",
3093                 .driver_data = (kernel_ulong_t)&marvell_pxa3xx_nfc_legacy_caps,
3094         },
3095         { /* sentinel */ },
3096 };
3097 MODULE_DEVICE_TABLE(platform, marvell_nfc_platform_ids);
3098
3099 static const struct of_device_id marvell_nfc_of_ids[] = {
3100         {
3101                 .compatible = "marvell,armada-8k-nand-controller",
3102                 .data = &marvell_armada_8k_nfc_caps,
3103         },
3104         {
3105                 .compatible = "marvell,armada370-nand-controller",
3106                 .data = &marvell_armada370_nfc_caps,
3107         },
3108         {
3109                 .compatible = "marvell,pxa3xx-nand-controller",
3110                 .data = &marvell_pxa3xx_nfc_caps,
3111         },
3112         /* Support for old/deprecated bindings: */
3113         {
3114                 .compatible = "marvell,armada-8k-nand",
3115                 .data = &marvell_armada_8k_nfc_legacy_caps,
3116         },
3117         {
3118                 .compatible = "marvell,armada370-nand",
3119                 .data = &marvell_armada370_nfc_legacy_caps,
3120         },
3121         {
3122                 .compatible = "marvell,pxa3xx-nand",
3123                 .data = &marvell_pxa3xx_nfc_legacy_caps,
3124         },
3125         { /* sentinel */ },
3126 };
3127 MODULE_DEVICE_TABLE(of, marvell_nfc_of_ids);
3128
3129 static struct platform_driver marvell_nfc_driver = {
3130         .driver = {
3131                 .name           = "marvell-nfc",
3132                 .of_match_table = marvell_nfc_of_ids,
3133                 .pm             = &marvell_nfc_pm_ops,
3134         },
3135         .id_table = marvell_nfc_platform_ids,
3136         .probe = marvell_nfc_probe,
3137         .remove = marvell_nfc_remove,
3138 };
3139 module_platform_driver(marvell_nfc_driver);
3140
3141 MODULE_LICENSE("GPL");
3142 MODULE_DESCRIPTION("Marvell NAND controller driver");