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