mtd: detect image format when writing
[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 && trx_fixup) {
663                 trx_fixup(fd, mtd);
664         }
665
666         if (!quiet)
667                 fprintf(stderr, "\b\b\b\b    ");
668
669         if (quiet < 2)
670                 fprintf(stderr, "\n");
671
672 #ifdef FIS_SUPPORT
673         if (fis_layout) {
674                 if (fis_remap(old_parts, n_old, new_parts, n_new) < 0)
675                         fprintf(stderr, "Failed to update the FIS partition table\n");
676         }
677 #endif
678
679         close(fd);
680         return 0;
681 }
682
683 static void usage(void)
684 {
685         fprintf(stderr, "Usage: mtd [<options> ...] <command> [<arguments> ...] <device>[:<device>...]\n\n"
686         "The device is in the format of mtdX (eg: mtd4) or its label.\n"
687         "mtd recognizes these commands:\n"
688         "        unlock                  unlock the device\n"
689         "        refresh                 refresh mtd partition\n"
690         "        erase                   erase all data on device\n"
691         "        verify <imagefile>|-    verify <imagefile> (use - for stdin) to device\n"
692         "        write <imagefile>|-     write <imagefile> (use - for stdin) to device\n"
693         "        jffs2write <file>       append <file> to the jffs2 partition on the device\n");
694         if (mtd_resetbc) {
695             fprintf(stderr,
696         "        resetbc <device>        reset the uboot boot counter\n");
697         }
698         if (mtd_fixtrx) {
699             fprintf(stderr,
700         "        fixtrx                  fix the checksum in a trx header on first boot\n");
701         }
702         if (mtd_fixseama) {
703             fprintf(stderr,
704         "        fixseama                fix the checksum in a seama header on first boot\n");
705         }
706         fprintf(stderr,
707         "Following options are available:\n"
708         "        -q                      quiet mode (once: no [w] on writing,\n"
709         "                                           twice: no status messages)\n"
710         "        -n                      write without first erasing the blocks\n"
711         "        -r                      reboot after successful command\n"
712         "        -f                      force write without trx checks\n"
713         "        -e <device>             erase <device> before executing the command\n"
714         "        -d <name>               directory for jffs2write, defaults to \"tmp\"\n"
715         "        -j <name>               integrate <file> into jffs2 data when writing an image\n"
716         "        -s <number>             skip the first n bytes when appending data to the jffs2 partiton, defaults to \"0\"\n"
717         "        -p                      write beginning at partition offset\n"
718         "        -l <length>             the length of data that we want to dump\n");
719         if (mtd_fixtrx) {
720             fprintf(stderr,
721         "        -o offset               offset of the image header in the partition(for fixtrx)\n");
722         }
723         fprintf(stderr,
724 #ifdef FIS_SUPPORT
725         "        -F <part>[:<size>[:<entrypoint>]][,<part>...]\n"
726         "                                alter the fis partition table to create new partitions replacing\n"
727         "                                the partitions provided as argument to the write command\n"
728         "                                (only valid together with the write command)\n"
729 #endif
730         "\n"
731         "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
732         "         mtd -r write linux.trx linux\n\n");
733         exit(1);
734 }
735
736 static void do_reboot(void)
737 {
738         fprintf(stderr, "Rebooting ...\n");
739         fflush(stderr);
740
741         /* try regular reboot method first */
742         system("/sbin/reboot");
743         sleep(2);
744
745         /* if we're still alive at this point, force the kernel to reboot */
746         syscall(SYS_reboot,LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,LINUX_REBOOT_CMD_RESTART,NULL);
747 }
748
749 int main (int argc, char **argv)
750 {
751         int ch, i, boot, imagefd = 0, force, unlocked;
752         char *erase[MAX_ARGS], *device = NULL;
753         char *fis_layout = NULL;
754         size_t offset = 0, part_offset = 0, dump_len = 0;
755         enum {
756                 CMD_ERASE,
757                 CMD_WRITE,
758                 CMD_UNLOCK,
759                 CMD_JFFS2WRITE,
760                 CMD_FIXTRX,
761                 CMD_FIXSEAMA,
762                 CMD_VERIFY,
763                 CMD_DUMP,
764                 CMD_RESETBC,
765         } cmd = -1;
766
767         erase[0] = NULL;
768         boot = 0;
769         force = 0;
770         buflen = 0;
771         quiet = 0;
772         no_erase = 0;
773
774         while ((ch = getopt(argc, argv,
775 #ifdef FIS_SUPPORT
776                         "F:"
777 #endif
778                         "frnqe:d:s:j:p:o:l:")) != -1)
779                 switch (ch) {
780                         case 'f':
781                                 force = 1;
782                                 break;
783                         case 'r':
784                                 boot = 1;
785                                 break;
786                         case 'n':
787                                 no_erase = 1;
788                                 break;
789                         case 'j':
790                                 jffs2file = optarg;
791                                 break;
792                         case 's':
793                                 errno = 0;
794                                 jffs2_skip_bytes = strtoul(optarg, 0, 0);
795                                 if (errno) {
796                                                 fprintf(stderr, "-s: illegal numeric string\n");
797                                                 usage();
798                                 }
799                                 break;
800                         case 'q':
801                                 quiet++;
802                                 break;
803                         case 'e':
804                                 i = 0;
805                                 while ((erase[i] != NULL) && ((i + 1) < MAX_ARGS))
806                                         i++;
807
808                                 erase[i++] = optarg;
809                                 erase[i] = NULL;
810                                 break;
811                         case 'd':
812                                 jffs2dir = optarg;
813                                 break;
814                         case 'p':
815                                 errno = 0;
816                                 part_offset = strtoul(optarg, 0, 0);
817                                 if (errno) {
818                                         fprintf(stderr, "-p: illegal numeric string\n");
819                                         usage();
820                                 }
821                                 break;
822                         case 'l':
823                                 errno = 0;
824                                 dump_len = strtoul(optarg, 0, 0);
825                                 if (errno) {
826                                         fprintf(stderr, "-l: illegal numeric string\n");
827                                         usage();
828                                 }
829                                 break;
830                         case 'o':
831                                 errno = 0;
832                                 offset = strtoul(optarg, 0, 0);
833                                 if (errno) {
834                                         fprintf(stderr, "-o: illegal numeric string\n");
835                                         usage();
836                                 }
837                                 break;
838 #ifdef FIS_SUPPORT
839                         case 'F':
840                                 fis_layout = optarg;
841                                 break;
842 #endif
843                         case '?':
844                         default:
845                                 usage();
846                 }
847         argc -= optind;
848         argv += optind;
849
850         if (argc < 2)
851                 usage();
852
853         if ((strcmp(argv[0], "unlock") == 0) && (argc == 2)) {
854                 cmd = CMD_UNLOCK;
855                 device = argv[1];
856         } else if ((strcmp(argv[0], "erase") == 0) && (argc == 2)) {
857                 cmd = CMD_ERASE;
858                 device = argv[1];
859         } else if (((strcmp(argv[0], "resetbc") == 0) && (argc == 2)) && mtd_resetbc) {
860                 cmd = CMD_RESETBC;
861                 device = argv[1];
862         } else if (((strcmp(argv[0], "fixtrx") == 0) && (argc == 2)) && mtd_fixtrx) {
863                 cmd = CMD_FIXTRX;
864                 device = argv[1];
865         } else if (((strcmp(argv[0], "fixseama") == 0) && (argc == 2)) && mtd_fixseama) {
866                 cmd = CMD_FIXSEAMA;
867                 device = argv[1];
868         } else if ((strcmp(argv[0], "verify") == 0) && (argc == 3)) {
869                 cmd = CMD_VERIFY;
870                 imagefile = argv[1];
871                 device = argv[2];
872         } else if ((strcmp(argv[0], "dump") == 0) && (argc == 2)) {
873                 cmd = CMD_DUMP;
874                 device = argv[1];
875         } else if ((strcmp(argv[0], "write") == 0) && (argc == 3)) {
876                 cmd = CMD_WRITE;
877                 device = argv[2];
878
879                 if (strcmp(argv[1], "-") == 0) {
880                         imagefile = "<stdin>";
881                         imagefd = 0;
882                 } else {
883                         imagefile = argv[1];
884                         if ((imagefd = open(argv[1], O_RDONLY)) < 0) {
885                                 fprintf(stderr, "Couldn't open image file: %s!\n", imagefile);
886                                 exit(1);
887                         }
888                 }
889
890                 if (!mtd_check(device)) {
891                         fprintf(stderr, "Can't open device for writing!\n");
892                         exit(1);
893                 }
894                 /* check trx file before erasing or writing anything */
895                 if (!image_check(imagefd, device) && !force) {
896                         fprintf(stderr, "Image check failed.\n");
897                         exit(1);
898                 }
899         } else if ((strcmp(argv[0], "jffs2write") == 0) && (argc == 3)) {
900                 cmd = CMD_JFFS2WRITE;
901                 device = argv[2];
902
903                 imagefile = argv[1];
904                 if (!mtd_check(device)) {
905                         fprintf(stderr, "Can't open device for writing!\n");
906                         exit(1);
907                 }
908         } else {
909                 usage();
910         }
911
912         sync();
913
914         i = 0;
915         unlocked = 0;
916         while (erase[i] != NULL) {
917                 mtd_unlock(erase[i]);
918                 mtd_erase(erase[i]);
919                 if (strcmp(erase[i], device) == 0)
920                         unlocked = 1;
921                 i++;
922         }
923
924         switch (cmd) {
925                 case CMD_UNLOCK:
926                         if (!unlocked)
927                                 mtd_unlock(device);
928                         break;
929                 case CMD_VERIFY:
930                         mtd_verify(device, imagefile);
931                         break;
932                 case CMD_DUMP:
933                         mtd_dump(device, offset, dump_len);
934                         break;
935                 case CMD_ERASE:
936                         if (!unlocked)
937                                 mtd_unlock(device);
938                         mtd_erase(device);
939                         break;
940                 case CMD_WRITE:
941                         if (!unlocked)
942                                 mtd_unlock(device);
943                         mtd_write(imagefd, device, fis_layout, part_offset);
944                         break;
945                 case CMD_JFFS2WRITE:
946                         if (!unlocked)
947                                 mtd_unlock(device);
948                         mtd_write_jffs2(device, imagefile, jffs2dir);
949                         break;
950                 case CMD_FIXTRX:
951                     if (mtd_fixtrx) {
952                             mtd_fixtrx(device, offset);
953             }
954                 case CMD_RESETBC:
955                     if (mtd_resetbc) {
956                             mtd_resetbc(device);
957             }
958                 case CMD_FIXSEAMA:
959                         if (mtd_fixseama)
960                             mtd_fixseama(device, 0);
961                         break;
962         }
963
964         sync();
965
966         if (boot)
967                 do_reboot();
968
969         return 0;
970 }