2 * mtd - simple memory technology device manipulation tool
4 * Copyright (C) 2005 Waldemar Brodkorb <wbx@dass-it.de>,
5 * Copyright (C) 2005-2009 Felix Fietkau <nbd@nbd.name>
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.
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.
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.
21 * The code is based on the linux-mtd examples.
33 #include <sys/ioctl.h>
34 #include <sys/syscall.h>
39 #include <sys/ioctl.h>
40 #include <sys/types.h>
41 #include <sys/param.h>
42 #include <sys/mount.h>
44 #include <sys/reboot.h>
45 #include <linux/reboot.h>
46 #include <mtd/mtd-user.h>
50 #include <libubox/md5.h>
53 #define JFFS2_DEFAULT_DIR "" /* directory name without /, empty means root dir */
55 #define TRX_MAGIC 0x48445230 /* "HDR0" */
56 #define SEAMA_MAGIC 0x5ea3a417
57 #define WRG_MAGIC 0x20040220
58 #define WRGG03_MAGIC 0x20080321
60 #if !defined(__BYTE_ORDER)
61 #error "Unknown byte order"
64 #if __BYTE_ORDER == __BIG_ENDIAN
65 #define cpu_to_be32(x) (x)
66 #define be32_to_cpu(x) (x)
67 #define le32_to_cpu(x) bswap_32(x)
68 #elif __BYTE_ORDER == __LITTLE_ENDIAN
69 #define cpu_to_be32(x) bswap_32(x)
70 #define be32_to_cpu(x) bswap_32(x)
71 #define le32_to_cpu(x) (x)
73 #error "Unsupported endianness"
76 enum mtd_image_format
{
77 MTD_IMAGE_FORMAT_UNKNOWN
,
79 MTD_IMAGE_FORMAT_SEAMA
,
81 MTD_IMAGE_FORMAT_WRGG03
,
84 static char *buf
= NULL
;
85 static char *imagefile
= NULL
;
86 static enum mtd_image_format imageformat
= MTD_IMAGE_FORMAT_UNKNOWN
;
87 static char *jffs2file
= NULL
, *jffs2dir
= JFFS2_DEFAULT_DIR
;
88 static int buflen
= 0;
93 int jffs2_skip_bytes
=0;
96 int mtd_open(const char *mtd
, bool block
)
102 int flags
= O_RDWR
| O_SYNC
;
105 snprintf(name
, sizeof(name
), "\"%s\"", mtd
);
106 if ((fp
= fopen("/proc/mtd", "r"))) {
107 while (fgets(dev
, sizeof(dev
), fp
)) {
108 if (sscanf(dev
, "mtd%d:", &i
) && strstr(dev
, name
)) {
109 snprintf(dev
, sizeof(dev
), "/dev/mtd%s/%d", (block
? "block" : ""), i
);
110 if ((ret
=open(dev
, flags
))<0) {
111 snprintf(dev
, sizeof(dev
), "/dev/mtd%s%d", (block
? "block" : ""), i
);
112 ret
=open(dev
, flags
);
121 return open(mtd
, flags
);
124 int mtd_check_open(const char *mtd
)
126 struct mtd_info_user mtdInfo
;
129 fd
= mtd_open(mtd
, false);
131 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
135 if(ioctl(fd
, MEMGETINFO
, &mtdInfo
)) {
136 fprintf(stderr
, "Could not get MTD device info from %s\n", mtd
);
140 mtdsize
= mtdInfo
.size
;
141 erasesize
= mtdInfo
.erasesize
;
142 mtdtype
= mtdInfo
.type
;
147 int mtd_block_is_bad(int fd
, int offset
)
152 if (mtdtype
== MTD_NANDFLASH
)
154 r
= ioctl(fd
, MEMGETBADBLOCK
, &o
);
157 fprintf(stderr
, "Failed to get erase block status\n");
164 int mtd_erase_block(int fd
, int offset
)
166 struct erase_info_user mtdEraseInfo
;
168 mtdEraseInfo
.start
= offset
;
169 mtdEraseInfo
.length
= erasesize
;
170 ioctl(fd
, MEMUNLOCK
, &mtdEraseInfo
);
171 if (ioctl (fd
, MEMERASE
, &mtdEraseInfo
) < 0)
177 int mtd_write_buffer(int fd
, const char *buf
, int offset
, int length
)
179 lseek(fd
, offset
, SEEK_SET
);
180 write(fd
, buf
, length
);
185 image_check(int imagefd
, const char *mtd
)
191 while (buflen
< sizeof(magic
)) {
192 bufread
= read(imagefd
, buf
+ buflen
, sizeof(magic
) - buflen
);
199 if (buflen
< sizeof(magic
)) {
200 fprintf(stdout
, "Could not get image magic\n");
204 magic
= ((uint32_t *)buf
)[0];
206 if (be32_to_cpu(magic
) == TRX_MAGIC
)
207 imageformat
= MTD_IMAGE_FORMAT_TRX
;
208 else if (be32_to_cpu(magic
) == SEAMA_MAGIC
)
209 imageformat
= MTD_IMAGE_FORMAT_SEAMA
;
210 else if (le32_to_cpu(magic
) == WRG_MAGIC
)
211 imageformat
= MTD_IMAGE_FORMAT_WRG
;
212 else if (le32_to_cpu(magic
) == WRGG03_MAGIC
)
213 imageformat
= MTD_IMAGE_FORMAT_WRGG03
;
215 switch (imageformat
) {
216 case MTD_IMAGE_FORMAT_TRX
:
218 ret
= trx_check(imagefd
, mtd
, buf
, &buflen
);
220 case MTD_IMAGE_FORMAT_SEAMA
:
221 case MTD_IMAGE_FORMAT_WRG
:
222 case MTD_IMAGE_FORMAT_WRGG03
:
226 if (!strcmp(mtd
, "firmware"))
235 static int mtd_check(const char *mtd
)
241 if (strchr(mtd
, ':')) {
247 next
= strchr(mtd
, ':');
253 fd
= mtd_check_open(mtd
);
258 buf
= malloc(erasesize
);
271 mtd_unlock(const char *mtd
)
273 struct erase_info_user mtdLockInfo
;
278 if (strchr(mtd
, ':')) {
284 next
= strchr(mtd
, ':');
290 fd
= mtd_check_open(mtd
);
292 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
297 fprintf(stderr
, "Unlocking %s ...\n", mtd
);
299 mtdLockInfo
.start
= 0;
300 mtdLockInfo
.length
= mtdsize
;
301 ioctl(fd
, MEMUNLOCK
, &mtdLockInfo
);
313 mtd_erase(const char *mtd
)
316 struct erase_info_user mtdEraseInfo
;
319 fprintf(stderr
, "Erasing %s ...\n", mtd
);
321 fd
= mtd_check_open(mtd
);
323 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
327 mtdEraseInfo
.length
= erasesize
;
329 for (mtdEraseInfo
.start
= 0;
330 mtdEraseInfo
.start
< mtdsize
;
331 mtdEraseInfo
.start
+= erasesize
) {
332 if (mtd_block_is_bad(fd
, mtdEraseInfo
.start
)) {
334 fprintf(stderr
, "\nSkipping bad block at 0x%x ", mtdEraseInfo
.start
);
336 ioctl(fd
, MEMUNLOCK
, &mtdEraseInfo
);
337 if(ioctl(fd
, MEMERASE
, &mtdEraseInfo
))
338 fprintf(stderr
, "Failed to erase block on %s at 0x%x\n", mtd
, mtdEraseInfo
.start
);
348 mtd_dump(const char *mtd
, int part_offset
, int size
)
350 int ret
= 0, offset
= 0;
355 fprintf(stderr
, "Dumping %s ...\n", mtd
);
357 fd
= mtd_check_open(mtd
);
359 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
367 lseek(fd
, part_offset
, SEEK_SET
);
369 buf
= malloc(erasesize
);
374 int len
= (size
> erasesize
) ? (erasesize
) : (size
);
375 int rlen
= read(fd
, buf
, len
);
383 if (!rlen
|| rlen
!= len
)
385 if (mtd_block_is_bad(fd
, offset
)) {
386 fprintf(stderr
, "skipping bad block at 0x%08x\n", offset
);
400 mtd_verify(const char *mtd
, char *file
)
402 uint32_t f_md5
[4], m_md5
[4];
409 fprintf(stderr
, "Verifying %s against %s ...\n", mtd
, file
);
411 if (stat(file
, &s
) || md5sum(file
, f_md5
) < 0) {
412 fprintf(stderr
, "Failed to hash %s\n", file
);
416 fd
= mtd_check_open(mtd
);
418 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
425 int len
= (s
.st_size
> sizeof(buf
)) ? (sizeof(buf
)) : (s
.st_size
);
426 int rlen
= read(fd
, buf
, len
);
436 md5_hash(buf
, rlen
, &ctx
);
438 } while (s
.st_size
> 0);
440 md5_end(m_md5
, &ctx
);
442 fprintf(stderr
, "%08x%08x%08x%08x - %s\n", m_md5
[0], m_md5
[1], m_md5
[2], m_md5
[3], mtd
);
443 fprintf(stderr
, "%08x%08x%08x%08x - %s\n", f_md5
[0], f_md5
[1], f_md5
[2], f_md5
[3], file
);
445 ret
= memcmp(f_md5
, m_md5
, sizeof(m_md5
));
447 fprintf(stderr
, "Success\n");
449 fprintf(stderr
, "Failed\n");
457 indicate_writing(const char *mtd
)
460 fprintf(stderr
, "\nWriting from %s to %s ... ", imagefile
, mtd
);
463 fprintf(stderr
, " [ ]");
467 mtd_write(int imagefd
, const char *mtd
, char *fis_layout
, size_t part_offset
)
475 int jffs2_replaced
= 0;
476 int skip_bad_blocks
= 0;
479 static struct fis_part new_parts
[MAX_ARGS
];
480 static struct fis_part old_parts
[MAX_ARGS
];
481 int n_new
= 0, n_old
= 0;
484 const char *tmp
= mtd
;
488 memset(&old_parts
, 0, sizeof(old_parts
));
489 memset(&new_parts
, 0, sizeof(new_parts
));
492 next
= strchr(tmp
, ':');
494 next
= (char *) tmp
+ strlen(tmp
);
496 memcpy(old_parts
[n_old
].name
, tmp
, next
- tmp
);
502 for (word
= strtok_r(fis_layout
, ",", &brkt
);
504 word
= strtok_r(NULL
, ",", &brkt
)) {
506 tmp
= strtok(word
, ":");
507 strncpy((char *) new_parts
[n_new
].name
, tmp
, sizeof(new_parts
[n_new
].name
) - 1);
509 tmp
= strtok(NULL
, ":");
513 new_parts
[n_new
].size
= strtoul(tmp
, NULL
, 0);
515 tmp
= strtok(NULL
, ":");
519 new_parts
[n_new
].loadaddr
= strtoul(tmp
, NULL
, 16);
523 ret
= fis_validate(old_parts
, n_old
, new_parts
, n_new
);
525 fprintf(stderr
, "Failed to validate the new FIS partition table\n");
533 if (strchr(mtd
, ':')) {
541 next
= strchr(mtd
, ':');
547 fd
= mtd_check_open(mtd
);
549 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
552 if (part_offset
> 0) {
553 fprintf(stderr
, "Seeking on mtd device '%s' to: %zu\n", mtd
, part_offset
);
554 lseek(fd
, part_offset
, SEEK_SET
);
557 indicate_writing(mtd
);
561 /* buffer may contain data already (from trx check or last mtd partition write attempt) */
562 while (buflen
< erasesize
) {
563 r
= read(imagefd
, buf
+ buflen
, erasesize
- buflen
);
565 if ((errno
== EINTR
) || (errno
== EAGAIN
))
582 if (buflen
< erasesize
) {
583 /* Pad block to eraseblock size */
584 memset(&buf
[buflen
], 0xff, erasesize
- buflen
);
592 indicate_writing(mtd
);
597 if (jffs2file
&& w
>= jffs2_skip_bytes
) {
598 if (memcmp(buf
, JFFS2_EOF
, sizeof(JFFS2_EOF
) - 1) == 0) {
600 fprintf(stderr
, "\b\b\b ");
602 fprintf(stderr
, "\nAppending jffs2 data from %s to %s..\n.", jffs2file
, mtd
);
603 /* got an EOF marker - this is the place to add some jffs2 data */
604 skip
= mtd_replace_jffs2(mtd
, fd
, e
, jffs2file
);
607 /* don't add it again */
617 /* no EOF marker, make sure we figure out the last inode number
618 * before appending some data */
619 mtd_parse_jffs2data(buf
, jffs2dir
);
622 /* need to erase the next block before writing data to it */
625 while (w
+ buflen
> e
- skip_bad_blocks
) {
627 fprintf(stderr
, "\b\b\b[e]");
629 if (mtd_block_is_bad(fd
, e
)) {
631 fprintf(stderr
, "\nSkipping bad block at 0x%08zx ", e
);
633 skip_bad_blocks
+= erasesize
;
636 // Move the file pointer along over the bad block.
637 lseek(fd
, erasesize
, SEEK_CUR
);
641 if (mtd_erase_block(fd
, e
) < 0) {
644 write(fd
, buf
+ offset
, e
- w
);
651 fprintf(stderr
, "\b\b\b \n");
654 fprintf(stderr
, "Failed to erase block\n");
659 /* erase the chunk */
665 fprintf(stderr
, "\b\b\b[w]");
667 if ((result
= write(fd
, buf
+ offset
, buflen
)) < buflen
) {
669 fprintf(stderr
, "Error writing image.\n");
672 fprintf(stderr
, "Insufficient space.\n");
682 if (jffs2_replaced
) {
683 switch (imageformat
) {
684 case MTD_IMAGE_FORMAT_TRX
:
688 case MTD_IMAGE_FORMAT_SEAMA
:
690 mtd_fixseama(mtd
, 0, 0);
692 case MTD_IMAGE_FORMAT_WRG
:
694 mtd_fixwrg(mtd
, 0, 0);
696 case MTD_IMAGE_FORMAT_WRGG03
:
698 mtd_fixwrgg(mtd
, 0, 0);
706 fprintf(stderr
, "\b\b\b\b ");
709 fprintf(stderr
, "\n");
713 if (fis_remap(old_parts
, n_old
, new_parts
, n_new
) < 0)
714 fprintf(stderr
, "Failed to update the FIS partition table\n");
722 static void usage(void)
724 fprintf(stderr
, "Usage: mtd [<options> ...] <command> [<arguments> ...] <device>[:<device>...]\n\n"
725 "The device is in the format of mtdX (eg: mtd4) or its label.\n"
726 "mtd recognizes these commands:\n"
727 " unlock unlock the device\n"
728 " refresh refresh mtd partition\n"
729 " erase erase all data on device\n"
730 " verify <imagefile>|- verify <imagefile> (use - for stdin) to device\n"
731 " write <imagefile>|- write <imagefile> (use - for stdin) to device\n"
732 " jffs2write <file> append <file> to the jffs2 partition on the device\n");
735 " resetbc <device> reset the uboot boot counter\n");
739 " fixtrx fix the checksum in a trx header on first boot\n");
743 " fixseama fix the checksum in a seama header on first boot\n");
747 " fixwrg fix the checksum in a wrg header on first boot\n");
751 " fixwrgg fix the checksum in a wrgg header on first boot\n");
754 "Following options are available:\n"
755 " -q quiet mode (once: no [w] on writing,\n"
756 " twice: no status messages)\n"
757 " -n write without first erasing the blocks\n"
758 " -r reboot after successful command\n"
759 " -f force write without trx checks\n"
760 " -e <device> erase <device> before executing the command\n"
761 " -d <name> directory for jffs2write, defaults to \"tmp\"\n"
762 " -j <name> integrate <file> into jffs2 data when writing an image\n"
763 " -s <number> skip the first n bytes when appending data to the jffs2 partiton, defaults to \"0\"\n"
764 " -p <number> write beginning at partition offset\n"
765 " -l <length> the length of data that we want to dump\n");
768 " -o offset offset of the image header in the partition(for fixtrx)\n");
770 if (mtd_fixtrx
|| mtd_fixseama
|| mtd_fixwrg
|| mtd_fixwrgg
) {
772 " -c datasize amount of data to be used for checksum calculation (for fixtrx / fixseama / fixwrg / fixwrgg)\n");
776 " -F <part>[:<size>[:<entrypoint>]][,<part>...]\n"
777 " alter the fis partition table to create new partitions replacing\n"
778 " the partitions provided as argument to the write command\n"
779 " (only valid together with the write command)\n"
782 "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
783 " mtd -r write linux.trx linux\n\n");
787 static void do_reboot(void)
789 fprintf(stderr
, "Rebooting ...\n");
792 /* try regular reboot method first */
793 system("/sbin/reboot");
796 /* if we're still alive at this point, force the kernel to reboot */
797 syscall(SYS_reboot
,LINUX_REBOOT_MAGIC1
,LINUX_REBOOT_MAGIC2
,LINUX_REBOOT_CMD_RESTART
,NULL
);
800 int main (int argc
, char **argv
)
802 int ch
, i
, boot
, imagefd
= 0, force
, unlocked
;
803 char *erase
[MAX_ARGS
], *device
= NULL
;
804 char *fis_layout
= NULL
;
805 size_t offset
= 0, data_size
= 0, part_offset
= 0, dump_len
= 0;
827 while ((ch
= getopt(argc
, argv
,
831 "frnqe:d:s:j:p:o:c:l:")) != -1)
847 jffs2_skip_bytes
= strtoul(optarg
, 0, 0);
849 fprintf(stderr
, "-s: illegal numeric string\n");
858 while ((erase
[i
] != NULL
) && ((i
+ 1) < MAX_ARGS
))
869 part_offset
= strtoul(optarg
, 0, 0);
871 fprintf(stderr
, "-p: illegal numeric string\n");
877 dump_len
= strtoul(optarg
, 0, 0);
879 fprintf(stderr
, "-l: illegal numeric string\n");
885 offset
= strtoul(optarg
, 0, 0);
887 fprintf(stderr
, "-o: illegal numeric string\n");
893 data_size
= strtoul(optarg
, 0, 0);
895 fprintf(stderr
, "-c: illegal numeric string\n");
914 if ((strcmp(argv
[0], "unlock") == 0) && (argc
== 2)) {
917 } else if ((strcmp(argv
[0], "erase") == 0) && (argc
== 2)) {
920 } else if (((strcmp(argv
[0], "resetbc") == 0) && (argc
== 2)) && mtd_resetbc
) {
923 } else if (((strcmp(argv
[0], "fixtrx") == 0) && (argc
== 2)) && mtd_fixtrx
) {
926 } else if (((strcmp(argv
[0], "fixseama") == 0) && (argc
== 2)) && mtd_fixseama
) {
929 } else if (((strcmp(argv
[0], "fixwrg") == 0) && (argc
== 2)) && mtd_fixwrg
) {
932 } else if (((strcmp(argv
[0], "fixwrgg") == 0) && (argc
== 2)) && mtd_fixwrgg
) {
935 } else if ((strcmp(argv
[0], "verify") == 0) && (argc
== 3)) {
939 } else if ((strcmp(argv
[0], "dump") == 0) && (argc
== 2)) {
942 } else if ((strcmp(argv
[0], "write") == 0) && (argc
== 3)) {
946 if (strcmp(argv
[1], "-") == 0) {
947 imagefile
= "<stdin>";
951 if ((imagefd
= open(argv
[1], O_RDONLY
)) < 0) {
952 fprintf(stderr
, "Couldn't open image file: %s!\n", imagefile
);
957 if (!mtd_check(device
)) {
958 fprintf(stderr
, "Can't open device for writing!\n");
961 /* check trx file before erasing or writing anything */
962 if (!image_check(imagefd
, device
) && !force
) {
963 fprintf(stderr
, "Image check failed.\n");
966 } else if ((strcmp(argv
[0], "jffs2write") == 0) && (argc
== 3)) {
967 cmd
= CMD_JFFS2WRITE
;
971 if (!mtd_check(device
)) {
972 fprintf(stderr
, "Can't open device for writing!\n");
983 while (erase
[i
] != NULL
) {
984 mtd_unlock(erase
[i
]);
986 if (strcmp(erase
[i
], device
) == 0)
997 mtd_verify(device
, imagefile
);
1000 mtd_dump(device
, offset
, dump_len
);
1010 mtd_write(imagefd
, device
, fis_layout
, part_offset
);
1012 case CMD_JFFS2WRITE
:
1015 mtd_write_jffs2(device
, imagefile
, jffs2dir
);
1019 mtd_fixtrx(device
, offset
, data_size
);
1024 mtd_resetbc(device
);
1029 mtd_fixseama(device
, 0, data_size
);
1033 mtd_fixwrg(device
, 0, data_size
);
1037 mtd_fixwrgg(device
, 0, data_size
);