GNU Linux-libre 4.19.286-gnu1
[releases.git] / drivers / mtd / nand / raw / brcmnand / brcmnand.c
1 /*
2  * Copyright © 2010-2015 Broadcom Corporation
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU General Public License for more details.
12  */
13
14 #include <linux/clk.h>
15 #include <linux/version.h>
16 #include <linux/module.h>
17 #include <linux/init.h>
18 #include <linux/delay.h>
19 #include <linux/device.h>
20 #include <linux/platform_device.h>
21 #include <linux/err.h>
22 #include <linux/completion.h>
23 #include <linux/interrupt.h>
24 #include <linux/spinlock.h>
25 #include <linux/dma-mapping.h>
26 #include <linux/ioport.h>
27 #include <linux/bug.h>
28 #include <linux/kernel.h>
29 #include <linux/bitops.h>
30 #include <linux/mm.h>
31 #include <linux/mtd/mtd.h>
32 #include <linux/mtd/rawnand.h>
33 #include <linux/mtd/partitions.h>
34 #include <linux/of.h>
35 #include <linux/of_platform.h>
36 #include <linux/slab.h>
37 #include <linux/list.h>
38 #include <linux/log2.h>
39
40 #include "brcmnand.h"
41
42 /*
43  * This flag controls if WP stays on between erase/write commands to mitigate
44  * flash corruption due to power glitches. Values:
45  * 0: NAND_WP is not used or not available
46  * 1: NAND_WP is set by default, cleared for erase/write operations
47  * 2: NAND_WP is always cleared
48  */
49 static int wp_on = 1;
50 module_param(wp_on, int, 0444);
51
52 /***********************************************************************
53  * Definitions
54  ***********************************************************************/
55
56 #define DRV_NAME                        "brcmnand"
57
58 #define CMD_NULL                        0x00
59 #define CMD_PAGE_READ                   0x01
60 #define CMD_SPARE_AREA_READ             0x02
61 #define CMD_STATUS_READ                 0x03
62 #define CMD_PROGRAM_PAGE                0x04
63 #define CMD_PROGRAM_SPARE_AREA          0x05
64 #define CMD_COPY_BACK                   0x06
65 #define CMD_DEVICE_ID_READ              0x07
66 #define CMD_BLOCK_ERASE                 0x08
67 #define CMD_FLASH_RESET                 0x09
68 #define CMD_BLOCKS_LOCK                 0x0a
69 #define CMD_BLOCKS_LOCK_DOWN            0x0b
70 #define CMD_BLOCKS_UNLOCK               0x0c
71 #define CMD_READ_BLOCKS_LOCK_STATUS     0x0d
72 #define CMD_PARAMETER_READ              0x0e
73 #define CMD_PARAMETER_CHANGE_COL        0x0f
74 #define CMD_LOW_LEVEL_OP                0x10
75
76 struct brcm_nand_dma_desc {
77         u32 next_desc;
78         u32 next_desc_ext;
79         u32 cmd_irq;
80         u32 dram_addr;
81         u32 dram_addr_ext;
82         u32 tfr_len;
83         u32 total_len;
84         u32 flash_addr;
85         u32 flash_addr_ext;
86         u32 cs;
87         u32 pad2[5];
88         u32 status_valid;
89 } __packed;
90
91 /* Bitfields for brcm_nand_dma_desc::status_valid */
92 #define FLASH_DMA_ECC_ERROR     (1 << 8)
93 #define FLASH_DMA_CORR_ERROR    (1 << 9)
94
95 /* 512B flash cache in the NAND controller HW */
96 #define FC_SHIFT                9U
97 #define FC_BYTES                512U
98 #define FC_WORDS                (FC_BYTES >> 2)
99
100 #define BRCMNAND_MIN_PAGESIZE   512
101 #define BRCMNAND_MIN_BLOCKSIZE  (8 * 1024)
102 #define BRCMNAND_MIN_DEVSIZE    (4ULL * 1024 * 1024)
103
104 #define NAND_CTRL_RDY                   (INTFC_CTLR_READY | INTFC_FLASH_READY)
105 #define NAND_POLL_STATUS_TIMEOUT_MS     100
106
107 /* Controller feature flags */
108 enum {
109         BRCMNAND_HAS_1K_SECTORS                 = BIT(0),
110         BRCMNAND_HAS_PREFETCH                   = BIT(1),
111         BRCMNAND_HAS_CACHE_MODE                 = BIT(2),
112         BRCMNAND_HAS_WP                         = BIT(3),
113 };
114
115 struct brcmnand_controller {
116         struct device           *dev;
117         struct nand_controller  controller;
118         void __iomem            *nand_base;
119         void __iomem            *nand_fc; /* flash cache */
120         void __iomem            *flash_dma_base;
121         unsigned int            irq;
122         unsigned int            dma_irq;
123         int                     nand_version;
124
125         /* Some SoCs provide custom interrupt status register(s) */
126         struct brcmnand_soc     *soc;
127
128         /* Some SoCs have a gateable clock for the controller */
129         struct clk              *clk;
130
131         int                     cmd_pending;
132         bool                    dma_pending;
133         struct completion       done;
134         struct completion       dma_done;
135
136         /* List of NAND hosts (one for each chip-select) */
137         struct list_head host_list;
138
139         struct brcm_nand_dma_desc *dma_desc;
140         dma_addr_t              dma_pa;
141
142         /* in-memory cache of the FLASH_CACHE, used only for some commands */
143         u8                      flash_cache[FC_BYTES];
144
145         /* Controller revision details */
146         const u16               *reg_offsets;
147         unsigned int            reg_spacing; /* between CS1, CS2, ... regs */
148         const u8                *cs_offsets; /* within each chip-select */
149         const u8                *cs0_offsets; /* within CS0, if different */
150         unsigned int            max_block_size;
151         const unsigned int      *block_sizes;
152         unsigned int            max_page_size;
153         const unsigned int      *page_sizes;
154         unsigned int            max_oob;
155         u32                     features;
156
157         /* for low-power standby/resume only */
158         u32                     nand_cs_nand_select;
159         u32                     nand_cs_nand_xor;
160         u32                     corr_stat_threshold;
161         u32                     flash_dma_mode;
162 };
163
164 struct brcmnand_cfg {
165         u64                     device_size;
166         unsigned int            block_size;
167         unsigned int            page_size;
168         unsigned int            spare_area_size;
169         unsigned int            device_width;
170         unsigned int            col_adr_bytes;
171         unsigned int            blk_adr_bytes;
172         unsigned int            ful_adr_bytes;
173         unsigned int            sector_size_1k;
174         unsigned int            ecc_level;
175         /* use for low-power standby/resume only */
176         u32                     acc_control;
177         u32                     config;
178         u32                     config_ext;
179         u32                     timing_1;
180         u32                     timing_2;
181 };
182
183 struct brcmnand_host {
184         struct list_head        node;
185
186         struct nand_chip        chip;
187         struct platform_device  *pdev;
188         int                     cs;
189
190         unsigned int            last_cmd;
191         unsigned int            last_byte;
192         u64                     last_addr;
193         struct brcmnand_cfg     hwcfg;
194         struct brcmnand_controller *ctrl;
195 };
196
197 enum brcmnand_reg {
198         BRCMNAND_CMD_START = 0,
199         BRCMNAND_CMD_EXT_ADDRESS,
200         BRCMNAND_CMD_ADDRESS,
201         BRCMNAND_INTFC_STATUS,
202         BRCMNAND_CS_SELECT,
203         BRCMNAND_CS_XOR,
204         BRCMNAND_LL_OP,
205         BRCMNAND_CS0_BASE,
206         BRCMNAND_CS1_BASE,              /* CS1 regs, if non-contiguous */
207         BRCMNAND_CORR_THRESHOLD,
208         BRCMNAND_CORR_THRESHOLD_EXT,
209         BRCMNAND_UNCORR_COUNT,
210         BRCMNAND_CORR_COUNT,
211         BRCMNAND_CORR_EXT_ADDR,
212         BRCMNAND_CORR_ADDR,
213         BRCMNAND_UNCORR_EXT_ADDR,
214         BRCMNAND_UNCORR_ADDR,
215         BRCMNAND_SEMAPHORE,
216         BRCMNAND_ID,
217         BRCMNAND_ID_EXT,
218         BRCMNAND_LL_RDATA,
219         BRCMNAND_OOB_READ_BASE,
220         BRCMNAND_OOB_READ_10_BASE,      /* offset 0x10, if non-contiguous */
221         BRCMNAND_OOB_WRITE_BASE,
222         BRCMNAND_OOB_WRITE_10_BASE,     /* offset 0x10, if non-contiguous */
223         BRCMNAND_FC_BASE,
224 };
225
226 /* BRCMNAND v4.0 */
227 static const u16 brcmnand_regs_v40[] = {
228         [BRCMNAND_CMD_START]            =  0x04,
229         [BRCMNAND_CMD_EXT_ADDRESS]      =  0x08,
230         [BRCMNAND_CMD_ADDRESS]          =  0x0c,
231         [BRCMNAND_INTFC_STATUS]         =  0x6c,
232         [BRCMNAND_CS_SELECT]            =  0x14,
233         [BRCMNAND_CS_XOR]               =  0x18,
234         [BRCMNAND_LL_OP]                = 0x178,
235         [BRCMNAND_CS0_BASE]             =  0x40,
236         [BRCMNAND_CS1_BASE]             =  0xd0,
237         [BRCMNAND_CORR_THRESHOLD]       =  0x84,
238         [BRCMNAND_CORR_THRESHOLD_EXT]   =     0,
239         [BRCMNAND_UNCORR_COUNT]         =     0,
240         [BRCMNAND_CORR_COUNT]           =     0,
241         [BRCMNAND_CORR_EXT_ADDR]        =  0x70,
242         [BRCMNAND_CORR_ADDR]            =  0x74,
243         [BRCMNAND_UNCORR_EXT_ADDR]      =  0x78,
244         [BRCMNAND_UNCORR_ADDR]          =  0x7c,
245         [BRCMNAND_SEMAPHORE]            =  0x58,
246         [BRCMNAND_ID]                   =  0x60,
247         [BRCMNAND_ID_EXT]               =  0x64,
248         [BRCMNAND_LL_RDATA]             = 0x17c,
249         [BRCMNAND_OOB_READ_BASE]        =  0x20,
250         [BRCMNAND_OOB_READ_10_BASE]     = 0x130,
251         [BRCMNAND_OOB_WRITE_BASE]       =  0x30,
252         [BRCMNAND_OOB_WRITE_10_BASE]    =     0,
253         [BRCMNAND_FC_BASE]              = 0x200,
254 };
255
256 /* BRCMNAND v5.0 */
257 static const u16 brcmnand_regs_v50[] = {
258         [BRCMNAND_CMD_START]            =  0x04,
259         [BRCMNAND_CMD_EXT_ADDRESS]      =  0x08,
260         [BRCMNAND_CMD_ADDRESS]          =  0x0c,
261         [BRCMNAND_INTFC_STATUS]         =  0x6c,
262         [BRCMNAND_CS_SELECT]            =  0x14,
263         [BRCMNAND_CS_XOR]               =  0x18,
264         [BRCMNAND_LL_OP]                = 0x178,
265         [BRCMNAND_CS0_BASE]             =  0x40,
266         [BRCMNAND_CS1_BASE]             =  0xd0,
267         [BRCMNAND_CORR_THRESHOLD]       =  0x84,
268         [BRCMNAND_CORR_THRESHOLD_EXT]   =     0,
269         [BRCMNAND_UNCORR_COUNT]         =     0,
270         [BRCMNAND_CORR_COUNT]           =     0,
271         [BRCMNAND_CORR_EXT_ADDR]        =  0x70,
272         [BRCMNAND_CORR_ADDR]            =  0x74,
273         [BRCMNAND_UNCORR_EXT_ADDR]      =  0x78,
274         [BRCMNAND_UNCORR_ADDR]          =  0x7c,
275         [BRCMNAND_SEMAPHORE]            =  0x58,
276         [BRCMNAND_ID]                   =  0x60,
277         [BRCMNAND_ID_EXT]               =  0x64,
278         [BRCMNAND_LL_RDATA]             = 0x17c,
279         [BRCMNAND_OOB_READ_BASE]        =  0x20,
280         [BRCMNAND_OOB_READ_10_BASE]     = 0x130,
281         [BRCMNAND_OOB_WRITE_BASE]       =  0x30,
282         [BRCMNAND_OOB_WRITE_10_BASE]    = 0x140,
283         [BRCMNAND_FC_BASE]              = 0x200,
284 };
285
286 /* BRCMNAND v6.0 - v7.1 */
287 static const u16 brcmnand_regs_v60[] = {
288         [BRCMNAND_CMD_START]            =  0x04,
289         [BRCMNAND_CMD_EXT_ADDRESS]      =  0x08,
290         [BRCMNAND_CMD_ADDRESS]          =  0x0c,
291         [BRCMNAND_INTFC_STATUS]         =  0x14,
292         [BRCMNAND_CS_SELECT]            =  0x18,
293         [BRCMNAND_CS_XOR]               =  0x1c,
294         [BRCMNAND_LL_OP]                =  0x20,
295         [BRCMNAND_CS0_BASE]             =  0x50,
296         [BRCMNAND_CS1_BASE]             =     0,
297         [BRCMNAND_CORR_THRESHOLD]       =  0xc0,
298         [BRCMNAND_CORR_THRESHOLD_EXT]   =  0xc4,
299         [BRCMNAND_UNCORR_COUNT]         =  0xfc,
300         [BRCMNAND_CORR_COUNT]           = 0x100,
301         [BRCMNAND_CORR_EXT_ADDR]        = 0x10c,
302         [BRCMNAND_CORR_ADDR]            = 0x110,
303         [BRCMNAND_UNCORR_EXT_ADDR]      = 0x114,
304         [BRCMNAND_UNCORR_ADDR]          = 0x118,
305         [BRCMNAND_SEMAPHORE]            = 0x150,
306         [BRCMNAND_ID]                   = 0x194,
307         [BRCMNAND_ID_EXT]               = 0x198,
308         [BRCMNAND_LL_RDATA]             = 0x19c,
309         [BRCMNAND_OOB_READ_BASE]        = 0x200,
310         [BRCMNAND_OOB_READ_10_BASE]     =     0,
311         [BRCMNAND_OOB_WRITE_BASE]       = 0x280,
312         [BRCMNAND_OOB_WRITE_10_BASE]    =     0,
313         [BRCMNAND_FC_BASE]              = 0x400,
314 };
315
316 /* BRCMNAND v7.1 */
317 static const u16 brcmnand_regs_v71[] = {
318         [BRCMNAND_CMD_START]            =  0x04,
319         [BRCMNAND_CMD_EXT_ADDRESS]      =  0x08,
320         [BRCMNAND_CMD_ADDRESS]          =  0x0c,
321         [BRCMNAND_INTFC_STATUS]         =  0x14,
322         [BRCMNAND_CS_SELECT]            =  0x18,
323         [BRCMNAND_CS_XOR]               =  0x1c,
324         [BRCMNAND_LL_OP]                =  0x20,
325         [BRCMNAND_CS0_BASE]             =  0x50,
326         [BRCMNAND_CS1_BASE]             =     0,
327         [BRCMNAND_CORR_THRESHOLD]       =  0xdc,
328         [BRCMNAND_CORR_THRESHOLD_EXT]   =  0xe0,
329         [BRCMNAND_UNCORR_COUNT]         =  0xfc,
330         [BRCMNAND_CORR_COUNT]           = 0x100,
331         [BRCMNAND_CORR_EXT_ADDR]        = 0x10c,
332         [BRCMNAND_CORR_ADDR]            = 0x110,
333         [BRCMNAND_UNCORR_EXT_ADDR]      = 0x114,
334         [BRCMNAND_UNCORR_ADDR]          = 0x118,
335         [BRCMNAND_SEMAPHORE]            = 0x150,
336         [BRCMNAND_ID]                   = 0x194,
337         [BRCMNAND_ID_EXT]               = 0x198,
338         [BRCMNAND_LL_RDATA]             = 0x19c,
339         [BRCMNAND_OOB_READ_BASE]        = 0x200,
340         [BRCMNAND_OOB_READ_10_BASE]     =     0,
341         [BRCMNAND_OOB_WRITE_BASE]       = 0x280,
342         [BRCMNAND_OOB_WRITE_10_BASE]    =     0,
343         [BRCMNAND_FC_BASE]              = 0x400,
344 };
345
346 /* BRCMNAND v7.2 */
347 static const u16 brcmnand_regs_v72[] = {
348         [BRCMNAND_CMD_START]            =  0x04,
349         [BRCMNAND_CMD_EXT_ADDRESS]      =  0x08,
350         [BRCMNAND_CMD_ADDRESS]          =  0x0c,
351         [BRCMNAND_INTFC_STATUS]         =  0x14,
352         [BRCMNAND_CS_SELECT]            =  0x18,
353         [BRCMNAND_CS_XOR]               =  0x1c,
354         [BRCMNAND_LL_OP]                =  0x20,
355         [BRCMNAND_CS0_BASE]             =  0x50,
356         [BRCMNAND_CS1_BASE]             =     0,
357         [BRCMNAND_CORR_THRESHOLD]       =  0xdc,
358         [BRCMNAND_CORR_THRESHOLD_EXT]   =  0xe0,
359         [BRCMNAND_UNCORR_COUNT]         =  0xfc,
360         [BRCMNAND_CORR_COUNT]           = 0x100,
361         [BRCMNAND_CORR_EXT_ADDR]        = 0x10c,
362         [BRCMNAND_CORR_ADDR]            = 0x110,
363         [BRCMNAND_UNCORR_EXT_ADDR]      = 0x114,
364         [BRCMNAND_UNCORR_ADDR]          = 0x118,
365         [BRCMNAND_SEMAPHORE]            = 0x150,
366         [BRCMNAND_ID]                   = 0x194,
367         [BRCMNAND_ID_EXT]               = 0x198,
368         [BRCMNAND_LL_RDATA]             = 0x19c,
369         [BRCMNAND_OOB_READ_BASE]        = 0x200,
370         [BRCMNAND_OOB_READ_10_BASE]     =     0,
371         [BRCMNAND_OOB_WRITE_BASE]       = 0x400,
372         [BRCMNAND_OOB_WRITE_10_BASE]    =     0,
373         [BRCMNAND_FC_BASE]              = 0x600,
374 };
375
376 enum brcmnand_cs_reg {
377         BRCMNAND_CS_CFG_EXT = 0,
378         BRCMNAND_CS_CFG,
379         BRCMNAND_CS_ACC_CONTROL,
380         BRCMNAND_CS_TIMING1,
381         BRCMNAND_CS_TIMING2,
382 };
383
384 /* Per chip-select offsets for v7.1 */
385 static const u8 brcmnand_cs_offsets_v71[] = {
386         [BRCMNAND_CS_ACC_CONTROL]       = 0x00,
387         [BRCMNAND_CS_CFG_EXT]           = 0x04,
388         [BRCMNAND_CS_CFG]               = 0x08,
389         [BRCMNAND_CS_TIMING1]           = 0x0c,
390         [BRCMNAND_CS_TIMING2]           = 0x10,
391 };
392
393 /* Per chip-select offsets for pre v7.1, except CS0 on <= v5.0 */
394 static const u8 brcmnand_cs_offsets[] = {
395         [BRCMNAND_CS_ACC_CONTROL]       = 0x00,
396         [BRCMNAND_CS_CFG_EXT]           = 0x04,
397         [BRCMNAND_CS_CFG]               = 0x04,
398         [BRCMNAND_CS_TIMING1]           = 0x08,
399         [BRCMNAND_CS_TIMING2]           = 0x0c,
400 };
401
402 /* Per chip-select offset for <= v5.0 on CS0 only */
403 static const u8 brcmnand_cs_offsets_cs0[] = {
404         [BRCMNAND_CS_ACC_CONTROL]       = 0x00,
405         [BRCMNAND_CS_CFG_EXT]           = 0x08,
406         [BRCMNAND_CS_CFG]               = 0x08,
407         [BRCMNAND_CS_TIMING1]           = 0x10,
408         [BRCMNAND_CS_TIMING2]           = 0x14,
409 };
410
411 /*
412  * Bitfields for the CFG and CFG_EXT registers. Pre-v7.1 controllers only had
413  * one config register, but once the bitfields overflowed, newer controllers
414  * (v7.1 and newer) added a CFG_EXT register and shuffled a few fields around.
415  */
416 enum {
417         CFG_BLK_ADR_BYTES_SHIFT         = 8,
418         CFG_COL_ADR_BYTES_SHIFT         = 12,
419         CFG_FUL_ADR_BYTES_SHIFT         = 16,
420         CFG_BUS_WIDTH_SHIFT             = 23,
421         CFG_BUS_WIDTH                   = BIT(CFG_BUS_WIDTH_SHIFT),
422         CFG_DEVICE_SIZE_SHIFT           = 24,
423
424         /* Only for pre-v7.1 (with no CFG_EXT register) */
425         CFG_PAGE_SIZE_SHIFT             = 20,
426         CFG_BLK_SIZE_SHIFT              = 28,
427
428         /* Only for v7.1+ (with CFG_EXT register) */
429         CFG_EXT_PAGE_SIZE_SHIFT         = 0,
430         CFG_EXT_BLK_SIZE_SHIFT          = 4,
431 };
432
433 /* BRCMNAND_INTFC_STATUS */
434 enum {
435         INTFC_FLASH_STATUS              = GENMASK(7, 0),
436
437         INTFC_ERASED                    = BIT(27),
438         INTFC_OOB_VALID                 = BIT(28),
439         INTFC_CACHE_VALID               = BIT(29),
440         INTFC_FLASH_READY               = BIT(30),
441         INTFC_CTLR_READY                = BIT(31),
442 };
443
444 static inline u32 nand_readreg(struct brcmnand_controller *ctrl, u32 offs)
445 {
446         return brcmnand_readl(ctrl->nand_base + offs);
447 }
448
449 static inline void nand_writereg(struct brcmnand_controller *ctrl, u32 offs,
450                                  u32 val)
451 {
452         brcmnand_writel(val, ctrl->nand_base + offs);
453 }
454
455 static int brcmnand_revision_init(struct brcmnand_controller *ctrl)
456 {
457         static const unsigned int block_sizes_v6[] = { 8, 16, 128, 256, 512, 1024, 2048, 0 };
458         static const unsigned int block_sizes_v4[] = { 16, 128, 8, 512, 256, 1024, 2048, 0 };
459         static const unsigned int page_sizes[] = { 512, 2048, 4096, 8192, 0 };
460
461         ctrl->nand_version = nand_readreg(ctrl, 0) & 0xffff;
462
463         /* Only support v4.0+? */
464         if (ctrl->nand_version < 0x0400) {
465                 dev_err(ctrl->dev, "version %#x not supported\n",
466                         ctrl->nand_version);
467                 return -ENODEV;
468         }
469
470         /* Register offsets */
471         if (ctrl->nand_version >= 0x0702)
472                 ctrl->reg_offsets = brcmnand_regs_v72;
473         else if (ctrl->nand_version >= 0x0701)
474                 ctrl->reg_offsets = brcmnand_regs_v71;
475         else if (ctrl->nand_version >= 0x0600)
476                 ctrl->reg_offsets = brcmnand_regs_v60;
477         else if (ctrl->nand_version >= 0x0500)
478                 ctrl->reg_offsets = brcmnand_regs_v50;
479         else if (ctrl->nand_version >= 0x0400)
480                 ctrl->reg_offsets = brcmnand_regs_v40;
481
482         /* Chip-select stride */
483         if (ctrl->nand_version >= 0x0701)
484                 ctrl->reg_spacing = 0x14;
485         else
486                 ctrl->reg_spacing = 0x10;
487
488         /* Per chip-select registers */
489         if (ctrl->nand_version >= 0x0701) {
490                 ctrl->cs_offsets = brcmnand_cs_offsets_v71;
491         } else {
492                 ctrl->cs_offsets = brcmnand_cs_offsets;
493
494                 /* v3.3-5.0 have a different CS0 offset layout */
495                 if (ctrl->nand_version >= 0x0303 &&
496                     ctrl->nand_version <= 0x0500)
497                         ctrl->cs0_offsets = brcmnand_cs_offsets_cs0;
498         }
499
500         /* Page / block sizes */
501         if (ctrl->nand_version >= 0x0701) {
502                 /* >= v7.1 use nice power-of-2 values! */
503                 ctrl->max_page_size = 16 * 1024;
504                 ctrl->max_block_size = 2 * 1024 * 1024;
505         } else {
506                 ctrl->page_sizes = page_sizes;
507                 if (ctrl->nand_version >= 0x0600)
508                         ctrl->block_sizes = block_sizes_v6;
509                 else
510                         ctrl->block_sizes = block_sizes_v4;
511
512                 if (ctrl->nand_version < 0x0400) {
513                         ctrl->max_page_size = 4096;
514                         ctrl->max_block_size = 512 * 1024;
515                 }
516         }
517
518         /* Maximum spare area sector size (per 512B) */
519         if (ctrl->nand_version >= 0x0702)
520                 ctrl->max_oob = 128;
521         else if (ctrl->nand_version >= 0x0600)
522                 ctrl->max_oob = 64;
523         else if (ctrl->nand_version >= 0x0500)
524                 ctrl->max_oob = 32;
525         else
526                 ctrl->max_oob = 16;
527
528         /* v6.0 and newer (except v6.1) have prefetch support */
529         if (ctrl->nand_version >= 0x0600 && ctrl->nand_version != 0x0601)
530                 ctrl->features |= BRCMNAND_HAS_PREFETCH;
531
532         /*
533          * v6.x has cache mode, but it's implemented differently. Ignore it for
534          * now.
535          */
536         if (ctrl->nand_version >= 0x0700)
537                 ctrl->features |= BRCMNAND_HAS_CACHE_MODE;
538
539         if (ctrl->nand_version >= 0x0500)
540                 ctrl->features |= BRCMNAND_HAS_1K_SECTORS;
541
542         if (ctrl->nand_version >= 0x0700)
543                 ctrl->features |= BRCMNAND_HAS_WP;
544         else if (of_property_read_bool(ctrl->dev->of_node, "brcm,nand-has-wp"))
545                 ctrl->features |= BRCMNAND_HAS_WP;
546
547         return 0;
548 }
549
550 static inline u32 brcmnand_read_reg(struct brcmnand_controller *ctrl,
551                 enum brcmnand_reg reg)
552 {
553         u16 offs = ctrl->reg_offsets[reg];
554
555         if (offs)
556                 return nand_readreg(ctrl, offs);
557         else
558                 return 0;
559 }
560
561 static inline void brcmnand_write_reg(struct brcmnand_controller *ctrl,
562                                       enum brcmnand_reg reg, u32 val)
563 {
564         u16 offs = ctrl->reg_offsets[reg];
565
566         if (offs)
567                 nand_writereg(ctrl, offs, val);
568 }
569
570 static inline void brcmnand_rmw_reg(struct brcmnand_controller *ctrl,
571                                     enum brcmnand_reg reg, u32 mask, unsigned
572                                     int shift, u32 val)
573 {
574         u32 tmp = brcmnand_read_reg(ctrl, reg);
575
576         tmp &= ~mask;
577         tmp |= val << shift;
578         brcmnand_write_reg(ctrl, reg, tmp);
579 }
580
581 static inline u32 brcmnand_read_fc(struct brcmnand_controller *ctrl, int word)
582 {
583         return __raw_readl(ctrl->nand_fc + word * 4);
584 }
585
586 static inline void brcmnand_write_fc(struct brcmnand_controller *ctrl,
587                                      int word, u32 val)
588 {
589         __raw_writel(val, ctrl->nand_fc + word * 4);
590 }
591
592 static void brcmnand_clear_ecc_addr(struct brcmnand_controller *ctrl)
593 {
594
595         /* Clear error addresses */
596         brcmnand_write_reg(ctrl, BRCMNAND_UNCORR_ADDR, 0);
597         brcmnand_write_reg(ctrl, BRCMNAND_CORR_ADDR, 0);
598         brcmnand_write_reg(ctrl, BRCMNAND_UNCORR_EXT_ADDR, 0);
599         brcmnand_write_reg(ctrl, BRCMNAND_CORR_EXT_ADDR, 0);
600 }
601
602 static u64 brcmnand_get_uncorrecc_addr(struct brcmnand_controller *ctrl)
603 {
604         u64 err_addr;
605
606         err_addr = brcmnand_read_reg(ctrl, BRCMNAND_UNCORR_ADDR);
607         err_addr |= ((u64)(brcmnand_read_reg(ctrl,
608                                              BRCMNAND_UNCORR_EXT_ADDR)
609                                              & 0xffff) << 32);
610
611         return err_addr;
612 }
613
614 static u64 brcmnand_get_correcc_addr(struct brcmnand_controller *ctrl)
615 {
616         u64 err_addr;
617
618         err_addr = brcmnand_read_reg(ctrl, BRCMNAND_CORR_ADDR);
619         err_addr |= ((u64)(brcmnand_read_reg(ctrl,
620                                              BRCMNAND_CORR_EXT_ADDR)
621                                              & 0xffff) << 32);
622
623         return err_addr;
624 }
625
626 static void brcmnand_set_cmd_addr(struct mtd_info *mtd, u64 addr)
627 {
628         struct nand_chip *chip =  mtd_to_nand(mtd);
629         struct brcmnand_host *host = nand_get_controller_data(chip);
630         struct brcmnand_controller *ctrl = host->ctrl;
631
632         brcmnand_write_reg(ctrl, BRCMNAND_CMD_EXT_ADDRESS,
633                            (host->cs << 16) | ((addr >> 32) & 0xffff));
634         (void)brcmnand_read_reg(ctrl, BRCMNAND_CMD_EXT_ADDRESS);
635         brcmnand_write_reg(ctrl, BRCMNAND_CMD_ADDRESS,
636                            lower_32_bits(addr));
637         (void)brcmnand_read_reg(ctrl, BRCMNAND_CMD_ADDRESS);
638 }
639
640 static inline u16 brcmnand_cs_offset(struct brcmnand_controller *ctrl, int cs,
641                                      enum brcmnand_cs_reg reg)
642 {
643         u16 offs_cs0 = ctrl->reg_offsets[BRCMNAND_CS0_BASE];
644         u16 offs_cs1 = ctrl->reg_offsets[BRCMNAND_CS1_BASE];
645         u8 cs_offs;
646
647         if (cs == 0 && ctrl->cs0_offsets)
648                 cs_offs = ctrl->cs0_offsets[reg];
649         else
650                 cs_offs = ctrl->cs_offsets[reg];
651
652         if (cs && offs_cs1)
653                 return offs_cs1 + (cs - 1) * ctrl->reg_spacing + cs_offs;
654
655         return offs_cs0 + cs * ctrl->reg_spacing + cs_offs;
656 }
657
658 static inline u32 brcmnand_count_corrected(struct brcmnand_controller *ctrl)
659 {
660         if (ctrl->nand_version < 0x0600)
661                 return 1;
662         return brcmnand_read_reg(ctrl, BRCMNAND_CORR_COUNT);
663 }
664
665 static void brcmnand_wr_corr_thresh(struct brcmnand_host *host, u8 val)
666 {
667         struct brcmnand_controller *ctrl = host->ctrl;
668         unsigned int shift = 0, bits;
669         enum brcmnand_reg reg = BRCMNAND_CORR_THRESHOLD;
670         int cs = host->cs;
671
672         if (ctrl->nand_version >= 0x0702)
673                 bits = 7;
674         else if (ctrl->nand_version >= 0x0600)
675                 bits = 6;
676         else if (ctrl->nand_version >= 0x0500)
677                 bits = 5;
678         else
679                 bits = 4;
680
681         if (ctrl->nand_version >= 0x0702) {
682                 if (cs >= 4)
683                         reg = BRCMNAND_CORR_THRESHOLD_EXT;
684                 shift = (cs % 4) * bits;
685         } else if (ctrl->nand_version >= 0x0600) {
686                 if (cs >= 5)
687                         reg = BRCMNAND_CORR_THRESHOLD_EXT;
688                 shift = (cs % 5) * bits;
689         }
690         brcmnand_rmw_reg(ctrl, reg, (bits - 1) << shift, shift, val);
691 }
692
693 static inline int brcmnand_cmd_shift(struct brcmnand_controller *ctrl)
694 {
695         if (ctrl->nand_version < 0x0602)
696                 return 24;
697         return 0;
698 }
699
700 /***********************************************************************
701  * NAND ACC CONTROL bitfield
702  *
703  * Some bits have remained constant throughout hardware revision, while
704  * others have shifted around.
705  ***********************************************************************/
706
707 /* Constant for all versions (where supported) */
708 enum {
709         /* See BRCMNAND_HAS_CACHE_MODE */
710         ACC_CONTROL_CACHE_MODE                          = BIT(22),
711
712         /* See BRCMNAND_HAS_PREFETCH */
713         ACC_CONTROL_PREFETCH                            = BIT(23),
714
715         ACC_CONTROL_PAGE_HIT                            = BIT(24),
716         ACC_CONTROL_WR_PREEMPT                          = BIT(25),
717         ACC_CONTROL_PARTIAL_PAGE                        = BIT(26),
718         ACC_CONTROL_RD_ERASED                           = BIT(27),
719         ACC_CONTROL_FAST_PGM_RDIN                       = BIT(28),
720         ACC_CONTROL_WR_ECC                              = BIT(30),
721         ACC_CONTROL_RD_ECC                              = BIT(31),
722 };
723
724 static inline u32 brcmnand_spare_area_mask(struct brcmnand_controller *ctrl)
725 {
726         if (ctrl->nand_version >= 0x0702)
727                 return GENMASK(7, 0);
728         else if (ctrl->nand_version >= 0x0600)
729                 return GENMASK(6, 0);
730         else
731                 return GENMASK(5, 0);
732 }
733
734 #define NAND_ACC_CONTROL_ECC_SHIFT      16
735 #define NAND_ACC_CONTROL_ECC_EXT_SHIFT  13
736
737 static inline u32 brcmnand_ecc_level_mask(struct brcmnand_controller *ctrl)
738 {
739         u32 mask = (ctrl->nand_version >= 0x0600) ? 0x1f : 0x0f;
740
741         mask <<= NAND_ACC_CONTROL_ECC_SHIFT;
742
743         /* v7.2 includes additional ECC levels */
744         if (ctrl->nand_version >= 0x0702)
745                 mask |= 0x7 << NAND_ACC_CONTROL_ECC_EXT_SHIFT;
746
747         return mask;
748 }
749
750 static void brcmnand_set_ecc_enabled(struct brcmnand_host *host, int en)
751 {
752         struct brcmnand_controller *ctrl = host->ctrl;
753         u16 offs = brcmnand_cs_offset(ctrl, host->cs, BRCMNAND_CS_ACC_CONTROL);
754         u32 acc_control = nand_readreg(ctrl, offs);
755         u32 ecc_flags = ACC_CONTROL_WR_ECC | ACC_CONTROL_RD_ECC;
756
757         if (en) {
758                 acc_control |= ecc_flags; /* enable RD/WR ECC */
759                 acc_control |= host->hwcfg.ecc_level
760                                << NAND_ACC_CONTROL_ECC_SHIFT;
761         } else {
762                 acc_control &= ~ecc_flags; /* disable RD/WR ECC */
763                 acc_control &= ~brcmnand_ecc_level_mask(ctrl);
764         }
765
766         nand_writereg(ctrl, offs, acc_control);
767 }
768
769 static inline int brcmnand_sector_1k_shift(struct brcmnand_controller *ctrl)
770 {
771         if (ctrl->nand_version >= 0x0702)
772                 return 9;
773         else if (ctrl->nand_version >= 0x0600)
774                 return 7;
775         else if (ctrl->nand_version >= 0x0500)
776                 return 6;
777         else
778                 return -1;
779 }
780
781 static int brcmnand_get_sector_size_1k(struct brcmnand_host *host)
782 {
783         struct brcmnand_controller *ctrl = host->ctrl;
784         int shift = brcmnand_sector_1k_shift(ctrl);
785         u16 acc_control_offs = brcmnand_cs_offset(ctrl, host->cs,
786                                                   BRCMNAND_CS_ACC_CONTROL);
787
788         if (shift < 0)
789                 return 0;
790
791         return (nand_readreg(ctrl, acc_control_offs) >> shift) & 0x1;
792 }
793
794 static void brcmnand_set_sector_size_1k(struct brcmnand_host *host, int val)
795 {
796         struct brcmnand_controller *ctrl = host->ctrl;
797         int shift = brcmnand_sector_1k_shift(ctrl);
798         u16 acc_control_offs = brcmnand_cs_offset(ctrl, host->cs,
799                                                   BRCMNAND_CS_ACC_CONTROL);
800         u32 tmp;
801
802         if (shift < 0)
803                 return;
804
805         tmp = nand_readreg(ctrl, acc_control_offs);
806         tmp &= ~(1 << shift);
807         tmp |= (!!val) << shift;
808         nand_writereg(ctrl, acc_control_offs, tmp);
809 }
810
811 /***********************************************************************
812  * CS_NAND_SELECT
813  ***********************************************************************/
814
815 enum {
816         CS_SELECT_NAND_WP                       = BIT(29),
817         CS_SELECT_AUTO_DEVICE_ID_CFG            = BIT(30),
818 };
819
820 static int bcmnand_ctrl_poll_status(struct brcmnand_controller *ctrl,
821                                     u32 mask, u32 expected_val,
822                                     unsigned long timeout_ms)
823 {
824         unsigned long limit;
825         u32 val;
826
827         if (!timeout_ms)
828                 timeout_ms = NAND_POLL_STATUS_TIMEOUT_MS;
829
830         limit = jiffies + msecs_to_jiffies(timeout_ms);
831         do {
832                 val = brcmnand_read_reg(ctrl, BRCMNAND_INTFC_STATUS);
833                 if ((val & mask) == expected_val)
834                         return 0;
835
836                 cpu_relax();
837         } while (time_after(limit, jiffies));
838
839         dev_warn(ctrl->dev, "timeout on status poll (expected %x got %x)\n",
840                  expected_val, val & mask);
841
842         return -ETIMEDOUT;
843 }
844
845 static inline void brcmnand_set_wp(struct brcmnand_controller *ctrl, bool en)
846 {
847         u32 val = en ? CS_SELECT_NAND_WP : 0;
848
849         brcmnand_rmw_reg(ctrl, BRCMNAND_CS_SELECT, CS_SELECT_NAND_WP, 0, val);
850 }
851
852 /***********************************************************************
853  * Flash DMA
854  ***********************************************************************/
855
856 enum flash_dma_reg {
857         FLASH_DMA_REVISION              = 0x00,
858         FLASH_DMA_FIRST_DESC            = 0x04,
859         FLASH_DMA_FIRST_DESC_EXT        = 0x08,
860         FLASH_DMA_CTRL                  = 0x0c,
861         FLASH_DMA_MODE                  = 0x10,
862         FLASH_DMA_STATUS                = 0x14,
863         FLASH_DMA_INTERRUPT_DESC        = 0x18,
864         FLASH_DMA_INTERRUPT_DESC_EXT    = 0x1c,
865         FLASH_DMA_ERROR_STATUS          = 0x20,
866         FLASH_DMA_CURRENT_DESC          = 0x24,
867         FLASH_DMA_CURRENT_DESC_EXT      = 0x28,
868 };
869
870 static inline bool has_flash_dma(struct brcmnand_controller *ctrl)
871 {
872         return ctrl->flash_dma_base;
873 }
874
875 static inline bool flash_dma_buf_ok(const void *buf)
876 {
877         return buf && !is_vmalloc_addr(buf) &&
878                 likely(IS_ALIGNED((uintptr_t)buf, 4));
879 }
880
881 static inline void flash_dma_writel(struct brcmnand_controller *ctrl, u8 offs,
882                                     u32 val)
883 {
884         brcmnand_writel(val, ctrl->flash_dma_base + offs);
885 }
886
887 static inline u32 flash_dma_readl(struct brcmnand_controller *ctrl, u8 offs)
888 {
889         return brcmnand_readl(ctrl->flash_dma_base + offs);
890 }
891
892 /* Low-level operation types: command, address, write, or read */
893 enum brcmnand_llop_type {
894         LL_OP_CMD,
895         LL_OP_ADDR,
896         LL_OP_WR,
897         LL_OP_RD,
898 };
899
900 /***********************************************************************
901  * Internal support functions
902  ***********************************************************************/
903
904 static inline bool is_hamming_ecc(struct brcmnand_controller *ctrl,
905                                   struct brcmnand_cfg *cfg)
906 {
907         if (ctrl->nand_version <= 0x0701)
908                 return cfg->sector_size_1k == 0 && cfg->spare_area_size == 16 &&
909                         cfg->ecc_level == 15;
910         else
911                 return cfg->sector_size_1k == 0 && ((cfg->spare_area_size == 16 &&
912                         cfg->ecc_level == 15) ||
913                         (cfg->spare_area_size == 28 && cfg->ecc_level == 16));
914 }
915
916 /*
917  * Set mtd->ooblayout to the appropriate mtd_ooblayout_ops given
918  * the layout/configuration.
919  * Returns -ERRCODE on failure.
920  */
921 static int brcmnand_hamming_ooblayout_ecc(struct mtd_info *mtd, int section,
922                                           struct mtd_oob_region *oobregion)
923 {
924         struct nand_chip *chip = mtd_to_nand(mtd);
925         struct brcmnand_host *host = nand_get_controller_data(chip);
926         struct brcmnand_cfg *cfg = &host->hwcfg;
927         int sas = cfg->spare_area_size << cfg->sector_size_1k;
928         int sectors = cfg->page_size / (512 << cfg->sector_size_1k);
929
930         if (section >= sectors)
931                 return -ERANGE;
932
933         oobregion->offset = (section * sas) + 6;
934         oobregion->length = 3;
935
936         return 0;
937 }
938
939 static int brcmnand_hamming_ooblayout_free(struct mtd_info *mtd, int section,
940                                            struct mtd_oob_region *oobregion)
941 {
942         struct nand_chip *chip = mtd_to_nand(mtd);
943         struct brcmnand_host *host = nand_get_controller_data(chip);
944         struct brcmnand_cfg *cfg = &host->hwcfg;
945         int sas = cfg->spare_area_size << cfg->sector_size_1k;
946         int sectors = cfg->page_size / (512 << cfg->sector_size_1k);
947
948         if (section >= sectors * 2)
949                 return -ERANGE;
950
951         oobregion->offset = (section / 2) * sas;
952
953         if (section & 1) {
954                 oobregion->offset += 9;
955                 oobregion->length = 7;
956         } else {
957                 oobregion->length = 6;
958
959                 /* First sector of each page may have BBI */
960                 if (!section) {
961                         /*
962                          * Small-page NAND use byte 6 for BBI while large-page
963                          * NAND use bytes 0 and 1.
964                          */
965                         if (cfg->page_size > 512) {
966                                 oobregion->offset += 2;
967                                 oobregion->length -= 2;
968                         } else {
969                                 oobregion->length--;
970                         }
971                 }
972         }
973
974         return 0;
975 }
976
977 static const struct mtd_ooblayout_ops brcmnand_hamming_ooblayout_ops = {
978         .ecc = brcmnand_hamming_ooblayout_ecc,
979         .free = brcmnand_hamming_ooblayout_free,
980 };
981
982 static int brcmnand_bch_ooblayout_ecc(struct mtd_info *mtd, int section,
983                                       struct mtd_oob_region *oobregion)
984 {
985         struct nand_chip *chip = mtd_to_nand(mtd);
986         struct brcmnand_host *host = nand_get_controller_data(chip);
987         struct brcmnand_cfg *cfg = &host->hwcfg;
988         int sas = cfg->spare_area_size << cfg->sector_size_1k;
989         int sectors = cfg->page_size / (512 << cfg->sector_size_1k);
990
991         if (section >= sectors)
992                 return -ERANGE;
993
994         oobregion->offset = (section * (sas + 1)) - chip->ecc.bytes;
995         oobregion->length = chip->ecc.bytes;
996
997         return 0;
998 }
999
1000 static int brcmnand_bch_ooblayout_free_lp(struct mtd_info *mtd, int section,
1001                                           struct mtd_oob_region *oobregion)
1002 {
1003         struct nand_chip *chip = mtd_to_nand(mtd);
1004         struct brcmnand_host *host = nand_get_controller_data(chip);
1005         struct brcmnand_cfg *cfg = &host->hwcfg;
1006         int sas = cfg->spare_area_size << cfg->sector_size_1k;
1007         int sectors = cfg->page_size / (512 << cfg->sector_size_1k);
1008
1009         if (section >= sectors)
1010                 return -ERANGE;
1011
1012         if (sas <= chip->ecc.bytes)
1013                 return 0;
1014
1015         oobregion->offset = section * sas;
1016         oobregion->length = sas - chip->ecc.bytes;
1017
1018         if (!section) {
1019                 oobregion->offset++;
1020                 oobregion->length--;
1021         }
1022
1023         return 0;
1024 }
1025
1026 static int brcmnand_bch_ooblayout_free_sp(struct mtd_info *mtd, int section,
1027                                           struct mtd_oob_region *oobregion)
1028 {
1029         struct nand_chip *chip = mtd_to_nand(mtd);
1030         struct brcmnand_host *host = nand_get_controller_data(chip);
1031         struct brcmnand_cfg *cfg = &host->hwcfg;
1032         int sas = cfg->spare_area_size << cfg->sector_size_1k;
1033
1034         if (section > 1 || sas - chip->ecc.bytes < 6 ||
1035             (section && sas - chip->ecc.bytes == 6))
1036                 return -ERANGE;
1037
1038         if (!section) {
1039                 oobregion->offset = 0;
1040                 oobregion->length = 5;
1041         } else {
1042                 oobregion->offset = 6;
1043                 oobregion->length = sas - chip->ecc.bytes - 6;
1044         }
1045
1046         return 0;
1047 }
1048
1049 static const struct mtd_ooblayout_ops brcmnand_bch_lp_ooblayout_ops = {
1050         .ecc = brcmnand_bch_ooblayout_ecc,
1051         .free = brcmnand_bch_ooblayout_free_lp,
1052 };
1053
1054 static const struct mtd_ooblayout_ops brcmnand_bch_sp_ooblayout_ops = {
1055         .ecc = brcmnand_bch_ooblayout_ecc,
1056         .free = brcmnand_bch_ooblayout_free_sp,
1057 };
1058
1059 static int brcmstb_choose_ecc_layout(struct brcmnand_host *host)
1060 {
1061         struct brcmnand_cfg *p = &host->hwcfg;
1062         struct mtd_info *mtd = nand_to_mtd(&host->chip);
1063         struct nand_ecc_ctrl *ecc = &host->chip.ecc;
1064         unsigned int ecc_level = p->ecc_level;
1065         int sas = p->spare_area_size << p->sector_size_1k;
1066         int sectors = p->page_size / (512 << p->sector_size_1k);
1067
1068         if (p->sector_size_1k)
1069                 ecc_level <<= 1;
1070
1071         if (is_hamming_ecc(host->ctrl, p)) {
1072                 ecc->bytes = 3 * sectors;
1073                 mtd_set_ooblayout(mtd, &brcmnand_hamming_ooblayout_ops);
1074                 return 0;
1075         }
1076
1077         /*
1078          * CONTROLLER_VERSION:
1079          *   < v5.0: ECC_REQ = ceil(BCH_T * 13/8)
1080          *  >= v5.0: ECC_REQ = ceil(BCH_T * 14/8)
1081          * But we will just be conservative.
1082          */
1083         ecc->bytes = DIV_ROUND_UP(ecc_level * 14, 8);
1084         if (p->page_size == 512)
1085                 mtd_set_ooblayout(mtd, &brcmnand_bch_sp_ooblayout_ops);
1086         else
1087                 mtd_set_ooblayout(mtd, &brcmnand_bch_lp_ooblayout_ops);
1088
1089         if (ecc->bytes >= sas) {
1090                 dev_err(&host->pdev->dev,
1091                         "error: ECC too large for OOB (ECC bytes %d, spare sector %d)\n",
1092                         ecc->bytes, sas);
1093                 return -EINVAL;
1094         }
1095
1096         return 0;
1097 }
1098
1099 static void brcmnand_wp(struct mtd_info *mtd, int wp)
1100 {
1101         struct nand_chip *chip = mtd_to_nand(mtd);
1102         struct brcmnand_host *host = nand_get_controller_data(chip);
1103         struct brcmnand_controller *ctrl = host->ctrl;
1104
1105         if ((ctrl->features & BRCMNAND_HAS_WP) && wp_on == 1) {
1106                 static int old_wp = -1;
1107                 int ret;
1108
1109                 if (old_wp != wp) {
1110                         dev_dbg(ctrl->dev, "WP %s\n", wp ? "on" : "off");
1111                         old_wp = wp;
1112                 }
1113
1114                 /*
1115                  * make sure ctrl/flash ready before and after
1116                  * changing state of #WP pin
1117                  */
1118                 ret = bcmnand_ctrl_poll_status(ctrl, NAND_CTRL_RDY |
1119                                                NAND_STATUS_READY,
1120                                                NAND_CTRL_RDY |
1121                                                NAND_STATUS_READY, 0);
1122                 if (ret)
1123                         return;
1124
1125                 brcmnand_set_wp(ctrl, wp);
1126                 nand_status_op(chip, NULL);
1127                 /* NAND_STATUS_WP 0x00 = protected, 0x80 = not protected */
1128                 ret = bcmnand_ctrl_poll_status(ctrl,
1129                                                NAND_CTRL_RDY |
1130                                                NAND_STATUS_READY |
1131                                                NAND_STATUS_WP,
1132                                                NAND_CTRL_RDY |
1133                                                NAND_STATUS_READY |
1134                                                (wp ? 0 : NAND_STATUS_WP), 0);
1135
1136                 if (ret)
1137                         dev_err_ratelimited(&host->pdev->dev,
1138                                             "nand #WP expected %s\n",
1139                                             wp ? "on" : "off");
1140         }
1141 }
1142
1143 /* Helper functions for reading and writing OOB registers */
1144 static inline u8 oob_reg_read(struct brcmnand_controller *ctrl, u32 offs)
1145 {
1146         u16 offset0, offset10, reg_offs;
1147
1148         offset0 = ctrl->reg_offsets[BRCMNAND_OOB_READ_BASE];
1149         offset10 = ctrl->reg_offsets[BRCMNAND_OOB_READ_10_BASE];
1150
1151         if (offs >= ctrl->max_oob)
1152                 return 0x77;
1153
1154         if (offs >= 16 && offset10)
1155                 reg_offs = offset10 + ((offs - 0x10) & ~0x03);
1156         else
1157                 reg_offs = offset0 + (offs & ~0x03);
1158
1159         return nand_readreg(ctrl, reg_offs) >> (24 - ((offs & 0x03) << 3));
1160 }
1161
1162 static inline void oob_reg_write(struct brcmnand_controller *ctrl, u32 offs,
1163                                  u32 data)
1164 {
1165         u16 offset0, offset10, reg_offs;
1166
1167         offset0 = ctrl->reg_offsets[BRCMNAND_OOB_WRITE_BASE];
1168         offset10 = ctrl->reg_offsets[BRCMNAND_OOB_WRITE_10_BASE];
1169
1170         if (offs >= ctrl->max_oob)
1171                 return;
1172
1173         if (offs >= 16 && offset10)
1174                 reg_offs = offset10 + ((offs - 0x10) & ~0x03);
1175         else
1176                 reg_offs = offset0 + (offs & ~0x03);
1177
1178         nand_writereg(ctrl, reg_offs, data);
1179 }
1180
1181 /*
1182  * read_oob_from_regs - read data from OOB registers
1183  * @ctrl: NAND controller
1184  * @i: sub-page sector index
1185  * @oob: buffer to read to
1186  * @sas: spare area sector size (i.e., OOB size per FLASH_CACHE)
1187  * @sector_1k: 1 for 1KiB sectors, 0 for 512B, other values are illegal
1188  */
1189 static int read_oob_from_regs(struct brcmnand_controller *ctrl, int i, u8 *oob,
1190                               int sas, int sector_1k)
1191 {
1192         int tbytes = sas << sector_1k;
1193         int j;
1194
1195         /* Adjust OOB values for 1K sector size */
1196         if (sector_1k && (i & 0x01))
1197                 tbytes = max(0, tbytes - (int)ctrl->max_oob);
1198         tbytes = min_t(int, tbytes, ctrl->max_oob);
1199
1200         for (j = 0; j < tbytes; j++)
1201                 oob[j] = oob_reg_read(ctrl, j);
1202         return tbytes;
1203 }
1204
1205 /*
1206  * write_oob_to_regs - write data to OOB registers
1207  * @i: sub-page sector index
1208  * @oob: buffer to write from
1209  * @sas: spare area sector size (i.e., OOB size per FLASH_CACHE)
1210  * @sector_1k: 1 for 1KiB sectors, 0 for 512B, other values are illegal
1211  */
1212 static int write_oob_to_regs(struct brcmnand_controller *ctrl, int i,
1213                              const u8 *oob, int sas, int sector_1k)
1214 {
1215         int tbytes = sas << sector_1k;
1216         int j;
1217
1218         /* Adjust OOB values for 1K sector size */
1219         if (sector_1k && (i & 0x01))
1220                 tbytes = max(0, tbytes - (int)ctrl->max_oob);
1221         tbytes = min_t(int, tbytes, ctrl->max_oob);
1222
1223         for (j = 0; j < tbytes; j += 4)
1224                 oob_reg_write(ctrl, j,
1225                                 (oob[j + 0] << 24) |
1226                                 (oob[j + 1] << 16) |
1227                                 (oob[j + 2] <<  8) |
1228                                 (oob[j + 3] <<  0));
1229         return tbytes;
1230 }
1231
1232 static irqreturn_t brcmnand_ctlrdy_irq(int irq, void *data)
1233 {
1234         struct brcmnand_controller *ctrl = data;
1235
1236         /* Discard all NAND_CTLRDY interrupts during DMA */
1237         if (ctrl->dma_pending)
1238                 return IRQ_HANDLED;
1239
1240         complete(&ctrl->done);
1241         return IRQ_HANDLED;
1242 }
1243
1244 /* Handle SoC-specific interrupt hardware */
1245 static irqreturn_t brcmnand_irq(int irq, void *data)
1246 {
1247         struct brcmnand_controller *ctrl = data;
1248
1249         if (ctrl->soc->ctlrdy_ack(ctrl->soc))
1250                 return brcmnand_ctlrdy_irq(irq, data);
1251
1252         return IRQ_NONE;
1253 }
1254
1255 static irqreturn_t brcmnand_dma_irq(int irq, void *data)
1256 {
1257         struct brcmnand_controller *ctrl = data;
1258
1259         complete(&ctrl->dma_done);
1260
1261         return IRQ_HANDLED;
1262 }
1263
1264 static void brcmnand_send_cmd(struct brcmnand_host *host, int cmd)
1265 {
1266         struct brcmnand_controller *ctrl = host->ctrl;
1267         int ret;
1268         u64 cmd_addr;
1269
1270         cmd_addr = brcmnand_read_reg(ctrl, BRCMNAND_CMD_ADDRESS);
1271
1272         dev_dbg(ctrl->dev, "send native cmd %d addr 0x%llx\n", cmd, cmd_addr);
1273
1274         BUG_ON(ctrl->cmd_pending != 0);
1275         ctrl->cmd_pending = cmd;
1276
1277         ret = bcmnand_ctrl_poll_status(ctrl, NAND_CTRL_RDY, NAND_CTRL_RDY, 0);
1278         WARN_ON(ret);
1279
1280         mb(); /* flush previous writes */
1281         brcmnand_write_reg(ctrl, BRCMNAND_CMD_START,
1282                            cmd << brcmnand_cmd_shift(ctrl));
1283 }
1284
1285 /***********************************************************************
1286  * NAND MTD API: read/program/erase
1287  ***********************************************************************/
1288
1289 static void brcmnand_cmd_ctrl(struct mtd_info *mtd, int dat,
1290         unsigned int ctrl)
1291 {
1292         /* intentionally left blank */
1293 }
1294
1295 static int brcmnand_waitfunc(struct mtd_info *mtd, struct nand_chip *this)
1296 {
1297         struct nand_chip *chip = mtd_to_nand(mtd);
1298         struct brcmnand_host *host = nand_get_controller_data(chip);
1299         struct brcmnand_controller *ctrl = host->ctrl;
1300         unsigned long timeo = msecs_to_jiffies(100);
1301
1302         dev_dbg(ctrl->dev, "wait on native cmd %d\n", ctrl->cmd_pending);
1303         if (ctrl->cmd_pending &&
1304                         wait_for_completion_timeout(&ctrl->done, timeo) <= 0) {
1305                 u32 cmd = brcmnand_read_reg(ctrl, BRCMNAND_CMD_START)
1306                                         >> brcmnand_cmd_shift(ctrl);
1307
1308                 dev_err_ratelimited(ctrl->dev,
1309                         "timeout waiting for command %#02x\n", cmd);
1310                 dev_err_ratelimited(ctrl->dev, "intfc status %08x\n",
1311                         brcmnand_read_reg(ctrl, BRCMNAND_INTFC_STATUS));
1312         }
1313         ctrl->cmd_pending = 0;
1314         return brcmnand_read_reg(ctrl, BRCMNAND_INTFC_STATUS) &
1315                                  INTFC_FLASH_STATUS;
1316 }
1317
1318 enum {
1319         LLOP_RE                         = BIT(16),
1320         LLOP_WE                         = BIT(17),
1321         LLOP_ALE                        = BIT(18),
1322         LLOP_CLE                        = BIT(19),
1323         LLOP_RETURN_IDLE                = BIT(31),
1324
1325         LLOP_DATA_MASK                  = GENMASK(15, 0),
1326 };
1327
1328 static int brcmnand_low_level_op(struct brcmnand_host *host,
1329                                  enum brcmnand_llop_type type, u32 data,
1330                                  bool last_op)
1331 {
1332         struct mtd_info *mtd = nand_to_mtd(&host->chip);
1333         struct nand_chip *chip = &host->chip;
1334         struct brcmnand_controller *ctrl = host->ctrl;
1335         u32 tmp;
1336
1337         tmp = data & LLOP_DATA_MASK;
1338         switch (type) {
1339         case LL_OP_CMD:
1340                 tmp |= LLOP_WE | LLOP_CLE;
1341                 break;
1342         case LL_OP_ADDR:
1343                 /* WE | ALE */
1344                 tmp |= LLOP_WE | LLOP_ALE;
1345                 break;
1346         case LL_OP_WR:
1347                 /* WE */
1348                 tmp |= LLOP_WE;
1349                 break;
1350         case LL_OP_RD:
1351                 /* RE */
1352                 tmp |= LLOP_RE;
1353                 break;
1354         }
1355         if (last_op)
1356                 /* RETURN_IDLE */
1357                 tmp |= LLOP_RETURN_IDLE;
1358
1359         dev_dbg(ctrl->dev, "ll_op cmd %#x\n", tmp);
1360
1361         brcmnand_write_reg(ctrl, BRCMNAND_LL_OP, tmp);
1362         (void)brcmnand_read_reg(ctrl, BRCMNAND_LL_OP);
1363
1364         brcmnand_send_cmd(host, CMD_LOW_LEVEL_OP);
1365         return brcmnand_waitfunc(mtd, chip);
1366 }
1367
1368 static void brcmnand_cmdfunc(struct mtd_info *mtd, unsigned command,
1369                              int column, int page_addr)
1370 {
1371         struct nand_chip *chip = mtd_to_nand(mtd);
1372         struct brcmnand_host *host = nand_get_controller_data(chip);
1373         struct brcmnand_controller *ctrl = host->ctrl;
1374         u64 addr = (u64)page_addr << chip->page_shift;
1375         int native_cmd = 0;
1376
1377         if (command == NAND_CMD_READID || command == NAND_CMD_PARAM ||
1378                         command == NAND_CMD_RNDOUT)
1379                 addr = (u64)column;
1380         /* Avoid propagating a negative, don't-care address */
1381         else if (page_addr < 0)
1382                 addr = 0;
1383
1384         dev_dbg(ctrl->dev, "cmd 0x%x addr 0x%llx\n", command,
1385                 (unsigned long long)addr);
1386
1387         host->last_cmd = command;
1388         host->last_byte = 0;
1389         host->last_addr = addr;
1390
1391         switch (command) {
1392         case NAND_CMD_RESET:
1393                 native_cmd = CMD_FLASH_RESET;
1394                 break;
1395         case NAND_CMD_STATUS:
1396                 native_cmd = CMD_STATUS_READ;
1397                 break;
1398         case NAND_CMD_READID:
1399                 native_cmd = CMD_DEVICE_ID_READ;
1400                 break;
1401         case NAND_CMD_READOOB:
1402                 native_cmd = CMD_SPARE_AREA_READ;
1403                 break;
1404         case NAND_CMD_ERASE1:
1405                 native_cmd = CMD_BLOCK_ERASE;
1406                 brcmnand_wp(mtd, 0);
1407                 break;
1408         case NAND_CMD_PARAM:
1409                 native_cmd = CMD_PARAMETER_READ;
1410                 break;
1411         case NAND_CMD_SET_FEATURES:
1412         case NAND_CMD_GET_FEATURES:
1413                 brcmnand_low_level_op(host, LL_OP_CMD, command, false);
1414                 brcmnand_low_level_op(host, LL_OP_ADDR, column, false);
1415                 break;
1416         case NAND_CMD_RNDOUT:
1417                 native_cmd = CMD_PARAMETER_CHANGE_COL;
1418                 addr &= ~((u64)(FC_BYTES - 1));
1419                 /*
1420                  * HW quirk: PARAMETER_CHANGE_COL requires SECTOR_SIZE_1K=0
1421                  * NB: hwcfg.sector_size_1k may not be initialized yet
1422                  */
1423                 if (brcmnand_get_sector_size_1k(host)) {
1424                         host->hwcfg.sector_size_1k =
1425                                 brcmnand_get_sector_size_1k(host);
1426                         brcmnand_set_sector_size_1k(host, 0);
1427                 }
1428                 break;
1429         }
1430
1431         if (!native_cmd)
1432                 return;
1433
1434         brcmnand_set_cmd_addr(mtd, addr);
1435         brcmnand_send_cmd(host, native_cmd);
1436         brcmnand_waitfunc(mtd, chip);
1437
1438         if (native_cmd == CMD_PARAMETER_READ ||
1439                         native_cmd == CMD_PARAMETER_CHANGE_COL) {
1440                 /* Copy flash cache word-wise */
1441                 u32 *flash_cache = (u32 *)ctrl->flash_cache;
1442                 int i;
1443
1444                 brcmnand_soc_data_bus_prepare(ctrl->soc, true);
1445
1446                 /*
1447                  * Must cache the FLASH_CACHE now, since changes in
1448                  * SECTOR_SIZE_1K may invalidate it
1449                  */
1450                 for (i = 0; i < FC_WORDS; i++)
1451                         /*
1452                          * Flash cache is big endian for parameter pages, at
1453                          * least on STB SoCs
1454                          */
1455                         flash_cache[i] = be32_to_cpu(brcmnand_read_fc(ctrl, i));
1456
1457                 brcmnand_soc_data_bus_unprepare(ctrl->soc, true);
1458
1459                 /* Cleanup from HW quirk: restore SECTOR_SIZE_1K */
1460                 if (host->hwcfg.sector_size_1k)
1461                         brcmnand_set_sector_size_1k(host,
1462                                                     host->hwcfg.sector_size_1k);
1463         }
1464
1465         /* Re-enable protection is necessary only after erase */
1466         if (command == NAND_CMD_ERASE1)
1467                 brcmnand_wp(mtd, 1);
1468 }
1469
1470 static uint8_t brcmnand_read_byte(struct mtd_info *mtd)
1471 {
1472         struct nand_chip *chip = mtd_to_nand(mtd);
1473         struct brcmnand_host *host = nand_get_controller_data(chip);
1474         struct brcmnand_controller *ctrl = host->ctrl;
1475         uint8_t ret = 0;
1476         int addr, offs;
1477
1478         switch (host->last_cmd) {
1479         case NAND_CMD_READID:
1480                 if (host->last_byte < 4)
1481                         ret = brcmnand_read_reg(ctrl, BRCMNAND_ID) >>
1482                                 (24 - (host->last_byte << 3));
1483                 else if (host->last_byte < 8)
1484                         ret = brcmnand_read_reg(ctrl, BRCMNAND_ID_EXT) >>
1485                                 (56 - (host->last_byte << 3));
1486                 break;
1487
1488         case NAND_CMD_READOOB:
1489                 ret = oob_reg_read(ctrl, host->last_byte);
1490                 break;
1491
1492         case NAND_CMD_STATUS:
1493                 ret = brcmnand_read_reg(ctrl, BRCMNAND_INTFC_STATUS) &
1494                                         INTFC_FLASH_STATUS;
1495                 if (wp_on) /* hide WP status */
1496                         ret |= NAND_STATUS_WP;
1497                 break;
1498
1499         case NAND_CMD_PARAM:
1500         case NAND_CMD_RNDOUT:
1501                 addr = host->last_addr + host->last_byte;
1502                 offs = addr & (FC_BYTES - 1);
1503
1504                 /* At FC_BYTES boundary, switch to next column */
1505                 if (host->last_byte > 0 && offs == 0)
1506                         nand_change_read_column_op(chip, addr, NULL, 0, false);
1507
1508                 ret = ctrl->flash_cache[offs];
1509                 break;
1510         case NAND_CMD_GET_FEATURES:
1511                 if (host->last_byte >= ONFI_SUBFEATURE_PARAM_LEN) {
1512                         ret = 0;
1513                 } else {
1514                         bool last = host->last_byte ==
1515                                 ONFI_SUBFEATURE_PARAM_LEN - 1;
1516                         brcmnand_low_level_op(host, LL_OP_RD, 0, last);
1517                         ret = brcmnand_read_reg(ctrl, BRCMNAND_LL_RDATA) & 0xff;
1518                 }
1519         }
1520
1521         dev_dbg(ctrl->dev, "read byte = 0x%02x\n", ret);
1522         host->last_byte++;
1523
1524         return ret;
1525 }
1526
1527 static void brcmnand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
1528 {
1529         int i;
1530
1531         for (i = 0; i < len; i++, buf++)
1532                 *buf = brcmnand_read_byte(mtd);
1533 }
1534
1535 static void brcmnand_write_buf(struct mtd_info *mtd, const uint8_t *buf,
1536                                    int len)
1537 {
1538         int i;
1539         struct nand_chip *chip = mtd_to_nand(mtd);
1540         struct brcmnand_host *host = nand_get_controller_data(chip);
1541
1542         switch (host->last_cmd) {
1543         case NAND_CMD_SET_FEATURES:
1544                 for (i = 0; i < len; i++)
1545                         brcmnand_low_level_op(host, LL_OP_WR, buf[i],
1546                                                   (i + 1) == len);
1547                 break;
1548         default:
1549                 BUG();
1550                 break;
1551         }
1552 }
1553
1554 /**
1555  * Construct a FLASH_DMA descriptor as part of a linked list. You must know the
1556  * following ahead of time:
1557  *  - Is this descriptor the beginning or end of a linked list?
1558  *  - What is the (DMA) address of the next descriptor in the linked list?
1559  */
1560 static int brcmnand_fill_dma_desc(struct brcmnand_host *host,
1561                                   struct brcm_nand_dma_desc *desc, u64 addr,
1562                                   dma_addr_t buf, u32 len, u8 dma_cmd,
1563                                   bool begin, bool end,
1564                                   dma_addr_t next_desc)
1565 {
1566         memset(desc, 0, sizeof(*desc));
1567         /* Descriptors are written in native byte order (wordwise) */
1568         desc->next_desc = lower_32_bits(next_desc);
1569         desc->next_desc_ext = upper_32_bits(next_desc);
1570         desc->cmd_irq = (dma_cmd << 24) |
1571                 (end ? (0x03 << 8) : 0) | /* IRQ | STOP */
1572                 (!!begin) | ((!!end) << 1); /* head, tail */
1573 #ifdef CONFIG_CPU_BIG_ENDIAN
1574         desc->cmd_irq |= 0x01 << 12;
1575 #endif
1576         desc->dram_addr = lower_32_bits(buf);
1577         desc->dram_addr_ext = upper_32_bits(buf);
1578         desc->tfr_len = len;
1579         desc->total_len = len;
1580         desc->flash_addr = lower_32_bits(addr);
1581         desc->flash_addr_ext = upper_32_bits(addr);
1582         desc->cs = host->cs;
1583         desc->status_valid = 0x01;
1584         return 0;
1585 }
1586
1587 /**
1588  * Kick the FLASH_DMA engine, with a given DMA descriptor
1589  */
1590 static void brcmnand_dma_run(struct brcmnand_host *host, dma_addr_t desc)
1591 {
1592         struct brcmnand_controller *ctrl = host->ctrl;
1593         unsigned long timeo = msecs_to_jiffies(100);
1594
1595         flash_dma_writel(ctrl, FLASH_DMA_FIRST_DESC, lower_32_bits(desc));
1596         (void)flash_dma_readl(ctrl, FLASH_DMA_FIRST_DESC);
1597         flash_dma_writel(ctrl, FLASH_DMA_FIRST_DESC_EXT, upper_32_bits(desc));
1598         (void)flash_dma_readl(ctrl, FLASH_DMA_FIRST_DESC_EXT);
1599
1600         /* Start FLASH_DMA engine */
1601         ctrl->dma_pending = true;
1602         mb(); /* flush previous writes */
1603         flash_dma_writel(ctrl, FLASH_DMA_CTRL, 0x03); /* wake | run */
1604
1605         if (wait_for_completion_timeout(&ctrl->dma_done, timeo) <= 0) {
1606                 dev_err(ctrl->dev,
1607                                 "timeout waiting for DMA; status %#x, error status %#x\n",
1608                                 flash_dma_readl(ctrl, FLASH_DMA_STATUS),
1609                                 flash_dma_readl(ctrl, FLASH_DMA_ERROR_STATUS));
1610         }
1611         ctrl->dma_pending = false;
1612         flash_dma_writel(ctrl, FLASH_DMA_CTRL, 0); /* force stop */
1613 }
1614
1615 static int brcmnand_dma_trans(struct brcmnand_host *host, u64 addr, u32 *buf,
1616                               u32 len, u8 dma_cmd)
1617 {
1618         struct brcmnand_controller *ctrl = host->ctrl;
1619         dma_addr_t buf_pa;
1620         int dir = dma_cmd == CMD_PAGE_READ ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
1621
1622         buf_pa = dma_map_single(ctrl->dev, buf, len, dir);
1623         if (dma_mapping_error(ctrl->dev, buf_pa)) {
1624                 dev_err(ctrl->dev, "unable to map buffer for DMA\n");
1625                 return -ENOMEM;
1626         }
1627
1628         brcmnand_fill_dma_desc(host, ctrl->dma_desc, addr, buf_pa, len,
1629                                    dma_cmd, true, true, 0);
1630
1631         brcmnand_dma_run(host, ctrl->dma_pa);
1632
1633         dma_unmap_single(ctrl->dev, buf_pa, len, dir);
1634
1635         if (ctrl->dma_desc->status_valid & FLASH_DMA_ECC_ERROR)
1636                 return -EBADMSG;
1637         else if (ctrl->dma_desc->status_valid & FLASH_DMA_CORR_ERROR)
1638                 return -EUCLEAN;
1639
1640         return 0;
1641 }
1642
1643 /*
1644  * Assumes proper CS is already set
1645  */
1646 static int brcmnand_read_by_pio(struct mtd_info *mtd, struct nand_chip *chip,
1647                                 u64 addr, unsigned int trans, u32 *buf,
1648                                 u8 *oob, u64 *err_addr)
1649 {
1650         struct brcmnand_host *host = nand_get_controller_data(chip);
1651         struct brcmnand_controller *ctrl = host->ctrl;
1652         int i, j, ret = 0;
1653
1654         brcmnand_clear_ecc_addr(ctrl);
1655
1656         for (i = 0; i < trans; i++, addr += FC_BYTES) {
1657                 brcmnand_set_cmd_addr(mtd, addr);
1658                 /* SPARE_AREA_READ does not use ECC, so just use PAGE_READ */
1659                 brcmnand_send_cmd(host, CMD_PAGE_READ);
1660                 brcmnand_waitfunc(mtd, chip);
1661
1662                 if (likely(buf)) {
1663                         brcmnand_soc_data_bus_prepare(ctrl->soc, false);
1664
1665                         for (j = 0; j < FC_WORDS; j++, buf++)
1666                                 *buf = brcmnand_read_fc(ctrl, j);
1667
1668                         brcmnand_soc_data_bus_unprepare(ctrl->soc, false);
1669                 }
1670
1671                 if (oob)
1672                         oob += read_oob_from_regs(ctrl, i, oob,
1673                                         mtd->oobsize / trans,
1674                                         host->hwcfg.sector_size_1k);
1675
1676                 if (ret != -EBADMSG) {
1677                         *err_addr = brcmnand_get_uncorrecc_addr(ctrl);
1678
1679                         if (*err_addr)
1680                                 ret = -EBADMSG;
1681                 }
1682
1683                 if (!ret) {
1684                         *err_addr = brcmnand_get_correcc_addr(ctrl);
1685
1686                         if (*err_addr)
1687                                 ret = -EUCLEAN;
1688                 }
1689         }
1690
1691         return ret;
1692 }
1693
1694 /*
1695  * Check a page to see if it is erased (w/ bitflips) after an uncorrectable ECC
1696  * error
1697  *
1698  * Because the HW ECC signals an ECC error if an erase paged has even a single
1699  * bitflip, we must check each ECC error to see if it is actually an erased
1700  * page with bitflips, not a truly corrupted page.
1701  *
1702  * On a real error, return a negative error code (-EBADMSG for ECC error), and
1703  * buf will contain raw data.
1704  * Otherwise, buf gets filled with 0xffs and return the maximum number of
1705  * bitflips-per-ECC-sector to the caller.
1706  *
1707  */
1708 static int brcmstb_nand_verify_erased_page(struct mtd_info *mtd,
1709                   struct nand_chip *chip, void *buf, u64 addr)
1710 {
1711         int i, sas;
1712         void *oob = chip->oob_poi;
1713         int bitflips = 0;
1714         int page = addr >> chip->page_shift;
1715         int ret;
1716
1717         if (!buf) {
1718                 buf = chip->data_buf;
1719                 /* Invalidate page cache */
1720                 chip->pagebuf = -1;
1721         }
1722
1723         sas = mtd->oobsize / chip->ecc.steps;
1724
1725         /* read without ecc for verification */
1726         ret = chip->ecc.read_page_raw(mtd, chip, buf, true, page);
1727         if (ret)
1728                 return ret;
1729
1730         for (i = 0; i < chip->ecc.steps; i++, oob += sas) {
1731                 ret = nand_check_erased_ecc_chunk(buf, chip->ecc.size,
1732                                                   oob, sas, NULL, 0,
1733                                                   chip->ecc.strength);
1734                 if (ret < 0)
1735                         return ret;
1736
1737                 bitflips = max(bitflips, ret);
1738         }
1739
1740         return bitflips;
1741 }
1742
1743 static int brcmnand_read(struct mtd_info *mtd, struct nand_chip *chip,
1744                          u64 addr, unsigned int trans, u32 *buf, u8 *oob)
1745 {
1746         struct brcmnand_host *host = nand_get_controller_data(chip);
1747         struct brcmnand_controller *ctrl = host->ctrl;
1748         u64 err_addr = 0;
1749         int err;
1750         bool retry = true;
1751
1752         dev_dbg(ctrl->dev, "read %llx -> %p\n", (unsigned long long)addr, buf);
1753
1754 try_dmaread:
1755         brcmnand_clear_ecc_addr(ctrl);
1756
1757         if (has_flash_dma(ctrl) && !oob && flash_dma_buf_ok(buf)) {
1758                 err = brcmnand_dma_trans(host, addr, buf, trans * FC_BYTES,
1759                                              CMD_PAGE_READ);
1760                 if (err) {
1761                         if (mtd_is_bitflip_or_eccerr(err))
1762                                 err_addr = addr;
1763                         else
1764                                 return -EIO;
1765                 }
1766         } else {
1767                 if (oob)
1768                         memset(oob, 0x99, mtd->oobsize);
1769
1770                 err = brcmnand_read_by_pio(mtd, chip, addr, trans, buf,
1771                                                oob, &err_addr);
1772         }
1773
1774         if (mtd_is_eccerr(err)) {
1775                 /*
1776                  * On controller version and 7.0, 7.1 , DMA read after a
1777                  * prior PIO read that reported uncorrectable error,
1778                  * the DMA engine captures this error following DMA read
1779                  * cleared only on subsequent DMA read, so just retry once
1780                  * to clear a possible false error reported for current DMA
1781                  * read
1782                  */
1783                 if ((ctrl->nand_version == 0x0700) ||
1784                     (ctrl->nand_version == 0x0701)) {
1785                         if (retry) {
1786                                 retry = false;
1787                                 goto try_dmaread;
1788                         }
1789                 }
1790
1791                 /*
1792                  * Controller version 7.2 has hw encoder to detect erased page
1793                  * bitflips, apply sw verification for older controllers only
1794                  */
1795                 if (ctrl->nand_version < 0x0702) {
1796                         err = brcmstb_nand_verify_erased_page(mtd, chip, buf,
1797                                                               addr);
1798                         /* erased page bitflips corrected */
1799                         if (err >= 0)
1800                                 return err;
1801                 }
1802
1803                 dev_dbg(ctrl->dev, "uncorrectable error at 0x%llx\n",
1804                         (unsigned long long)err_addr);
1805                 mtd->ecc_stats.failed++;
1806                 /* NAND layer expects zero on ECC errors */
1807                 return 0;
1808         }
1809
1810         if (mtd_is_bitflip(err)) {
1811                 unsigned int corrected = brcmnand_count_corrected(ctrl);
1812
1813                 dev_dbg(ctrl->dev, "corrected error at 0x%llx\n",
1814                         (unsigned long long)err_addr);
1815                 mtd->ecc_stats.corrected += corrected;
1816                 /* Always exceed the software-imposed threshold */
1817                 return max(mtd->bitflip_threshold, corrected);
1818         }
1819
1820         return 0;
1821 }
1822
1823 static int brcmnand_read_page(struct mtd_info *mtd, struct nand_chip *chip,
1824                               uint8_t *buf, int oob_required, int page)
1825 {
1826         struct brcmnand_host *host = nand_get_controller_data(chip);
1827         u8 *oob = oob_required ? (u8 *)chip->oob_poi : NULL;
1828
1829         nand_read_page_op(chip, page, 0, NULL, 0);
1830
1831         return brcmnand_read(mtd, chip, host->last_addr,
1832                         mtd->writesize >> FC_SHIFT, (u32 *)buf, oob);
1833 }
1834
1835 static int brcmnand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1836                                   uint8_t *buf, int oob_required, int page)
1837 {
1838         struct brcmnand_host *host = nand_get_controller_data(chip);
1839         u8 *oob = oob_required ? (u8 *)chip->oob_poi : NULL;
1840         int ret;
1841
1842         nand_read_page_op(chip, page, 0, NULL, 0);
1843
1844         brcmnand_set_ecc_enabled(host, 0);
1845         ret = brcmnand_read(mtd, chip, host->last_addr,
1846                         mtd->writesize >> FC_SHIFT, (u32 *)buf, oob);
1847         brcmnand_set_ecc_enabled(host, 1);
1848         return ret;
1849 }
1850
1851 static int brcmnand_read_oob(struct mtd_info *mtd, struct nand_chip *chip,
1852                              int page)
1853 {
1854         return brcmnand_read(mtd, chip, (u64)page << chip->page_shift,
1855                         mtd->writesize >> FC_SHIFT,
1856                         NULL, (u8 *)chip->oob_poi);
1857 }
1858
1859 static int brcmnand_read_oob_raw(struct mtd_info *mtd, struct nand_chip *chip,
1860                                  int page)
1861 {
1862         struct brcmnand_host *host = nand_get_controller_data(chip);
1863
1864         brcmnand_set_ecc_enabled(host, 0);
1865         brcmnand_read(mtd, chip, (u64)page << chip->page_shift,
1866                 mtd->writesize >> FC_SHIFT,
1867                 NULL, (u8 *)chip->oob_poi);
1868         brcmnand_set_ecc_enabled(host, 1);
1869         return 0;
1870 }
1871
1872 static int brcmnand_write(struct mtd_info *mtd, struct nand_chip *chip,
1873                           u64 addr, const u32 *buf, u8 *oob)
1874 {
1875         struct brcmnand_host *host = nand_get_controller_data(chip);
1876         struct brcmnand_controller *ctrl = host->ctrl;
1877         unsigned int i, j, trans = mtd->writesize >> FC_SHIFT;
1878         int status, ret = 0;
1879
1880         dev_dbg(ctrl->dev, "write %llx <- %p\n", (unsigned long long)addr, buf);
1881
1882         if (unlikely((unsigned long)buf & 0x03)) {
1883                 dev_warn(ctrl->dev, "unaligned buffer: %p\n", buf);
1884                 buf = (u32 *)((unsigned long)buf & ~0x03);
1885         }
1886
1887         brcmnand_wp(mtd, 0);
1888
1889         for (i = 0; i < ctrl->max_oob; i += 4)
1890                 oob_reg_write(ctrl, i, 0xffffffff);
1891
1892         if (has_flash_dma(ctrl) && !oob && flash_dma_buf_ok(buf)) {
1893                 if (brcmnand_dma_trans(host, addr, (u32 *)buf,
1894                                         mtd->writesize, CMD_PROGRAM_PAGE))
1895                         ret = -EIO;
1896                 goto out;
1897         }
1898
1899         for (i = 0; i < trans; i++, addr += FC_BYTES) {
1900                 /* full address MUST be set before populating FC */
1901                 brcmnand_set_cmd_addr(mtd, addr);
1902
1903                 if (buf) {
1904                         brcmnand_soc_data_bus_prepare(ctrl->soc, false);
1905
1906                         for (j = 0; j < FC_WORDS; j++, buf++)
1907                                 brcmnand_write_fc(ctrl, j, *buf);
1908
1909                         brcmnand_soc_data_bus_unprepare(ctrl->soc, false);
1910                 } else if (oob) {
1911                         for (j = 0; j < FC_WORDS; j++)
1912                                 brcmnand_write_fc(ctrl, j, 0xffffffff);
1913                 }
1914
1915                 if (oob) {
1916                         oob += write_oob_to_regs(ctrl, i, oob,
1917                                         mtd->oobsize / trans,
1918                                         host->hwcfg.sector_size_1k);
1919                 }
1920
1921                 /* we cannot use SPARE_AREA_PROGRAM when PARTIAL_PAGE_EN=0 */
1922                 brcmnand_send_cmd(host, CMD_PROGRAM_PAGE);
1923                 status = brcmnand_waitfunc(mtd, chip);
1924
1925                 if (status & NAND_STATUS_FAIL) {
1926                         dev_info(ctrl->dev, "program failed at %llx\n",
1927                                 (unsigned long long)addr);
1928                         ret = -EIO;
1929                         goto out;
1930                 }
1931         }
1932 out:
1933         brcmnand_wp(mtd, 1);
1934         return ret;
1935 }
1936
1937 static int brcmnand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
1938                                const uint8_t *buf, int oob_required, int page)
1939 {
1940         struct brcmnand_host *host = nand_get_controller_data(chip);
1941         void *oob = oob_required ? chip->oob_poi : NULL;
1942
1943         nand_prog_page_begin_op(chip, page, 0, NULL, 0);
1944         brcmnand_write(mtd, chip, host->last_addr, (const u32 *)buf, oob);
1945
1946         return nand_prog_page_end_op(chip);
1947 }
1948
1949 static int brcmnand_write_page_raw(struct mtd_info *mtd,
1950                                    struct nand_chip *chip, const uint8_t *buf,
1951                                    int oob_required, int page)
1952 {
1953         struct brcmnand_host *host = nand_get_controller_data(chip);
1954         void *oob = oob_required ? chip->oob_poi : NULL;
1955
1956         nand_prog_page_begin_op(chip, page, 0, NULL, 0);
1957         brcmnand_set_ecc_enabled(host, 0);
1958         brcmnand_write(mtd, chip, host->last_addr, (const u32 *)buf, oob);
1959         brcmnand_set_ecc_enabled(host, 1);
1960
1961         return nand_prog_page_end_op(chip);
1962 }
1963
1964 static int brcmnand_write_oob(struct mtd_info *mtd, struct nand_chip *chip,
1965                                   int page)
1966 {
1967         return brcmnand_write(mtd, chip, (u64)page << chip->page_shift,
1968                                   NULL, chip->oob_poi);
1969 }
1970
1971 static int brcmnand_write_oob_raw(struct mtd_info *mtd, struct nand_chip *chip,
1972                                   int page)
1973 {
1974         struct brcmnand_host *host = nand_get_controller_data(chip);
1975         int ret;
1976
1977         brcmnand_set_ecc_enabled(host, 0);
1978         ret = brcmnand_write(mtd, chip, (u64)page << chip->page_shift, NULL,
1979                                  (u8 *)chip->oob_poi);
1980         brcmnand_set_ecc_enabled(host, 1);
1981
1982         return ret;
1983 }
1984
1985 /***********************************************************************
1986  * Per-CS setup (1 NAND device)
1987  ***********************************************************************/
1988
1989 static int brcmnand_set_cfg(struct brcmnand_host *host,
1990                             struct brcmnand_cfg *cfg)
1991 {
1992         struct brcmnand_controller *ctrl = host->ctrl;
1993         struct nand_chip *chip = &host->chip;
1994         u16 cfg_offs = brcmnand_cs_offset(ctrl, host->cs, BRCMNAND_CS_CFG);
1995         u16 cfg_ext_offs = brcmnand_cs_offset(ctrl, host->cs,
1996                         BRCMNAND_CS_CFG_EXT);
1997         u16 acc_control_offs = brcmnand_cs_offset(ctrl, host->cs,
1998                         BRCMNAND_CS_ACC_CONTROL);
1999         u8 block_size = 0, page_size = 0, device_size = 0;
2000         u32 tmp;
2001
2002         if (ctrl->block_sizes) {
2003                 int i, found;
2004
2005                 for (i = 0, found = 0; ctrl->block_sizes[i]; i++)
2006                         if (ctrl->block_sizes[i] * 1024 == cfg->block_size) {
2007                                 block_size = i;
2008                                 found = 1;
2009                         }
2010                 if (!found) {
2011                         dev_warn(ctrl->dev, "invalid block size %u\n",
2012                                         cfg->block_size);
2013                         return -EINVAL;
2014                 }
2015         } else {
2016                 block_size = ffs(cfg->block_size) - ffs(BRCMNAND_MIN_BLOCKSIZE);
2017         }
2018
2019         if (cfg->block_size < BRCMNAND_MIN_BLOCKSIZE || (ctrl->max_block_size &&
2020                                 cfg->block_size > ctrl->max_block_size)) {
2021                 dev_warn(ctrl->dev, "invalid block size %u\n",
2022                                 cfg->block_size);
2023                 block_size = 0;
2024         }
2025
2026         if (ctrl->page_sizes) {
2027                 int i, found;
2028
2029                 for (i = 0, found = 0; ctrl->page_sizes[i]; i++)
2030                         if (ctrl->page_sizes[i] == cfg->page_size) {
2031                                 page_size = i;
2032                                 found = 1;
2033                         }
2034                 if (!found) {
2035                         dev_warn(ctrl->dev, "invalid page size %u\n",
2036                                         cfg->page_size);
2037                         return -EINVAL;
2038                 }
2039         } else {
2040                 page_size = ffs(cfg->page_size) - ffs(BRCMNAND_MIN_PAGESIZE);
2041         }
2042
2043         if (cfg->page_size < BRCMNAND_MIN_PAGESIZE || (ctrl->max_page_size &&
2044                                 cfg->page_size > ctrl->max_page_size)) {
2045                 dev_warn(ctrl->dev, "invalid page size %u\n", cfg->page_size);
2046                 return -EINVAL;
2047         }
2048
2049         if (fls64(cfg->device_size) < fls64(BRCMNAND_MIN_DEVSIZE)) {
2050                 dev_warn(ctrl->dev, "invalid device size 0x%llx\n",
2051                         (unsigned long long)cfg->device_size);
2052                 return -EINVAL;
2053         }
2054         device_size = fls64(cfg->device_size) - fls64(BRCMNAND_MIN_DEVSIZE);
2055
2056         tmp = (cfg->blk_adr_bytes << CFG_BLK_ADR_BYTES_SHIFT) |
2057                 (cfg->col_adr_bytes << CFG_COL_ADR_BYTES_SHIFT) |
2058                 (cfg->ful_adr_bytes << CFG_FUL_ADR_BYTES_SHIFT) |
2059                 (!!(cfg->device_width == 16) << CFG_BUS_WIDTH_SHIFT) |
2060                 (device_size << CFG_DEVICE_SIZE_SHIFT);
2061         if (cfg_offs == cfg_ext_offs) {
2062                 tmp |= (page_size << CFG_PAGE_SIZE_SHIFT) |
2063                        (block_size << CFG_BLK_SIZE_SHIFT);
2064                 nand_writereg(ctrl, cfg_offs, tmp);
2065         } else {
2066                 nand_writereg(ctrl, cfg_offs, tmp);
2067                 tmp = (page_size << CFG_EXT_PAGE_SIZE_SHIFT) |
2068                       (block_size << CFG_EXT_BLK_SIZE_SHIFT);
2069                 nand_writereg(ctrl, cfg_ext_offs, tmp);
2070         }
2071
2072         tmp = nand_readreg(ctrl, acc_control_offs);
2073         tmp &= ~brcmnand_ecc_level_mask(ctrl);
2074         tmp |= cfg->ecc_level << NAND_ACC_CONTROL_ECC_SHIFT;
2075         tmp &= ~brcmnand_spare_area_mask(ctrl);
2076         tmp |= cfg->spare_area_size;
2077         nand_writereg(ctrl, acc_control_offs, tmp);
2078
2079         brcmnand_set_sector_size_1k(host, cfg->sector_size_1k);
2080
2081         /* threshold = ceil(BCH-level * 0.75) */
2082         brcmnand_wr_corr_thresh(host, DIV_ROUND_UP(chip->ecc.strength * 3, 4));
2083
2084         return 0;
2085 }
2086
2087 static void brcmnand_print_cfg(struct brcmnand_host *host,
2088                                char *buf, struct brcmnand_cfg *cfg)
2089 {
2090         buf += sprintf(buf,
2091                 "%lluMiB total, %uKiB blocks, %u%s pages, %uB OOB, %u-bit",
2092                 (unsigned long long)cfg->device_size >> 20,
2093                 cfg->block_size >> 10,
2094                 cfg->page_size >= 1024 ? cfg->page_size >> 10 : cfg->page_size,
2095                 cfg->page_size >= 1024 ? "KiB" : "B",
2096                 cfg->spare_area_size, cfg->device_width);
2097
2098         /* Account for Hamming ECC and for BCH 512B vs 1KiB sectors */
2099         if (is_hamming_ecc(host->ctrl, cfg))
2100                 sprintf(buf, ", Hamming ECC");
2101         else if (cfg->sector_size_1k)
2102                 sprintf(buf, ", BCH-%u (1KiB sector)", cfg->ecc_level << 1);
2103         else
2104                 sprintf(buf, ", BCH-%u", cfg->ecc_level);
2105 }
2106
2107 /*
2108  * Minimum number of bytes to address a page. Calculated as:
2109  *     roundup(log2(size / page-size) / 8)
2110  *
2111  * NB: the following does not "round up" for non-power-of-2 'size'; but this is
2112  *     OK because many other things will break if 'size' is irregular...
2113  */
2114 static inline int get_blk_adr_bytes(u64 size, u32 writesize)
2115 {
2116         return ALIGN(ilog2(size) - ilog2(writesize), 8) >> 3;
2117 }
2118
2119 static int brcmnand_setup_dev(struct brcmnand_host *host)
2120 {
2121         struct mtd_info *mtd = nand_to_mtd(&host->chip);
2122         struct nand_chip *chip = &host->chip;
2123         struct brcmnand_controller *ctrl = host->ctrl;
2124         struct brcmnand_cfg *cfg = &host->hwcfg;
2125         char msg[128];
2126         u32 offs, tmp, oob_sector;
2127         int ret;
2128
2129         memset(cfg, 0, sizeof(*cfg));
2130
2131         ret = of_property_read_u32(nand_get_flash_node(chip),
2132                                    "brcm,nand-oob-sector-size",
2133                                    &oob_sector);
2134         if (ret) {
2135                 /* Use detected size */
2136                 cfg->spare_area_size = mtd->oobsize /
2137                                         (mtd->writesize >> FC_SHIFT);
2138         } else {
2139                 cfg->spare_area_size = oob_sector;
2140         }
2141         if (cfg->spare_area_size > ctrl->max_oob)
2142                 cfg->spare_area_size = ctrl->max_oob;
2143         /*
2144          * Set oobsize to be consistent with controller's spare_area_size, as
2145          * the rest is inaccessible.
2146          */
2147         mtd->oobsize = cfg->spare_area_size * (mtd->writesize >> FC_SHIFT);
2148
2149         cfg->device_size = mtd->size;
2150         cfg->block_size = mtd->erasesize;
2151         cfg->page_size = mtd->writesize;
2152         cfg->device_width = (chip->options & NAND_BUSWIDTH_16) ? 16 : 8;
2153         cfg->col_adr_bytes = 2;
2154         cfg->blk_adr_bytes = get_blk_adr_bytes(mtd->size, mtd->writesize);
2155
2156         if (chip->ecc.mode != NAND_ECC_HW) {
2157                 dev_err(ctrl->dev, "only HW ECC supported; selected: %d\n",
2158                         chip->ecc.mode);
2159                 return -EINVAL;
2160         }
2161
2162         if (chip->ecc.algo == NAND_ECC_UNKNOWN) {
2163                 if (chip->ecc.strength == 1 && chip->ecc.size == 512)
2164                         /* Default to Hamming for 1-bit ECC, if unspecified */
2165                         chip->ecc.algo = NAND_ECC_HAMMING;
2166                 else
2167                         /* Otherwise, BCH */
2168                         chip->ecc.algo = NAND_ECC_BCH;
2169         }
2170
2171         if (chip->ecc.algo == NAND_ECC_HAMMING && (chip->ecc.strength != 1 ||
2172                                                    chip->ecc.size != 512)) {
2173                 dev_err(ctrl->dev, "invalid Hamming params: %d bits per %d bytes\n",
2174                         chip->ecc.strength, chip->ecc.size);
2175                 return -EINVAL;
2176         }
2177
2178         switch (chip->ecc.size) {
2179         case 512:
2180                 if (chip->ecc.algo == NAND_ECC_HAMMING)
2181                         cfg->ecc_level = 15;
2182                 else
2183                         cfg->ecc_level = chip->ecc.strength;
2184                 cfg->sector_size_1k = 0;
2185                 break;
2186         case 1024:
2187                 if (!(ctrl->features & BRCMNAND_HAS_1K_SECTORS)) {
2188                         dev_err(ctrl->dev, "1KB sectors not supported\n");
2189                         return -EINVAL;
2190                 }
2191                 if (chip->ecc.strength & 0x1) {
2192                         dev_err(ctrl->dev,
2193                                 "odd ECC not supported with 1KB sectors\n");
2194                         return -EINVAL;
2195                 }
2196
2197                 cfg->ecc_level = chip->ecc.strength >> 1;
2198                 cfg->sector_size_1k = 1;
2199                 break;
2200         default:
2201                 dev_err(ctrl->dev, "unsupported ECC size: %d\n",
2202                         chip->ecc.size);
2203                 return -EINVAL;
2204         }
2205
2206         cfg->ful_adr_bytes = cfg->blk_adr_bytes;
2207         if (mtd->writesize > 512)
2208                 cfg->ful_adr_bytes += cfg->col_adr_bytes;
2209         else
2210                 cfg->ful_adr_bytes += 1;
2211
2212         ret = brcmnand_set_cfg(host, cfg);
2213         if (ret)
2214                 return ret;
2215
2216         brcmnand_set_ecc_enabled(host, 1);
2217
2218         brcmnand_print_cfg(host, msg, cfg);
2219         dev_info(ctrl->dev, "detected %s\n", msg);
2220
2221         /* Configure ACC_CONTROL */
2222         offs = brcmnand_cs_offset(ctrl, host->cs, BRCMNAND_CS_ACC_CONTROL);
2223         tmp = nand_readreg(ctrl, offs);
2224         tmp &= ~ACC_CONTROL_PARTIAL_PAGE;
2225         tmp &= ~ACC_CONTROL_RD_ERASED;
2226
2227         /* We need to turn on Read from erased paged protected by ECC */
2228         if (ctrl->nand_version >= 0x0702)
2229                 tmp |= ACC_CONTROL_RD_ERASED;
2230         tmp &= ~ACC_CONTROL_FAST_PGM_RDIN;
2231         if (ctrl->features & BRCMNAND_HAS_PREFETCH)
2232                 tmp &= ~ACC_CONTROL_PREFETCH;
2233
2234         nand_writereg(ctrl, offs, tmp);
2235
2236         return 0;
2237 }
2238
2239 static int brcmnand_attach_chip(struct nand_chip *chip)
2240 {
2241         struct mtd_info *mtd = nand_to_mtd(chip);
2242         struct brcmnand_host *host = nand_get_controller_data(chip);
2243         int ret;
2244
2245         chip->options |= NAND_NO_SUBPAGE_WRITE;
2246         /*
2247          * Avoid (for instance) kmap()'d buffers from JFFS2, which we can't DMA
2248          * to/from, and have nand_base pass us a bounce buffer instead, as
2249          * needed.
2250          */
2251         chip->options |= NAND_USE_BOUNCE_BUFFER;
2252
2253         if (chip->bbt_options & NAND_BBT_USE_FLASH)
2254                 chip->bbt_options |= NAND_BBT_NO_OOB;
2255
2256         if (brcmnand_setup_dev(host))
2257                 return -ENXIO;
2258
2259         chip->ecc.size = host->hwcfg.sector_size_1k ? 1024 : 512;
2260
2261         /* only use our internal HW threshold */
2262         mtd->bitflip_threshold = 1;
2263
2264         ret = brcmstb_choose_ecc_layout(host);
2265
2266         /* If OOB is written with ECC enabled it will cause ECC errors */
2267         if (is_hamming_ecc(host->ctrl, &host->hwcfg)) {
2268                 chip->ecc.write_oob = brcmnand_write_oob_raw;
2269                 chip->ecc.read_oob = brcmnand_read_oob_raw;
2270         }
2271
2272         return ret;
2273 }
2274
2275 static const struct nand_controller_ops brcmnand_controller_ops = {
2276         .attach_chip = brcmnand_attach_chip,
2277 };
2278
2279 static int brcmnand_init_cs(struct brcmnand_host *host, struct device_node *dn)
2280 {
2281         struct brcmnand_controller *ctrl = host->ctrl;
2282         struct platform_device *pdev = host->pdev;
2283         struct mtd_info *mtd;
2284         struct nand_chip *chip;
2285         int ret;
2286         u16 cfg_offs;
2287
2288         ret = of_property_read_u32(dn, "reg", &host->cs);
2289         if (ret) {
2290                 dev_err(&pdev->dev, "can't get chip-select\n");
2291                 return -ENXIO;
2292         }
2293
2294         mtd = nand_to_mtd(&host->chip);
2295         chip = &host->chip;
2296
2297         nand_set_flash_node(chip, dn);
2298         nand_set_controller_data(chip, host);
2299         mtd->name = devm_kasprintf(&pdev->dev, GFP_KERNEL, "brcmnand.%d",
2300                                    host->cs);
2301         if (!mtd->name)
2302                 return -ENOMEM;
2303
2304         mtd->owner = THIS_MODULE;
2305         mtd->dev.parent = &pdev->dev;
2306
2307         chip->IO_ADDR_R = (void __iomem *)0xdeadbeef;
2308         chip->IO_ADDR_W = (void __iomem *)0xdeadbeef;
2309
2310         chip->cmd_ctrl = brcmnand_cmd_ctrl;
2311         chip->cmdfunc = brcmnand_cmdfunc;
2312         chip->waitfunc = brcmnand_waitfunc;
2313         chip->read_byte = brcmnand_read_byte;
2314         chip->read_buf = brcmnand_read_buf;
2315         chip->write_buf = brcmnand_write_buf;
2316
2317         chip->ecc.mode = NAND_ECC_HW;
2318         chip->ecc.read_page = brcmnand_read_page;
2319         chip->ecc.write_page = brcmnand_write_page;
2320         chip->ecc.read_page_raw = brcmnand_read_page_raw;
2321         chip->ecc.write_page_raw = brcmnand_write_page_raw;
2322         chip->ecc.write_oob_raw = brcmnand_write_oob_raw;
2323         chip->ecc.read_oob_raw = brcmnand_read_oob_raw;
2324         chip->ecc.read_oob = brcmnand_read_oob;
2325         chip->ecc.write_oob = brcmnand_write_oob;
2326
2327         chip->controller = &ctrl->controller;
2328
2329         /*
2330          * The bootloader might have configured 16bit mode but
2331          * NAND READID command only works in 8bit mode. We force
2332          * 8bit mode here to ensure that NAND READID commands works.
2333          */
2334         cfg_offs = brcmnand_cs_offset(ctrl, host->cs, BRCMNAND_CS_CFG);
2335         nand_writereg(ctrl, cfg_offs,
2336                       nand_readreg(ctrl, cfg_offs) & ~CFG_BUS_WIDTH);
2337
2338         ret = nand_scan(chip, 1);
2339         if (ret)
2340                 return ret;
2341
2342         ret = mtd_device_register(mtd, NULL, 0);
2343         if (ret)
2344                 nand_cleanup(chip);
2345
2346         return ret;
2347 }
2348
2349 static void brcmnand_save_restore_cs_config(struct brcmnand_host *host,
2350                                             int restore)
2351 {
2352         struct brcmnand_controller *ctrl = host->ctrl;
2353         u16 cfg_offs = brcmnand_cs_offset(ctrl, host->cs, BRCMNAND_CS_CFG);
2354         u16 cfg_ext_offs = brcmnand_cs_offset(ctrl, host->cs,
2355                         BRCMNAND_CS_CFG_EXT);
2356         u16 acc_control_offs = brcmnand_cs_offset(ctrl, host->cs,
2357                         BRCMNAND_CS_ACC_CONTROL);
2358         u16 t1_offs = brcmnand_cs_offset(ctrl, host->cs, BRCMNAND_CS_TIMING1);
2359         u16 t2_offs = brcmnand_cs_offset(ctrl, host->cs, BRCMNAND_CS_TIMING2);
2360
2361         if (restore) {
2362                 nand_writereg(ctrl, cfg_offs, host->hwcfg.config);
2363                 if (cfg_offs != cfg_ext_offs)
2364                         nand_writereg(ctrl, cfg_ext_offs,
2365                                       host->hwcfg.config_ext);
2366                 nand_writereg(ctrl, acc_control_offs, host->hwcfg.acc_control);
2367                 nand_writereg(ctrl, t1_offs, host->hwcfg.timing_1);
2368                 nand_writereg(ctrl, t2_offs, host->hwcfg.timing_2);
2369         } else {
2370                 host->hwcfg.config = nand_readreg(ctrl, cfg_offs);
2371                 if (cfg_offs != cfg_ext_offs)
2372                         host->hwcfg.config_ext =
2373                                 nand_readreg(ctrl, cfg_ext_offs);
2374                 host->hwcfg.acc_control = nand_readreg(ctrl, acc_control_offs);
2375                 host->hwcfg.timing_1 = nand_readreg(ctrl, t1_offs);
2376                 host->hwcfg.timing_2 = nand_readreg(ctrl, t2_offs);
2377         }
2378 }
2379
2380 static int brcmnand_suspend(struct device *dev)
2381 {
2382         struct brcmnand_controller *ctrl = dev_get_drvdata(dev);
2383         struct brcmnand_host *host;
2384
2385         list_for_each_entry(host, &ctrl->host_list, node)
2386                 brcmnand_save_restore_cs_config(host, 0);
2387
2388         ctrl->nand_cs_nand_select = brcmnand_read_reg(ctrl, BRCMNAND_CS_SELECT);
2389         ctrl->nand_cs_nand_xor = brcmnand_read_reg(ctrl, BRCMNAND_CS_XOR);
2390         ctrl->corr_stat_threshold =
2391                 brcmnand_read_reg(ctrl, BRCMNAND_CORR_THRESHOLD);
2392
2393         if (has_flash_dma(ctrl))
2394                 ctrl->flash_dma_mode = flash_dma_readl(ctrl, FLASH_DMA_MODE);
2395
2396         return 0;
2397 }
2398
2399 static int brcmnand_resume(struct device *dev)
2400 {
2401         struct brcmnand_controller *ctrl = dev_get_drvdata(dev);
2402         struct brcmnand_host *host;
2403
2404         if (has_flash_dma(ctrl)) {
2405                 flash_dma_writel(ctrl, FLASH_DMA_MODE, ctrl->flash_dma_mode);
2406                 flash_dma_writel(ctrl, FLASH_DMA_ERROR_STATUS, 0);
2407         }
2408
2409         brcmnand_write_reg(ctrl, BRCMNAND_CS_SELECT, ctrl->nand_cs_nand_select);
2410         brcmnand_write_reg(ctrl, BRCMNAND_CS_XOR, ctrl->nand_cs_nand_xor);
2411         brcmnand_write_reg(ctrl, BRCMNAND_CORR_THRESHOLD,
2412                         ctrl->corr_stat_threshold);
2413         if (ctrl->soc) {
2414                 /* Clear/re-enable interrupt */
2415                 ctrl->soc->ctlrdy_ack(ctrl->soc);
2416                 ctrl->soc->ctlrdy_set_enabled(ctrl->soc, true);
2417         }
2418
2419         list_for_each_entry(host, &ctrl->host_list, node) {
2420                 struct nand_chip *chip = &host->chip;
2421
2422                 brcmnand_save_restore_cs_config(host, 1);
2423
2424                 /* Reset the chip, required by some chips after power-up */
2425                 nand_reset_op(chip);
2426         }
2427
2428         return 0;
2429 }
2430
2431 const struct dev_pm_ops brcmnand_pm_ops = {
2432         .suspend                = brcmnand_suspend,
2433         .resume                 = brcmnand_resume,
2434 };
2435 EXPORT_SYMBOL_GPL(brcmnand_pm_ops);
2436
2437 static const struct of_device_id brcmnand_of_match[] = {
2438         { .compatible = "brcm,brcmnand-v4.0" },
2439         { .compatible = "brcm,brcmnand-v5.0" },
2440         { .compatible = "brcm,brcmnand-v6.0" },
2441         { .compatible = "brcm,brcmnand-v6.1" },
2442         { .compatible = "brcm,brcmnand-v6.2" },
2443         { .compatible = "brcm,brcmnand-v7.0" },
2444         { .compatible = "brcm,brcmnand-v7.1" },
2445         { .compatible = "brcm,brcmnand-v7.2" },
2446         {},
2447 };
2448 MODULE_DEVICE_TABLE(of, brcmnand_of_match);
2449
2450 /***********************************************************************
2451  * Platform driver setup (per controller)
2452  ***********************************************************************/
2453
2454 int brcmnand_probe(struct platform_device *pdev, struct brcmnand_soc *soc)
2455 {
2456         struct device *dev = &pdev->dev;
2457         struct device_node *dn = dev->of_node, *child;
2458         struct brcmnand_controller *ctrl;
2459         struct resource *res;
2460         int ret;
2461
2462         /* We only support device-tree instantiation */
2463         if (!dn)
2464                 return -ENODEV;
2465
2466         if (!of_match_node(brcmnand_of_match, dn))
2467                 return -ENODEV;
2468
2469         ctrl = devm_kzalloc(dev, sizeof(*ctrl), GFP_KERNEL);
2470         if (!ctrl)
2471                 return -ENOMEM;
2472
2473         dev_set_drvdata(dev, ctrl);
2474         ctrl->dev = dev;
2475
2476         init_completion(&ctrl->done);
2477         init_completion(&ctrl->dma_done);
2478         nand_controller_init(&ctrl->controller);
2479         ctrl->controller.ops = &brcmnand_controller_ops;
2480         INIT_LIST_HEAD(&ctrl->host_list);
2481
2482         /* NAND register range */
2483         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2484         ctrl->nand_base = devm_ioremap_resource(dev, res);
2485         if (IS_ERR(ctrl->nand_base))
2486                 return PTR_ERR(ctrl->nand_base);
2487
2488         /* Enable clock before using NAND registers */
2489         ctrl->clk = devm_clk_get(dev, "nand");
2490         if (!IS_ERR(ctrl->clk)) {
2491                 ret = clk_prepare_enable(ctrl->clk);
2492                 if (ret)
2493                         return ret;
2494         } else {
2495                 ret = PTR_ERR(ctrl->clk);
2496                 if (ret == -EPROBE_DEFER)
2497                         return ret;
2498
2499                 ctrl->clk = NULL;
2500         }
2501
2502         /* Initialize NAND revision */
2503         ret = brcmnand_revision_init(ctrl);
2504         if (ret)
2505                 goto err;
2506
2507         /*
2508          * Most chips have this cache at a fixed offset within 'nand' block.
2509          * Some must specify this region separately.
2510          */
2511         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "nand-cache");
2512         if (res) {
2513                 ctrl->nand_fc = devm_ioremap_resource(dev, res);
2514                 if (IS_ERR(ctrl->nand_fc)) {
2515                         ret = PTR_ERR(ctrl->nand_fc);
2516                         goto err;
2517                 }
2518         } else {
2519                 ctrl->nand_fc = ctrl->nand_base +
2520                                 ctrl->reg_offsets[BRCMNAND_FC_BASE];
2521         }
2522
2523         /* FLASH_DMA */
2524         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "flash-dma");
2525         if (res) {
2526                 ctrl->flash_dma_base = devm_ioremap_resource(dev, res);
2527                 if (IS_ERR(ctrl->flash_dma_base)) {
2528                         ret = PTR_ERR(ctrl->flash_dma_base);
2529                         goto err;
2530                 }
2531
2532                 flash_dma_writel(ctrl, FLASH_DMA_MODE, 1); /* linked-list */
2533                 flash_dma_writel(ctrl, FLASH_DMA_ERROR_STATUS, 0);
2534
2535                 /* Allocate descriptor(s) */
2536                 ctrl->dma_desc = dmam_alloc_coherent(dev,
2537                                                      sizeof(*ctrl->dma_desc),
2538                                                      &ctrl->dma_pa, GFP_KERNEL);
2539                 if (!ctrl->dma_desc) {
2540                         ret = -ENOMEM;
2541                         goto err;
2542                 }
2543
2544                 ctrl->dma_irq = platform_get_irq(pdev, 1);
2545                 if ((int)ctrl->dma_irq < 0) {
2546                         dev_err(dev, "missing FLASH_DMA IRQ\n");
2547                         ret = -ENODEV;
2548                         goto err;
2549                 }
2550
2551                 ret = devm_request_irq(dev, ctrl->dma_irq,
2552                                 brcmnand_dma_irq, 0, DRV_NAME,
2553                                 ctrl);
2554                 if (ret < 0) {
2555                         dev_err(dev, "can't allocate IRQ %d: error %d\n",
2556                                         ctrl->dma_irq, ret);
2557                         goto err;
2558                 }
2559
2560                 dev_info(dev, "enabling FLASH_DMA\n");
2561         }
2562
2563         /* Disable automatic device ID config, direct addressing */
2564         brcmnand_rmw_reg(ctrl, BRCMNAND_CS_SELECT,
2565                          CS_SELECT_AUTO_DEVICE_ID_CFG | 0xff, 0, 0);
2566         /* Disable XOR addressing */
2567         brcmnand_rmw_reg(ctrl, BRCMNAND_CS_XOR, 0xff, 0, 0);
2568
2569         if (ctrl->features & BRCMNAND_HAS_WP) {
2570                 /* Permanently disable write protection */
2571                 if (wp_on == 2)
2572                         brcmnand_set_wp(ctrl, false);
2573         } else {
2574                 wp_on = 0;
2575         }
2576
2577         /* IRQ */
2578         ctrl->irq = platform_get_irq(pdev, 0);
2579         if ((int)ctrl->irq < 0) {
2580                 dev_err(dev, "no IRQ defined\n");
2581                 ret = -ENODEV;
2582                 goto err;
2583         }
2584
2585         /*
2586          * Some SoCs integrate this controller (e.g., its interrupt bits) in
2587          * interesting ways
2588          */
2589         if (soc) {
2590                 ctrl->soc = soc;
2591
2592                 ret = devm_request_irq(dev, ctrl->irq, brcmnand_irq, 0,
2593                                        DRV_NAME, ctrl);
2594
2595                 /* Enable interrupt */
2596                 ctrl->soc->ctlrdy_ack(ctrl->soc);
2597                 ctrl->soc->ctlrdy_set_enabled(ctrl->soc, true);
2598         } else {
2599                 /* Use standard interrupt infrastructure */
2600                 ret = devm_request_irq(dev, ctrl->irq, brcmnand_ctlrdy_irq, 0,
2601                                        DRV_NAME, ctrl);
2602         }
2603         if (ret < 0) {
2604                 dev_err(dev, "can't allocate IRQ %d: error %d\n",
2605                         ctrl->irq, ret);
2606                 goto err;
2607         }
2608
2609         for_each_available_child_of_node(dn, child) {
2610                 if (of_device_is_compatible(child, "brcm,nandcs")) {
2611                         struct brcmnand_host *host;
2612
2613                         host = devm_kzalloc(dev, sizeof(*host), GFP_KERNEL);
2614                         if (!host) {
2615                                 of_node_put(child);
2616                                 ret = -ENOMEM;
2617                                 goto err;
2618                         }
2619                         host->pdev = pdev;
2620                         host->ctrl = ctrl;
2621
2622                         ret = brcmnand_init_cs(host, child);
2623                         if (ret) {
2624                                 devm_kfree(dev, host);
2625                                 continue; /* Try all chip-selects */
2626                         }
2627
2628                         list_add_tail(&host->node, &ctrl->host_list);
2629                 }
2630         }
2631
2632         /* No chip-selects could initialize properly */
2633         if (list_empty(&ctrl->host_list)) {
2634                 ret = -ENODEV;
2635                 goto err;
2636         }
2637
2638         return 0;
2639
2640 err:
2641         clk_disable_unprepare(ctrl->clk);
2642         return ret;
2643
2644 }
2645 EXPORT_SYMBOL_GPL(brcmnand_probe);
2646
2647 int brcmnand_remove(struct platform_device *pdev)
2648 {
2649         struct brcmnand_controller *ctrl = dev_get_drvdata(&pdev->dev);
2650         struct brcmnand_host *host;
2651
2652         list_for_each_entry(host, &ctrl->host_list, node)
2653                 nand_release(&host->chip);
2654
2655         clk_disable_unprepare(ctrl->clk);
2656
2657         dev_set_drvdata(&pdev->dev, NULL);
2658
2659         return 0;
2660 }
2661 EXPORT_SYMBOL_GPL(brcmnand_remove);
2662
2663 MODULE_LICENSE("GPL v2");
2664 MODULE_AUTHOR("Kevin Cernekee");
2665 MODULE_AUTHOR("Brian Norris");
2666 MODULE_DESCRIPTION("NAND driver for Broadcom chips");
2667 MODULE_ALIAS("platform:brcmnand");