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>
51 #include <libubox/md5.h>
54 #define JFFS2_DEFAULT_DIR "" /* directory name without /, empty means root dir */
56 #define TRX_MAGIC 0x48445230 /* "HDR0" */
57 #define SEAMA_MAGIC 0x5ea3a417
58 #define WRG_MAGIC 0x20040220
59 #define WRGG03_MAGIC 0x20080321
61 #if !defined(__BYTE_ORDER)
62 #error "Unknown byte order"
65 #if __BYTE_ORDER == __BIG_ENDIAN
66 #define cpu_to_be32(x) (x)
67 #define be32_to_cpu(x) (x)
68 #define le32_to_cpu(x) bswap_32(x)
69 #elif __BYTE_ORDER == __LITTLE_ENDIAN
70 #define cpu_to_be32(x) bswap_32(x)
71 #define be32_to_cpu(x) bswap_32(x)
72 #define le32_to_cpu(x) (x)
74 #error "Unsupported endianness"
77 enum mtd_image_format
{
78 MTD_IMAGE_FORMAT_UNKNOWN
,
80 MTD_IMAGE_FORMAT_SEAMA
,
82 MTD_IMAGE_FORMAT_WRGG03
,
85 static char *buf
= NULL
;
86 static char *imagefile
= NULL
;
87 static enum mtd_image_format imageformat
= MTD_IMAGE_FORMAT_UNKNOWN
;
88 static char *jffs2file
= NULL
, *jffs2dir
= JFFS2_DEFAULT_DIR
;
89 static char *tpl_uboot_args_part
;
90 static int buflen
= 0;
95 int jffs2_skip_bytes
=0;
97 uint32_t opt_trxmagic
= TRX_MAGIC
;
99 int mtd_open(const char *mtd
, bool block
)
105 int flags
= O_RDWR
| O_SYNC
;
108 snprintf(name
, sizeof(name
), "\"%s\"", mtd
);
109 if ((fp
= fopen("/proc/mtd", "r"))) {
110 while (fgets(dev
, sizeof(dev
), fp
)) {
111 if (sscanf(dev
, "mtd%d:", &i
) && strstr(dev
, name
)) {
112 snprintf(dev
, sizeof(dev
), "/dev/mtd%s/%d", (block
? "block" : ""), i
);
113 if ((ret
=open(dev
, flags
))<0) {
114 snprintf(dev
, sizeof(dev
), "/dev/mtd%s%d", (block
? "block" : ""), i
);
115 ret
=open(dev
, flags
);
124 return open(mtd
, flags
);
127 int mtd_check_open(const char *mtd
)
129 struct mtd_info_user mtdInfo
;
132 fd
= mtd_open(mtd
, false);
134 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
138 if(ioctl(fd
, MEMGETINFO
, &mtdInfo
)) {
139 fprintf(stderr
, "Could not get MTD device info from %s\n", mtd
);
143 mtdsize
= mtdInfo
.size
;
144 erasesize
= mtdInfo
.erasesize
;
145 mtdtype
= mtdInfo
.type
;
150 int mtd_block_is_bad(int fd
, int offset
)
155 if (mtdtype
== MTD_NANDFLASH
)
157 r
= ioctl(fd
, MEMGETBADBLOCK
, &o
);
160 fprintf(stderr
, "Failed to get erase block status\n");
167 int mtd_erase_block(int fd
, int offset
)
169 struct erase_info_user mtdEraseInfo
;
171 mtdEraseInfo
.start
= offset
;
172 mtdEraseInfo
.length
= erasesize
;
173 ioctl(fd
, MEMUNLOCK
, &mtdEraseInfo
);
174 if (ioctl (fd
, MEMERASE
, &mtdEraseInfo
) < 0)
180 int mtd_write_buffer(int fd
, const char *buf
, int offset
, int length
)
182 lseek(fd
, offset
, SEEK_SET
);
183 write(fd
, buf
, length
);
188 image_check(int imagefd
, const char *mtd
)
194 while (buflen
< sizeof(magic
)) {
195 bufread
= read(imagefd
, buf
+ buflen
, sizeof(magic
) - buflen
);
202 if (buflen
< sizeof(magic
)) {
203 fprintf(stdout
, "Could not get image magic\n");
207 magic
= ((uint32_t *)buf
)[0];
209 if (be32_to_cpu(magic
) == opt_trxmagic
)
210 imageformat
= MTD_IMAGE_FORMAT_TRX
;
211 else if (be32_to_cpu(magic
) == SEAMA_MAGIC
)
212 imageformat
= MTD_IMAGE_FORMAT_SEAMA
;
213 else if (le32_to_cpu(magic
) == WRG_MAGIC
)
214 imageformat
= MTD_IMAGE_FORMAT_WRG
;
215 else if (le32_to_cpu(magic
) == WRGG03_MAGIC
)
216 imageformat
= MTD_IMAGE_FORMAT_WRGG03
;
218 switch (imageformat
) {
219 case MTD_IMAGE_FORMAT_TRX
:
221 ret
= trx_check(imagefd
, mtd
, buf
, &buflen
);
223 case MTD_IMAGE_FORMAT_SEAMA
:
224 case MTD_IMAGE_FORMAT_WRG
:
225 case MTD_IMAGE_FORMAT_WRGG03
:
229 if (!strcmp(mtd
, "firmware"))
238 static int mtd_check(const char *mtd
)
244 if (strchr(mtd
, ':')) {
250 next
= strchr(mtd
, ':');
256 fd
= mtd_check_open(mtd
);
261 buf
= malloc(erasesize
);
274 mtd_unlock(const char *mtd
)
276 struct erase_info_user mtdLockInfo
;
281 if (strchr(mtd
, ':')) {
287 next
= strchr(mtd
, ':');
293 fd
= mtd_check_open(mtd
);
295 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
300 fprintf(stderr
, "Unlocking %s ...\n", mtd
);
302 mtdLockInfo
.start
= 0;
303 mtdLockInfo
.length
= mtdsize
;
304 ioctl(fd
, MEMUNLOCK
, &mtdLockInfo
);
316 mtd_erase(const char *mtd
)
319 struct erase_info_user mtdEraseInfo
;
322 fprintf(stderr
, "Erasing %s ...\n", mtd
);
324 fd
= mtd_check_open(mtd
);
326 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
330 mtdEraseInfo
.length
= erasesize
;
332 for (mtdEraseInfo
.start
= 0;
333 mtdEraseInfo
.start
< mtdsize
;
334 mtdEraseInfo
.start
+= erasesize
) {
335 if (mtd_block_is_bad(fd
, mtdEraseInfo
.start
)) {
337 fprintf(stderr
, "\nSkipping bad block at 0x%x ", mtdEraseInfo
.start
);
339 ioctl(fd
, MEMUNLOCK
, &mtdEraseInfo
);
340 if(ioctl(fd
, MEMERASE
, &mtdEraseInfo
))
341 fprintf(stderr
, "Failed to erase block on %s at 0x%x\n", mtd
, mtdEraseInfo
.start
);
351 mtd_dump(const char *mtd
, int part_offset
, int size
)
353 int ret
= 0, offset
= 0;
358 fprintf(stderr
, "Dumping %s ...\n", mtd
);
360 fd
= mtd_check_open(mtd
);
362 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
370 lseek(fd
, part_offset
, SEEK_SET
);
372 buf
= malloc(erasesize
);
377 int len
= (size
> erasesize
) ? (erasesize
) : (size
);
378 int rlen
= read(fd
, buf
, len
);
386 if (!rlen
|| rlen
!= len
)
388 if (mtd_block_is_bad(fd
, offset
)) {
389 fprintf(stderr
, "skipping bad block at 0x%08x\n", offset
);
403 mtd_verify(const char *mtd
, char *file
)
405 uint32_t f_md5
[4], m_md5
[4];
412 fprintf(stderr
, "Verifying %s against %s ...\n", mtd
, file
);
414 if (stat(file
, &s
) || md5sum(file
, f_md5
) < 0) {
415 fprintf(stderr
, "Failed to hash %s\n", file
);
419 fd
= mtd_check_open(mtd
);
421 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
428 int len
= (s
.st_size
> sizeof(buf
)) ? (sizeof(buf
)) : (s
.st_size
);
429 int rlen
= read(fd
, buf
, len
);
439 md5_hash(buf
, rlen
, &ctx
);
441 } while (s
.st_size
> 0);
443 md5_end(m_md5
, &ctx
);
445 fprintf(stderr
, "%08x%08x%08x%08x - %s\n", m_md5
[0], m_md5
[1], m_md5
[2], m_md5
[3], mtd
);
446 fprintf(stderr
, "%08x%08x%08x%08x - %s\n", f_md5
[0], f_md5
[1], f_md5
[2], f_md5
[3], file
);
448 ret
= memcmp(f_md5
, m_md5
, sizeof(m_md5
));
450 fprintf(stderr
, "Success\n");
452 fprintf(stderr
, "Failed\n");
460 indicate_writing(const char *mtd
)
463 fprintf(stderr
, "\nWriting from %s to %s ... ", imagefile
, mtd
);
466 fprintf(stderr
, " [ ]");
470 mtd_write(int imagefd
, const char *mtd
, char *fis_layout
, size_t part_offset
)
479 int jffs2_replaced
= 0;
480 int skip_bad_blocks
= 0;
483 static struct fis_part new_parts
[MAX_ARGS
];
484 static struct fis_part old_parts
[MAX_ARGS
];
485 struct fis_part
*cur_part
= NULL
;
486 int n_new
= 0, n_old
= 0;
489 const char *tmp
= mtd
;
493 memset(&old_parts
, 0, sizeof(old_parts
));
494 memset(&new_parts
, 0, sizeof(new_parts
));
496 cur_part
= new_parts
;
499 next
= strchr(tmp
, ':');
501 next
= (char *) tmp
+ strlen(tmp
);
503 memcpy(old_parts
[n_old
].name
, tmp
, next
- tmp
);
509 for (word
= strtok_r(fis_layout
, ",", &brkt
);
511 word
= strtok_r(NULL
, ",", &brkt
)) {
513 tmp
= strtok(word
, ":");
514 strncpy((char *) new_parts
[n_new
].name
, tmp
, sizeof(new_parts
[n_new
].name
) - 1);
516 tmp
= strtok(NULL
, ":");
520 new_parts
[n_new
].size
= strtoul(tmp
, NULL
, 0);
522 tmp
= strtok(NULL
, ":");
526 new_parts
[n_new
].loadaddr
= strtoul(tmp
, NULL
, 16);
530 ret
= fis_validate(old_parts
, n_old
, new_parts
, n_new
);
532 fprintf(stderr
, "Failed to validate the new FIS partition table\n");
540 if (strchr(mtd
, ':')) {
548 next
= strchr(mtd
, ':');
554 fd
= mtd_check_open(mtd
);
556 fprintf(stderr
, "Could not open mtd device: %s\n", mtd
);
559 if (part_offset
> 0) {
560 fprintf(stderr
, "Seeking on mtd device '%s' to: %zu\n", mtd
, part_offset
);
561 lseek(fd
, part_offset
, SEEK_SET
);
564 /* Write TP-Link recovery flag */
565 if (tpl_uboot_args_part
&& mtd_tpl_recoverflag_write
) {
567 fprintf(stderr
, "Writing recovery flag to %s\n", tpl_uboot_args_part
);
568 result
= mtd_tpl_recoverflag_write(tpl_uboot_args_part
, true);
570 fprintf(stderr
, "Could not write TP-Link recovery flag to %s: %i", mtd
, result
);
575 indicate_writing(mtd
);
579 /* buffer may contain data already (from trx check or last mtd partition write attempt) */
580 while (buflen
< erasesize
) {
581 r
= read(imagefd
, buf
+ buflen
, erasesize
- buflen
);
583 if ((errno
== EINTR
) || (errno
== EAGAIN
))
603 if (buflen
< erasesize
) {
604 /* Pad block to eraseblock size */
605 memset(&buf
[buflen
], 0xff, erasesize
- buflen
);
614 indicate_writing(mtd
);
619 if (jffs2file
&& w
>= jffs2_skip_bytes
) {
620 if (memcmp(buf
, JFFS2_EOF
, sizeof(JFFS2_EOF
) - 1) == 0) {
622 fprintf(stderr
, "\b\b\b ");
624 fprintf(stderr
, "\nAppending jffs2 data from %s to %s..\n.", jffs2file
, mtd
);
625 /* got an EOF marker - this is the place to add some jffs2 data */
626 skip
= mtd_replace_jffs2(mtd
, fd
, e
, jffs2file
);
629 /* don't add it again */
640 /* no EOF marker, make sure we figure out the last inode number
641 * before appending some data */
642 mtd_parse_jffs2data(buf
, jffs2dir
);
645 /* need to erase the next block before writing data to it */
648 while (w
+ buflen
> e
- skip_bad_blocks
) {
650 fprintf(stderr
, "\b\b\b[e]");
652 if (mtd_block_is_bad(fd
, e
)) {
654 fprintf(stderr
, "\nSkipping bad block at 0x%08zx ", e
);
656 skip_bad_blocks
+= erasesize
;
659 // Move the file pointer along over the bad block.
660 lseek(fd
, erasesize
, SEEK_CUR
);
664 if (mtd_erase_block(fd
, e
+ part_offset
) < 0) {
667 write(fd
, buf
+ offset
, e
- w
);
674 fprintf(stderr
, "\b\b\b \n");
677 fprintf(stderr
, "Failed to erase block\n");
682 /* erase the chunk */
688 fprintf(stderr
, "\b\b\b[w]");
690 if ((result
= write(fd
, buf
+ offset
, buflen
)) < buflen
) {
692 fprintf(stderr
, "Error writing image.\n");
695 fprintf(stderr
, "Insufficient space.\n");
702 if (cur_part
&& cur_part
->size
703 && cur_part
< &new_parts
[MAX_ARGS
- 1]
704 && cur_part
->length
+ buflen_raw
> cur_part
->size
)
707 cur_part
->length
+= buflen_raw
;
708 cur_part
->crc
= crc32(cur_part
->crc
, buf
, buflen_raw
);
716 if (jffs2_replaced
) {
717 switch (imageformat
) {
718 case MTD_IMAGE_FORMAT_TRX
:
722 case MTD_IMAGE_FORMAT_SEAMA
:
724 mtd_fixseama(mtd
, 0, 0);
726 case MTD_IMAGE_FORMAT_WRG
:
728 mtd_fixwrg(mtd
, 0, 0);
730 case MTD_IMAGE_FORMAT_WRGG03
:
732 mtd_fixwrgg(mtd
, 0, 0);
740 fprintf(stderr
, "\b\b\b\b ");
743 fprintf(stderr
, "\n");
747 if (fis_remap(old_parts
, n_old
, new_parts
, n_new
) < 0)
748 fprintf(stderr
, "Failed to update the FIS partition table\n");
754 /* Clear TP-Link recovery flag */
755 if (tpl_uboot_args_part
&& mtd_tpl_recoverflag_write
) {
757 fprintf(stderr
, "Removing recovery flag from %s\n", tpl_uboot_args_part
);
758 result
= mtd_tpl_recoverflag_write(tpl_uboot_args_part
, false);
760 fprintf(stderr
, "Could not clear TP-Link recovery flag to %s: %i", mtd
, result
);
768 static void usage(void)
770 fprintf(stderr
, "Usage: mtd [<options> ...] <command> [<arguments> ...] <device>[:<device>...]\n\n"
771 "The device is in the format of mtdX (eg: mtd4) or its label.\n"
772 "mtd recognizes these commands:\n"
773 " unlock unlock the device\n"
774 " refresh refresh mtd partition\n"
775 " erase erase all data on device\n"
776 " verify <imagefile>|- verify <imagefile> (use - for stdin) to device\n"
777 " write <imagefile>|- write <imagefile> (use - for stdin) to device\n"
778 " jffs2write <file> append <file> to the jffs2 partition on the device\n");
781 " resetbc <device> reset the uboot boot counter\n");
785 " fixtrx fix the checksum in a trx header on first boot\n");
789 " fixseama fix the checksum in a seama header on first boot\n");
793 " fixwrg fix the checksum in a wrg header on first boot\n");
797 " fixwrgg fix the checksum in a wrgg header on first boot\n");
800 "Following options are available:\n"
801 " -q quiet mode (once: no [w] on writing,\n"
802 " twice: no status messages)\n"
803 " -n write without first erasing the blocks\n"
804 " -r reboot after successful command\n"
805 " -f force write without trx checks\n"
806 " -e <device> erase <device> before executing the command\n"
807 " -d <name> directory for jffs2write, defaults to \"tmp\"\n"
808 " -j <name> integrate <file> into jffs2 data when writing an image\n"
809 " -s <number> skip the first n bytes when appending data to the jffs2 partiton, defaults to \"0\"\n"
810 " -p <number> write beginning at partition offset\n"
811 " -l <length> the length of data that we want to dump\n");
814 " -M <magic> magic number of the image header in the partition (for fixtrx)\n"
815 " -o offset offset of the image header in the partition(for fixtrx)\n");
817 if (mtd_fixtrx
|| mtd_fixseama
|| mtd_fixwrg
|| mtd_fixwrgg
) {
819 " -c datasize amount of data to be used for checksum calculation (for fixtrx / fixseama / fixwrg / fixwrgg)\n");
821 if (mtd_tpl_recoverflag_write
) {
823 " -t <partition> write TP-Link recovery-flag to <partition> (for write)\n");
827 " -F <part>[:<size>[:<entrypoint>]][,<part>...]\n"
828 " alter the fis partition table to create new partitions replacing\n"
829 " the partitions provided as argument to the write command\n"
830 " (only valid together with the write command)\n"
833 "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
834 " mtd -r write linux.trx linux\n\n");
838 static void do_reboot(void)
840 fprintf(stderr
, "Rebooting ...\n");
843 /* try regular reboot method first */
844 system("/sbin/reboot");
847 /* if we're still alive at this point, force the kernel to reboot */
848 syscall(SYS_reboot
,LINUX_REBOOT_MAGIC1
,LINUX_REBOOT_MAGIC2
,LINUX_REBOOT_CMD_RESTART
,NULL
);
851 int main (int argc
, char **argv
)
853 int ch
, i
, boot
, imagefd
= 0, force
, unlocked
;
854 char *erase
[MAX_ARGS
], *device
= NULL
;
855 char *fis_layout
= NULL
;
856 size_t offset
= 0, data_size
= 0, part_offset
= 0, dump_len
= 0;
878 while ((ch
= getopt(argc
, argv
,
882 "frnqe:d:s:j:p:o:c:t:l:M:")) != -1)
898 jffs2_skip_bytes
= strtoul(optarg
, 0, 0);
900 fprintf(stderr
, "-s: illegal numeric string\n");
909 while ((erase
[i
] != NULL
) && ((i
+ 1) < MAX_ARGS
))
920 part_offset
= strtoul(optarg
, 0, 0);
922 fprintf(stderr
, "-p: illegal numeric string\n");
928 dump_len
= strtoul(optarg
, 0, 0);
930 fprintf(stderr
, "-l: illegal numeric string\n");
936 opt_trxmagic
= strtoul(optarg
, 0, 0);
938 fprintf(stderr
, "-M: illegal numeric string\n");
944 offset
= strtoul(optarg
, 0, 0);
946 fprintf(stderr
, "-o: illegal numeric string\n");
952 data_size
= strtoul(optarg
, 0, 0);
954 fprintf(stderr
, "-c: illegal numeric string\n");
959 tpl_uboot_args_part
= optarg
;
976 if ((strcmp(argv
[0], "unlock") == 0) && (argc
== 2)) {
979 } else if ((strcmp(argv
[0], "erase") == 0) && (argc
== 2)) {
982 } else if (((strcmp(argv
[0], "resetbc") == 0) && (argc
== 2)) && mtd_resetbc
) {
985 } else if (((strcmp(argv
[0], "fixtrx") == 0) && (argc
== 2)) && mtd_fixtrx
) {
988 } else if (((strcmp(argv
[0], "fixseama") == 0) && (argc
== 2)) && mtd_fixseama
) {
991 } else if (((strcmp(argv
[0], "fixwrg") == 0) && (argc
== 2)) && mtd_fixwrg
) {
994 } else if (((strcmp(argv
[0], "fixwrgg") == 0) && (argc
== 2)) && mtd_fixwrgg
) {
997 } else if ((strcmp(argv
[0], "verify") == 0) && (argc
== 3)) {
1001 } else if ((strcmp(argv
[0], "dump") == 0) && (argc
== 2)) {
1004 } else if ((strcmp(argv
[0], "write") == 0) && (argc
== 3)) {
1008 if (strcmp(argv
[1], "-") == 0) {
1009 imagefile
= "<stdin>";
1012 imagefile
= argv
[1];
1013 if ((imagefd
= open(argv
[1], O_RDONLY
)) < 0) {
1014 fprintf(stderr
, "Couldn't open image file: %s!\n", imagefile
);
1019 if (!mtd_check(device
)) {
1020 fprintf(stderr
, "Can't open device for writing!\n");
1023 /* check trx file before erasing or writing anything */
1024 if (!image_check(imagefd
, device
) && !force
) {
1025 fprintf(stderr
, "Image check failed.\n");
1028 } else if ((strcmp(argv
[0], "jffs2write") == 0) && (argc
== 3)) {
1029 cmd
= CMD_JFFS2WRITE
;
1032 imagefile
= argv
[1];
1033 if (!mtd_check(device
)) {
1034 fprintf(stderr
, "Can't open device for writing!\n");
1045 while (erase
[i
] != NULL
) {
1046 mtd_unlock(erase
[i
]);
1047 mtd_erase(erase
[i
]);
1048 if (strcmp(erase
[i
], device
) == 0)
1059 mtd_verify(device
, imagefile
);
1062 mtd_dump(device
, offset
, dump_len
);
1072 mtd_write(imagefd
, device
, fis_layout
, part_offset
);
1074 case CMD_JFFS2WRITE
:
1077 mtd_write_jffs2(device
, imagefile
, jffs2dir
);
1081 mtd_fixtrx(device
, offset
, data_size
);
1086 mtd_resetbc(device
);
1091 mtd_fixseama(device
, 0, data_size
);
1095 mtd_fixwrg(device
, 0, data_size
);
1099 mtd_fixwrgg(device
, 0, data_size
);