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