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