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