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