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