]> git.kernelconcepts.de Git - karo-tx-redboot.git/blob - packages/devs/flash/arm/mxc/v2_0/src/mxc_nfc.c
cleanup
[karo-tx-redboot.git] / packages / devs / flash / arm / mxc / v2_0 / src / mxc_nfc.c
1 //==========================================================================
2 //
3 //              mxc_nfc.c
4 //
5 //              Flash programming to support NAND flash on Freescale MXC platforms
6 //
7 //==========================================================================
8 //####ECOSGPLCOPYRIGHTBEGIN####
9 // -------------------------------------------
10 // This file is part of eCos, the Embedded Configurable Operating System.
11 // Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
12 //
13 // eCos is free software; you can redistribute it and/or modify it under
14 // the terms of the GNU General Public License as published by the Free
15 // Software Foundation; either version 2 or (at your option) any later version.
16 //
17 // eCos is distributed in the hope that it will be useful, but WITHOUT ANY
18 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 // FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20 // for more details.
21 //
22 // You should have received a copy of the GNU General Public License along
23 // with eCos; if not, write to the Free Software Foundation, Inc.,
24 // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
25 //
26 // As a special exception, if other files instantiate templates or use macros
27 // or inline functions from this file, or you compile this file and link it
28 // with other works to produce a work based on this file, this file does not
29 // by itself cause the resulting work to be covered by the GNU General Public
30 // License. However the source code for this file must still be made available
31 // in accordance with section (3) of the GNU General Public License.
32 //
33 // This exception does not invalidate any other reasons why a work based on
34 // this file might be covered by the GNU General Public License.
35 //
36 // Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
37 // at http://sources.redhat.com/ecos/ecos-license/
38 // -------------------------------------------
39 //####ECOSGPLCOPYRIGHTEND####
40 //==========================================================================
41 //#####DESCRIPTIONBEGIN####
42 //
43 // Author(s):    Kevin Zhang <k.zhang@freescale.com>
44 // Contributors: Kevin Zhang <k.zhang@freescale.com>
45 // Date:                 2006-01-23 Initial version
46 // Date:                 2007-12-20 Update to support 4K page and bbt management.
47 // Purpose:
48 // Description:
49 //       -- Add bad block management according to Linux NAND MTD implementation.
50 //              Reference linux/drivers/mtd/nand/nand_bbt.c by Thomas Gleixner
51 //              Summary:
52 //                 1. Last 4 blocks are reserved for one main BBT and one
53 //                        mirror BBT (2 spare ones just in case a block turns bad.)
54 //                 2. The main BBT block's spare area starts with "Bbt0" followed
55 //                        by a version number starting from 1.
56 //                 3. The mirror BBT block's spare area starts with "1tbB" followed
57 //                        by a version number also starting from 1.
58 //                 4. The actual main area, starting from first page in the BBT block,
59 //                        is used to indicate if a block is bad or not through 2bit/block:
60 //                              * The table uses 2 bits per block
61 //                              * 11b:  block is good
62 //                              * 00b:  block is factory marked bad
63 //                              * 01b:  block is marked bad due to wear
64 //                              * 10b:  block is marked reserved (for BBT)
65 //              Redboot operations: During boot, it searches for the marker for
66 //                                                      either main BBT or mirror BBT based on the marker:
67 //                 case 1: Neither table is found:
68 //                                 Do the bad block scan of the whole flash with ECC off. Use
69 //                                 manufactor marked BI field to decide if a block is bad and
70 //                                 then build the BBT in RAM. Then write this table to both
71 //                                 main BBT block and mirror BBT block.
72 //                 case 2: Only one table is found:
73 //                                 Load the BBT from the flash and stored in the RAM.
74 //                                 Then build the 2nd BBT in the flash.
75 //                 case 3: If both tables found, load the one with higher version in the
76 //                                 RAM and then update the block with older BBT info with the
77 //                                 newer one. If same version, just then read out the table in
78 //                                 RAM.
79 //
80 //####DESCRIPTIONEND####
81 //
82 //==========================================================================
83
84 #include <pkgconf/hal.h>
85 #include <cyg/hal/hal_arch.h>
86 #include <cyg/hal/hal_cache.h>
87 #include <cyg/io/nand_bbt.h>
88 #include <redboot.h>
89 #include <stdlib.h>
90
91 #include CYGHWR_MEMORY_LAYOUT_H
92
93 #include <cyg/hal/hal_io.h>
94 #define  _FLASH_PRIVATE_
95 #include <cyg/io/flash.h>
96
97 #include CYGHWR_FLASH_NAND_BBT_HEADER
98
99 #include <cyg/io/imx_nfc.h>
100
101 #define ECC_FORCE_ON    1
102 #define ECC_FORCE_OFF   2
103
104 typedef u64 flash_addr_t;
105
106 enum blk_bad_type
107 {
108         BLK_GOOD = 0,
109         BLK_BAD_RUNTIME = 1,
110         BLK_RESERVED = 2,
111         BLK_BAD_FACTORY = 3,
112 };
113
114 #define diag_printf1(fmt...) CYG_MACRO_START                                            \
115                 if (g_nfc_debug_level >= NFC_DEBUG_MIN) diag_printf(fmt);       \
116 CYG_MACRO_END
117
118 #define MXC_UNLOCK_BLK_END              0xFFFF
119
120 extern unsigned int hal_timer_count(void);
121 int nfc_program_region(flash_addr_t addr, u8 *buf, u32 len);
122 int nfc_erase_region(flash_addr_t addr, u32 len, bool skip_bad, bool verbose);
123
124 static int nfc_write_pg_random(u32 pg_no, u32 pg_off, u8 *buf, u32 ecc_force);
125 static int nfc_read_pg_random(u32 pg_no, u32 pg_off, u32 ecc_force, u32 cs_line,
126                                                           u32 num_of_nand_chips);
127 static int nfc_erase_blk(u32 ra);
128 static void print_page(u32 addr, bool spare_only);
129 static int nfc_read_page(u32 cs_line, u32 pg_no, u32 pg_off);
130 static int mxc_nfc_scan(bool lowlevel);
131 static void read_nflash_id(u32 *id, u32 cs_line);
132 static int nfc_program_blk(u32 ra, u8 *buf, u32 len);
133
134 static void print_pkt_16(u16 *pkt, u32 len);
135
136 // globals
137 static int nand_flash_index = -1;
138 static int g_ecc_enable = true;
139 static int g_spare_only_read_ok = true;
140 static int g_nfc_debug_level = NFC_DEBUG_NONE;
141 static bool g_nfc_debug_measure = false;
142 static bool g_is_2k_page = false;
143 static unsigned int g_block_offset;
144 static bool g_is_4k_page = false;
145 static unsigned int g_nfc_version = MXC_NFC_V1; // default to version 1.0
146 static int      num_of_nand_chips = 1;
147 static int num_of_nand_chips_for_nandsize = 1;
148 static int scale_block_cnt = 1;
149
150 #define nfc_printf(level, args...) CYG_MACRO_START      \
151                 if (g_nfc_debug_level >= level)                         \
152                         diag_printf(args);                                              \
153 CYG_MACRO_END
154
155 #if defined(NFC_V2_0) || defined(NFC_V2_1)
156 #include <cyg/io/mxc_nfc_v2.h>
157 #elif defined(NFC_V3_0)
158 #include <cyg/io/mxc_nfc_v3.h>
159 #else
160 #include <cyg/io/mxc_nfc.h>
161 #endif
162
163 #ifndef NAND_LAUNCH_REG
164 #define NAND_LAUNCH_REG                         0xDEADEEEE
165 #define NAND_CONFIGURATION1_REG         0xDEADEEEE
166 #define NFC_FLASH_CONFIG2_REG           0xDEADEEEE
167 #define NFC_FLASH_CONFIG2_ECC_EN        0xDEADEEEE
168 #define write_nfc_ip_reg(a, b)
169 #endif
170
171 #ifndef MXCFLASH_SELECT_MULTI
172 void flash_query(void *data)
173 #else
174 void nandflash_query(void *data)
175 #endif
176 {
177         u32 id[2];
178         read_nflash_id(&id[0], 0);
179         nfc_printf(NFC_DEBUG_MAX, "%s(ID=0x%02x: 0x%02x, 0x%02x, 0x%02x)\n", __FUNCTION__,
180                            id[0] & 0xff, (id[0] >> 8) & 0xff, (id[0] >> 16) & 0xff, id[0] >> 24);
181         memcpy(data, id, sizeof(id));
182 }
183
184 #ifndef MXCFLASH_SELECT_MULTI
185 int flash_program_buf(void *addr, void *data, int len)
186 #else
187 int nandflash_program_buf(void *addr, void *data, int len)
188 #endif
189 {
190         nfc_printf(NFC_DEBUG_MAX, "%s(addr=%p, data=%p, len=0x%08x)\n",
191                            __FUNCTION__, addr, data, len);
192         return nfc_program_region((u32)addr, data, len);
193 }
194
195 #ifndef MXCFLASH_SELECT_MULTI
196 int flash_erase_block(void *block, unsigned int size)
197 #else
198 int nandflash_erase_block(void *block, unsigned int size)
199 #endif
200 {
201         nfc_printf(NFC_DEBUG_MAX, "%s(block=%p, size=0x%08x)\n",
202                            __FUNCTION__, block, size);
203         return nfc_erase_region((u32)block, size, 1, 0);
204 }
205
206 #ifndef MXCFLASH_SELECT_MULTI
207 bool flash_code_overlaps(void *start, void *end)
208 #else
209 bool nandflash_code_overlaps(void *start, void *end)
210 #endif
211 {
212         extern unsigned char _stext[], _etext[];
213
214         return ((((unsigned long)&_stext >= (unsigned long)start) &&
215                          ((unsigned long)&_stext < (unsigned long)end)) ||
216                         (((unsigned long)&_etext >= (unsigned long)start) &&
217                          ((unsigned long)&_etext < (unsigned long)end)));
218 }
219
220 #ifndef MXCFLASH_SELECT_MULTI
221 int flash_hwr_map_error(int e)
222 #else
223 int nandflash_hwr_map_error(int e)
224 #endif
225 {
226         return e;
227 }
228
229 #ifndef MXCFLASH_SELECT_MULTI
230 int flash_lock_block(void *block)
231 #else
232 int nandflash_lock_block(void *block)
233 #endif
234 {
235         // Not supported yet
236         return 0;
237 }
238
239 #ifndef MXCFLASH_SELECT_MULTI
240 int flash_unlock_block(void *block, int block_size, int blocks)
241 #else
242 int nandflash_unlock_block(void *block, int block_size, int blocks)
243 #endif
244 {
245         // Not supported yet
246         return 0;
247 }
248
249 //----------------------------------------------------------------------------
250 // Now that device properties are defined, include magic for defining
251 // accessor type and constants.
252 #include <cyg/io/flash_dev.h>
253
254 // Information about supported devices
255 typedef struct flash_dev_info {
256         cyg_uint16       device_id;
257         cyg_uint16       device_id2;
258         cyg_uint16       device_id3;
259         cyg_uint16       device_id4;
260         cyg_uint16       page_size;
261         cyg_uint16       spare_size;
262         cyg_uint32       pages_per_block;
263         cyg_uint32       block_size;
264         cyg_int32        block_count;
265         cyg_uint32       device_size;
266         cyg_uint32       port_size;             // x8 or x16 IO
267         cyg_uint32       type;                  // SLC vs MLC
268         cyg_uint32       options;
269         cyg_uint32       fis_start_addr;
270         cyg_uint32       bi_off;
271         cyg_uint32       bbt_blk_max_nr;
272         cyg_uint8        vendor_info[96];
273         cyg_uint32       col_cycle;                // number of column address cycles
274         cyg_uint32       row_cycle;                // number of row address cycles
275         cyg_uint32       max_bad_blk;
276 } flash_dev_info_t;
277
278 static const flash_dev_info_t *flash_dev_info;
279 static const flash_dev_info_t supported_devices[] = {
280 #include <cyg/io/mxc_nand_parts.inl>
281 };
282 #define NUM_DEVICES NUM_ELEMS(supported_devices)
283
284 #define COL_CYCLE                                       flash_dev_info->col_cycle
285 #define ROW_CYCLE                                       flash_dev_info->row_cycle
286 #define NF_PG_SZ                                        ((flash_dev_info->page_size) * num_of_nand_chips)
287 #define NF_SPARE_SZ                                     ((flash_dev_info->spare_size) * num_of_nand_chips)
288 #define NF_PG_PER_BLK                           flash_dev_info->pages_per_block
289 #define NF_DEV_SZ                                       ((flash_dev_info->device_size) * num_of_nand_chips_for_nandsize)
290 #define NF_BLK_SZ                                       ((flash_dev_info->block_size) * num_of_nand_chips)
291 #define NF_BLK_CNT                                      ((flash_dev_info->block_count) / scale_block_cnt)
292 #define NF_VEND_INFO                            flash_dev_info->vendor_info
293 #define NF_OPTIONS                                      flash_dev_info->options
294 #define NF_BBT_MAX_NR                           flash_dev_info->bbt_blk_max_nr
295 #define NF_OPTIONS                                      flash_dev_info->options
296 #define NF_BI_OFF                                       flash_dev_info->bi_off
297
298 #define MXC_NAND_ADDR_MASK                              (NF_DEV_SZ - 1)
299 #define BLOCK_TO_OFFSET(blk)                    ((blk) * NF_PG_PER_BLK * NF_PG_SZ)
300 #define BLOCK_TO_PAGE(blk)                              ((blk) * NF_PG_PER_BLK)
301 #define BLOCK_PAGE_TO_OFFSET(blk, pge)  (((blk) * NF_PG_PER_BLK + (pge)) * NF_PG_SZ)
302 #define OFFSET_TO_BLOCK(offset)                 ((u32)((offset) / (NF_PG_SZ * NF_PG_PER_BLK)))
303 #define OFFSET_TO_PAGE(offset)                  ((u32)((offset) / NF_PG_SZ) % NF_PG_PER_BLK)
304
305 static u8 *g_bbt, *g_page_buf;
306 static u32 g_bbt_sz;
307 static bool mxcnfc_init_ok = false;
308 static bool mxc_nfc_scan_done;
309
310 // this callback allows the platform specific function to be called right
311 // after flash_dev_query()
312 nfc_setup_func_t *nfc_setup = NULL;
313
314 // this callback allows the platform specific iomux setup
315 nfc_iomuxsetup_func_t *nfc_iomux_setup = NULL;
316
317 static flash_addr_t flash_region_start;
318 static flash_addr_t flash_region_end;
319 static int flash_enable;
320
321 /* This assumes reading the flash with monotonically increasing flash addresses */
322 static flash_addr_t nfc_l_to_p(flash_addr_t addr)
323 {
324         if (g_block_offset == 0) {
325                 return addr;
326         } else {
327                 flash_addr_t ra;
328                 u32 block = (addr & MXC_NAND_ADDR_MASK) / NF_BLK_SZ;
329                 u32 offset = addr % NF_BLK_SZ;
330
331                 ra = (block + g_block_offset) * NF_BLK_SZ + offset;
332                 if (offset == 0) {
333                         nfc_printf(NFC_DEBUG_MIN,
334                                            "Remapping block %u at addr 0x%08llx to block %u at addr 0x%08llx\n",
335                                            block, (u64)addr, block + g_block_offset, (u64)ra);
336                 }
337                 return ra;
338         }
339 }
340
341 static int flash_addr_valid(flash_addr_t addr)
342 {
343         if (addr < flash_region_start || addr >= flash_region_end) {
344                 diag_printf("Flash address 0x%08llx is outside valid region 0x%08llx..0x%08llx\n",
345                                         (u64)addr, (u64)flash_region_start, (u64)flash_region_end);
346         }
347         return addr >= flash_region_start && addr < flash_region_end;
348 }
349
350 /* FIXME: we should pass flash_addr_t as arguments */
351 void mxc_flash_enable(void *start, void *end)
352 {
353         flash_addr_t s = (unsigned long)start & MXC_NAND_ADDR_MASK;
354         flash_addr_t e = (unsigned long)end & MXC_NAND_ADDR_MASK;
355
356         if (flash_enable++ == 0) {
357                 flash_region_start = s;
358                 flash_region_end = e;
359                 diag_printf1("Enabling flash region 0x%08llx..0x%08llx\n",
360                                          (u64)s, (u64)e);
361                 g_block_offset = 0;
362         } else {
363                 if (s < flash_region_start ||
364                         e > flash_region_end) {
365                         diag_printf("** WARNING: Enable 0x%08llx..0x%08llx outside enabled flash region 0x%08llx..0x%08llx\n",
366                                                 (u64)s, (u64)e, (u64)flash_region_start, (u64)flash_region_end);
367                 }
368         }
369 }
370
371 void mxc_flash_disable(void *start, void *end)
372 {
373         flash_addr_t s = (unsigned long)start & MXC_NAND_ADDR_MASK;
374         flash_addr_t e = (unsigned long)end & MXC_NAND_ADDR_MASK;
375
376         if (flash_enable) {
377                 if (--flash_enable == 0) {
378                         diag_printf1("Disabling flash region 0x%08llx..0x%08llx\n",
379                                                  (u64)s, (u64)e);
380                         if (s != flash_region_start ||
381                                 e != flash_region_end) {
382                                 diag_printf("** Error: Disable 0x%08llx..0x%08llx not equal to enabled flash region 0x%08llx..0x%08llx\n",
383                                                 (u64)s, (u64)e, (u64)flash_region_start, (u64)flash_region_end);
384                         }
385                 }
386         } else {
387                 diag_printf("** Error: unbalanced call to flash_disable()\n");
388         }
389 }
390
391 int
392 #ifndef MXCFLASH_SELECT_MULTI
393 flash_hwr_init(void)
394 #else
395 nandflash_hwr_init(void)
396 #endif
397 {
398         u32 id[2];
399         int i;
400
401         nfc_printf(NFC_DEBUG_MAX, "%s()\n", __FUNCTION__);
402
403         if (nfc_iomux_setup)
404                 nfc_iomux_setup();
405
406         NFC_SET_NFC_ACTIVE_CS(0);
407         NFC_CMD_INPUT(FLASH_Reset);
408
409         // Look through table for device data
410         flash_dev_query(&id[0]);
411         flash_dev_info = supported_devices;
412         for (i = 0; i < NUM_DEVICES; i++) {
413                 if ((flash_dev_info->device_id == (id[0] & 0xffff)) &&
414                         (flash_dev_info->device_id2 == 0xFFFF ||
415                          flash_dev_info->device_id2 == (id[0] >> 16)))
416                         break;
417                 flash_dev_info++;
418         }
419
420         // Did we find the device? If not, return error.
421         if (NUM_DEVICES == i) {
422                 diag_printf("Unrecognized NAND part: 0x%02x, 0x%02x, 0x%02x, 0x%02x\n",
423                                         id[0] & 0xff, (id[0] >> 8) & 0xff, (id[0] >> 16) & 0xff, id[0] >> 24);
424                 return FLASH_ERR_DRV_WRONG_PART;
425         }
426
427         nand_flash_index = i;
428         mxcnfc_init_ok = true;
429
430         if (NF_PG_SZ == 2048) {
431                 g_is_2k_page = true;
432                 g_spare_only_read_ok = false;
433         }
434         if (NF_PG_SZ == 4096) {
435                 g_is_4k_page = true;
436                 g_spare_only_read_ok = false;
437         }
438
439         nfc_printf(NFC_DEBUG_MED, "%s(): %d out of NUM_DEVICES=%d, id=0x%02x\n",
440                            __FUNCTION__, i, NUM_DEVICES, flash_dev_info->device_id);
441
442         if (nfc_setup) {
443                 g_nfc_version = nfc_setup(NF_PG_SZ / num_of_nand_chips, flash_dev_info->port_size,
444                                                                   flash_dev_info->type, num_of_nand_chips);
445         }
446         diag_printf1("NFC version: %02x\n", g_nfc_version);
447         if (g_nfc_version == MXC_NFC_V3) {
448                 for (i = 2; i <= NUM_OF_CS_LINES; i++) {
449                         u32 id_tmp[2];
450                         read_nflash_id(&id_tmp[0], i - 1);
451                         if (id[0] != id_tmp[0]) {
452                                 break;
453                         }
454                         /* Support interleave with 1, 2, 4, 8 chips */
455                         if (i == (num_of_nand_chips * 2)) {
456                                 num_of_nand_chips = i;
457                         }
458                         NFC_CMD_INPUT(FLASH_Reset);
459                 }
460
461                 if (nfc_setup && (num_of_nand_chips > 1)) {
462                         nfc_setup(NF_PG_SZ / num_of_nand_chips, flash_dev_info->port_size,
463                                                    flash_dev_info->type, num_of_nand_chips);
464                 }
465         }
466
467         NFC_ARCH_INIT();
468
469         g_bbt_sz = NF_BLK_CNT / 4;
470         g_bbt = malloc(g_bbt_sz); // two bit for each block
471         if (g_bbt == NULL) {
472                 diag_printf("%s(): failed to allocate %d byte for bbt\n", __FUNCTION__, g_bbt_sz);
473                 return FLASH_ERR_PROTOCOL;
474         }
475
476         g_page_buf = malloc(NF_PG_SZ); // for programming less than one page size buffer
477         if (g_page_buf == NULL) {
478                 diag_printf("%s(): failed to allocate %d byte page buffer\n", __FUNCTION__,
479                                         NF_PG_SZ);
480                 return FLASH_ERR_PROTOCOL;
481         }
482         memset(g_bbt, 0, g_bbt_sz);
483
484         /* For now cap off the Device size to 2GB */
485         i = 1;
486         while ((i <= num_of_nand_chips) && ((NF_DEV_SZ * i) < 0x80000000)) {
487                 num_of_nand_chips_for_nandsize = i;
488                 i *= 2;
489         }
490
491         scale_block_cnt = num_of_nand_chips / num_of_nand_chips_for_nandsize;
492         // Hard wired for now
493         flash_info.block_size = NF_BLK_SZ;
494         flash_info.blocks = NF_BLK_CNT - CYGNUM_FLASH_NAND_BBT_BLOCKS;
495         flash_info.start = (void *)MXC_NAND_BASE_DUMMY;
496         flash_info.end = (void *)(MXC_NAND_BASE_DUMMY + NF_DEV_SZ -
497                                                           CYGNUM_FLASH_NAND_BBT_BLOCKS * NF_BLK_SZ);
498
499         mxc_nfc_scan(false); // look for table
500
501         diag_printf1("%s(): block_size=0x%08x, blocks=0x%08x, start=%p, end=%p\n",
502                                  __FUNCTION__, flash_info.block_size, flash_info.blocks,
503                                  flash_info.start, flash_info.end);
504
505         return FLASH_ERR_OK;
506 }
507
508 // used by redboot/current/src/flash.c
509 int mxc_nand_fis_start(void)
510 {
511         return flash_dev_info->fis_start_addr * num_of_nand_chips;
512 }
513
514 static inline u8 get_byte(cyg_uint16 *buf, int offs)
515 {
516         cyg_uint16 word = buf[offs >> 1];
517         if (offs & 1) {
518                 return word >> 8;
519         }
520         return word & 0xff;
521 }
522
523 static inline void store_byte(cyg_uint16 *buf, int offs, u8 val)
524 {
525         cyg_uint16 word = buf[offs >> 1];
526
527         if (offs & 1) {
528                 word = (word & 0x00ff) | ((u16)val << 8);
529         } else {
530                 word = (word & 0xff00) | val;
531         }
532         buf[offs >> 1] = word;
533 }
534
535 static inline bool nfc_verify_addr(unsigned long dst, unsigned long len)
536 {
537         if (dst < NAND_MAIN_BUF0 || dst + len >= NAND_SPAR_BUF3 + NFC_SPARE_BUF_SZ) {
538                 diag_printf("%s: Bad NFC Buffer address 0x%08lx\n", __FUNCTION__, dst);
539                 return false;
540         }
541         return true;
542 }
543
544 static void nfc_buf_read(void *dst, unsigned long src, u32 len)
545 {
546         u16 *s = (u16 *)(src & ~1);
547         u8 *bp = dst;
548
549         if (len == 0) {
550                 return;
551         }
552         if (src + len < src) {
553                 diag_printf("%s: Bad address range 0x%08lx .. 0x%08lx\n", __FUNCTION__,
554                                         src, src + len);
555         }
556         if ((unsigned long)dst + len < (unsigned long)dst) {
557                 diag_printf("%s: Bad address range 0x%08lx .. 0x%08lx\n", __FUNCTION__,
558                                         (unsigned long)dst, (unsigned long)dst + len);
559         }
560         if (src < NAND_MAIN_BUF0 || src + len >= NAND_SPAR_BUF3 + NF_PG_SZ) {
561                 diag_printf("%s: Bad NFC Buffer address 0x%08lx\n", __FUNCTION__, src);
562                 return;
563         }
564         if ((unsigned long)dst >= NAND_MAIN_BUF0 &&
565                 (unsigned long)dst < NAND_SPAR_BUF3 + NF_PG_SZ) {
566                 diag_printf("%s: Bad memory address 0x%08lx\n", __FUNCTION__,
567                                         (unsigned long)dst);
568                 return;
569         }
570         if (src & 1) {
571                 *bp++ = get_byte(s, 1);
572                 s++;
573                 len--;
574         }
575         if ((unsigned long)bp & 1) {
576                 while (len > 1) {
577                         u16 word = *s++;
578                         *bp++ = word & 0xff;
579                         *bp++ = word >> 8;
580                         len -= 2;
581                 }
582         } else {
583                 u16 *wp = (u16 *)bp;
584
585                 while (len > 1) {
586                         *wp++ = *s++;
587                         len -= 2;
588                 }
589                 bp = (u8*)wp;
590         }
591         if (len != 0) {
592                 u16 word = *s;
593                 *bp = word & 0xff;
594         }
595 }
596
597 static void nfc_buf_write(unsigned long dst, void *src, u32 len)
598 {
599         u8 *bp = src;
600         u16 *d = (u16 *)(dst & ~1);
601
602         if (len == 0) {
603                 return;
604         }
605         if (!nfc_verify_addr(dst, len)) {
606                 return;
607         }
608         if (dst & 1) {
609                 store_byte(d, 1, *bp);
610                 d++;
611                 bp++;
612                 len--;
613         }
614         if ((unsigned long)bp & 1) {
615                 while (len > 1) {
616                         u16 word;
617                         word = *bp++;
618                         word |= (u16)(*bp++) << 8;
619                         *d++ = word;
620                         len -= 2;
621                 }
622         } else {
623                 u16 *wp = (u16 *)bp;
624                 while (len > 1) {
625                         *d++ = *wp++;
626                         len -= 2;
627                 }
628                 bp = (u8 *)wp;
629         }
630         if (len != 0) {
631                 store_byte(d, 1, *bp);
632         }
633 }
634
635 #ifndef NFC_V3_0
636 /*!
637  * Starts the address input cycles for different operations as defined in ops.
638  *
639  * @param ops                   operations as defined in enum nfc_addr_ops
640  * @param pg_no                 page number offset from 0
641  * @param pg_off                byte offset within the page
642  * @param is_erase              don't care for earlier NFC
643  * @param cs_line                don't care for earlier NFC
644  */
645 static void start_nfc_addr_ops(u32 ops, u32 pg_no, u32 pg_off, u32 is_erase,
646                                    u32 cs_line, u32 num_of_chips)
647 {
648         int i;
649
650         switch (ops) {
651         case FLASH_Read_ID:
652                 /* Only supports one NAND chip (CS0) */
653                 if (cs_line != 0)
654                         return;
655                 NFC_ADDR_INPUT(0);
656                 return;
657         case FLASH_Read_Mode1:
658         case FLASH_Program:
659                 for (i = 0; i < COL_CYCLE; i++, pg_off >>= 8) {
660                         NFC_ADDR_INPUT(pg_off & 0xFF);
661                 }
662                 // don't break on purpose
663         case FLASH_Block_Erase:
664                 for (i = 0; i < ROW_CYCLE; i++, pg_no >>= 8) {
665                         NFC_ADDR_INPUT(pg_no & 0xFF);
666                 }
667                 break;
668         default:
669                 diag_printf("!!!!!! %s(): wrong ops: %d !!!!!\n", __FUNCTION__, ops);
670                 return;
671         }
672 }
673 #endif                                  // #ifndef NFC_V3_0
674
675 static void read_nflash_id(u32 *id, u32 cs_line)
676 {
677         volatile u32 *ptr = (volatile u32*)NAND_MAIN_BUF0;
678
679     nfc_printf(NFC_DEBUG_MIN, "%s: read flash id from chip %d @ %p\n",
680                            __FUNCTION__, cs_line, ptr);
681
682         NFC_PRESET(MXC_UNLOCK_BLK_END);
683         NFC_SET_NFC_ACTIVE_CS(cs_line);
684         NFC_CMD_INPUT(FLASH_Read_ID);
685
686         start_nfc_addr_ops(FLASH_Read_ID, 0, 0, 0, cs_line, num_of_nand_chips);
687         NFC_DATA_OUTPUT(RAM_BUF_0, FDO_FLASH_ID, g_ecc_enable);
688
689     *id++ = *ptr++;
690     *id++ = *ptr++;
691 }
692
693 static void mark_blk_bad(unsigned int block, unsigned char *buf,
694                                                  enum blk_bad_type bad_type)
695 {
696         unsigned int off = block >> 2;           // byte offset - each byte can hold status for 4 blocks
697         unsigned int sft = (block & 3) << 1;  // bit shift 0, 2, 4, 6
698         unsigned char val = buf[off];
699
700         if (block > NF_BLK_CNT) {
701                 diag_printf("%s: Block number %u out of range: 0..%u\n", __FUNCTION__,
702                                         block, NF_BLK_CNT - 1);
703                 return;
704         }
705         val = (val & ~(3 << sft)) | (bad_type << sft);
706         buf[off] = val;
707 }
708
709 /*!
710  * Checks to see if a block is bad. If buf is not NULL, it indicates a valid
711  * BBT in the RAM. In this case, it assumes to have 2-bit to represent each
712  * block for good or bad
713  *                              * 11b:  block is good
714  *                              * 00b:  block is factory marked bad
715  *                              * 01b:  block is marked bad due to wear
716  *                              * 10b:  block is marked reserved (for BBT)
717  * If buf is NULL, then it indicates a low level scan based on the certain
718  * offset value in certain pages and certain offset to be non-0xFF. In this
719  * case, the HW ECC will be turned off.
720  *
721  * @param block         0-based block number
722  * @param buf           BBT buffer. Could be NULL (see above explanation)
723  *
724  * @return                      1 if bad block; 0 otherwise
725  */
726 static int nfc_is_badblock(u32 block, u8 *buf)
727 {
728         u32 off;           // byte offset
729         u32 sft;           // bit shift 0, 2, 4, 6
730         flash_addr_t addr;
731         u16 temp, i;
732         int res;
733         u32 pg_no;
734
735         if (buf) {
736                 // use BBT
737                 off = block >> 2;               // byte offset
738                 sft = (block & 3) << 1;  // bit shift 0, 2, 4, 6
739                 res = (buf[off] >> sft) & 0x3;
740                 if (res) {
741                         addr = BLOCK_TO_OFFSET(block);
742                         diag_printf1("Block %u at %08llx is marked %s (%d) in BBT@%p[%02x] mask %02x\n",
743                                                  block, (u64)addr, res == BLK_RESERVED ? "reserved" :
744                                                  res == BLK_BAD_FACTORY ? "factory bad" : "runtime bad",
745                                                  res, buf, off, 3 << sft);
746                 }
747                 return res;
748         }
749
750         // need to do low level scan with ECC off
751         if (NF_OPTIONS & NAND_BBT_SCANLSTPAGE) {
752                 if (g_is_4k_page || g_is_2k_page) {
753                         addr = (block + 1) * NF_BLK_SZ - NF_PG_SZ;
754                         pg_no = addr / NF_PG_SZ;
755                         for (i = 0; i < num_of_nand_chips; i++) {
756                                 // we don't do partial page read here. No ecc either
757                                 nfc_read_pg_random(pg_no, 0, ECC_FORCE_OFF, i, num_of_nand_chips);
758                                 temp = readw((u32)NAND_MAIN_BUF0 + NF_BI_OFF);
759                                 if ((temp & 0xFF) != 0xFF) {
760                                         return BLK_BAD_FACTORY;
761                                 }
762                         }
763                 } else {
764                         diag_printf("only 2K/4K page is supported\n");
765                         // die here -- need to fix the SW
766                         while (1);
767                 }
768                 return 0;
769         }
770         addr = block * NF_BLK_SZ;
771         pg_no = addr / NF_PG_SZ;
772         for (i = 0; i < num_of_nand_chips; i++) {
773                 nfc_read_pg_random(pg_no, 0, ECC_FORCE_OFF, i, num_of_nand_chips); // no ecc
774                 if (g_is_2k_page || g_is_4k_page) {
775                         temp = readw(NAND_MAIN_BUF0 + NF_BI_OFF);
776                 } else {
777                         temp = readw(NAND_SPAR_BUF0 + 4) >> 8; // BI is at 5th byte in spare area
778                 }
779                 if ((temp & 0xFF) != 0xFF) {
780                         return BLK_BAD_FACTORY;
781                 }
782         }
783         if (NF_OPTIONS & NAND_BBT_SCAN2NDPAGE) {
784                 addr += NF_PG_SZ;
785                 pg_no++;
786                 for (i = 0; i < num_of_nand_chips; i++) {
787                         nfc_read_pg_random(pg_no, 0, ECC_FORCE_OFF, i, num_of_nand_chips); // no ecc
788                         if (g_is_2k_page || g_is_4k_page) {
789                                 temp = readw(NAND_MAIN_BUF0 + NF_BI_OFF);
790                         } else {
791                                 temp = readw(NAND_SPAR_BUF0 + 4) >> 8; // BI is at 5th byte in spare area
792                         }
793                         if ((temp & 0xFF) != 0xFF) {
794                                 return BLK_BAD_FACTORY;
795                         }
796                 }
797         }
798         return 0;
799 }
800
801 /*
802  * check_short_pattern - [GENERIC] check if a pattern is in the buffer
803  * @buf:        the buffer to search
804  * @td:         search pattern descriptor
805  *
806  * Check for a pattern at the given place. Used to search bad block
807  * tables and good / bad block identifiers.
808 */
809 static int check_short_pattern(void *buf, struct nand_bbt_descr *td)
810 {
811         int i;
812
813         for (i = 0; i < td->len; i++) {
814                 if (get_byte(buf, td->offs + i) != td->pattern[i]) {
815                         return -1;
816                 }
817         }
818         return 0;
819 }
820
821 static int nfc_write_page(u32 pg_no, u32 pg_off, u32 ecc_force);
822 /*
823  * Program g_bbt into the NAND block with offset at g_main_bbt_addr.
824  * This assumes that the g_bbt has been built already.
825  *
826  * If g_main_bbt_addr is 0, search for a free block from the bottom 4 blocks (but make
827  * sure not re-using the mirror block). If g_mirror_bbt_page is 0, do the same thing.
828  * Otherwise, just use g_main_bbt_addr, g_mirror_bbt_page numbers to prgram the
829  * g_bbt into those two blocks.
830  * todo: need to do the version to see which one is newer.
831  *
832  * @return      0 if successful; -1 otherwise.
833  */
834 static int mxc_nfc_write_bbt_page(struct nand_bbt_descr *td)
835 {
836         int ret;
837         u32 block = td->pages / NF_PG_PER_BLK;
838         flash_addr_t addr = td->pages * NF_PG_SZ;
839
840         ret = nfc_erase_blk(addr);
841         if (ret != 0) {
842                 diag_printf("Failed to erase bbt block %u\n", block);
843                 return ret;
844         }
845         ret = nfc_write_page(td->pages, 0, 0);
846         if (ret != 0) {
847                 diag_printf("Failed to write bbt block %u\n", block);
848                 return ret;
849         }
850         mark_blk_bad(block, g_bbt, BLK_RESERVED);
851         return 0;
852 }
853
854 static inline void mxc_nfc_buf_clear(unsigned long buf, u8 pattern, int size)
855 {
856         int i;
857         u16 *p = (u16 *)buf;
858         u16 fill = pattern;
859
860         fill = (fill << 8) | pattern;
861         for (i = 0; i < size >> 1; i++) {
862                 p[i] = fill;
863         }
864 }
865
866 static int mxc_nfc_write_bbt(struct nand_bbt_descr *td, struct nand_bbt_descr *md)
867 {
868         int ret = -1;
869         int block;
870         int pg_offs = 0;
871         int page = 0;
872         u16 *buf = (u16 *)NAND_MAIN_BUF0;
873
874         for (block = NF_BLK_CNT - 1; block >= NF_BLK_CNT - td->maxblocks - 1; block--) {
875                 int pg = block * NF_PG_PER_BLK;
876
877                 if ((nfc_is_badblock(block, g_bbt) & 1) == 0) {
878                         if (md != NULL && md->pages == pg) {
879                                 continue;
880                         }
881                         td->pages = pg;
882                         break;
883                 }
884         }
885         if (td->pages < 0) {
886                 return -1;
887         }
888         mxc_nfc_buf_clear(NAND_SPAR_BUF0, 0xff, NF_SPARE_SZ);
889         mxc_nfc_buf_clear(NAND_MAIN_BUF0, 0xff, NF_PG_SZ);
890         diag_printf1("%s: Updating bbt %c%c%c%c version %d\n", __FUNCTION__,
891                                  td->pattern[0], td->pattern[1], td->pattern[2], td->pattern[3], td->version);
892         nfc_buf_write(NAND_SPAR_BUF0 + td->offs, td->pattern, td->len);
893         store_byte((u16 *)NAND_SPAR_BUF0, td->veroffs, td->version);
894
895         for (block = 0, pg_offs = 0; block < NF_BLK_CNT; pg_offs++) {
896                 u16 tmp = 0xffff;
897                 int i;
898
899                 if (pg_offs << 1 >= NF_PG_SZ) {
900                         ret = mxc_nfc_write_bbt_page(td);
901                         if (ret != 0) {
902                                 return ret;
903                         }
904                         page++;
905                         mxc_nfc_buf_clear(NAND_SPAR_BUF0, 0xff, NF_SPARE_SZ);
906                         mxc_nfc_buf_clear(NAND_MAIN_BUF0, 0xff, NF_PG_SZ);
907                         pg_offs = 0;
908                 }
909                 for (i = 0; i < 16 && block < NF_BLK_CNT; i += 2, block++) {
910                         u8 code = nfc_is_badblock(block, g_bbt);
911                         if ((code & 1) != 0) {
912                                 tmp &= ~(code << i);
913                                 diag_printf1("%s: bad block %u pattern[%p] 0x%04x mask 0x%04x\n", __FUNCTION__,
914                                                          block, &buf[pg_offs], tmp, 0x03 << i);
915                         }
916                 }
917                 buf[pg_offs] = tmp;
918         }
919         if (pg_offs > 0) {
920                 diag_printf1("%s: Writing final bbt block %d page %d\n", __FUNCTION__,
921                                          td->pages / NF_PG_PER_BLK, page);
922                 ret = mxc_nfc_write_bbt_page(td);
923         }
924         return ret;
925 }
926
927 static int mxc_nfc_update_bbt(struct nand_bbt_descr *td, struct nand_bbt_descr *md)
928 {
929         int ret;
930
931         if (td == NULL) {
932                 return -1;
933         }
934         if (td->pages < 0 && (md == NULL || md->pages == -1)) {
935                 td->version = 1;
936         } else {
937                 if (md != NULL && md->pages >= 0) {
938                         if (md->version >= td->version) {
939                                 td->version = ++md->version;
940                         } else {
941                                 md->version = ++td->version;
942                         }
943                 } else {
944                         td->version++;
945                 }
946         }
947         ret = mxc_nfc_write_bbt(td, md);
948         if (ret) {
949                 diag_printf("** Error: Failed to update main BBT\n");
950         }
951         if (md) {
952                 ret = mxc_nfc_write_bbt(md, td);
953                 if (ret) {
954                         diag_printf("** Error: Failed to update mirror BBT\n");
955                 }
956         }
957         return ret;
958 }
959
960 static int program_bbt_to_flash(void)
961 {
962         return mxc_nfc_update_bbt(g_mxc_nfc_bbt_main_descr, g_mxc_nfc_bbt_mirror_descr);
963 }
964
965 /*!
966  * Unconditionally erase a block without checking the BI field.
967  * Note that there is NO error checking for passed-in ra.
968  *
969  * @param ra            starting address in the raw address space (offset)
970  *                                      Must be block-aligned
971  * @return                      0 if successful; -1 otherwise
972  */
973 static int nfc_erase_blk(u32 ra)
974 {
975         u16 flash_status, i;
976         u32 pg_no, pg_off;
977
978         if (g_nfc_version == MXC_NFC_V3) {
979                 // combine the two commands for erase
980                 writel((FLASH_Start_Erase << 8) | FLASH_Block_Erase, NAND_CMD_REG);
981                 pg_no = ra / NF_PG_SZ;
982                 pg_off = ra % NF_PG_SZ;
983                 for (i = 0; i < num_of_nand_chips; i++) {
984                         start_nfc_addr_ops(FLASH_Block_Erase, pg_no, pg_off, 1, i, num_of_nand_chips);
985                         // start auto-erase
986                         writel(NAND_LAUNCH_AUTO_ERASE, NAND_LAUNCH_REG);
987                         wait_op_done();
988                         pg_off = 0;
989                 }
990                 flash_status = NFC_STATUS_READ();
991                 // check I/O bit 0 to see if it is 0 for success
992                 if ((flash_status & ((0x1 << num_of_nand_chips) - 1)) != 0) {
993                         return -1;
994                 }
995         } else {
996                 NFC_CMD_INPUT(FLASH_Block_Erase);
997                 start_nfc_addr_ops(FLASH_Block_Erase, ra / NF_PG_SZ, ra % NF_PG_SZ,
998                                                    1, 0, num_of_nand_chips);
999                 NFC_CMD_INPUT(FLASH_Start_Erase);
1000
1001                 flash_status = NFC_STATUS_READ();
1002
1003                 // check I/O bit 0 to see if it is 0 for success
1004                 if ((flash_status & 0x1) != 0) {
1005                         return -1;
1006                 }
1007         }
1008         return 0;
1009 }
1010
1011 /*!
1012  * Program a block of data in the flash. This function doesn't do
1013  * bad block checking. But if program fails, it return error.
1014  * Note: If "len" is less than a block it will program up to a page's
1015  *               boundary. If not within a page boundary, then it fills the
1016  *               rest of the page with 0xFF.
1017  *
1018  * @param ra            destination raw flash address
1019  * @param buf           source address in the RAM
1020  * @param len           len to be programmed
1021  *
1022  * @return                      0 if successful; -1 otherwise
1023  */
1024 static int nfc_program_blk(u32 ra, u8 *buf, u32 len)
1025 {
1026         u32 temp = num_of_nand_chips;
1027
1028         /* Needed when romupdate is called */
1029         if (ra == 0)
1030                 num_of_nand_chips = 1;
1031
1032         for (; len >= NF_PG_SZ; len -= NF_PG_SZ) {
1033                 if (nfc_write_pg_random(ra / NF_PG_SZ, ra % NF_PG_SZ, buf, 0) != 0) {
1034                         return -1;
1035                 }
1036                 ra += NF_PG_SZ;
1037                 buf += NF_PG_SZ;
1038         }
1039         if (len != 0) {
1040                 memset(g_page_buf + len, 0xFF, NF_PG_SZ - len);
1041                 memcpy(g_page_buf, buf, len);
1042                 if (nfc_write_pg_random(ra / NF_PG_SZ, ra % NF_PG_SZ, g_page_buf, 0) != 0) {
1043                         num_of_nand_chips = temp;
1044                         return -1;
1045                 }
1046         }
1047         num_of_nand_chips = temp;
1048         return 0;
1049 }
1050
1051 /*!
1052  * Erase a range of NAND flash good blocks only.
1053  * It skips bad blocks and update the BBT once it sees new bad block due to erase.
1054  * @param addr                  raw NAND flash address. it has to be block size aligned
1055  * @param len                   number of bytes
1056  * @param skip_bad              if 1, don't erase bad block; otherwise, always erase
1057  * @param verbose               use true to print more messages
1058  *
1059  * @return                              FLASH_ERR_OK (0) if successful; non-zero otherwise
1060  */
1061 int nfc_erase_region(flash_addr_t addr, u32 len, bool skip_bad, bool verbose)
1062 {
1063         u32 sz, blk, update = 0, j = 0;
1064
1065         nfc_printf(NFC_DEBUG_MED, "%s: addr=0x%08llx len=0x%08x\n",
1066                            __FUNCTION__, (u64)addr, len);
1067
1068         if ((addr % NF_BLK_SZ) != 0) {
1069                 diag_printf("Error: flash address 0x%08llx not block aligned\n", addr);
1070                 return FLASH_ERR_INVALID;
1071         }
1072         if ((len % NF_BLK_SZ) != 0 || len == 0) {
1073                 diag_printf("Error: invalid length %u (must be > 0 and block aligned)\n", len);
1074                 return FLASH_ERR_INVALID;
1075         }
1076         addr = nfc_l_to_p(addr);
1077         // now addr has to be block aligned
1078         for (sz = 0; sz < len; addr += NF_BLK_SZ, j++, sz += NF_BLK_SZ) {
1079                 blk = OFFSET_TO_BLOCK(addr);
1080                 if (skip_bad && nfc_is_badblock(blk, g_bbt)) {
1081                         diag_printf("\nSkipping bad block %u at addr 0x%08llx\n",
1082                                                 blk, (u64)addr);
1083                         continue;
1084                 }
1085                 if (nfc_erase_blk(addr) != 0) {
1086                         diag_printf("\n** Error: Failed to erase block %u at addr 0x%08llx\n",
1087                                             blk, (u64)addr);
1088                         mark_blk_bad(blk, g_bbt, BLK_BAD_RUNTIME);
1089                         // we don't need to update the table immediately here since even
1090                         // with power loss now, we should see the same erase error again.
1091                         update++;
1092                         continue;
1093                 }
1094                 if (verbose) {
1095                         if ((j % 0x20) == 0)
1096                                 diag_printf("\n%s 0x%08llx: ", skip_bad ? "Erase" : "FORCE erase", (u64)addr);
1097                         diag_printf(".");
1098                 }
1099         }
1100         if (update) {
1101                 if (program_bbt_to_flash() != 0) {
1102                         diag_printf("\nError: Failed to update bad block table\n");
1103                         return FLASH_ERR_PROGRAM;
1104                 }
1105                 diag_printf("\nnew bad blocks=%d\n", update);
1106         }
1107         return FLASH_ERR_OK;
1108 }
1109
1110 /*!
1111  * Program a range of NAND flash in blocks only.
1112  * It skips bad blocks and update the BBT once it sees new bad block due to program.
1113  * @param addr                  raw NAND flash address. it has to be block size aligned
1114  * @param len                   number of bytes
1115  * @return                              FLASH_ERR_OK (0) if successful; non-zero otherwise
1116  */
1117 int nfc_program_region(flash_addr_t addr, u8 *buf, u32 len)
1118 {
1119         u32 sz, blk, update = 0, partial_block_size;
1120
1121         nfc_printf(NFC_DEBUG_MED, "%s: addr=0x%08llx, len=0x%08x\n",
1122                            __FUNCTION__, (u64)addr, len);
1123
1124         if ((addr % (NF_PG_SZ / num_of_nand_chips)) != 0) {
1125                 diag_printf("Error: flash address 0x%08llx not page aligned\n", (u64)addr);
1126                 return FLASH_ERR_INVALID;
1127         }
1128         if (len == 0) {
1129                 diag_printf("Error: invalid length\n");
1130                 return FLASH_ERR_INVALID;
1131         }
1132
1133         partial_block_size = addr % NF_BLK_SZ;
1134
1135         addr = nfc_l_to_p(addr);
1136         while (1) {
1137                 if (!flash_addr_valid(addr)) {
1138                         diag_printf("\nToo many bad blocks in flash region 0x%08llx..0x%08llx\n",
1139                                                 (u64)flash_region_start, (u64)flash_region_end);
1140                         return FLASH_ERR_INVALID;
1141                 }
1142                 blk = OFFSET_TO_BLOCK(addr);
1143                 if (nfc_is_badblock(blk, g_bbt)) {
1144                         diag_printf("\nSkipping bad block %u at addr 0x%08llx\n", blk, addr);
1145                         goto incr_address;
1146                 }
1147
1148                 sz = (len >= partial_block_size) ? partial_block_size : len;
1149
1150                 if (nfc_program_blk(addr, buf, sz) != 0) {
1151                         update++;
1152                         diag_printf("\nError: Failed to program flash block %u at addr 0x%08llx\n",
1153                                                 blk, (u64)addr);
1154                         mark_blk_bad(blk, g_bbt, BLK_BAD_RUNTIME);
1155                         // we don't need to update the table immediately here since even
1156                         // with power loss now, we should see the same program error again.
1157                         goto incr_address;
1158                 }
1159                 diag_printf(".");
1160
1161                 len -= sz;
1162                 buf += sz;
1163                 if (len == 0)
1164                         break;
1165
1166 incr_address:
1167                 addr += partial_block_size;
1168                 partial_block_size = NF_BLK_SZ;
1169                 g_block_offset++;
1170         }
1171         if (update) {
1172                 if (program_bbt_to_flash() != 0) {
1173                         diag_printf("\nError: Failed to update bad block table\n");
1174                         return -1;
1175                 }
1176         }
1177         return FLASH_ERR_OK;
1178 }
1179
1180 /*!
1181  * Read data from raw NAND flash address to memory. The MSB of the passed-
1182  * in flash address will be masked off inside the function.
1183  * It skips bad blocks and read good blocks of data for "len" bytes.
1184  *
1185  * @param addr                  NAND flash address.
1186  * @param buf                   memory buf where data will be copied to
1187  * @param len                   number of bytes
1188  * @return                              FLASH_ERR_OK (0) if successful; non-zero otherwise
1189  */
1190 int nfc_read_region(flash_addr_t addr, u8 *buf, u32 len)
1191 {
1192         u32 start_point = 0, pg_no;
1193         unsigned int offset = addr % NF_PG_SZ;
1194         int chk_bad = 1;
1195
1196         nfc_printf(NFC_DEBUG_MED, "%s: addr=0x%08llx, offset=%03x buf=0x%p, len=0x%08x\n",
1197                            __FUNCTION__, addr, offset, buf, len);
1198
1199         addr = nfc_l_to_p(addr);
1200         if (addr < (u32)flash_info.start || (addr + len) > (u32)flash_info.end || len == 0) {
1201                 diag_printf("** Error: flash address 0x%08llx..0x%08llx outside valid range %p..%p\n",
1202                                         (u64)addr, (u64)addr + len - 1, flash_info.start, flash_info.end);
1203                 return FLASH_ERR_INVALID;
1204         }
1205
1206         while (len > 0) {
1207                 int i;
1208
1209                 if (!flash_addr_valid(addr)) {
1210                         diag_printf("Too many bad blocks in flash region 0x%08llx..0x%08llx\n",
1211                                                 (u64)flash_region_start, (u64)flash_region_end);
1212                         return FLASH_ERR_INVALID;
1213                 }
1214                 if (chk_bad) {
1215                         int blk = OFFSET_TO_BLOCK(addr);
1216
1217                         if (nfc_is_badblock(blk, g_bbt)) {
1218                                 diag_printf("Skipping bad block %u at addr 0x%08llx\n", blk, (u64)addr);
1219                                 addr += NF_BLK_SZ;
1220                                 g_block_offset++;
1221                                 continue;
1222                         }
1223                         chk_bad = 0;
1224                 }
1225
1226                 pg_no = addr / NF_PG_SZ;
1227                 if (offset != 0) {
1228                         /* Find which interleaved NAND device */
1229                         start_point = offset / (NF_PG_SZ / num_of_nand_chips);
1230                 } else {
1231                         start_point = 0;
1232                 }
1233                 for (i = start_point; i < num_of_nand_chips; i++) {
1234                         int chunk_size = (NF_PG_SZ - offset) / num_of_nand_chips;
1235
1236                         if (chunk_size > len)
1237                                 chunk_size = len;
1238                         nfc_printf(NFC_DEBUG_MED, "Reading page %d addr 0x%08llx chip %d len 0x%03x\n",
1239                                            pg_no, (u64)addr, i, chunk_size);
1240                         if (nfc_read_page(i, pg_no, 0) != 0) {
1241                                 diag_printf("** Error: Failed to read flash block %u at addr 0x%08llx\n",
1242                                                         OFFSET_TO_BLOCK(addr), (u64)addr);
1243                                 return FLASH_ERR_INVALID;
1244                         }
1245                         // now do the copying
1246                         nfc_buf_read(buf, NAND_MAIN_BUF0 + offset, chunk_size);
1247
1248                         buf += chunk_size;
1249                         len -= chunk_size;
1250                         addr += NF_PG_SZ / num_of_nand_chips - offset;
1251                         offset = 0;
1252                 }
1253                 chk_bad = (addr % NF_BLK_SZ) == 0;
1254         }
1255
1256         return FLASH_ERR_OK;
1257 }
1258
1259 /*
1260  * Support only either program for main area only. Or spare-area only for 512B.
1261  * If one wants to write to the spare-area, then before calling this function,
1262  * the spare area NFC RAM buffer has to be setup already. This function doesn't touch
1263  * the spare area NFC RAM buffer.
1264  *
1265  * @param pg_no                 page number offset from 0
1266  * @param pg_off                byte offset within the page
1267  * @param buf                   data buffer in the RAM to be written to NAND flash
1268  * @param ecc_force             can force ecc to be off. Otherwise, by default it is on
1269  *                                              unless the page offset is non-zero
1270  *
1271  * @return      0 if successful; non-zero otherwise
1272  */
1273 // SP-only opearation is not supported anymore !!!
1274 static int nfc_write_pg_random(u32 pg_no, u32 pg_off, u8 *buf, u32 ecc_force)
1275 {
1276         u16 flash_status;
1277         u32 ecc = NFC_FLASH_CONFIG2_ECC_EN, v, i;
1278         u32 write_count = NF_PG_SZ, start_point = 0, rba, rba_count = 0;
1279
1280         // the 2nd condition is to test for unaligned page address -- ecc has to be off.
1281         if (ecc_force == ECC_FORCE_OFF || pg_off != 0) {
1282                 ecc = 0;
1283         }
1284
1285         diag_printf1("%s(0x%x, 0x%x, %d)\n", __FUNCTION__, pg_no, pg_off, ecc_force);
1286
1287         switch (g_nfc_version & 0xf0) {
1288         case MXC_NFC_V3:
1289                 /* Check if Page size is greater than NFC buffer */
1290                 do {
1291                         if (write_count <= NFC_BUFSIZE) {
1292                                 // No need to worry about the spare area
1293                                 nfc_buf_write(NAND_MAIN_BUF0, buf, write_count);
1294                                 write_count = 0;
1295                         } else {
1296                                 // No need to worry about the spare area
1297                                 nfc_buf_write(NAND_MAIN_BUF0, buf, NFC_BUFSIZE);
1298                                 write_count -= NFC_BUFSIZE;
1299                                 buf += NFC_BUFSIZE;
1300                         }
1301                         // combine the two commands for program
1302                         writel((FLASH_Program << 8) | FLASH_Send_Data, NAND_CMD_REG);
1303
1304                         for (i = start_point; i < num_of_nand_chips; i++) {
1305                                 rba = rba_count * ((NF_PG_SZ / num_of_nand_chips) / 512);
1306                                 /* Completely wrote out the NFC buffer, break and copy more to the NFC buffer */
1307                                 if (rba > 7) {
1308                                         rba_count = 0;
1309                                         break;
1310                                 }
1311
1312                                 // For ECC
1313                                 v = readl(NFC_FLASH_CONFIG2_REG) & ~NFC_FLASH_CONFIG2_ECC_EN;
1314                                 // setup config2 register for ECC enable or not
1315                                 write_nfc_ip_reg(v | ecc, NFC_FLASH_CONFIG2_REG);
1316
1317                                 start_nfc_addr_ops(FLASH_Program, pg_no, pg_off, 0, i, num_of_nand_chips);
1318
1319                                 // start auto-program
1320                                 writel(NAND_LAUNCH_AUTO_PROG, NAND_LAUNCH_REG);
1321                                 if (i < (num_of_nand_chips - i))
1322                                         wait_for_auto_prog_done();
1323                                 else
1324                                         wait_op_done();
1325                                 pg_off = 0;
1326                                 rba_count++;
1327                         }
1328                         start_point = i;
1329                 } while (write_count > 0);
1330                 flash_status = NFC_STATUS_READ();
1331                 // check I/O bit 0 to see if it is 0 for success
1332                 if ((flash_status & ((0x1 << num_of_nand_chips) - 1)) != 0) {
1333                         return -1;
1334                 }
1335                 break;
1336         default:
1337                 if (g_nfc_version != MXC_NFC_V1) {
1338                         int i;
1339
1340                         for (i = 1; i < NFC_SPARE_BUF_SZ / 16; i++) {
1341                                 memcpy((void *)(NAND_SPAR_BUF0 + i * NFC_SPARE_BUF_SZ),
1342                                            (void *)(NAND_SPAR_BUF0 + i * 16), 16);
1343                         }
1344                 }
1345                 nfc_buf_write(NAND_MAIN_BUF0, buf, NF_PG_SZ);
1346 #ifdef BARKER_CODE_SWAP_LOC
1347                 // To replace the data at offset MXC_NAND_BOOT_LOAD_BARKER with
1348                 // the address of the NFC base. This is needed for certain platforms.
1349                 if (pg_no == 0) {
1350                         diag_printf("\n[INFO]: copy data at 0x%x to spare area and set it to 0x%x\n",
1351                                                 BARKER_CODE_SWAP_LOC, BARKER_CODE_VAL);
1352                         writel(readl(NFC_BASE + BARKER_CODE_SWAP_LOC), NAND_SPAR_BUF0);
1353                         // todo: set BARKER_CODE_VAL and BARKER_CODE_SWAP_LOC for skye, etc.
1354                         writel(BARKER_CODE_VAL, NFC_BASE + BARKER_CODE_SWAP_LOC);
1355                 }
1356 #endif
1357                 NFC_CMD_INPUT(FLASH_Send_Data);
1358                 start_nfc_addr_ops(FLASH_Program, pg_no, pg_off, 0, 0, num_of_nand_chips);
1359
1360                 NFC_DATA_INPUT(RAM_BUF_0, NFC_MAIN_ONLY, ecc);
1361                 if (g_is_4k_page && PG_2K_DATA_OP_MULTI_CYCLES()) {
1362                         diag_printf("4K page with multi cycle write is not supported\n");
1363                         return -1;
1364                 }
1365                 if (g_is_2k_page && PG_2K_DATA_OP_MULTI_CYCLES()) {
1366                         NFC_DATA_INPUT_2k(RAM_BUF_1);
1367                         NFC_DATA_INPUT_2k(RAM_BUF_2);
1368                         NFC_DATA_INPUT_2k(RAM_BUF_3);
1369                 }
1370                 NFC_CMD_INPUT(FLASH_Program);
1371
1372                 flash_status = NFC_STATUS_READ();
1373                 // check I/O bit 0 to see if it is 0 for success
1374                 if ((flash_status & 0x1) != 0) {
1375                         diag_printf("** Error: failed to program page %u at 0x%08x status=0x%02x\n",
1376                                                 pg_no, pg_no * NF_PG_SZ + pg_off, flash_status);
1377                         return -1;
1378                 }
1379         }
1380         return 0;
1381 }
1382
1383 #ifndef NFC_V3_0
1384 // for version V1 and V2 of NFC
1385 static int nfc_read_pg_random(u32 pg_no, u32 pg_off, u32 ecc_force, u32 cs_line,
1386                                                           u32 num_of_nand_chips)
1387 {
1388         u32 t1, ecc = 1;
1389         u8 t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0;
1390         int res = 0;
1391
1392         nfc_printf(NFC_DEBUG_MAX, "%s: reading page %u offset 0x%03x (addr 0x%08llx)\n",
1393                            __FUNCTION__, pg_no, pg_off, (flash_addr_t)pg_no * NF_PG_SZ + pg_off);
1394
1395         if (ecc_force == ECC_FORCE_OFF || pg_off != 0 )
1396                 ecc = 0;
1397
1398         NFC_CMD_INPUT(FLASH_Read_Mode1);
1399         start_nfc_addr_ops(FLASH_Read_Mode1, pg_no, pg_off, 0, 0, num_of_nand_chips);
1400
1401         if (g_is_2k_page || g_is_4k_page) {
1402                 NFC_CMD_INPUT(FLASH_Read_Mode1_LG);
1403         }
1404
1405         NFC_DATA_OUTPUT(RAM_BUF_0, FDO_PAGE_SPARE, ecc);
1406         switch (g_nfc_version & 0xf0) {
1407         case MXC_NFC_V1:
1408                 t1 = readw(ECC_STATUS_RESULT_REG);
1409                 if (g_is_2k_page && PG_2K_DATA_OP_MULTI_CYCLES()) {
1410                         NFC_DATA_OUTPUT(RAM_BUF_1, FDO_PAGE_SPARE, ecc);
1411                         t2 = readw(ECC_STATUS_RESULT_REG);
1412                         NFC_DATA_OUTPUT(RAM_BUF_2, FDO_PAGE_SPARE, ecc);
1413                         t3 = readw(ECC_STATUS_RESULT_REG);
1414                         NFC_DATA_OUTPUT(RAM_BUF_3, FDO_PAGE_SPARE, ecc);
1415                         t4 = readw(ECC_STATUS_RESULT_REG);
1416                 }
1417
1418                 if (ecc && ((t1 & 0xA) != 0x0 || (t2 & 0xA) != 0x0 ||
1419                                         (t3 & 0xA) != 0x0 || (t4 & 0xA) != 0x0)) {
1420                         diag_printf("\n** Error: ECC error page %u, col %u: ECC status=0x%x:0x%x:0x%x:0x%x\n",
1421                                                 pg_no, pg_off, t1, t2, t3, t4);
1422                         res = -1;
1423                         goto out;
1424                 }
1425                 break;
1426         case MXC_NFC_V2:
1427                 if (g_is_2k_page && PG_2K_DATA_OP_MULTI_CYCLES()) {
1428                         NFC_DATA_OUTPUT(RAM_BUF_1, FDO_PAGE_SPARE, ecc);
1429                         NFC_DATA_OUTPUT(RAM_BUF_2, FDO_PAGE_SPARE, ecc);
1430                         NFC_DATA_OUTPUT(RAM_BUF_3, FDO_PAGE_SPARE, ecc);
1431                 }
1432                 if (ecc) {
1433                         t1 = readl(ECC_STATUS_RESULT_REG);
1434                         if (g_is_2k_page || g_is_4k_page) {
1435                                 t2 = (t1 >> 4) & 0xF;
1436                                 t3 = (t1 >> 8) & 0xF;
1437                                 t4 = (t1 >> 12) & 0xF;
1438                                 if (g_is_4k_page) {
1439                                         t5 = (t1 >> 16) & 0xF;
1440                                         t6 = (t1 >> 20) & 0xF;
1441                                         t7 = (t1 >> 24) & 0xF;
1442                                         t8 = (t1 >> 28) & 0xF;
1443                                 }
1444                         }
1445                         if ((t1 = (t1 & 0xF)) > 4 || t2 > 4 || t3 > 4 || t4 > 4 ||
1446                                 t5 > 4 || t6 > 4 || t7 > 4 || t8 > 4) {
1447                                 diag_printf("\n** Error: ECC error reading block %u page %u\n",
1448                                                         pg_no / NF_PG_PER_BLK, pg_no % NF_PG_PER_BLK);
1449                                 diag_printf("   ECC status=%x:%x:%x:%x:%x:%x:%x:%x\n",
1450                                                         t1, t2, t3, t4, t5, t6, t7, t8);
1451                                 res = -1;
1452                                 goto out;
1453                         }
1454                 }
1455                 break;
1456         default:
1457                 diag_printf("Unknown NFC version: %d\n", g_nfc_version);
1458                 return -1;
1459         }
1460         if (g_nfc_version != MXC_NFC_V1) {
1461                 int i;
1462
1463                 for (i = 1; i < NFC_SPARE_BUF_SZ / 16; i++) {
1464                         memcpy((void *)(NAND_SPAR_BUF0 + i * 16),
1465                                    (void *)(NAND_SPAR_BUF0 + i * NFC_SPARE_BUF_SZ), 16);
1466                 }
1467         }
1468 #ifdef BARKER_CODE_SWAP_LOC
1469         // To replace the data at offset BARKER_CODE_SWAP_LOC with the address of the NFC base
1470         // This is needed for certain platforms
1471         if (pg_no == 0) {
1472                 diag_printf("\n[INFO]: copy back data from spare to 0x%x\n", BARKER_CODE_SWAP_LOC);
1473                 writel(readl(NAND_SPAR_BUF0), NFC_BASE + BARKER_CODE_SWAP_LOC);
1474         }
1475 #endif
1476
1477 out:
1478         return res;
1479 }
1480 #endif                  // ifndef NFC_V3_0
1481
1482 /*!
1483  * Read a page's both main and spare area from NAND flash to the internal RAM buffer.
1484  * It always reads data to the internal buffer 0.
1485  *
1486  * @param cs_line       which NAND device is used
1487  * @param pg_no    page number of the device
1488  * @param pg_off        offset within a page
1489  *
1490  * @return                              0 if no error or 1-bit error; -1 otherwise
1491  */
1492 static int nfc_read_page(u32 cs_line, u32 pg_no, u32 pg_off)
1493 {
1494         return nfc_read_pg_random(pg_no, pg_off, ECC_FORCE_ON, cs_line, num_of_nand_chips);
1495 }
1496
1497 static int nfc_write_page(u32 pg_no, u32 pg_off, u32 ecc_force)
1498 {
1499         u16 flash_status;
1500         u32 ecc = NFC_FLASH_CONFIG2_ECC_EN;
1501
1502         diag_printf1("Writing page %u addr 0x%08llx\n",
1503                                  pg_no, (u64)pg_no * NF_PG_SZ + pg_off);
1504         if (ecc_force == ECC_FORCE_OFF || pg_off != 0) {
1505                 ecc = 0;
1506         }
1507
1508         if (g_nfc_version == MXC_NFC_V3) {
1509                 int i;
1510                 u32 v;
1511                 u32 start_point = 0, rba, rba_count = 0;
1512
1513                 // combine the two commands for program
1514                 writel((FLASH_Program << 8) | FLASH_Send_Data, NAND_CMD_REG);
1515
1516                 for (i = start_point; i < num_of_nand_chips; i++) {
1517                         rba = rba_count * ((NF_PG_SZ / num_of_nand_chips) / 512);
1518                         /* Completely wrote out the NFC buffer, break and copy more to the NFC buffer */
1519                         if (rba > 7) {
1520                                 rba_count = 0;
1521                                 break;
1522                         }
1523
1524                         // For ECC
1525                         v = readl(NFC_FLASH_CONFIG2_REG) & ~NFC_FLASH_CONFIG2_ECC_EN;
1526                         // setup config2 register for ECC enable or not
1527                         write_nfc_ip_reg(v | ecc, NFC_FLASH_CONFIG2_REG);
1528
1529                         start_nfc_addr_ops(FLASH_Program, pg_no, pg_off, 0, i, num_of_nand_chips);
1530
1531                         // start auto-program
1532                         writel(NAND_LAUNCH_AUTO_PROG, NAND_LAUNCH_REG);
1533                         if (i < (num_of_nand_chips - i))
1534                                 wait_for_auto_prog_done();
1535                         else
1536                                 wait_op_done();
1537                         pg_off = 0;
1538                         rba_count++;
1539                 }
1540                 start_point = i;
1541                 flash_status = NFC_STATUS_READ();
1542         } else {
1543                 if (g_nfc_version != MXC_NFC_V1) {
1544                         int i;
1545
1546                         for (i = NFC_SPARE_BUF_SZ / 16 - 1; i >= 0; i--) {
1547                                 memcpy((void *)(NAND_SPAR_BUF0 + i * NFC_SPARE_BUF_SZ),
1548                                            (void *)(NAND_SPAR_BUF0 + i * 16), 16);
1549                         }
1550                 }
1551                 NFC_CMD_INPUT(FLASH_Send_Data);
1552                 start_nfc_addr_ops(FLASH_Program, pg_no, pg_off, 0, 0, num_of_nand_chips);
1553
1554                 NFC_DATA_INPUT(RAM_BUF_0, NFC_MAIN_ONLY, ecc);
1555                 if (g_is_4k_page && PG_2K_DATA_OP_MULTI_CYCLES()) {
1556                         diag_printf("4K page with multi cycle write is not supported\n");
1557                         return -1;
1558                 }
1559                 if (g_is_2k_page && PG_2K_DATA_OP_MULTI_CYCLES()) {
1560                         NFC_DATA_INPUT_2k(RAM_BUF_1);
1561                         NFC_DATA_INPUT_2k(RAM_BUF_2);
1562                         NFC_DATA_INPUT_2k(RAM_BUF_3);
1563                 }
1564                 NFC_CMD_INPUT(FLASH_Program);
1565
1566                 flash_status = NFC_STATUS_READ();
1567         }
1568         if ((flash_status & 0x1) != 0) {
1569                 diag_printf("** Error: failed to program page %u at addr 0x%08llx\n",
1570                                         pg_no, (u64)pg_no * NF_PG_SZ + pg_off);
1571                 return -1;
1572         }
1573         return 0;
1574 }
1575
1576 // Read data into buffer
1577 #ifndef MXCFLASH_SELECT_MULTI
1578 int flash_read_buf(void *addr, void *data, int len)
1579 #else
1580 int nandflash_read_buf(void *addr, void *data, int len)
1581 #endif
1582 {
1583         flash_addr_t flash_addr = (unsigned long)addr;
1584         return nfc_read_region(flash_addr, data, len);
1585 }
1586
1587 void mxc_nfc_print_info(void)
1588 {
1589         diag_printf("[0x%08x bytes]: %u blocks of %u pages of %u bytes each.\n",
1590                                 NF_DEV_SZ, NF_BLK_CNT,
1591                                 NF_PG_PER_BLK, NF_PG_SZ);
1592 }
1593
1594 static int mxc_nfc_isbad_bbt(u16 *bbt, int block)
1595 {
1596         cyg_uint8 res;
1597
1598         block <<= 1;
1599         res = (get_byte(bbt, block >> 3) >> (block & 0x06)) & 0x03;
1600         res ^= 0x03;
1601         return res;
1602 }
1603
1604 static int mxc_nfc_search_bbt(struct nand_bbt_descr *td)
1605 {
1606         int i;
1607
1608         td->pages = -1;
1609         for (i = 0; i < NF_BBT_MAX_NR; i++) {
1610                 u32 blk = NF_BLK_CNT - i - 1;
1611                 flash_addr_t addr = blk * NF_BLK_SZ;
1612
1613                 if (nfc_read_pg_random(addr / NF_PG_SZ, addr % NF_PG_SZ,
1614                                                            ECC_FORCE_ON, 0, num_of_nand_chips) != 0) {
1615                         diag_printf("Failed to read bbt page %u at 0x%08llx\n",
1616                                                 (u32)(addr / NF_PG_SZ), addr);
1617                         continue;
1618                 }
1619                 if (check_short_pattern((void *)NAND_SPAR_BUF0, td) == 0) {
1620                         diag_printf1("found BBT at block %u addr %08llx\n", blk, (u64)addr);
1621                         td->pages = blk * NF_PG_PER_BLK;
1622                         td->version = get_byte((void *)NAND_SPAR_BUF0, td->veroffs);
1623                         mark_blk_bad(blk, g_bbt, BLK_RESERVED);
1624                         diag_printf1("Found version %d BBT at block %d (0x%08llx)\n",
1625                                                  td->version, td->pages / NF_PG_PER_BLK,
1626                                                  (u64)td->pages * NF_PG_SZ);
1627                         return 0;
1628                 }
1629         }
1630         return 1;
1631 }
1632
1633 /*
1634  * Look for the BBT depending on the passed-in lowlevel value.
1635  * @param       lowlevel        If true, then it does a low level scan based on factory
1636  *                                              marked BI(block info) field with ECC off to decide if a
1637  *                                              block is bad.
1638  *                                              If false, then it checks to see if an existing BBT in the
1639  *                                              flash or not. If not, then it returns -1. If yes, it will
1640  *                                              prints out the number of bad blocks.
1641  *
1642  * @return      number of bad blocks for the whole nand flash
1643  *
1644  * Note: For a brand new flash, this function has to be called with
1645  *               lowlevel=true.
1646  *
1647  *
1648  */
1649 static int mxc_nfc_scan(bool lowlevel)
1650 {
1651         u32 bad = 0, i;
1652         u32 count1 = 0, count2 = 0;
1653         u8 *buf = NULL;
1654         struct nand_bbt_descr *td = g_mxc_nfc_bbt_main_descr;
1655         struct nand_bbt_descr *md = g_mxc_nfc_bbt_mirror_descr;
1656
1657         nfc_printf(NFC_DEBUG_MAX, "%s()\n", __FUNCTION__);
1658         mxc_nfc_scan_done = 0;
1659
1660         if (g_nfc_debug_measure) {
1661                 count1 = hal_timer_count();
1662         }
1663         // read out the last 4 blocks for marker
1664         // need to keep where is the td and md block number
1665         if (!lowlevel) {
1666                 struct nand_bbt_descr *bd;
1667
1668                 diag_printf1("Searching for BBT in the flash ...\n");
1669                 if (mxc_nfc_search_bbt(td) != 0) {
1670                         diag_printf("No main BBT found in flash\n");
1671                 }
1672                 if (md && mxc_nfc_search_bbt(md) != 0) {
1673                         diag_printf("No mirror BBT found in flash\n");
1674                 }
1675                 if (td->pages == -1 && (!md || md->pages == -1)) {
1676                         diag_printf("No BBT found. Need to do \"nand scan\" first\n");
1677                         return -1;
1678                 }
1679                 if (td->pages >= 0 && (md == NULL || md->version <= td->version)) {
1680                         bd = td;
1681                         nfc_printf(NFC_DEBUG_MIN, "Using normal bbt at page %d\n", bd->pages);
1682                 } else if (md != NULL && md->pages >= 0) {
1683                         bd = md;
1684                         nfc_printf(NFC_DEBUG_MIN, "Using mirror bbt at page %d\n", bd->pages);
1685                 } else {
1686                         diag_printf("** Error: Failed to read bbt from flash\n");
1687                         return -1;
1688                 }
1689                 nfc_read_page(0, bd->pages, 0);
1690                 for (i = 0; i < NF_BLK_CNT; i++) {
1691                         int res = mxc_nfc_isbad_bbt((u16 *)NAND_MAIN_BUF0, i);
1692                         if (res) {
1693                                 // construct the bad block table
1694                                 mark_blk_bad(i, g_bbt, res);
1695                                 bad++;
1696                         }
1697                 }
1698                 buf = g_bbt;
1699         } else {
1700                 diag_printf("Doing low level scan to construct BBT\n");
1701                 for (i = 0; i < NF_BLK_CNT; i++) {
1702                         int res = nfc_is_badblock(i, buf);
1703                         if (res) {
1704                                 // construct the bad block table
1705                                 if (!buf)
1706                                         mark_blk_bad(i, g_bbt, res);
1707                                 bad++;
1708                         }
1709                 }
1710         }
1711         diag_printf1("Total bad blocks: %d\n", bad);
1712         if (g_nfc_debug_measure) {
1713                 count2 = hal_timer_count();
1714                 diag_printf("counter1=0x%x, counter2=0x%x, diff=0x%x (%u usec)\n",
1715                                         count1, count2, count2 - count1,
1716                                         (count2 - count1) * 1000000 / 32768);
1717         }
1718         mxc_nfc_scan_done = 1;
1719         return bad;
1720 }
1721
1722 ////////////////////////// "nand" commands support /////////////////////////
1723 // Image management functions
1724 local_cmd_entry("info",
1725                                 "Show nand flash info (number of good/bad blocks)",
1726                                 "",
1727                                 nand_info,
1728                                 NAND_cmds
1729                    );
1730
1731 local_cmd_entry("show",
1732                                 "Show a page main/spare areas or spare area only (-s)",
1733                                 "-f <raw page address> [-s]",
1734                                 nand_show,
1735                                 NAND_cmds
1736                    );
1737
1738 local_cmd_entry("read",
1739                                 "Read data from nand flash into RAM",
1740                                 "-f <raw addr> -b <mem_load_addr> -l <byte len> [-c <col>]\n"
1741                                 "      Note -c is only for 2K-page for value <0, 2048+64-1>",
1742                                 nand_read,
1743                                 NAND_cmds
1744                    );
1745
1746 local_cmd_entry("write",
1747                                 "Write data from RAM into nand flash",
1748                                 "-f <raw address> -b <memory_address> -l <image_length> [-c <col_addr>]",
1749                                 nand_write,
1750                                 NAND_cmds
1751                    );
1752
1753 local_cmd_entry("erase",
1754                                 "Erase nand flash contents",
1755                                 "-f <raw address> -l <length> [-o]\n"
1756                                 "             -o: force erase (even for bad blocks)",
1757                                 nand_erase,
1758                                 NAND_cmds
1759                    );
1760
1761 local_cmd_entry("scan",
1762                                 "Scan bad blocks and may also save bad block table into the NAND flash.",
1763                                 "[-o] [-r]\n"
1764                                 "No argument: save existing bad block table (BBT)\n"
1765                                 "            -r: re-scan with ECC off and save BBT -- for brand NEW flash\n"
1766                                 "            -o: force erase all, reconstruct BBT (no ECC) and save BBT -- for development.",
1767                                 nand_scan,
1768                                 NAND_cmds
1769                    );
1770
1771 local_cmd_entry("debug",
1772                                 "Various NAND debug features ",
1773                                 "<0> no debug messages <default>\n"
1774                                 "             <1> min debug messages\n"
1775                                 "             <2> med debug messages\n"
1776                                 "             <3> max debug messages\n"
1777                                 "             <4> enable(default)/disable h/w ECC for both r/w\n"
1778                                 "             <5> disable(default)/enalbe spare-only read\n"
1779                                 "             <9> enable/disable measurement\n"
1780                                 "             no parameter - display current debug setup",
1781                                 nand_debug_fun,
1782                                 NAND_cmds
1783                                 );
1784
1785 local_cmd_entry("bad",
1786                                 "Mark bad block in BBT",
1787                                 "[-f <raw address>] [-b <block number>] [-c]\n"
1788                                 "           -c: clear bad block mark\n"
1789                                 "           -f and -b are mutually exclusive",
1790                                 nand_bad,
1791                                 NAND_cmds
1792                                 );
1793
1794 // Define table boundaries
1795 CYG_HAL_TABLE_BEGIN( __NAND_cmds_TAB__, NAND_cmds);
1796 CYG_HAL_TABLE_END( __NAND_cmds_TAB_END__, NAND_cmds);
1797
1798 extern struct cmd __NAND_cmds_TAB__[], __NAND_cmds_TAB_END__;
1799
1800 // CLI function
1801 static cmd_fun do_nand_cmds;
1802 RedBoot_nested_cmd("nand",
1803                    "Utility function to NAND flash using raw address",
1804                    "{cmds}",
1805                    do_nand_cmds,
1806                    __NAND_cmds_TAB__, &__NAND_cmds_TAB_END__
1807                   );
1808
1809 static void nand_usage(char *why)
1810 {
1811         diag_printf("*** invalid 'nand' command: %s\n", why);
1812         cmd_usage(__NAND_cmds_TAB__, &__NAND_cmds_TAB_END__, "nand ");
1813 }
1814
1815 static u32 curr_addr;
1816 static void nand_show(int argc, char *argv[])
1817 {
1818         u32 ra;
1819         bool flash_addr_set = false;
1820         bool spar_only = false;
1821         struct option_info opts[2];
1822
1823         init_opts(&opts[0], 'f', true, OPTION_ARG_TYPE_NUM,
1824                           &ra, &flash_addr_set, "NAND FLASH memory byte address");
1825         init_opts(&opts[1], 's', false, OPTION_ARG_TYPE_FLG,
1826                           &spar_only, NULL, "Spare only");
1827
1828         if (!scan_opts(argc, argv, 2, opts, 2, 0, 0, 0)) {
1829                 return;
1830         }
1831         if (!flash_addr_set) {
1832                 ra = curr_addr;
1833                 curr_addr += NF_PG_SZ;
1834         } else {
1835                 curr_addr = ra;
1836         }
1837
1838         if (ra % NF_PG_SZ) {
1839                 diag_printf("** Error: flash address must be page aligned\n");
1840                 return;
1841         }
1842
1843         ra &= MXC_NAND_ADDR_MASK;
1844         if (nfc_is_badblock(OFFSET_TO_BLOCK(ra), g_bbt)) {
1845                 diag_printf("This is a bad block\n");
1846         }
1847
1848         print_page(ra, spar_only);
1849 }
1850
1851 /*!
1852  * For low level nand read command. It doesn't check for bad block or not
1853  */
1854 static void nand_read(int argc, char *argv[])
1855 {
1856         int len;
1857         u32 mem_addr, ra, col, i, pg_no, pg_off;
1858         bool mem_addr_set = false;
1859         bool flash_addr_set = false;
1860         bool length_set = false;
1861         bool col_set = false;
1862         struct option_info opts[4];
1863         int j = 0;
1864         bool ecc_status = g_ecc_enable;
1865
1866         init_opts(&opts[0], 'b', true, OPTION_ARG_TYPE_NUM,
1867                           &mem_addr, &mem_addr_set, "memory base address");
1868         init_opts(&opts[1], 'f', true, OPTION_ARG_TYPE_NUM,
1869                           &ra, &flash_addr_set, "FLASH memory base address");
1870         init_opts(&opts[2], 'l', true, OPTION_ARG_TYPE_NUM,
1871                           &len, &length_set, "image length [in FLASH]");
1872         init_opts(&opts[3], 'c', true, OPTION_ARG_TYPE_NUM,
1873                           &col, &col_set, "column addr");
1874
1875         if (!scan_opts(argc, argv, 2, opts, 4, 0, 0, 0)) {
1876                 nand_usage("invalid arguments");
1877                 return;
1878         }
1879
1880         if (ra % NF_PG_SZ) {
1881                 diag_printf("** Error: flash address must be page aligned\n");
1882                 return;
1883         }
1884
1885         if (!mem_addr_set || !flash_addr_set || !length_set) {
1886                 nand_usage("** Error: required parameter missing");
1887                 return;
1888         }
1889         if ((mem_addr < (CYG_ADDRESS)ram_start) ||
1890                 ((mem_addr+len) >= (CYG_ADDRESS)ram_end)) {
1891                 diag_printf("** WARNING: RAM address: 0x%08x may be invalid\n", mem_addr);
1892                 diag_printf("   valid range is 0x%p-0x%p\n", ram_start, ram_end);
1893         }
1894
1895         if (col_set) {
1896                 diag_printf("Random read at page %u, column 0x%04x\n",
1897                                         ra / NF_PG_SZ, col);
1898
1899                 if (g_is_2k_page || g_is_4k_page) {
1900                         g_ecc_enable = false;
1901                 }
1902                 nfc_read_pg_random(ra / NF_PG_SZ, col, ECC_FORCE_OFF, 0, num_of_nand_chips);
1903                 if (g_is_2k_page || g_is_4k_page) {
1904                         g_ecc_enable = ecc_status;
1905                 }
1906                 nfc_buf_read((void *)mem_addr, NAND_MAIN_BUF0, NF_PG_SZ);
1907                 return;
1908         }
1909
1910         // ensure integer multiple of page size
1911         len = (len + NF_PG_SZ - 1) & ~(NF_PG_SZ - 1);
1912         ra &= MXC_NAND_ADDR_MASK;
1913         do {
1914                 if (OFFSET_TO_BLOCK(ra) > (NF_BLK_CNT - 1)) {
1915                         diag_printf("\n** Error: flash address: 0x%08x out of range\n", ra);
1916                         return;
1917                 }
1918                 pg_no = ra / NF_PG_SZ;
1919                 pg_off = ra % NF_PG_SZ;
1920                 for (i = 0; i < num_of_nand_chips; i++) {
1921                         if (nfc_read_page(i, pg_no, pg_off) != 0) {
1922                                 diag_printf("\n** Error: uncorrectable ECC at addr 0x%08x\n", ra);
1923                                 diag_printf("use 'nand bad -b %u' to mark this block in BBT\n",
1924                                                         pg_no / NF_PG_PER_BLK);
1925                         }
1926                         if ((j++ % 0x20) == 0)
1927                                 diag_printf("\n%s 0x%08x: ", __FUNCTION__, ra);
1928                         diag_printf(".");
1929
1930                         nfc_buf_read((void *)mem_addr, NAND_MAIN_BUF0, NF_PG_SZ / num_of_nand_chips);
1931
1932                         ra += NF_PG_SZ / num_of_nand_chips;
1933                         mem_addr += NF_PG_SZ / num_of_nand_chips;
1934                         len -= NF_PG_SZ / num_of_nand_chips;
1935                         pg_off = 0;
1936                 }
1937         } while (len > 0);
1938         diag_printf("\n");
1939 }
1940
1941 static void nand_write(int argc, char *argv[])
1942 {
1943         int len, len_st, j = 0;
1944         u32 mem_addr, mem_addr_st, ra, col;
1945         bool mem_addr_set = false;
1946         bool flash_addr_set = false;
1947         bool length_set = false;
1948         bool col_set = false;
1949         struct option_info opts[4];
1950         bool ecc_status = g_ecc_enable;
1951
1952         init_opts(&opts[0], 'b', true, OPTION_ARG_TYPE_NUM,
1953                           &mem_addr, &mem_addr_set, "memory base address");
1954         init_opts(&opts[1], 'f', true, OPTION_ARG_TYPE_NUM,
1955                           &ra, &flash_addr_set, "FLASH memory base address");
1956         init_opts(&opts[2], 'l', true, OPTION_ARG_TYPE_NUM,
1957                           &len, &length_set, "image length [in FLASH]");
1958         init_opts(&opts[3], 'c', true, OPTION_ARG_TYPE_NUM,
1959                           &col, &col_set, "column addr");
1960         if (!scan_opts(argc, argv, 2, opts, 4, 0, 0, 0)) {
1961                 nand_usage("invalid arguments");
1962                 return;
1963         }
1964
1965         if (!mem_addr_set || !flash_addr_set || !length_set) {
1966                 nand_usage("required parameter missing");
1967                 return;
1968         }
1969
1970         if ((mem_addr < (CYG_ADDRESS)ram_start) ||
1971                 ((mem_addr+len) >= (CYG_ADDRESS)ram_end)) {
1972                 diag_printf("** WARNING: RAM address: %p may be invalid\n", (void *)mem_addr);
1973                 diag_printf("   valid range is %p-%p\n", (void *)ram_start, (void *)ram_end);
1974         }
1975
1976         if (col_set) {
1977                 diag_printf("Random write at page %u, column %u\n", ra / NF_PG_SZ, col);
1978
1979                 if (g_is_2k_page || g_is_4k_page) {
1980                         g_ecc_enable = false;
1981                 }
1982                 nfc_write_pg_random(ra / NF_PG_SZ, col, (u8 *)mem_addr, 0);
1983                 if (g_is_2k_page || g_is_4k_page) {
1984                         g_ecc_enable = ecc_status;
1985                 }
1986                 return;
1987         }
1988
1989         if ((ra % NF_PG_SZ) != 0) {
1990                 diag_printf("** Error: flash address must be page aligned\n");
1991                 return;
1992         }
1993
1994         mem_addr_st = mem_addr;
1995         len_st = len;
1996         ra &= MXC_NAND_ADDR_MASK;
1997         do {
1998                 if (OFFSET_TO_BLOCK(ra) > (NF_BLK_CNT - 1)) {
1999                         diag_printf("\nOut of range: addr=0x%08x\n", ra);
2000                         return;
2001                 }
2002                 if (nfc_is_badblock(OFFSET_TO_BLOCK(ra), g_bbt)) {
2003                         diag_printf("\nSkipping bad block %u at addr=0x%08llx\n",
2004                                                 OFFSET_TO_BLOCK(ra), (u64)ra);
2005                         ra = (OFFSET_TO_BLOCK(ra) + 1) *  NF_BLK_SZ;
2006                         continue;
2007                 }
2008
2009                 if ((ra % NF_BLK_SZ) == 0) {
2010                          mem_addr_st = mem_addr;
2011                          len_st = len;
2012                 }
2013                 if (nfc_write_pg_random(ra / NF_PG_SZ, ra % NF_PG_SZ, (u8 *)mem_addr, 0) != 0) {
2014                         if (g_nfc_debug_level >= NFC_DEBUG_DEF) {
2015                                 diag_printf("\nWarning %d: program error at addr 0x%x\n", __LINE__, ra);
2016                         }
2017                         mark_blk_bad(OFFSET_TO_BLOCK(ra), g_bbt, BLK_BAD_RUNTIME);
2018                         ra = (OFFSET_TO_BLOCK(ra) + 1) *  NF_BLK_SZ; //make sure block size aligned
2019                         mem_addr = mem_addr_st; // rewind to blocl boundary
2020                         len = len_st;
2021                         continue;
2022                 }
2023                 if ((j++ % 0x20) == 0)
2024                         diag_printf("\nProgramming 0x%08x: ", ra);
2025                 diag_printf(".");
2026
2027                 len -= NF_PG_SZ;
2028                 ra += NF_PG_SZ;
2029                 mem_addr += NF_PG_SZ;
2030         } while (len > 0);
2031         diag_printf("\n");
2032 }
2033
2034 void nand_debug_fun(int argc, char *argv[])
2035 {
2036         int opt;
2037         const char *dbg_lvl_str;
2038
2039         if (argc == 3) {
2040                 opt = argv[2][0] - '0';
2041                 switch (opt) {
2042                 case 0:
2043                         g_nfc_debug_level = NFC_DEBUG_NONE;
2044                         break;
2045                 case 1:
2046                         g_nfc_debug_level = NFC_DEBUG_MIN;
2047                         break;
2048                 case 2:
2049                         g_nfc_debug_level = NFC_DEBUG_MED;
2050                         break;
2051                 case 3:
2052                         g_nfc_debug_level = NFC_DEBUG_MAX;
2053                         break;
2054                 case 4:
2055                         g_ecc_enable = g_ecc_enable? false: true;
2056                         break;
2057                 case 5:
2058                         // toggle g_spare_only_read_ok
2059                         g_spare_only_read_ok = g_spare_only_read_ok? false: true;
2060                         break;
2061                 case 9:
2062                         g_nfc_debug_measure = g_nfc_debug_measure? false: true;
2063                         break;
2064
2065                 default:
2066                         diag_printf("%s(%s) not supported\n", __FUNCTION__, argv[2]);
2067                 }
2068         }
2069         switch (g_nfc_debug_level) {
2070         case NFC_DEBUG_NONE:
2071                 dbg_lvl_str = "none";
2072                 break;
2073         case NFC_DEBUG_MIN:
2074                 dbg_lvl_str = "min";
2075                 break;
2076         case NFC_DEBUG_MED:
2077                 dbg_lvl_str = "med";
2078                 break;
2079         case NFC_DEBUG_MAX:
2080                 dbg_lvl_str = "max";
2081                 break;
2082         default:
2083                 dbg_lvl_str = "invalid";
2084         }
2085         diag_printf("Current debug options are:\n");
2086         diag_printf("    h/w ECC: %s\n", g_ecc_enable ? "on" : "off");
2087         diag_printf("    sp-only read: %s\n", g_spare_only_read_ok ? "on" : "off");
2088         diag_printf("    measurement: %s\n", g_nfc_debug_measure ? "on" : "off");
2089         diag_printf("    message level: %s\n", dbg_lvl_str);
2090 }
2091
2092 static void nand_erase(int argc, char *argv[])
2093 {
2094         u32 len, ra;
2095         bool faddr_set = false;
2096         bool force_erase_set = false;
2097         bool length_set = false;
2098         struct option_info opts[4];
2099
2100         init_opts(&opts[0], 'f', true, OPTION_ARG_TYPE_NUM,
2101                   &ra, &faddr_set, "FLASH memory base address");
2102         init_opts(&opts[1], 'l', true, OPTION_ARG_TYPE_NUM,
2103                   &len, &length_set, "length in bytes");
2104         init_opts(&opts[2], 'o', false, OPTION_ARG_TYPE_FLG,
2105                   &force_erase_set, &force_erase_set, "force erases block");
2106
2107         if (!scan_opts(argc, argv, 2, opts, 4, 0, 0, 0)) {
2108                 nand_usage("invalid arguments");
2109                 return;
2110         }
2111
2112         if (!faddr_set || !length_set) {
2113                 nand_usage("missing argument");
2114                 return;
2115         }
2116         if ((ra % NF_BLK_SZ) != 0 ||
2117                 (len % NF_BLK_SZ) != 0 || len == 0) {
2118                 diag_printf("Address or length is not block aligned or length is zero!\n");
2119                 diag_printf("Block size is 0x%x\n", NF_BLK_SZ);
2120                 return;
2121         }
2122
2123         if (!verify_action("About to erase 0x%x bytes from nand offset 0x%x\n", len, ra)) {
2124                 diag_printf("** Aborted\n");
2125                 return;
2126         }
2127
2128         // now ra is block aligned
2129         if (force_erase_set == true) {
2130                 diag_printf("Force erase ...");
2131                 nfc_erase_region(ra, len, 0, 1);
2132                 diag_printf("\n");
2133         } else {
2134                 nfc_erase_region(ra, len, 1, 1);
2135         }
2136         diag_printf("\n");
2137 }
2138
2139 extern void romupdate(int argc, char *argv[]);
2140 static void nand_scan(int argc, char *argv[])
2141 {
2142         bool force_erase = false;
2143         bool force_rescan = false;
2144         struct option_info opts[2];
2145
2146         init_opts(&opts[0], 'o', false, OPTION_ARG_TYPE_FLG,
2147                   &force_erase, NULL, "force erases block first");
2148
2149         init_opts(&opts[1], 'r', false, OPTION_ARG_TYPE_FLG,
2150                   &force_rescan, NULL, "force low level re-scan");
2151
2152         if (!scan_opts(argc, argv, 2, opts, 2, 0, 0, 0)) {
2153                 nand_usage("invalid arguments");
2154                 return;
2155         }
2156
2157         if (!force_erase && !force_rescan && !mxc_nfc_scan_done) {
2158                 diag_printf("Need to build BBT first with \"nand scan [-o|-r]\"\n");
2159                 return;
2160         }
2161         if (force_erase) {
2162                 void *bbt = g_bbt;
2163
2164                 diag_printf("Force erase first ...\n");
2165                 g_bbt = NULL;
2166                 // do force erase, skipping bad blocks. After this call, g_bbt should be re-built
2167                 // for the whole NAND flash.
2168                 if (nfc_erase_region(0, NF_DEV_SZ, true, false) != 0) {
2169                         g_bbt = bbt;
2170                         return;
2171                 }
2172                 g_bbt = bbt;
2173                 mxc_nfc_scan_done = 0;
2174                 diag_printf("\n");
2175         }
2176         if (force_rescan) {
2177                 diag_printf("Force re-scan ...\n");
2178                 memset(g_bbt, 0, g_bbt_sz);
2179                 mxc_nfc_scan(true);
2180         }
2181         // program g_bbt into the flash
2182         diag_printf("Writing BBT to flash\n");
2183         if (program_bbt_to_flash() != 0) {
2184                 diag_printf("Error: Failed to write BBT to flash\n");
2185         }
2186         if (force_erase) {
2187                 romupdate(0, NULL);
2188         }
2189 }
2190
2191 static void nand_info(int argc, char *argv[])
2192 {
2193         u32 i, j = 0;
2194
2195         if (nand_flash_index == -1) {
2196                 diag_printf("Can't find valid NAND flash: %d\n", __LINE__);
2197                 return;
2198         }
2199
2200         diag_printf("\nType:\t\t %s\n", NF_VEND_INFO);
2201         diag_printf("Total size:\t 0x%08x bytes (%d MiB)\n", NF_DEV_SZ, NF_DEV_SZ / SZ_1M);
2202         diag_printf("Total blocks:\t 0x%x (%d)\n", NF_BLK_CNT, NF_BLK_CNT);
2203         diag_printf("Block size:\t 0x%x (%d)\n", NF_BLK_SZ, NF_BLK_SZ);
2204         diag_printf("Page size:\t 0x%x (%d)\n", NF_PG_SZ, NF_PG_SZ);
2205         diag_printf("Spare size:\t 0x%x (%d)\n", NF_SPARE_SZ, NF_SPARE_SZ);
2206         diag_printf("Pages per block: 0x%x (%d)\n", NF_PG_PER_BLK, NF_PG_PER_BLK);
2207
2208         if (mxc_nfc_scan(false) == -1) {
2209                 return;
2210         }
2211         diag_printf("\n");
2212         for (i = 0; i < NF_BLK_CNT; i++) {
2213                 int res = nfc_is_badblock(i, g_bbt);
2214                 if (res & ~BLK_RESERVED) {
2215                         diag_printf("block %d at offset 0x%08x is a %s bad block\n",
2216                                                 i, i * NF_BLK_SZ, res == BLK_BAD_FACTORY ? "factory" : "runtime");
2217                         j++;
2218                 }
2219         }
2220         diag_printf("==================================\n");
2221         diag_printf("Found %d bad block(s) out of %d\n", j, i);
2222 }
2223
2224 static void nand_bad(int argc, char *argv[])
2225 {
2226         u32 ra;
2227         u32 block;
2228         bool ra_set = false;
2229         bool block_set = false;
2230         bool clear = false;
2231         struct option_info opts[3];
2232         int bad;
2233
2234         init_opts(&opts[0], 'f', true, OPTION_ARG_TYPE_NUM,
2235                           &ra, &ra_set, "FLASH memory base address");
2236         init_opts(&opts[1], 'b', true, OPTION_ARG_TYPE_NUM,
2237                           &block, &block_set, "block number");
2238         init_opts(&opts[2], 'c', false, OPTION_ARG_TYPE_FLG,
2239                           &clear, NULL, "clear bad block marker");
2240
2241         if (!scan_opts(argc, argv, 2, opts, NUM_ELEMS(opts), NULL, 0, NULL)) {
2242                 nand_usage("invalid arguments");
2243                 return;
2244         }
2245
2246         if (!ra_set && !block_set) {
2247                 nand_usage("missing argument");
2248                 return;
2249         }
2250         if (ra_set && block_set) {
2251                 nand_usage("options -f and -b are mutually exclusive");
2252                 return;
2253         } else if (ra_set) {
2254                 block = OFFSET_TO_BLOCK(ra & MXC_NAND_ADDR_MASK);
2255         } else {
2256                 ra = BLOCK_TO_OFFSET(block) + (unsigned long)flash_info.start;
2257         }
2258         if ((ra % NF_BLK_SZ) != 0) {
2259                 diag_printf("Address is not block aligned!\n");
2260                 diag_printf("Block size is 0x%08x\n", NF_BLK_SZ);
2261                 return;
2262         }
2263
2264         bad = nfc_is_badblock(block, g_bbt);
2265         if ((bad && !clear) || (!bad && clear)) {
2266                 diag_printf("block %5u at address 0x%08x is already %s\n",
2267                                         block, ra, bad ? "bad" : "good");
2268                 return;
2269         }
2270         if (clear && bad != BLK_BAD_RUNTIME) {
2271                 diag_printf("Refusing to mark a factory bad block as good!\n");
2272                 return;
2273         }
2274         if (!verify_action("Mark block %u at address 0x%08x %s in BBT",
2275                                            block, ra, clear ? "good" : "bad")) {
2276                 diag_printf("** Aborted\n");
2277                 return;
2278         }
2279
2280         nfc_printf(NFC_DEBUG_MIN, "Marking block %5u at 0x%08x %s\n",
2281                            block, ra, clear ? "good" : "bad");
2282         mark_blk_bad(block, g_bbt, clear ? 0 : BLK_BAD_RUNTIME);
2283         mxc_nfc_update_bbt(g_mxc_nfc_bbt_main_descr,
2284                                            g_mxc_nfc_bbt_mirror_descr);
2285 }
2286
2287 static void do_nand_cmds(int argc, char *argv[])
2288 {
2289         struct cmd *cmd;
2290
2291         if (!mxcnfc_init_ok) {
2292 #ifdef CYGHWR_DEVS_FLASH_MXC_MULTI
2293                 diag_printf("Warning: NAND flash hasn't been initialized. Try \"factive nand\" first\n\n");
2294 #else
2295                 diag_printf("Error: NAND flash hasn't been initialized\n");
2296 #endif
2297                 return;
2298         }
2299
2300         if (argc < 2) {
2301                 nand_usage("too few arguments");
2302                 return;
2303         }
2304
2305         if ((cmd = cmd_search(__NAND_cmds_TAB__, &__NAND_cmds_TAB_END__,
2306                                                   argv[1])) != NULL) {
2307                 cmd->fun(argc, argv);
2308                 return;
2309         }
2310         nand_usage("unrecognized command");
2311 }
2312
2313 /*!
2314  * Display a memory region by 16-bit words
2315  * @param pkt   pointer to the starting address of the memory
2316  * @param len   byte length of the buffer to be displayed
2317  */
2318 static void print_pkt_16(u16 *pkt, u32 len)
2319 {
2320         diag_printf("******************** %d bytes********************\n", len);
2321         u32 i = 0, tempLen = (len + 1) / 2;
2322
2323         while (tempLen != 0) {
2324                 if (tempLen >= 8) {
2325                         diag_printf("[%03x-%03x] ", i * 2, (i * 2) + 14);
2326                         diag_printf("%04x %04x %04x %04x %04x %04x %04x %04x\n",
2327                                                 pkt[i], pkt[i + 1], pkt[i + 2], pkt[i + 3],
2328                                                 pkt[i + 4], pkt[i + 5], pkt[i + 6], pkt[i + 7]);
2329                         tempLen -= 8;
2330                         i += 8;
2331                 } else {
2332                         if (tempLen != 0) {
2333                                 diag_printf("[%03x-%03x]", i * 2, (i + tempLen) * 2);
2334                                 while (tempLen-- != 0) {
2335                                         diag_printf(" %04x", pkt[i++]);
2336                                 }
2337                                 diag_printf("\n");
2338                         }
2339                         diag_printf("*************************************************\n");
2340                         return;
2341                 }
2342         }
2343 }
2344
2345 // addr = starting byte address within NAND flash
2346 static void print_page(u32 addr, bool spare_only)
2347 {
2348         u32 i, pg_no, pg_off;
2349         u32 blk_num = OFFSET_TO_BLOCK(addr), pg_num = OFFSET_TO_PAGE(addr);
2350
2351         if (addr % NF_PG_SZ) {
2352                 diag_printf("Non page-aligned read not supported here: 0x%x\n", addr);
2353                 return;
2354         }
2355         if (spare_only) {
2356                 diag_printf("Error %d: Not supported\n", __LINE__);
2357                 return;
2358         } else {
2359                 pg_no = addr / NF_PG_SZ;
2360                 pg_off = addr % NF_PG_SZ;
2361                 for (i = 0; i < num_of_nand_chips; i++) {
2362                         if (nfc_read_page(i, pg_no, pg_off) != 0) {
2363                                 diag_printf("Error %d: uncorrectable. But still printing ...\n", __LINE__);
2364                         }
2365                         pg_off = 0;
2366                         diag_printf("\n============ Printing block(%d) page(%d)  ==============\n",
2367                                                                   blk_num, pg_num);
2368
2369                         diag_printf("<<<<<<<<< spare area >>>>>>>>>\n");
2370                         print_pkt_16((u16*)NAND_SPAR_BUF0, NF_SPARE_SZ);
2371
2372                         if (!spare_only) {
2373                                 diag_printf("<<<<<<<<< main area >>>>>>>>>\n");
2374                                 print_pkt_16((u16*)NAND_MAIN_BUF0, NF_PG_SZ / num_of_nand_chips);
2375                         }
2376
2377                         diag_printf("\n");
2378                 }
2379         }
2380 }