use COMMAND_PARSE_ENABLE macro where appropriate
[fw/openocd] / src / flash / nand.c
1 /***************************************************************************
2  *   Copyright (C) 2007 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Partially based on drivers/mtd/nand_ids.c from Linux.                 *
6  *   Copyright (C) 2002 Thomas Gleixner <tglx@linutronix.de>               *
7  *                                                                         *
8  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program; if not, write to the                         *
20  *   Free Software Foundation, Inc.,                                       *
21  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
22  ***************************************************************************/
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include "nand.h"
28 #include "time_support.h"
29 #include "fileio.h"
30
31 static int nand_read_page(struct nand_device *nand, uint32_t page, uint8_t *data, uint32_t data_size, uint8_t *oob, uint32_t oob_size);
32 //static int nand_read_plain(struct nand_device *nand, uint32_t address, uint8_t *data, uint32_t data_size);
33
34 static int nand_write_page(struct nand_device *nand, uint32_t page, uint8_t *data, uint32_t data_size, uint8_t *oob, uint32_t oob_size);
35
36 /* NAND flash controller
37  */
38 extern struct nand_flash_controller davinci_nand_controller;
39 extern struct nand_flash_controller lpc3180_nand_controller;
40 extern struct nand_flash_controller orion_nand_controller;
41 extern struct nand_flash_controller s3c2410_nand_controller;
42 extern struct nand_flash_controller s3c2412_nand_controller;
43 extern struct nand_flash_controller s3c2440_nand_controller;
44 extern struct nand_flash_controller s3c2443_nand_controller;
45 extern struct nand_flash_controller imx31_nand_flash_controller;
46
47 /* extern struct nand_flash_controller boundary_scan_nand_controller; */
48
49 static struct nand_flash_controller *nand_flash_controllers[] =
50 {
51         &davinci_nand_controller,
52         &lpc3180_nand_controller,
53         &orion_nand_controller,
54         &s3c2410_nand_controller,
55         &s3c2412_nand_controller,
56         &s3c2440_nand_controller,
57         &s3c2443_nand_controller,
58         &imx31_nand_flash_controller,
59 /*      &boundary_scan_nand_controller, */
60         NULL
61 };
62
63 /* configured NAND devices and NAND Flash command handler */
64 static struct nand_device *nand_devices = NULL;
65 static struct command *nand_cmd;
66
67 /*      Chip ID list
68  *
69  *      Name, ID code, pagesize, chipsize in MegaByte, eraseblock size,
70  *      options
71  *
72  *      Pagesize; 0, 256, 512
73  *      0       get this information from the extended chip ID
74  *      256     256 Byte page size
75  *      512     512 Byte page size
76  */
77 static struct nand_info nand_flash_ids[] =
78 {
79         /* start "museum" IDs */
80         {"NAND 1MiB 5V 8-bit",          0x6e, 256, 1, 0x1000, 0},
81         {"NAND 2MiB 5V 8-bit",          0x64, 256, 2, 0x1000, 0},
82         {"NAND 4MiB 5V 8-bit",          0x6b, 512, 4, 0x2000, 0},
83         {"NAND 1MiB 3,3V 8-bit",        0xe8, 256, 1, 0x1000, 0},
84         {"NAND 1MiB 3,3V 8-bit",        0xec, 256, 1, 0x1000, 0},
85         {"NAND 2MiB 3,3V 8-bit",        0xea, 256, 2, 0x1000, 0},
86         {"NAND 4MiB 3,3V 8-bit",        0xd5, 512, 4, 0x2000, 0},
87         {"NAND 4MiB 3,3V 8-bit",        0xe3, 512, 4, 0x2000, 0},
88         {"NAND 4MiB 3,3V 8-bit",        0xe5, 512, 4, 0x2000, 0},
89         {"NAND 8MiB 3,3V 8-bit",        0xd6, 512, 8, 0x2000, 0},
90
91         {"NAND 8MiB 1,8V 8-bit",        0x39, 512, 8, 0x2000, 0},
92         {"NAND 8MiB 3,3V 8-bit",        0xe6, 512, 8, 0x2000, 0},
93         {"NAND 8MiB 1,8V 16-bit",       0x49, 512, 8, 0x2000, NAND_BUSWIDTH_16},
94         {"NAND 8MiB 3,3V 16-bit",       0x59, 512, 8, 0x2000, NAND_BUSWIDTH_16},
95         /* end "museum" IDs */
96
97         {"NAND 16MiB 1,8V 8-bit",       0x33, 512, 16, 0x4000, 0},
98         {"NAND 16MiB 3,3V 8-bit",       0x73, 512, 16, 0x4000, 0},
99         {"NAND 16MiB 1,8V 16-bit",      0x43, 512, 16, 0x4000, NAND_BUSWIDTH_16},
100         {"NAND 16MiB 3,3V 16-bit",      0x53, 512, 16, 0x4000, NAND_BUSWIDTH_16},
101
102         {"NAND 32MiB 1,8V 8-bit",       0x35, 512, 32, 0x4000, 0},
103         {"NAND 32MiB 3,3V 8-bit",       0x75, 512, 32, 0x4000, 0},
104         {"NAND 32MiB 1,8V 16-bit",      0x45, 512, 32, 0x4000, NAND_BUSWIDTH_16},
105         {"NAND 32MiB 3,3V 16-bit",      0x55, 512, 32, 0x4000, NAND_BUSWIDTH_16},
106
107         {"NAND 64MiB 1,8V 8-bit",       0x36, 512, 64, 0x4000, 0},
108         {"NAND 64MiB 3,3V 8-bit",       0x76, 512, 64, 0x4000, 0},
109         {"NAND 64MiB 1,8V 16-bit",      0x46, 512, 64, 0x4000, NAND_BUSWIDTH_16},
110         {"NAND 64MiB 3,3V 16-bit",      0x56, 512, 64, 0x4000, NAND_BUSWIDTH_16},
111
112         {"NAND 128MiB 1,8V 8-bit",      0x78, 512, 128, 0x4000, 0},
113         {"NAND 128MiB 1,8V 8-bit",      0x39, 512, 128, 0x4000, 0},
114         {"NAND 128MiB 3,3V 8-bit",      0x79, 512, 128, 0x4000, 0},
115         {"NAND 128MiB 1,8V 16-bit",     0x72, 512, 128, 0x4000, NAND_BUSWIDTH_16},
116         {"NAND 128MiB 1,8V 16-bit",     0x49, 512, 128, 0x4000, NAND_BUSWIDTH_16},
117         {"NAND 128MiB 3,3V 16-bit",     0x74, 512, 128, 0x4000, NAND_BUSWIDTH_16},
118         {"NAND 128MiB 3,3V 16-bit",     0x59, 512, 128, 0x4000, NAND_BUSWIDTH_16},
119
120         {"NAND 256MiB 3,3V 8-bit",      0x71, 512, 256, 0x4000, 0},
121
122         {"NAND 64MiB 1,8V 8-bit",       0xA2, 0,  64, 0, LP_OPTIONS},
123         {"NAND 64MiB 3,3V 8-bit",       0xF2, 0,  64, 0, LP_OPTIONS},
124         {"NAND 64MiB 1,8V 16-bit",      0xB2, 0,  64, 0, LP_OPTIONS16},
125         {"NAND 64MiB 3,3V 16-bit",      0xC2, 0,  64, 0, LP_OPTIONS16},
126
127         {"NAND 128MiB 1,8V 8-bit",      0xA1, 0, 128, 0, LP_OPTIONS},
128         {"NAND 128MiB 3,3V 8-bit",      0xF1, 0, 128, 0, LP_OPTIONS},
129         {"NAND 128MiB 1,8V 16-bit",     0xB1, 0, 128, 0, LP_OPTIONS16},
130         {"NAND 128MiB 3,3V 16-bit",     0xC1, 0, 128, 0, LP_OPTIONS16},
131
132         {"NAND 256MiB 1,8V 8-bit",      0xAA, 0, 256, 0, LP_OPTIONS},
133         {"NAND 256MiB 3,3V 8-bit",      0xDA, 0, 256, 0, LP_OPTIONS},
134         {"NAND 256MiB 1,8V 16-bit",     0xBA, 0, 256, 0, LP_OPTIONS16},
135         {"NAND 256MiB 3,3V 16-bit",     0xCA, 0, 256, 0, LP_OPTIONS16},
136
137         {"NAND 512MiB 1,8V 8-bit",      0xAC, 0, 512, 0, LP_OPTIONS},
138         {"NAND 512MiB 3,3V 8-bit",      0xDC, 0, 512, 0, LP_OPTIONS},
139         {"NAND 512MiB 1,8V 16-bit",     0xBC, 0, 512, 0, LP_OPTIONS16},
140         {"NAND 512MiB 3,3V 16-bit",     0xCC, 0, 512, 0, LP_OPTIONS16},
141
142         {"NAND 1GiB 1,8V 8-bit",        0xA3, 0, 1024, 0, LP_OPTIONS},
143         {"NAND 1GiB 3,3V 8-bit",        0xD3, 0, 1024, 0, LP_OPTIONS},
144         {"NAND 1GiB 1,8V 16-bit",       0xB3, 0, 1024, 0, LP_OPTIONS16},
145         {"NAND 1GiB 3,3V 16-bit",       0xC3, 0, 1024, 0, LP_OPTIONS16},
146
147         {"NAND 2GiB 1,8V 8-bit",        0xA5, 0, 2048, 0, LP_OPTIONS},
148         {"NAND 2GiB 3,3V 8-bit",        0xD5, 0, 2048, 0, LP_OPTIONS},
149         {"NAND 2GiB 1,8V 16-bit",       0xB5, 0, 2048, 0, LP_OPTIONS16},
150         {"NAND 2GiB 3,3V 16-bit",       0xC5, 0, 2048, 0, LP_OPTIONS16},
151
152         {NULL, 0, 0, 0, 0, 0 }
153 };
154
155 /* Manufacturer ID list
156  */
157 static struct nand_manufacturer nand_manuf_ids[] =
158 {
159         {0x0, "unknown"},
160         {NAND_MFR_TOSHIBA, "Toshiba"},
161         {NAND_MFR_SAMSUNG, "Samsung"},
162         {NAND_MFR_FUJITSU, "Fujitsu"},
163         {NAND_MFR_NATIONAL, "National"},
164         {NAND_MFR_RENESAS, "Renesas"},
165         {NAND_MFR_STMICRO, "ST Micro"},
166         {NAND_MFR_HYNIX, "Hynix"},
167         {NAND_MFR_MICRON, "Micron"},
168         {0x0, NULL},
169 };
170
171 /*
172  * Define default oob placement schemes for large and small page devices
173  */
174
175 #if 0
176 static struct nand_ecclayout nand_oob_8 = {
177         .eccbytes = 3,
178         .eccpos = {0, 1, 2},
179         .oobfree = {
180                 {.offset = 3,
181                  .length = 2},
182                 {.offset = 6,
183                  .length = 2}}
184 };
185 #endif
186
187 static struct nand_ecclayout nand_oob_16 = {
188         .eccbytes = 6,
189         .eccpos = {0, 1, 2, 3, 6, 7},
190         .oobfree = {
191                 {.offset = 8,
192                  . length = 8}}
193 };
194
195 static struct nand_ecclayout nand_oob_64 = {
196         .eccbytes = 24,
197         .eccpos = {
198                    40, 41, 42, 43, 44, 45, 46, 47,
199                    48, 49, 50, 51, 52, 53, 54, 55,
200                    56, 57, 58, 59, 60, 61, 62, 63},
201         .oobfree = {
202                 {.offset = 2,
203                  .length = 38}}
204 };
205
206 /* nand device <nand_controller> [controller options]
207  */
208 COMMAND_HANDLER(handle_nand_device_command)
209 {
210         int i;
211         int retval;
212
213         if (CMD_ARGC < 1)
214         {
215                 LOG_WARNING("incomplete flash device nand configuration");
216                 return ERROR_FLASH_BANK_INVALID;
217         }
218
219         for (i = 0; nand_flash_controllers[i]; i++)
220         {
221                 struct nand_device *p, *c;
222
223                 if (strcmp(CMD_ARGV[0], nand_flash_controllers[i]->name) == 0)
224                 {
225                         /* register flash specific commands */
226                         if ((retval = nand_flash_controllers[i]->register_commands(CMD_CTX)) != ERROR_OK)
227                         {
228                                 LOG_ERROR("couldn't register '%s' commands", CMD_ARGV[0]);
229                                 return retval;
230                         }
231
232                         c = malloc(sizeof(struct nand_device));
233
234                         c->controller = nand_flash_controllers[i];
235                         c->controller_priv = NULL;
236                         c->manufacturer = NULL;
237                         c->device = NULL;
238                         c->bus_width = 0;
239                         c->address_cycles = 0;
240                         c->page_size = 0;
241                         c->use_raw = 0;
242                         c->next = NULL;
243
244                         retval = CALL_COMMAND_HANDLER(nand_flash_controllers[i]->nand_device_command, c);
245                         if (ERROR_OK != retval)
246                         {
247                                 LOG_ERROR("'%s' driver rejected nand flash", c->controller->name);
248                                 free(c);
249                                 return ERROR_OK;
250                         }
251
252                         /* put NAND device in linked list */
253                         if (nand_devices)
254                         {
255                                 /* find last flash device */
256                                 for (p = nand_devices; p && p->next; p = p->next);
257                                 if (p)
258                                         p->next = c;
259                         }
260                         else
261                         {
262                                 nand_devices = c;
263                         }
264
265                         return ERROR_OK;
266                 }
267         }
268
269         /* no valid NAND controller was found (i.e. the configuration option,
270          * didn't match one of the compiled-in controllers)
271          */
272         LOG_ERROR("No valid NAND flash controller found (%s)", CMD_ARGV[0]);
273         LOG_ERROR("compiled-in NAND flash controllers:");
274         for (i = 0; nand_flash_controllers[i]; i++)
275         {
276                 LOG_ERROR("%i: %s", i, nand_flash_controllers[i]->name);
277         }
278
279         return ERROR_OK;
280 }
281
282 int nand_register_commands(struct command_context *cmd_ctx)
283 {
284         nand_cmd = register_command(cmd_ctx, NULL, "nand", NULL, COMMAND_ANY, "NAND specific commands");
285
286         register_command(cmd_ctx, nand_cmd, "device", handle_nand_device_command, COMMAND_CONFIG, NULL);
287
288         return ERROR_OK;
289 }
290
291 struct nand_device *get_nand_device_by_num(int num)
292 {
293         struct nand_device *p;
294         int i = 0;
295
296         for (p = nand_devices; p; p = p->next)
297         {
298                 if (i++ == num)
299                 {
300                         return p;
301                 }
302         }
303
304         return NULL;
305 }
306
307 COMMAND_HELPER(nand_command_get_device_by_num, unsigned name_index,
308                 struct nand_device **nand)
309 {
310         const char *str = CMD_ARGV[name_index];
311         unsigned num;
312         COMMAND_PARSE_NUMBER(uint, str, num);
313         *nand = get_nand_device_by_num(num);
314         if (!*nand) {
315                 command_print(CMD_CTX, "NAND flash device '#%s' is out of bounds", str);
316                 return ERROR_INVALID_ARGUMENTS;
317         }
318         return ERROR_OK;
319 }
320
321 static int nand_build_bbt(struct nand_device *nand, int first, int last)
322 {
323         uint32_t page = 0x0;
324         int i;
325         uint8_t oob[6];
326
327         if ((first < 0) || (first >= nand->num_blocks))
328                 first = 0;
329
330         if ((last >= nand->num_blocks) || (last == -1))
331                 last = nand->num_blocks - 1;
332
333         for (i = first; i < last; i++)
334         {
335                 nand_read_page(nand, page, NULL, 0, oob, 6);
336
337                 if (((nand->device->options & NAND_BUSWIDTH_16) && ((oob[0] & oob[1]) != 0xff))
338                         || (((nand->page_size == 512) && (oob[5] != 0xff)) ||
339                                 ((nand->page_size == 2048) && (oob[0] != 0xff))))
340                 {
341                         LOG_WARNING("bad block: %i", i);
342                         nand->blocks[i].is_bad = 1;
343                 }
344                 else
345                 {
346                         nand->blocks[i].is_bad = 0;
347                 }
348
349                 page += (nand->erase_size / nand->page_size);
350         }
351
352         return ERROR_OK;
353 }
354
355 int nand_read_status(struct nand_device *nand, uint8_t *status)
356 {
357         if (!nand->device)
358                 return ERROR_NAND_DEVICE_NOT_PROBED;
359
360         /* Send read status command */
361         nand->controller->command(nand, NAND_CMD_STATUS);
362
363         alive_sleep(1);
364
365         /* read status */
366         if (nand->device->options & NAND_BUSWIDTH_16)
367         {
368                 uint16_t data;
369                 nand->controller->read_data(nand, &data);
370                 *status = data & 0xff;
371         }
372         else
373         {
374                 nand->controller->read_data(nand, status);
375         }
376
377         return ERROR_OK;
378 }
379
380 static int nand_poll_ready(struct nand_device *nand, int timeout)
381 {
382         uint8_t status;
383
384         nand->controller->command(nand, NAND_CMD_STATUS);
385         do {
386                 if (nand->device->options & NAND_BUSWIDTH_16) {
387                         uint16_t data;
388                         nand->controller->read_data(nand, &data);
389                         status = data & 0xff;
390                 } else {
391                         nand->controller->read_data(nand, &status);
392                 }
393                 if (status & NAND_STATUS_READY)
394                         break;
395                 alive_sleep(1);
396         } while (timeout--);
397
398         return (status & NAND_STATUS_READY) != 0;
399 }
400
401 int nand_probe(struct nand_device *nand)
402 {
403         uint8_t manufacturer_id, device_id;
404         uint8_t id_buff[6];
405         int retval;
406         int i;
407
408         /* clear device data */
409         nand->device = NULL;
410         nand->manufacturer = NULL;
411
412         /* clear device parameters */
413         nand->bus_width = 0;
414         nand->address_cycles = 0;
415         nand->page_size = 0;
416         nand->erase_size = 0;
417
418         /* initialize controller (device parameters are zero, use controller default) */
419         if ((retval = nand->controller->init(nand) != ERROR_OK))
420         {
421                 switch (retval)
422                 {
423                         case ERROR_NAND_OPERATION_FAILED:
424                                 LOG_DEBUG("controller initialization failed");
425                                 return ERROR_NAND_OPERATION_FAILED;
426                         case ERROR_NAND_OPERATION_NOT_SUPPORTED:
427                                 LOG_ERROR("BUG: controller reported that it doesn't support default parameters");
428                                 return ERROR_NAND_OPERATION_FAILED;
429                         default:
430                                 LOG_ERROR("BUG: unknown controller initialization failure");
431                                 return ERROR_NAND_OPERATION_FAILED;
432                 }
433         }
434
435         nand->controller->command(nand, NAND_CMD_RESET);
436         nand->controller->reset(nand);
437
438         nand->controller->command(nand, NAND_CMD_READID);
439         nand->controller->address(nand, 0x0);
440
441         if (nand->bus_width == 8)
442         {
443                 nand->controller->read_data(nand, &manufacturer_id);
444                 nand->controller->read_data(nand, &device_id);
445         }
446         else
447         {
448                 uint16_t data_buf;
449                 nand->controller->read_data(nand, &data_buf);
450                 manufacturer_id = data_buf & 0xff;
451                 nand->controller->read_data(nand, &data_buf);
452                 device_id = data_buf & 0xff;
453         }
454
455         for (i = 0; nand_flash_ids[i].name; i++)
456         {
457                 if (nand_flash_ids[i].id == device_id)
458                 {
459                         nand->device = &nand_flash_ids[i];
460                         break;
461                 }
462         }
463
464         for (i = 0; nand_manuf_ids[i].name; i++)
465         {
466                 if (nand_manuf_ids[i].id == manufacturer_id)
467                 {
468                         nand->manufacturer = &nand_manuf_ids[i];
469                         break;
470                 }
471         }
472
473         if (!nand->manufacturer)
474         {
475                 nand->manufacturer = &nand_manuf_ids[0];
476                 nand->manufacturer->id = manufacturer_id;
477         }
478
479         if (!nand->device)
480         {
481                 LOG_ERROR("unknown NAND flash device found, manufacturer id: 0x%2.2x device id: 0x%2.2x",
482                         manufacturer_id, device_id);
483                 return ERROR_NAND_OPERATION_FAILED;
484         }
485
486         LOG_DEBUG("found %s (%s)", nand->device->name, nand->manufacturer->name);
487
488         /* initialize device parameters */
489
490         /* bus width */
491         if (nand->device->options & NAND_BUSWIDTH_16)
492                 nand->bus_width = 16;
493         else
494                 nand->bus_width = 8;
495
496         /* Do we need extended device probe information? */
497         if (nand->device->page_size == 0 ||
498             nand->device->erase_size == 0)
499         {
500                 if (nand->bus_width == 8)
501                 {
502                         nand->controller->read_data(nand, id_buff + 3);
503                         nand->controller->read_data(nand, id_buff + 4);
504                         nand->controller->read_data(nand, id_buff + 5);
505                 }
506                 else
507                 {
508                         uint16_t data_buf;
509
510                         nand->controller->read_data(nand, &data_buf);
511                         id_buff[3] = data_buf;
512
513                         nand->controller->read_data(nand, &data_buf);
514                         id_buff[4] = data_buf;
515
516                         nand->controller->read_data(nand, &data_buf);
517                         id_buff[5] = data_buf >> 8;
518                 }
519         }
520
521         /* page size */
522         if (nand->device->page_size == 0)
523         {
524                 nand->page_size = 1 << (10 + (id_buff[4] & 3));
525         }
526         else if (nand->device->page_size == 256)
527         {
528                 LOG_ERROR("NAND flashes with 256 byte pagesize are not supported");
529                 return ERROR_NAND_OPERATION_FAILED;
530         }
531         else
532         {
533                 nand->page_size = nand->device->page_size;
534         }
535
536         /* number of address cycles */
537         if (nand->page_size <= 512)
538         {
539                 /* small page devices */
540                 if (nand->device->chip_size <= 32)
541                         nand->address_cycles = 3;
542                 else if (nand->device->chip_size <= 8*1024)
543                         nand->address_cycles = 4;
544                 else
545                 {
546                         LOG_ERROR("BUG: small page NAND device with more than 8 GiB encountered");
547                         nand->address_cycles = 5;
548                 }
549         }
550         else
551         {
552                 /* large page devices */
553                 if (nand->device->chip_size <= 128)
554                         nand->address_cycles = 4;
555                 else if (nand->device->chip_size <= 32*1024)
556                         nand->address_cycles = 5;
557                 else
558                 {
559                         LOG_ERROR("BUG: large page NAND device with more than 32 GiB encountered");
560                         nand->address_cycles = 6;
561                 }
562         }
563
564         /* erase size */
565         if (nand->device->erase_size == 0)
566         {
567                 switch ((id_buff[4] >> 4) & 3) {
568                 case 0:
569                         nand->erase_size = 64 << 10;
570                         break;
571                 case 1:
572                         nand->erase_size = 128 << 10;
573                         break;
574                 case 2:
575                         nand->erase_size = 256 << 10;
576                         break;
577                 case 3:
578                         nand->erase_size =512 << 10;
579                         break;
580                 }
581         }
582         else
583         {
584                 nand->erase_size = nand->device->erase_size;
585         }
586
587         /* initialize controller, but leave parameters at the controllers default */
588         if ((retval = nand->controller->init(nand) != ERROR_OK))
589         {
590                 switch (retval)
591                 {
592                         case ERROR_NAND_OPERATION_FAILED:
593                                 LOG_DEBUG("controller initialization failed");
594                                 return ERROR_NAND_OPERATION_FAILED;
595                         case ERROR_NAND_OPERATION_NOT_SUPPORTED:
596                                 LOG_ERROR("controller doesn't support requested parameters (buswidth: %i, address cycles: %i, page size: %i)",
597                                         nand->bus_width, nand->address_cycles, nand->page_size);
598                                 return ERROR_NAND_OPERATION_FAILED;
599                         default:
600                                 LOG_ERROR("BUG: unknown controller initialization failure");
601                                 return ERROR_NAND_OPERATION_FAILED;
602                 }
603         }
604
605         nand->num_blocks = (nand->device->chip_size * 1024) / (nand->erase_size / 1024);
606         nand->blocks = malloc(sizeof(struct nand_block) * nand->num_blocks);
607
608         for (i = 0; i < nand->num_blocks; i++)
609         {
610                 nand->blocks[i].size = nand->erase_size;
611                 nand->blocks[i].offset = i * nand->erase_size;
612                 nand->blocks[i].is_erased = -1;
613                 nand->blocks[i].is_bad = -1;
614         }
615
616         return ERROR_OK;
617 }
618
619 static int nand_erase(struct nand_device *nand, int first_block, int last_block)
620 {
621         int i;
622         uint32_t page;
623         uint8_t status;
624         int retval;
625
626         if (!nand->device)
627                 return ERROR_NAND_DEVICE_NOT_PROBED;
628
629         if ((first_block < 0) || (last_block > nand->num_blocks))
630                 return ERROR_INVALID_ARGUMENTS;
631
632         /* make sure we know if a block is bad before erasing it */
633         for (i = first_block; i <= last_block; i++)
634         {
635                 if (nand->blocks[i].is_bad == -1)
636                 {
637                         nand_build_bbt(nand, i, last_block);
638                         break;
639                 }
640         }
641
642         for (i = first_block; i <= last_block; i++)
643         {
644                 /* Send erase setup command */
645                 nand->controller->command(nand, NAND_CMD_ERASE1);
646
647                 page = i * (nand->erase_size / nand->page_size);
648
649                 /* Send page address */
650                 if (nand->page_size <= 512)
651                 {
652                         /* row */
653                         nand->controller->address(nand, page & 0xff);
654                         nand->controller->address(nand, (page >> 8) & 0xff);
655
656                         /* 3rd cycle only on devices with more than 32 MiB */
657                         if (nand->address_cycles >= 4)
658                                 nand->controller->address(nand, (page >> 16) & 0xff);
659
660                         /* 4th cycle only on devices with more than 8 GiB */
661                         if (nand->address_cycles >= 5)
662                                 nand->controller->address(nand, (page >> 24) & 0xff);
663                 }
664                 else
665                 {
666                         /* row */
667                         nand->controller->address(nand, page & 0xff);
668                         nand->controller->address(nand, (page >> 8) & 0xff);
669
670                         /* 3rd cycle only on devices with more than 128 MiB */
671                         if (nand->address_cycles >= 5)
672                                 nand->controller->address(nand, (page >> 16) & 0xff);
673                 }
674
675                 /* Send erase confirm command */
676                 nand->controller->command(nand, NAND_CMD_ERASE2);
677
678                 retval = nand->controller->nand_ready ?
679                                 nand->controller->nand_ready(nand, 1000) :
680                                 nand_poll_ready(nand, 1000);
681                 if (!retval) {
682                         LOG_ERROR("timeout waiting for NAND flash block erase to complete");
683                         return ERROR_NAND_OPERATION_TIMEOUT;
684                 }
685
686                 if ((retval = nand_read_status(nand, &status)) != ERROR_OK)
687                 {
688                         LOG_ERROR("couldn't read status");
689                         return ERROR_NAND_OPERATION_FAILED;
690                 }
691
692                 if (status & 0x1)
693                 {
694                         LOG_ERROR("didn't erase %sblock %d; status: 0x%2.2x",
695                                         (nand->blocks[i].is_bad == 1)
696                                                 ? "bad " : "",
697                                         i, status);
698                         /* continue; other blocks might still be erasable */
699                 }
700
701                 nand->blocks[i].is_erased = 1;
702         }
703
704         return ERROR_OK;
705 }
706
707 #if 0
708 static int nand_read_plain(struct nand_device *nand, uint32_t address, uint8_t *data, uint32_t data_size)
709 {
710         uint8_t *page;
711
712         if (!nand->device)
713                 return ERROR_NAND_DEVICE_NOT_PROBED;
714
715         if (address % nand->page_size)
716         {
717                 LOG_ERROR("reads need to be page aligned");
718                 return ERROR_NAND_OPERATION_FAILED;
719         }
720
721         page = malloc(nand->page_size);
722
723         while (data_size > 0)
724         {
725                 uint32_t thisrun_size = (data_size > nand->page_size) ? nand->page_size : data_size;
726                 uint32_t page_address;
727
728
729                 page_address = address / nand->page_size;
730
731                 nand_read_page(nand, page_address, page, nand->page_size, NULL, 0);
732
733                 memcpy(data, page, thisrun_size);
734
735                 address += thisrun_size;
736                 data += thisrun_size;
737                 data_size -= thisrun_size;
738         }
739
740         free(page);
741
742         return ERROR_OK;
743 }
744
745 static int nand_write_plain(struct nand_device *nand, uint32_t address, uint8_t *data, uint32_t data_size)
746 {
747         uint8_t *page;
748
749         if (!nand->device)
750                 return ERROR_NAND_DEVICE_NOT_PROBED;
751
752         if (address % nand->page_size)
753         {
754                 LOG_ERROR("writes need to be page aligned");
755                 return ERROR_NAND_OPERATION_FAILED;
756         }
757
758         page = malloc(nand->page_size);
759
760         while (data_size > 0)
761         {
762                 uint32_t thisrun_size = (data_size > nand->page_size) ? nand->page_size : data_size;
763                 uint32_t page_address;
764
765                 memset(page, 0xff, nand->page_size);
766                 memcpy(page, data, thisrun_size);
767
768                 page_address = address / nand->page_size;
769
770                 nand_write_page(nand, page_address, page, nand->page_size, NULL, 0);
771
772                 address += thisrun_size;
773                 data += thisrun_size;
774                 data_size -= thisrun_size;
775         }
776
777         free(page);
778
779         return ERROR_OK;
780 }
781 #endif
782
783 int nand_write_page(struct nand_device *nand, uint32_t page, uint8_t *data, uint32_t data_size, uint8_t *oob, uint32_t oob_size)
784 {
785         uint32_t block;
786
787         if (!nand->device)
788                 return ERROR_NAND_DEVICE_NOT_PROBED;
789
790         block = page / (nand->erase_size / nand->page_size);
791         if (nand->blocks[block].is_erased == 1)
792                 nand->blocks[block].is_erased = 0;
793
794         if (nand->use_raw || nand->controller->write_page == NULL)
795                 return nand_write_page_raw(nand, page, data, data_size, oob, oob_size);
796         else
797                 return nand->controller->write_page(nand, page, data, data_size, oob, oob_size);
798 }
799
800 static int nand_read_page(struct nand_device *nand, uint32_t page, uint8_t *data, uint32_t data_size, uint8_t *oob, uint32_t oob_size)
801 {
802         if (!nand->device)
803                 return ERROR_NAND_DEVICE_NOT_PROBED;
804
805         if (nand->use_raw || nand->controller->read_page == NULL)
806                 return nand_read_page_raw(nand, page, data, data_size, oob, oob_size);
807         else
808                 return nand->controller->read_page(nand, page, data, data_size, oob, oob_size);
809 }
810
811 int nand_read_page_raw(struct nand_device *nand, uint32_t page, uint8_t *data, uint32_t data_size, uint8_t *oob, uint32_t oob_size)
812 {
813         uint32_t i;
814
815         if (!nand->device)
816                 return ERROR_NAND_DEVICE_NOT_PROBED;
817
818         if (nand->page_size <= 512)
819         {
820                 /* small page device */
821                 if (data)
822                         nand->controller->command(nand, NAND_CMD_READ0);
823                 else
824                         nand->controller->command(nand, NAND_CMD_READOOB);
825
826                 /* column (always 0, we start at the beginning of a page/OOB area) */
827                 nand->controller->address(nand, 0x0);
828
829                 /* row */
830                 nand->controller->address(nand, page & 0xff);
831                 nand->controller->address(nand, (page >> 8) & 0xff);
832
833                 /* 4th cycle only on devices with more than 32 MiB */
834                 if (nand->address_cycles >= 4)
835                         nand->controller->address(nand, (page >> 16) & 0xff);
836
837                 /* 5th cycle only on devices with more than 8 GiB */
838                 if (nand->address_cycles >= 5)
839                         nand->controller->address(nand, (page >> 24) & 0xff);
840         }
841         else
842         {
843                 /* large page device */
844                 nand->controller->command(nand, NAND_CMD_READ0);
845
846                 /* column (0 when we start at the beginning of a page,
847                  * or 2048 for the beginning of OOB area)
848                  */
849                 nand->controller->address(nand, 0x0);
850                 if (data)
851                         nand->controller->address(nand, 0x0);
852                 else
853                         nand->controller->address(nand, 0x8);
854
855                 /* row */
856                 nand->controller->address(nand, page & 0xff);
857                 nand->controller->address(nand, (page >> 8) & 0xff);
858
859                 /* 5th cycle only on devices with more than 128 MiB */
860                 if (nand->address_cycles >= 5)
861                         nand->controller->address(nand, (page >> 16) & 0xff);
862
863                 /* large page devices need a start command */
864                 nand->controller->command(nand, NAND_CMD_READSTART);
865         }
866
867         if (nand->controller->nand_ready) {
868                 if (!nand->controller->nand_ready(nand, 100))
869                         return ERROR_NAND_OPERATION_TIMEOUT;
870         } else {
871                 alive_sleep(1);
872         }
873
874         if (data)
875         {
876                 if (nand->controller->read_block_data != NULL)
877                         (nand->controller->read_block_data)(nand, data, data_size);
878                 else
879                 {
880                         for (i = 0; i < data_size;)
881                         {
882                                 if (nand->device->options & NAND_BUSWIDTH_16)
883                                 {
884                                         nand->controller->read_data(nand, data);
885                                         data += 2;
886                                         i += 2;
887                                 }
888                                 else
889                                 {
890                                         nand->controller->read_data(nand, data);
891                                         data += 1;
892                                         i += 1;
893                                 }
894                         }
895                 }
896         }
897
898         if (oob)
899         {
900                 if (nand->controller->read_block_data != NULL)
901                         (nand->controller->read_block_data)(nand, oob, oob_size);
902                 else
903                 {
904                         for (i = 0; i < oob_size;)
905                         {
906                                 if (nand->device->options & NAND_BUSWIDTH_16)
907                                 {
908                                         nand->controller->read_data(nand, oob);
909                                         oob += 2;
910                                         i += 2;
911                                 }
912                                 else
913                                 {
914                                         nand->controller->read_data(nand, oob);
915                                         oob += 1;
916                                         i += 1;
917                                 }
918                         }
919                 }
920         }
921
922         return ERROR_OK;
923 }
924
925 int nand_write_page_raw(struct nand_device *nand, uint32_t page, uint8_t *data, uint32_t data_size, uint8_t *oob, uint32_t oob_size)
926 {
927         uint32_t i;
928         int retval;
929         uint8_t status;
930
931         if (!nand->device)
932                 return ERROR_NAND_DEVICE_NOT_PROBED;
933
934         nand->controller->command(nand, NAND_CMD_SEQIN);
935
936         if (nand->page_size <= 512)
937         {
938                 /* column (always 0, we start at the beginning of a page/OOB area) */
939                 nand->controller->address(nand, 0x0);
940
941                 /* row */
942                 nand->controller->address(nand, page & 0xff);
943                 nand->controller->address(nand, (page >> 8) & 0xff);
944
945                 /* 4th cycle only on devices with more than 32 MiB */
946                 if (nand->address_cycles >= 4)
947                         nand->controller->address(nand, (page >> 16) & 0xff);
948
949                 /* 5th cycle only on devices with more than 8 GiB */
950                 if (nand->address_cycles >= 5)
951                         nand->controller->address(nand, (page >> 24) & 0xff);
952         }
953         else
954         {
955                 /* column (0 when we start at the beginning of a page,
956                  * or 2048 for the beginning of OOB area)
957                  */
958                 nand->controller->address(nand, 0x0);
959                 if (data)
960                         nand->controller->address(nand, 0x0);
961                 else
962                         nand->controller->address(nand, 0x8);
963
964                 /* row */
965                 nand->controller->address(nand, page & 0xff);
966                 nand->controller->address(nand, (page >> 8) & 0xff);
967
968                 /* 5th cycle only on devices with more than 128 MiB */
969                 if (nand->address_cycles >= 5)
970                         nand->controller->address(nand, (page >> 16) & 0xff);
971         }
972
973         if (data)
974         {
975                 if (nand->controller->write_block_data != NULL)
976                         (nand->controller->write_block_data)(nand, data, data_size);
977                 else
978                 {
979                         for (i = 0; i < data_size;)
980                         {
981                                 if (nand->device->options & NAND_BUSWIDTH_16)
982                                 {
983                                         uint16_t data_buf = le_to_h_u16(data);
984                                         nand->controller->write_data(nand, data_buf);
985                                         data += 2;
986                                         i += 2;
987                                 }
988                                 else
989                                 {
990                                         nand->controller->write_data(nand, *data);
991                                         data += 1;
992                                         i += 1;
993                                 }
994                         }
995                 }
996         }
997
998         if (oob)
999         {
1000                 if (nand->controller->write_block_data != NULL)
1001                         (nand->controller->write_block_data)(nand, oob, oob_size);
1002                 else
1003                 {
1004                         for (i = 0; i < oob_size;)
1005                         {
1006                                 if (nand->device->options & NAND_BUSWIDTH_16)
1007                                 {
1008                                         uint16_t oob_buf = le_to_h_u16(data);
1009                                         nand->controller->write_data(nand, oob_buf);
1010                                         oob += 2;
1011                                         i += 2;
1012                                 }
1013                                 else
1014                                 {
1015                                         nand->controller->write_data(nand, *oob);
1016                                         oob += 1;
1017                                         i += 1;
1018                                 }
1019                         }
1020                 }
1021         }
1022
1023         nand->controller->command(nand, NAND_CMD_PAGEPROG);
1024
1025         retval = nand->controller->nand_ready ?
1026                         nand->controller->nand_ready(nand, 100) :
1027                         nand_poll_ready(nand, 100);
1028         if (!retval)
1029                 return ERROR_NAND_OPERATION_TIMEOUT;
1030
1031         if ((retval = nand_read_status(nand, &status)) != ERROR_OK)
1032         {
1033                 LOG_ERROR("couldn't read status");
1034                 return ERROR_NAND_OPERATION_FAILED;
1035         }
1036
1037         if (status & NAND_STATUS_FAIL)
1038         {
1039                 LOG_ERROR("write operation didn't pass, status: 0x%2.2x", status);
1040                 return ERROR_NAND_OPERATION_FAILED;
1041         }
1042
1043         return ERROR_OK;
1044 }
1045
1046 COMMAND_HANDLER(handle_nand_list_command)
1047 {
1048         struct nand_device *p;
1049         int i;
1050
1051         if (!nand_devices)
1052         {
1053                 command_print(CMD_CTX, "no NAND flash devices configured");
1054                 return ERROR_OK;
1055         }
1056
1057         for (p = nand_devices, i = 0; p; p = p->next, i++)
1058         {
1059                 if (p->device)
1060                         command_print(CMD_CTX, "#%i: %s (%s) "
1061                                 "pagesize: %i, buswidth: %i,\n\t"
1062                                 "blocksize: %i, blocks: %i",
1063                                 i, p->device->name, p->manufacturer->name,
1064                                 p->page_size, p->bus_width,
1065                                 p->erase_size, p->num_blocks);
1066                 else
1067                         command_print(CMD_CTX, "#%i: not probed", i);
1068         }
1069
1070         return ERROR_OK;
1071 }
1072
1073 COMMAND_HANDLER(handle_nand_info_command)
1074 {
1075         int i = 0;
1076         int j = 0;
1077         int first = -1;
1078         int last = -1;
1079
1080         struct nand_device *p;
1081         int retval = CALL_COMMAND_HANDLER(nand_command_get_device_by_num, 0, &p);
1082         if (ERROR_OK != retval)
1083                 return retval;
1084
1085         switch (CMD_ARGC) {
1086         default:
1087                 return ERROR_COMMAND_SYNTAX_ERROR;
1088         case 1:
1089                 first = 0;
1090                 last = INT32_MAX;
1091                 break;
1092         case 2:
1093                 COMMAND_PARSE_NUMBER(int, CMD_ARGV[1], i);
1094                 first = last = i;
1095                 i = 0;
1096                 break;
1097         case 3:
1098                 COMMAND_PARSE_NUMBER(int, CMD_ARGV[1], first);
1099                 COMMAND_PARSE_NUMBER(int, CMD_ARGV[2], last);
1100                 break;
1101         }
1102
1103         if (NULL == p->device)
1104         {
1105                 command_print(CMD_CTX, "#%s: not probed", CMD_ARGV[0]);
1106                 return ERROR_OK;
1107         }
1108
1109         if (first >= p->num_blocks)
1110                 first = p->num_blocks - 1;
1111
1112         if (last >= p->num_blocks)
1113                 last = p->num_blocks - 1;
1114
1115         command_print(CMD_CTX, "#%i: %s (%s) pagesize: %i, buswidth: %i, erasesize: %i",
1116                 i++, p->device->name, p->manufacturer->name, p->page_size, p->bus_width, p->erase_size);
1117
1118         for (j = first; j <= last; j++)
1119         {
1120                 char *erase_state, *bad_state;
1121
1122                 if (p->blocks[j].is_erased == 0)
1123                         erase_state = "not erased";
1124                 else if (p->blocks[j].is_erased == 1)
1125                         erase_state = "erased";
1126                 else
1127                         erase_state = "erase state unknown";
1128
1129                 if (p->blocks[j].is_bad == 0)
1130                         bad_state = "";
1131                 else if (p->blocks[j].is_bad == 1)
1132                         bad_state = " (marked bad)";
1133                 else
1134                         bad_state = " (block condition unknown)";
1135
1136                 command_print(CMD_CTX,
1137                               "\t#%i: 0x%8.8" PRIx32 " (%" PRId32 "kB) %s%s",
1138                               j,
1139                               p->blocks[j].offset,
1140                               p->blocks[j].size / 1024,
1141                               erase_state,
1142                               bad_state);
1143         }
1144
1145         return ERROR_OK;
1146 }
1147
1148 COMMAND_HANDLER(handle_nand_probe_command)
1149 {
1150         if (CMD_ARGC != 1)
1151         {
1152                 return ERROR_COMMAND_SYNTAX_ERROR;
1153         }
1154
1155         struct nand_device *p;
1156         int retval = CALL_COMMAND_HANDLER(nand_command_get_device_by_num, 0, &p);
1157         if (ERROR_OK != retval)
1158                 return retval;
1159
1160         if ((retval = nand_probe(p)) == ERROR_OK)
1161         {
1162                 command_print(CMD_CTX, "NAND flash device '%s' found", p->device->name);
1163         }
1164         else if (retval == ERROR_NAND_OPERATION_FAILED)
1165         {
1166                 command_print(CMD_CTX, "probing failed for NAND flash device");
1167         }
1168         else
1169         {
1170                 command_print(CMD_CTX, "unknown error when probing NAND flash device");
1171         }
1172
1173         return ERROR_OK;
1174 }
1175
1176 COMMAND_HANDLER(handle_nand_erase_command)
1177 {
1178         if (CMD_ARGC != 1 && CMD_ARGC != 3)
1179         {
1180                 return ERROR_COMMAND_SYNTAX_ERROR;
1181
1182         }
1183
1184         struct nand_device *p;
1185         int retval = CALL_COMMAND_HANDLER(nand_command_get_device_by_num, 0, &p);
1186         if (ERROR_OK != retval)
1187                 return retval;
1188
1189         unsigned long offset;
1190         unsigned long length;
1191
1192         /* erase specified part of the chip; or else everything */
1193         if (CMD_ARGC == 3) {
1194                 unsigned long size = p->erase_size * p->num_blocks;
1195
1196                 COMMAND_PARSE_NUMBER(ulong, CMD_ARGV[1], offset);
1197                 if ((offset % p->erase_size) != 0 || offset >= size)
1198                         return ERROR_INVALID_ARGUMENTS;
1199
1200                 COMMAND_PARSE_NUMBER(ulong, CMD_ARGV[2], length);
1201                 if ((length == 0) || (length % p->erase_size) != 0
1202                                 || (length + offset) > size)
1203                         return ERROR_INVALID_ARGUMENTS;
1204
1205                 offset /= p->erase_size;
1206                 length /= p->erase_size;
1207         } else {
1208                 offset = 0;
1209                 length = p->num_blocks;
1210         }
1211
1212         retval = nand_erase(p, offset, offset + length - 1);
1213         if (retval == ERROR_OK)
1214         {
1215                 command_print(CMD_CTX, "erased blocks %lu to %lu "
1216                                 "on NAND flash device #%s '%s'",
1217                                 offset, offset + length,
1218                                 CMD_ARGV[0], p->device->name);
1219         }
1220         else if (retval == ERROR_NAND_OPERATION_FAILED)
1221         {
1222                 command_print(CMD_CTX, "erase failed");
1223         }
1224         else
1225         {
1226                 command_print(CMD_CTX, "unknown error when erasing NAND flash device");
1227         }
1228
1229         return ERROR_OK;
1230 }
1231
1232 COMMAND_HANDLER(handle_nand_check_bad_blocks_command)
1233 {
1234         int first = -1;
1235         int last = -1;
1236
1237         if ((CMD_ARGC < 1) || (CMD_ARGC > 3) || (CMD_ARGC == 2))
1238         {
1239                 return ERROR_COMMAND_SYNTAX_ERROR;
1240
1241         }
1242
1243         struct nand_device *p;
1244         int retval = CALL_COMMAND_HANDLER(nand_command_get_device_by_num, 0, &p);
1245         if (ERROR_OK != retval)
1246                 return retval;
1247
1248         if (CMD_ARGC == 3)
1249         {
1250                 unsigned long offset;
1251                 unsigned long length;
1252
1253                 COMMAND_PARSE_NUMBER(ulong, CMD_ARGV[1], offset);
1254                 if (offset % p->erase_size)
1255                         return ERROR_INVALID_ARGUMENTS;
1256                 offset /= p->erase_size;
1257
1258                 COMMAND_PARSE_NUMBER(ulong, CMD_ARGV[2], length);
1259                 if (length % p->erase_size)
1260                         return ERROR_INVALID_ARGUMENTS;
1261
1262                 length -= 1;
1263                 length /= p->erase_size;
1264
1265                 first = offset;
1266                 last = offset + length;
1267         }
1268
1269         retval = nand_build_bbt(p, first, last);
1270         if (retval == ERROR_OK)
1271         {
1272                 command_print(CMD_CTX, "checked NAND flash device for bad blocks, "
1273                                 "use \"nand info\" command to list blocks");
1274         }
1275         else if (retval == ERROR_NAND_OPERATION_FAILED)
1276         {
1277                 command_print(CMD_CTX, "error when checking for bad blocks on "
1278                                 "NAND flash device");
1279         }
1280         else
1281         {
1282                 command_print(CMD_CTX, "unknown error when checking for bad "
1283                                 "blocks on NAND flash device");
1284         }
1285
1286         return ERROR_OK;
1287 }
1288
1289 struct nand_fileio_state {
1290         uint32_t address;
1291         uint32_t size;
1292
1293         uint8_t *page;
1294         uint32_t page_size;
1295
1296         enum oob_formats oob_format;
1297         uint8_t *oob;
1298         uint32_t oob_size;
1299
1300         const int *eccpos;
1301
1302         bool file_opened;
1303         struct fileio fileio;
1304
1305         struct duration bench;
1306 };
1307
1308 static void nand_fileio_init(struct nand_fileio_state *state)
1309 {
1310         memset(state, 0, sizeof(*state));
1311         state->oob_format = NAND_OOB_NONE;
1312 }
1313
1314 static int nand_fileio_start(struct command_context *cmd_ctx,
1315                 struct nand_device *nand, const char *filename, int filemode,
1316                 struct nand_fileio_state *state)
1317 {
1318         if (state->address % nand->page_size)
1319         {
1320                 command_print(cmd_ctx, "only page-aligned addresses are supported");
1321                 return ERROR_COMMAND_SYNTAX_ERROR;
1322         }
1323
1324         duration_start(&state->bench);
1325
1326         if (NULL != filename)
1327         {
1328                 int retval = fileio_open(&state->fileio, filename, filemode, FILEIO_BINARY);
1329                 if (ERROR_OK != retval)
1330                 {
1331                         const char *msg = (FILEIO_READ == filemode) ? "read" : "write";
1332                         command_print(cmd_ctx, "failed to open '%s' for %s access",
1333                                         filename, msg);
1334                         return retval;
1335                 }
1336                 state->file_opened = true;
1337         }
1338
1339         if (!(state->oob_format & NAND_OOB_ONLY))
1340         {
1341                 state->page_size = nand->page_size;
1342                 state->page = malloc(nand->page_size);
1343         }
1344
1345         if (state->oob_format & (NAND_OOB_RAW | NAND_OOB_SW_ECC | NAND_OOB_SW_ECC_KW))
1346         {
1347                 if (nand->page_size == 512)
1348                 {
1349                         state->oob_size = 16;
1350                         state->eccpos = nand_oob_16.eccpos;
1351                 }
1352                 else if (nand->page_size == 2048)
1353                 {
1354                         state->oob_size = 64;
1355                         state->eccpos = nand_oob_64.eccpos;
1356                 }
1357                 state->oob = malloc(state->oob_size);
1358         }
1359
1360         return ERROR_OK;
1361 }
1362 static int nand_fileio_cleanup(struct nand_fileio_state *state)
1363 {
1364         if (state->file_opened)
1365                 fileio_close(&state->fileio);
1366
1367         if (state->oob)
1368         {
1369                 free(state->oob);
1370                 state->oob = NULL;
1371         }
1372         if (state->page)
1373         {
1374                 free(state->page);
1375                 state->page = NULL;
1376         }
1377         return ERROR_OK;
1378 }
1379 static int nand_fileio_finish(struct nand_fileio_state *state)
1380 {
1381         nand_fileio_cleanup(state);
1382         return duration_measure(&state->bench);
1383 }
1384
1385 static COMMAND_HELPER(nand_fileio_parse_args, struct nand_fileio_state *state,
1386                 struct nand_device **dev, enum fileio_access filemode,
1387                 bool need_size, bool sw_ecc)
1388 {
1389         nand_fileio_init(state);
1390
1391         unsigned minargs = need_size ? 4 : 3;
1392         if (CMD_ARGC < minargs)
1393                 return ERROR_COMMAND_SYNTAX_ERROR;
1394
1395         struct nand_device *nand;
1396         int retval = CALL_COMMAND_HANDLER(nand_command_get_device_by_num, 0, &nand);
1397         if (ERROR_OK != retval)
1398                 return retval;
1399
1400         if (NULL == nand->device)
1401         {
1402                 command_print(CMD_CTX, "#%s: not probed", CMD_ARGV[0]);
1403                 return ERROR_OK;
1404         }
1405
1406         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], state->address);
1407         if (need_size)
1408         {
1409                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], state->size);
1410                         if (state->size % nand->page_size)
1411                         {
1412                                 command_print(CMD_CTX, "only page-aligned sizes are supported");
1413                                 return ERROR_COMMAND_SYNTAX_ERROR;
1414                         }
1415         }
1416
1417         if (CMD_ARGC > minargs)
1418         {
1419                 for (unsigned i = minargs; i < CMD_ARGC; i++)
1420                 {
1421                         if (!strcmp(CMD_ARGV[i], "oob_raw"))
1422                                 state->oob_format |= NAND_OOB_RAW;
1423                         else if (!strcmp(CMD_ARGV[i], "oob_only"))
1424                                 state->oob_format |= NAND_OOB_RAW | NAND_OOB_ONLY;
1425                         else if (sw_ecc && !strcmp(CMD_ARGV[i], "oob_softecc"))
1426                                 state->oob_format |= NAND_OOB_SW_ECC;
1427                         else if (sw_ecc && !strcmp(CMD_ARGV[i], "oob_softecc_kw"))
1428                                 state->oob_format |= NAND_OOB_SW_ECC_KW;
1429                         else
1430                         {
1431                                 command_print(CMD_CTX, "unknown option: %s", CMD_ARGV[i]);
1432                                 return ERROR_COMMAND_SYNTAX_ERROR;
1433                         }
1434                 }
1435         }
1436
1437         retval = nand_fileio_start(CMD_CTX, nand, CMD_ARGV[1], filemode, state);
1438         if (ERROR_OK != retval)
1439                 return retval;
1440
1441         if (!need_size)
1442                 state->size = state->fileio.size;
1443
1444         *dev = nand;
1445
1446         return ERROR_OK;
1447 }
1448
1449 /**
1450  * @returns If no error occurred, returns number of bytes consumed;
1451  * otherwise, returns a negative error code.)
1452  */
1453 static int nand_fileio_read(struct nand_device *nand,
1454                 struct nand_fileio_state *s)
1455 {
1456         size_t total_read = 0;
1457         size_t one_read;
1458
1459         if (NULL != s->page)
1460         {
1461                 fileio_read(&s->fileio, s->page_size, s->page, &one_read);
1462                 if (one_read < s->page_size)
1463                         memset(s->page + one_read, 0xff, s->page_size - one_read);
1464                 total_read += one_read;
1465         }
1466
1467         if (s->oob_format & NAND_OOB_SW_ECC)
1468         {
1469                 uint8_t ecc[3];
1470                 memset(s->oob, 0xff, s->oob_size);
1471                 for (uint32_t i = 0, j = 0; i < s->page_size; i += 256)
1472                 {
1473                         nand_calculate_ecc(nand, s->page + i, ecc);
1474                         s->oob[s->eccpos[j++]] = ecc[0];
1475                         s->oob[s->eccpos[j++]] = ecc[1];
1476                         s->oob[s->eccpos[j++]] = ecc[2];
1477                 }
1478         }
1479         else if (s->oob_format & NAND_OOB_SW_ECC_KW)
1480         {
1481                 /*
1482                  * In this case eccpos is not used as
1483                  * the ECC data is always stored contigously
1484                  * at the end of the OOB area.  It consists
1485                  * of 10 bytes per 512-byte data block.
1486                  */
1487                 uint8_t *ecc = s->oob + s->oob_size - s->page_size / 512 * 10;
1488                 memset(s->oob, 0xff, s->oob_size);
1489                 for (uint32_t i = 0; i < s->page_size; i += 512)
1490                 {
1491                         nand_calculate_ecc_kw(nand, s->page + i, ecc);
1492                         ecc += 10;
1493                 }
1494         }
1495         else if (NULL != s->oob)
1496         {
1497                 fileio_read(&s->fileio, s->oob_size, s->oob, &one_read);
1498                 if (one_read < s->oob_size)
1499                         memset(s->oob + one_read, 0xff, s->oob_size - one_read);
1500                 total_read += one_read;
1501         }
1502         return total_read;
1503 }
1504
1505 COMMAND_HANDLER(handle_nand_write_command)
1506 {
1507         struct nand_device *nand = NULL;
1508         struct nand_fileio_state s;
1509         int retval = CALL_COMMAND_HANDLER(nand_fileio_parse_args,
1510                         &s, &nand, FILEIO_READ, false, true);
1511         if (ERROR_OK != retval)
1512                 return retval;
1513
1514         uint32_t total_bytes = s.size;
1515         while (s.size > 0)
1516         {
1517                 int bytes_read = nand_fileio_read(nand, &s);
1518                 if (bytes_read <= 0)
1519                 {
1520                         command_print(CMD_CTX, "error while reading file");
1521                         return nand_fileio_cleanup(&s);
1522                 }
1523                 s.size -= bytes_read;
1524
1525                 retval = nand_write_page(nand, s.address / nand->page_size,
1526                                 s.page, s.page_size, s.oob, s.oob_size);
1527                 if (ERROR_OK != retval)
1528                 {
1529                         command_print(CMD_CTX, "failed writing file %s "
1530                                 "to NAND flash %s at offset 0x%8.8" PRIx32,
1531                                 CMD_ARGV[1], CMD_ARGV[0], s.address);
1532                         return nand_fileio_cleanup(&s);
1533                 }
1534                 s.address += s.page_size;
1535         }
1536
1537         if (nand_fileio_finish(&s))
1538         {
1539                 command_print(CMD_CTX, "wrote file %s to NAND flash %s up to "
1540                                 "offset 0x%8.8" PRIx32 " in %fs (%0.3f kb/s)",
1541                                 CMD_ARGV[1], CMD_ARGV[0], s.address, duration_elapsed(&s.bench),
1542                                 duration_kbps(&s.bench, total_bytes));
1543         }
1544         return ERROR_OK;
1545 }
1546
1547 COMMAND_HANDLER(handle_nand_verify_command)
1548 {
1549         struct nand_device *nand = NULL;
1550         struct nand_fileio_state file;
1551         int retval = CALL_COMMAND_HANDLER(nand_fileio_parse_args,
1552                         &file, &nand, FILEIO_READ, false, true);
1553         if (ERROR_OK != retval)
1554                 return retval;
1555
1556         struct nand_fileio_state dev;
1557         nand_fileio_init(&dev);
1558         dev.address = file.address;
1559         dev.size = file.size;
1560         dev.oob_format = file.oob_format;
1561         retval = nand_fileio_start(CMD_CTX, nand, NULL, FILEIO_NONE, &dev);
1562         if (ERROR_OK != retval)
1563                 return retval;
1564
1565         while (file.size > 0)
1566         {
1567                 int retval = nand_read_page(nand, dev.address / dev.page_size,
1568                                 dev.page, dev.page_size, dev.oob, dev.oob_size);
1569                 if (ERROR_OK != retval)
1570                 {
1571                         command_print(CMD_CTX, "reading NAND flash page failed");
1572                         nand_fileio_cleanup(&dev);
1573                         return nand_fileio_cleanup(&file);
1574                 }
1575
1576                 int bytes_read = nand_fileio_read(nand, &file);
1577                 if (bytes_read <= 0)
1578                 {
1579                         command_print(CMD_CTX, "error while reading file");
1580                         nand_fileio_cleanup(&dev);
1581                         return nand_fileio_cleanup(&file);
1582                 }
1583
1584                 if ((dev.page && memcmp(dev.page, file.page, dev.page_size)) ||
1585                     (dev.oob && memcmp(dev.oob, file.oob, dev.oob_size)) )
1586                 {
1587                         command_print(CMD_CTX, "NAND flash contents differ "
1588                                                 "at 0x%8.8" PRIx32, dev.address);
1589                         nand_fileio_cleanup(&dev);
1590                         return nand_fileio_cleanup(&file);
1591                 }
1592
1593                 file.size -= bytes_read;
1594                 file.address += nand->page_size;
1595         }
1596
1597         if (nand_fileio_finish(&file) == ERROR_OK)
1598         {
1599                 command_print(CMD_CTX, "verified file %s in NAND flash %s "
1600                                 "up to offset 0x%8.8" PRIx32 " in %fs (%0.3f kb/s)",
1601                                 CMD_ARGV[1], CMD_ARGV[0], dev.address, duration_elapsed(&file.bench),
1602                                 duration_kbps(&file.bench, dev.size));
1603         }
1604
1605         return nand_fileio_cleanup(&dev);
1606 }
1607
1608 COMMAND_HANDLER(handle_nand_dump_command)
1609 {
1610         struct nand_device *nand = NULL;
1611         struct nand_fileio_state s;
1612         int retval = CALL_COMMAND_HANDLER(nand_fileio_parse_args,
1613                         &s, &nand, FILEIO_WRITE, true, false);
1614         if (ERROR_OK != retval)
1615                 return retval;
1616
1617         while (s.size > 0)
1618         {
1619                 size_t size_written;
1620                 int retval = nand_read_page(nand, s.address / nand->page_size,
1621                                 s.page, s.page_size, s.oob, s.oob_size);
1622                 if (ERROR_OK != retval)
1623                 {
1624                         command_print(CMD_CTX, "reading NAND flash page failed");
1625                         return nand_fileio_cleanup(&s);
1626                 }
1627
1628                 if (NULL != s.page)
1629                         fileio_write(&s.fileio, s.page_size, s.page, &size_written);
1630
1631                 if (NULL != s.oob)
1632                         fileio_write(&s.fileio, s.oob_size, s.oob, &size_written);
1633
1634                 s.size -= nand->page_size;
1635                 s.address += nand->page_size;
1636         }
1637
1638         if (nand_fileio_finish(&s) == ERROR_OK)
1639         {
1640                 command_print(CMD_CTX, "dumped %zu bytes in %fs (%0.3f kb/s)", 
1641                                 s.fileio.size, duration_elapsed(&s.bench),
1642                                 duration_kbps(&s.bench, s.fileio.size));
1643         }
1644         return ERROR_OK;
1645 }
1646
1647 COMMAND_HANDLER(handle_nand_raw_access_command)
1648 {
1649         if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
1650         {
1651                 return ERROR_COMMAND_SYNTAX_ERROR;
1652         }
1653
1654         struct nand_device *p;
1655         int retval = CALL_COMMAND_HANDLER(nand_command_get_device_by_num, 0, &p);
1656         if (ERROR_OK != retval)
1657                 return retval;
1658
1659         if (NULL == p->device)
1660         {
1661                 command_print(CMD_CTX, "#%s: not probed", CMD_ARGV[0]);
1662                 return ERROR_OK;
1663         }
1664
1665         if (CMD_ARGC == 2)
1666                 COMMAND_PARSE_ENABLE(CMD_ARGV[1], p->use_raw);
1667
1668         const char *msg = p->use_raw ? "enabled" : "disabled";
1669         command_print(CMD_CTX, "raw access is %s", msg);
1670
1671         return ERROR_OK;
1672 }
1673
1674 int nand_init(struct command_context *cmd_ctx)
1675 {
1676         if (!nand_devices)
1677                 return ERROR_OK;
1678
1679         register_command(cmd_ctx, nand_cmd, "list",
1680                         handle_nand_list_command, COMMAND_EXEC,
1681                         "list configured NAND flash devices");
1682         register_command(cmd_ctx, nand_cmd, "info",
1683                         handle_nand_info_command, COMMAND_EXEC,
1684                         "print info about NAND flash device <num>");
1685         register_command(cmd_ctx, nand_cmd, "probe",
1686                         handle_nand_probe_command, COMMAND_EXEC,
1687                         "identify NAND flash device <num>");
1688
1689         register_command(cmd_ctx, nand_cmd, "check_bad_blocks",
1690                         handle_nand_check_bad_blocks_command, COMMAND_EXEC,
1691                         "check NAND flash device <num> for bad blocks [<offset> <length>]");
1692         register_command(cmd_ctx, nand_cmd, "erase",
1693                         handle_nand_erase_command, COMMAND_EXEC,
1694                         "erase blocks on NAND flash device <num> [<offset> <length>]");
1695         register_command(cmd_ctx, nand_cmd, "dump",
1696                         handle_nand_dump_command, COMMAND_EXEC,
1697                         "dump from NAND flash device <num> <filename> "
1698                          "<offset> <length> [oob_raw | oob_only]");
1699         register_command(cmd_ctx, nand_cmd, "verify",
1700                         &handle_nand_verify_command, COMMAND_EXEC,
1701                         "verify NAND flash device <num> <filename> <offset> "
1702                         "[oob_raw | oob_only | oob_softecc | oob_softecc_kw]");
1703         register_command(cmd_ctx, nand_cmd, "write",
1704                         handle_nand_write_command, COMMAND_EXEC,
1705                         "write to NAND flash device <num> <filename> <offset> "
1706                         "[oob_raw | oob_only | oob_softecc | oob_softecc_kw]");
1707
1708         register_command(cmd_ctx, nand_cmd, "raw_access",
1709                         handle_nand_raw_access_command, COMMAND_EXEC,
1710                         "raw access to NAND flash device <num> ['enable'|'disable']");
1711
1712         return ERROR_OK;
1713 }