mtd: fix Seama format after replacing EOF with sysupgrade data
[openwrt.git] / package / system / mtd / src / mtd.c
1 /*
2  * mtd - simple memory technology device manipulation tool
3  *
4  * Copyright (C) 2005      Waldemar Brodkorb <wbx@dass-it.de>,
5  * Copyright (C) 2005-2009 Felix Fietkau <nbd@openwrt.org>
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License v2
9  * as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  *
20  *
21  * The code is based on the linux-mtd examples.
22  */
23
24 #define _GNU_SOURCE
25 #include <byteswap.h>
26 #include <limits.h>
27 #include <unistd.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <stdint.h>
31 #include <signal.h>
32 #include <sys/ioctl.h>
33 #include <sys/syscall.h>
34 #include <fcntl.h>
35 #include <errno.h>
36 #include <time.h>
37 #include <string.h>
38 #include <sys/ioctl.h>
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #include <sys/mount.h>
42 #include <sys/stat.h>
43 #include <sys/reboot.h>
44 #include <linux/reboot.h>
45 #include <mtd/mtd-user.h>
46 #include "fis.h"
47 #include "mtd.h"
48
49 #include <libubox/md5.h>
50
51 #define MAX_ARGS 8
52 #define JFFS2_DEFAULT_DIR       "" /* directory name without /, empty means root dir */
53
54 #define TRX_MAGIC               0x48445230      /* "HDR0" */
55 #define SEAMA_MAGIC             0x5ea3a417
56
57 #if !defined(__BYTE_ORDER)
58 #error "Unknown byte order"
59 #endif
60
61 #if __BYTE_ORDER == __BIG_ENDIAN
62 #define cpu_to_be32(x)  (x)
63 #define be32_to_cpu(x)  (x)
64 #elif __BYTE_ORDER == __LITTLE_ENDIAN
65 #define cpu_to_be32(x)  bswap_32(x)
66 #define be32_to_cpu(x)  bswap_32(x)
67 #else
68 #error "Unsupported endianness"
69 #endif
70
71 enum mtd_image_format {
72         MTD_IMAGE_FORMAT_UNKNOWN,
73         MTD_IMAGE_FORMAT_TRX,
74         MTD_IMAGE_FORMAT_SEAMA,
75 };
76
77 static char *buf = NULL;
78 static char *imagefile = NULL;
79 static enum mtd_image_format imageformat = MTD_IMAGE_FORMAT_UNKNOWN;
80 static char *jffs2file = NULL, *jffs2dir = JFFS2_DEFAULT_DIR;
81 static int buflen = 0;
82 int quiet;
83 int no_erase;
84 int mtdsize = 0;
85 int erasesize = 0;
86 int jffs2_skip_bytes=0;
87 int mtdtype = 0;
88
89 int mtd_open(const char *mtd, bool block)
90 {
91         FILE *fp;
92         char dev[PATH_MAX];
93         int i;
94         int ret;
95         int flags = O_RDWR | O_SYNC;
96         char name[PATH_MAX];
97
98         snprintf(name, sizeof(name), "\"%s\"", mtd);
99         if ((fp = fopen("/proc/mtd", "r"))) {
100                 while (fgets(dev, sizeof(dev), fp)) {
101                         if (sscanf(dev, "mtd%d:", &i) && strstr(dev, name)) {
102                                 snprintf(dev, sizeof(dev), "/dev/mtd%s/%d", (block ? "block" : ""), i);
103                                 if ((ret=open(dev, flags))<0) {
104                                         snprintf(dev, sizeof(dev), "/dev/mtd%s%d", (block ? "block" : ""), i);
105                                         ret=open(dev, flags);
106                                 }
107                                 fclose(fp);
108                                 return ret;
109                         }
110                 }
111                 fclose(fp);
112         }
113
114         return open(mtd, flags);
115 }
116
117 int mtd_check_open(const char *mtd)
118 {
119         struct mtd_info_user mtdInfo;
120         int fd;
121
122         fd = mtd_open(mtd, false);
123         if(fd < 0) {
124                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
125                 return -1;
126         }
127
128         if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
129                 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
130                 close(fd);
131                 return -1;
132         }
133         mtdsize = mtdInfo.size;
134         erasesize = mtdInfo.erasesize;
135         mtdtype = mtdInfo.type;
136
137         return fd;
138 }
139
140 int mtd_block_is_bad(int fd, int offset)
141 {
142         int r = 0;
143         loff_t o = offset;
144
145         if (mtdtype == MTD_NANDFLASH)
146         {
147                 r = ioctl(fd, MEMGETBADBLOCK, &o);
148                 if (r < 0)
149                 {
150                         fprintf(stderr, "Failed to get erase block status\n");
151                         exit(1);
152                 }
153         }
154         return r;
155 }
156
157 int mtd_erase_block(int fd, int offset)
158 {
159         struct erase_info_user mtdEraseInfo;
160
161         mtdEraseInfo.start = offset;
162         mtdEraseInfo.length = erasesize;
163         ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
164         if (ioctl (fd, MEMERASE, &mtdEraseInfo) < 0)
165                 return -1;
166
167         return 0;
168 }
169
170 int mtd_write_buffer(int fd, const char *buf, int offset, int length)
171 {
172         lseek(fd, offset, SEEK_SET);
173         write(fd, buf, length);
174         return 0;
175 }
176
177 static int
178 image_check(int imagefd, const char *mtd)
179 {
180         uint32_t magic;
181         int ret = 1;
182
183         if (buflen < sizeof(magic)) {
184                 buflen += read(imagefd, buf + buflen, sizeof(magic) - buflen);
185                 if (buflen < sizeof(magic)) {
186                         fprintf(stdout, "Could not get image magic\n");
187                         return 0;
188                 }
189         }
190         magic = ((uint32_t *)buf)[0];
191
192         if (be32_to_cpu(magic) == TRX_MAGIC)
193                 imageformat = MTD_IMAGE_FORMAT_TRX;
194         else if (be32_to_cpu(magic) == SEAMA_MAGIC)
195                 imageformat = MTD_IMAGE_FORMAT_SEAMA;
196
197         switch (imageformat) {
198         case MTD_IMAGE_FORMAT_TRX:
199                 if (trx_check)
200                         ret = trx_check(imagefd, mtd, buf, &buflen);
201                 break;
202         case MTD_IMAGE_FORMAT_SEAMA:
203                 break;
204         default:
205 #ifdef target_brcm
206                 if (!strcmp(mtd, "firmware"))
207                         ret = 0;
208 #endif
209                 break;
210         }
211
212         return ret;
213 }
214
215 static int mtd_check(const char *mtd)
216 {
217         char *next = NULL;
218         char *str = NULL;
219         int fd;
220
221         if (strchr(mtd, ':')) {
222                 str = strdup(mtd);
223                 mtd = str;
224         }
225
226         do {
227                 next = strchr(mtd, ':');
228                 if (next) {
229                         *next = 0;
230                         next++;
231                 }
232
233                 fd = mtd_check_open(mtd);
234                 if (fd < 0)
235                         return 0;
236
237                 if (!buf)
238                         buf = malloc(erasesize);
239
240                 close(fd);
241                 mtd = next;
242         } while (next);
243
244         if (str)
245                 free(str);
246
247         return 1;
248 }
249
250 static int
251 mtd_unlock(const char *mtd)
252 {
253         struct erase_info_user mtdLockInfo;
254         char *next = NULL;
255         char *str = NULL;
256         int fd;
257
258         if (strchr(mtd, ':')) {
259                 str = strdup(mtd);
260                 mtd = str;
261         }
262
263         do {
264                 next = strchr(mtd, ':');
265                 if (next) {
266                         *next = 0;
267                         next++;
268                 }
269
270                 fd = mtd_check_open(mtd);
271                 if(fd < 0) {
272                         fprintf(stderr, "Could not open mtd device: %s\n", mtd);
273                         exit(1);
274                 }
275
276                 if (quiet < 2)
277                         fprintf(stderr, "Unlocking %s ...\n", mtd);
278
279                 mtdLockInfo.start = 0;
280                 mtdLockInfo.length = mtdsize;
281                 ioctl(fd, MEMUNLOCK, &mtdLockInfo);
282                 close(fd);
283                 mtd = next;
284         } while (next);
285
286         if (str)
287                 free(str);
288
289         return 0;
290 }
291
292 static int
293 mtd_erase(const char *mtd)
294 {
295         int fd;
296         struct erase_info_user mtdEraseInfo;
297
298         if (quiet < 2)
299                 fprintf(stderr, "Erasing %s ...\n", mtd);
300
301         fd = mtd_check_open(mtd);
302         if(fd < 0) {
303                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
304                 exit(1);
305         }
306
307         mtdEraseInfo.length = erasesize;
308
309         for (mtdEraseInfo.start = 0;
310                  mtdEraseInfo.start < mtdsize;
311                  mtdEraseInfo.start += erasesize) {
312                 if (mtd_block_is_bad(fd, mtdEraseInfo.start)) {
313                         if (!quiet)
314                                 fprintf(stderr, "\nSkipping bad block at 0x%x   ", mtdEraseInfo.start);
315                 } else {
316                         ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
317                         if(ioctl(fd, MEMERASE, &mtdEraseInfo))
318                                 fprintf(stderr, "Failed to erase block on %s at 0x%x\n", mtd, mtdEraseInfo.start);
319                 }
320         }
321
322         close(fd);
323         return 0;
324
325 }
326
327 static int
328 mtd_dump(const char *mtd, int part_offset, int size)
329 {
330         int ret = 0, offset = 0;
331         int fd;
332         char *buf;
333
334         if (quiet < 2)
335                 fprintf(stderr, "Dumping %s ...\n", mtd);
336
337         fd = mtd_check_open(mtd);
338         if(fd < 0) {
339                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
340                 return -1;
341         }
342
343         if (!size)
344                 size = mtdsize;
345
346         if (part_offset)
347                 lseek(fd, part_offset, SEEK_SET);
348
349         buf = malloc(erasesize);
350         if (!buf)
351                 return -1;
352
353         do {
354                 int len = (size > erasesize) ? (erasesize) : (size);
355                 int rlen = read(fd, buf, len);
356
357                 if (rlen < 0) {
358                         if (errno == EINTR)
359                                 continue;
360                         ret = -1;
361                         goto out;
362                 }
363                 if (!rlen || rlen != len)
364                         break;
365                 if (mtd_block_is_bad(fd, offset)) {
366                         fprintf(stderr, "skipping bad block at 0x%08x\n", offset);
367                 } else {
368                         size -= rlen;
369                         write(1, buf, rlen);
370                 }
371                 offset += rlen;
372         } while (size > 0);
373
374 out:
375         close(fd);
376         return ret;
377 }
378
379 static int
380 mtd_verify(const char *mtd, char *file)
381 {
382         uint32_t f_md5[4], m_md5[4];
383         struct stat s;
384         md5_ctx_t ctx;
385         int ret = 0;
386         int fd;
387
388         if (quiet < 2)
389                 fprintf(stderr, "Verifying %s against %s ...\n", mtd, file);
390
391         if (stat(file, &s) || md5sum(file, f_md5) < 0) {
392                 fprintf(stderr, "Failed to hash %s\n", file);
393                 return -1;
394         }
395
396         fd = mtd_check_open(mtd);
397         if(fd < 0) {
398                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
399                 return -1;
400         }
401
402         md5_begin(&ctx);
403         do {
404                 char buf[256];
405                 int len = (s.st_size > sizeof(buf)) ? (sizeof(buf)) : (s.st_size);
406                 int rlen = read(fd, buf, len);
407
408                 if (rlen < 0) {
409                         if (errno == EINTR)
410                                 continue;
411                         ret = -1;
412                         goto out;
413                 }
414                 if (!rlen)
415                         break;
416                 md5_hash(buf, rlen, &ctx);
417                 s.st_size -= rlen;
418         } while (s.st_size > 0);
419
420         md5_end(m_md5, &ctx);
421
422         fprintf(stderr, "%08x%08x%08x%08x - %s\n", m_md5[0], m_md5[1], m_md5[2], m_md5[3], mtd);
423         fprintf(stderr, "%08x%08x%08x%08x - %s\n", f_md5[0], f_md5[1], f_md5[2], f_md5[3], file);
424
425         ret = memcmp(f_md5, m_md5, sizeof(m_md5));
426         if (!ret)
427                 fprintf(stderr, "Success\n");
428         else
429                 fprintf(stderr, "Failed\n");
430
431 out:
432         close(fd);
433         return ret;
434 }
435
436 static void
437 indicate_writing(const char *mtd)
438 {
439         if (quiet < 2)
440                 fprintf(stderr, "\nWriting from %s to %s ... ", imagefile, mtd);
441
442         if (!quiet)
443                 fprintf(stderr, " [ ]");
444 }
445
446 static int
447 mtd_write(int imagefd, const char *mtd, char *fis_layout, size_t part_offset)
448 {
449         char *next = NULL;
450         char *str = NULL;
451         int fd, result;
452         ssize_t r, w, e;
453         ssize_t skip = 0;
454         uint32_t offset = 0;
455         int jffs2_replaced = 0;
456         int skip_bad_blocks = 0;
457
458 #ifdef FIS_SUPPORT
459         static struct fis_part new_parts[MAX_ARGS];
460         static struct fis_part old_parts[MAX_ARGS];
461         int n_new = 0, n_old = 0;
462
463         if (fis_layout) {
464                 const char *tmp = mtd;
465                 char *word, *brkt;
466                 int ret;
467
468                 memset(&old_parts, 0, sizeof(old_parts));
469                 memset(&new_parts, 0, sizeof(new_parts));
470
471                 do {
472                         next = strchr(tmp, ':');
473                         if (!next)
474                                 next = (char *) tmp + strlen(tmp);
475
476                         memcpy(old_parts[n_old].name, tmp, next - tmp);
477
478                         n_old++;
479                         tmp = next + 1;
480                 } while(*next);
481
482                 for (word = strtok_r(fis_layout, ",", &brkt);
483                      word;
484                          word = strtok_r(NULL, ",", &brkt)) {
485
486                         tmp = strtok(word, ":");
487                         strncpy((char *) new_parts[n_new].name, tmp, sizeof(new_parts[n_new].name) - 1);
488
489                         tmp = strtok(NULL, ":");
490                         if (!tmp)
491                                 goto next;
492
493                         new_parts[n_new].size = strtoul(tmp, NULL, 0);
494
495                         tmp = strtok(NULL, ":");
496                         if (!tmp)
497                                 goto next;
498
499                         new_parts[n_new].loadaddr = strtoul(tmp, NULL, 16);
500 next:
501                         n_new++;
502                 }
503                 ret = fis_validate(old_parts, n_old, new_parts, n_new);
504                 if (ret < 0) {
505                         fprintf(stderr, "Failed to validate the new FIS partition table\n");
506                         exit(1);
507                 }
508                 if (ret == 0)
509                         fis_layout = NULL;
510         }
511 #endif
512
513         if (strchr(mtd, ':')) {
514                 str = strdup(mtd);
515                 mtd = str;
516         }
517
518         r = 0;
519
520 resume:
521         next = strchr(mtd, ':');
522         if (next) {
523                 *next = 0;
524                 next++;
525         }
526
527         fd = mtd_check_open(mtd);
528         if(fd < 0) {
529                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
530                 exit(1);
531         }
532         if (part_offset > 0) {
533                 fprintf(stderr, "Seeking on mtd device '%s' to: %zu\n", mtd, part_offset);
534                 lseek(fd, part_offset, SEEK_SET);
535         }
536
537         indicate_writing(mtd);
538
539         w = e = 0;
540         for (;;) {
541                 /* buffer may contain data already (from trx check or last mtd partition write attempt) */
542                 while (buflen < erasesize) {
543                         r = read(imagefd, buf + buflen, erasesize - buflen);
544                         if (r < 0) {
545                                 if ((errno == EINTR) || (errno == EAGAIN))
546                                         continue;
547                                 else {
548                                         perror("read");
549                                         break;
550                                 }
551                         }
552
553                         if (r == 0)
554                                 break;
555
556                         buflen += r;
557                 }
558
559                 if (buflen == 0)
560                         break;
561
562                 if (buflen < erasesize) {
563                         /* Pad block to eraseblock size */
564                         memset(&buf[buflen], 0xff, erasesize - buflen);
565                         buflen = erasesize;
566                 }
567
568                 if (skip > 0) {
569                         skip -= buflen;
570                         buflen = 0;
571                         if (skip <= 0)
572                                 indicate_writing(mtd);
573
574                         continue;
575                 }
576
577                 if (jffs2file && w >= jffs2_skip_bytes) {
578                         if (memcmp(buf, JFFS2_EOF, sizeof(JFFS2_EOF) - 1) == 0) {
579                                 if (!quiet)
580                                         fprintf(stderr, "\b\b\b   ");
581                                 if (quiet < 2)
582                                         fprintf(stderr, "\nAppending jffs2 data from %s to %s...", jffs2file, mtd);
583                                 /* got an EOF marker - this is the place to add some jffs2 data */
584                                 skip = mtd_replace_jffs2(mtd, fd, e, jffs2file);
585                                 jffs2_replaced = 1;
586
587                                 /* don't add it again */
588                                 jffs2file = NULL;
589
590                                 w += skip;
591                                 e += skip;
592                                 skip -= buflen;
593                                 buflen = 0;
594                                 offset = 0;
595                                 continue;
596                         }
597                         /* no EOF marker, make sure we figure out the last inode number
598                          * before appending some data */
599                         mtd_parse_jffs2data(buf, jffs2dir);
600                 }
601
602                 /* need to erase the next block before writing data to it */
603                 if(!no_erase)
604                 {
605                         while (w + buflen > e - skip_bad_blocks) {
606                                 if (!quiet)
607                                         fprintf(stderr, "\b\b\b[e]");
608
609                                 if (mtd_block_is_bad(fd, e)) {
610                                         if (!quiet)
611                                                 fprintf(stderr, "\nSkipping bad block at 0x%08zx   ", e);
612
613                                         skip_bad_blocks += erasesize;
614                                         e += erasesize;
615
616                                         // Move the file pointer along over the bad block.
617                                         lseek(fd, erasesize, SEEK_CUR);
618                                         continue;
619                                 }
620
621                                 if (mtd_erase_block(fd, e) < 0) {
622                                         if (next) {
623                                                 if (w < e) {
624                                                         write(fd, buf + offset, e - w);
625                                                         offset = e - w;
626                                                 }
627                                                 w = 0;
628                                                 e = 0;
629                                                 close(fd);
630                                                 mtd = next;
631                                                 fprintf(stderr, "\b\b\b   \n");
632                                                 goto resume;
633                                         } else {
634                                                 fprintf(stderr, "Failed to erase block\n");
635                                                 exit(1);
636                                         }
637                                 }
638
639                                 /* erase the chunk */
640                                 e += erasesize;
641                         }
642                 }
643
644                 if (!quiet)
645                         fprintf(stderr, "\b\b\b[w]");
646
647                 if ((result = write(fd, buf + offset, buflen)) < buflen) {
648                         if (result < 0) {
649                                 fprintf(stderr, "Error writing image.\n");
650                                 exit(1);
651                         } else {
652                                 fprintf(stderr, "Insufficient space.\n");
653                                 exit(1);
654                         }
655                 }
656                 w += buflen;
657
658                 buflen = 0;
659                 offset = 0;
660         }
661
662         if (jffs2_replaced) {
663                 switch (imageformat) {
664                 case MTD_IMAGE_FORMAT_TRX:
665                         if (trx_fixup)
666                                 trx_fixup(fd, mtd);
667                         break;
668                 case MTD_IMAGE_FORMAT_SEAMA:
669                         if (mtd_fixseama)
670                                 mtd_fixseama(mtd, 0);
671                         break;
672                 default:
673                         break;
674                 }
675         }
676
677         if (!quiet)
678                 fprintf(stderr, "\b\b\b\b    ");
679
680         if (quiet < 2)
681                 fprintf(stderr, "\n");
682
683 #ifdef FIS_SUPPORT
684         if (fis_layout) {
685                 if (fis_remap(old_parts, n_old, new_parts, n_new) < 0)
686                         fprintf(stderr, "Failed to update the FIS partition table\n");
687         }
688 #endif
689
690         close(fd);
691         return 0;
692 }
693
694 static void usage(void)
695 {
696         fprintf(stderr, "Usage: mtd [<options> ...] <command> [<arguments> ...] <device>[:<device>...]\n\n"
697         "The device is in the format of mtdX (eg: mtd4) or its label.\n"
698         "mtd recognizes these commands:\n"
699         "        unlock                  unlock the device\n"
700         "        refresh                 refresh mtd partition\n"
701         "        erase                   erase all data on device\n"
702         "        verify <imagefile>|-    verify <imagefile> (use - for stdin) to device\n"
703         "        write <imagefile>|-     write <imagefile> (use - for stdin) to device\n"
704         "        jffs2write <file>       append <file> to the jffs2 partition on the device\n");
705         if (mtd_resetbc) {
706             fprintf(stderr,
707         "        resetbc <device>        reset the uboot boot counter\n");
708         }
709         if (mtd_fixtrx) {
710             fprintf(stderr,
711         "        fixtrx                  fix the checksum in a trx header on first boot\n");
712         }
713         if (mtd_fixseama) {
714             fprintf(stderr,
715         "        fixseama                fix the checksum in a seama header on first boot\n");
716         }
717         fprintf(stderr,
718         "Following options are available:\n"
719         "        -q                      quiet mode (once: no [w] on writing,\n"
720         "                                           twice: no status messages)\n"
721         "        -n                      write without first erasing the blocks\n"
722         "        -r                      reboot after successful command\n"
723         "        -f                      force write without trx checks\n"
724         "        -e <device>             erase <device> before executing the command\n"
725         "        -d <name>               directory for jffs2write, defaults to \"tmp\"\n"
726         "        -j <name>               integrate <file> into jffs2 data when writing an image\n"
727         "        -s <number>             skip the first n bytes when appending data to the jffs2 partiton, defaults to \"0\"\n"
728         "        -p                      write beginning at partition offset\n"
729         "        -l <length>             the length of data that we want to dump\n");
730         if (mtd_fixtrx) {
731             fprintf(stderr,
732         "        -o offset               offset of the image header in the partition(for fixtrx)\n");
733         }
734         fprintf(stderr,
735 #ifdef FIS_SUPPORT
736         "        -F <part>[:<size>[:<entrypoint>]][,<part>...]\n"
737         "                                alter the fis partition table to create new partitions replacing\n"
738         "                                the partitions provided as argument to the write command\n"
739         "                                (only valid together with the write command)\n"
740 #endif
741         "\n"
742         "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
743         "         mtd -r write linux.trx linux\n\n");
744         exit(1);
745 }
746
747 static void do_reboot(void)
748 {
749         fprintf(stderr, "Rebooting ...\n");
750         fflush(stderr);
751
752         /* try regular reboot method first */
753         system("/sbin/reboot");
754         sleep(2);
755
756         /* if we're still alive at this point, force the kernel to reboot */
757         syscall(SYS_reboot,LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,LINUX_REBOOT_CMD_RESTART,NULL);
758 }
759
760 int main (int argc, char **argv)
761 {
762         int ch, i, boot, imagefd = 0, force, unlocked;
763         char *erase[MAX_ARGS], *device = NULL;
764         char *fis_layout = NULL;
765         size_t offset = 0, part_offset = 0, dump_len = 0;
766         enum {
767                 CMD_ERASE,
768                 CMD_WRITE,
769                 CMD_UNLOCK,
770                 CMD_JFFS2WRITE,
771                 CMD_FIXTRX,
772                 CMD_FIXSEAMA,
773                 CMD_VERIFY,
774                 CMD_DUMP,
775                 CMD_RESETBC,
776         } cmd = -1;
777
778         erase[0] = NULL;
779         boot = 0;
780         force = 0;
781         buflen = 0;
782         quiet = 0;
783         no_erase = 0;
784
785         while ((ch = getopt(argc, argv,
786 #ifdef FIS_SUPPORT
787                         "F:"
788 #endif
789                         "frnqe:d:s:j:p:o:l:")) != -1)
790                 switch (ch) {
791                         case 'f':
792                                 force = 1;
793                                 break;
794                         case 'r':
795                                 boot = 1;
796                                 break;
797                         case 'n':
798                                 no_erase = 1;
799                                 break;
800                         case 'j':
801                                 jffs2file = optarg;
802                                 break;
803                         case 's':
804                                 errno = 0;
805                                 jffs2_skip_bytes = strtoul(optarg, 0, 0);
806                                 if (errno) {
807                                                 fprintf(stderr, "-s: illegal numeric string\n");
808                                                 usage();
809                                 }
810                                 break;
811                         case 'q':
812                                 quiet++;
813                                 break;
814                         case 'e':
815                                 i = 0;
816                                 while ((erase[i] != NULL) && ((i + 1) < MAX_ARGS))
817                                         i++;
818
819                                 erase[i++] = optarg;
820                                 erase[i] = NULL;
821                                 break;
822                         case 'd':
823                                 jffs2dir = optarg;
824                                 break;
825                         case 'p':
826                                 errno = 0;
827                                 part_offset = strtoul(optarg, 0, 0);
828                                 if (errno) {
829                                         fprintf(stderr, "-p: illegal numeric string\n");
830                                         usage();
831                                 }
832                                 break;
833                         case 'l':
834                                 errno = 0;
835                                 dump_len = strtoul(optarg, 0, 0);
836                                 if (errno) {
837                                         fprintf(stderr, "-l: illegal numeric string\n");
838                                         usage();
839                                 }
840                                 break;
841                         case 'o':
842                                 errno = 0;
843                                 offset = strtoul(optarg, 0, 0);
844                                 if (errno) {
845                                         fprintf(stderr, "-o: illegal numeric string\n");
846                                         usage();
847                                 }
848                                 break;
849 #ifdef FIS_SUPPORT
850                         case 'F':
851                                 fis_layout = optarg;
852                                 break;
853 #endif
854                         case '?':
855                         default:
856                                 usage();
857                 }
858         argc -= optind;
859         argv += optind;
860
861         if (argc < 2)
862                 usage();
863
864         if ((strcmp(argv[0], "unlock") == 0) && (argc == 2)) {
865                 cmd = CMD_UNLOCK;
866                 device = argv[1];
867         } else if ((strcmp(argv[0], "erase") == 0) && (argc == 2)) {
868                 cmd = CMD_ERASE;
869                 device = argv[1];
870         } else if (((strcmp(argv[0], "resetbc") == 0) && (argc == 2)) && mtd_resetbc) {
871                 cmd = CMD_RESETBC;
872                 device = argv[1];
873         } else if (((strcmp(argv[0], "fixtrx") == 0) && (argc == 2)) && mtd_fixtrx) {
874                 cmd = CMD_FIXTRX;
875                 device = argv[1];
876         } else if (((strcmp(argv[0], "fixseama") == 0) && (argc == 2)) && mtd_fixseama) {
877                 cmd = CMD_FIXSEAMA;
878                 device = argv[1];
879         } else if ((strcmp(argv[0], "verify") == 0) && (argc == 3)) {
880                 cmd = CMD_VERIFY;
881                 imagefile = argv[1];
882                 device = argv[2];
883         } else if ((strcmp(argv[0], "dump") == 0) && (argc == 2)) {
884                 cmd = CMD_DUMP;
885                 device = argv[1];
886         } else if ((strcmp(argv[0], "write") == 0) && (argc == 3)) {
887                 cmd = CMD_WRITE;
888                 device = argv[2];
889
890                 if (strcmp(argv[1], "-") == 0) {
891                         imagefile = "<stdin>";
892                         imagefd = 0;
893                 } else {
894                         imagefile = argv[1];
895                         if ((imagefd = open(argv[1], O_RDONLY)) < 0) {
896                                 fprintf(stderr, "Couldn't open image file: %s!\n", imagefile);
897                                 exit(1);
898                         }
899                 }
900
901                 if (!mtd_check(device)) {
902                         fprintf(stderr, "Can't open device for writing!\n");
903                         exit(1);
904                 }
905                 /* check trx file before erasing or writing anything */
906                 if (!image_check(imagefd, device) && !force) {
907                         fprintf(stderr, "Image check failed.\n");
908                         exit(1);
909                 }
910         } else if ((strcmp(argv[0], "jffs2write") == 0) && (argc == 3)) {
911                 cmd = CMD_JFFS2WRITE;
912                 device = argv[2];
913
914                 imagefile = argv[1];
915                 if (!mtd_check(device)) {
916                         fprintf(stderr, "Can't open device for writing!\n");
917                         exit(1);
918                 }
919         } else {
920                 usage();
921         }
922
923         sync();
924
925         i = 0;
926         unlocked = 0;
927         while (erase[i] != NULL) {
928                 mtd_unlock(erase[i]);
929                 mtd_erase(erase[i]);
930                 if (strcmp(erase[i], device) == 0)
931                         unlocked = 1;
932                 i++;
933         }
934
935         switch (cmd) {
936                 case CMD_UNLOCK:
937                         if (!unlocked)
938                                 mtd_unlock(device);
939                         break;
940                 case CMD_VERIFY:
941                         mtd_verify(device, imagefile);
942                         break;
943                 case CMD_DUMP:
944                         mtd_dump(device, offset, dump_len);
945                         break;
946                 case CMD_ERASE:
947                         if (!unlocked)
948                                 mtd_unlock(device);
949                         mtd_erase(device);
950                         break;
951                 case CMD_WRITE:
952                         if (!unlocked)
953                                 mtd_unlock(device);
954                         mtd_write(imagefd, device, fis_layout, part_offset);
955                         break;
956                 case CMD_JFFS2WRITE:
957                         if (!unlocked)
958                                 mtd_unlock(device);
959                         mtd_write_jffs2(device, imagefile, jffs2dir);
960                         break;
961                 case CMD_FIXTRX:
962                     if (mtd_fixtrx) {
963                             mtd_fixtrx(device, offset);
964             }
965                 case CMD_RESETBC:
966                     if (mtd_resetbc) {
967                             mtd_resetbc(device);
968             }
969                 case CMD_FIXSEAMA:
970                         if (mtd_fixseama)
971                             mtd_fixseama(device, 0);
972                         break;
973         }
974
975         sync();
976
977         if (boot)
978                 do_reboot();
979
980         return 0;
981 }