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@openwrt.org>
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.
32 #include <sys/ioctl.h>
33 #include <sys/syscall.h>
38 #include <sys/ioctl.h>
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #include <sys/mount.h>
43 #include <sys/reboot.h>
44 #include <linux/reboot.h>
45 #include <mtd/mtd-user.h>
49 #include <libubox/md5.h>
52 #define JFFS2_DEFAULT_DIR "" /* directory name without /, empty means root dir */
54 #define TRX_MAGIC 0x48445230 /* "HDR0" */
55 #define SEAMA_MAGIC 0x5ea3a417
57 #if !defined(__BYTE_ORDER)
58 #error "Unknown byte order"
61 #if __BYTE_ORDER == __BIG_ENDIAN
62 #define cpu_to_be32(x) (x)
63 #define be32_to_cpu(x) (x)
64 #elif __BYTE_ORDER == __LITTLE_ENDIAN
65 #define cpu_to_be32(x) bswap_32(x)
66 #define be32_to_cpu(x) bswap_32(x)
68 #error "Unsupported endianness"
71 enum mtd_image_format {
72 MTD_IMAGE_FORMAT_UNKNOWN,
74 MTD_IMAGE_FORMAT_SEAMA,
77 static char *buf = NULL;
78 static char *imagefile = NULL;
79 static enum mtd_image_format imageformat = MTD_IMAGE_FORMAT_UNKNOWN;
80 static char *jffs2file = NULL, *jffs2dir = JFFS2_DEFAULT_DIR;
81 static int buflen = 0;
86 int jffs2_skip_bytes=0;
89 int mtd_open(const char *mtd, bool block)
95 int flags = O_RDWR | O_SYNC;
98 snprintf(name, sizeof(name), "\"%s\"", mtd);
99 if ((fp = fopen("/proc/mtd", "r"))) {
100 while (fgets(dev, sizeof(dev), fp)) {
101 if (sscanf(dev, "mtd%d:", &i) && strstr(dev, name)) {
102 snprintf(dev, sizeof(dev), "/dev/mtd%s/%d", (block ? "block" : ""), i);
103 if ((ret=open(dev, flags))<0) {
104 snprintf(dev, sizeof(dev), "/dev/mtd%s%d", (block ? "block" : ""), i);
105 ret=open(dev, flags);
114 return open(mtd, flags);
117 int mtd_check_open(const char *mtd)
119 struct mtd_info_user mtdInfo;
122 fd = mtd_open(mtd, false);
124 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
128 if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
129 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
133 mtdsize = mtdInfo.size;
134 erasesize = mtdInfo.erasesize;
135 mtdtype = mtdInfo.type;
140 int mtd_block_is_bad(int fd, int offset)
145 if (mtdtype == MTD_NANDFLASH)
147 r = ioctl(fd, MEMGETBADBLOCK, &o);
150 fprintf(stderr, "Failed to get erase block status\n");
157 int mtd_erase_block(int fd, int offset)
159 struct erase_info_user mtdEraseInfo;
161 mtdEraseInfo.start = offset;
162 mtdEraseInfo.length = erasesize;
163 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
164 if (ioctl (fd, MEMERASE, &mtdEraseInfo) < 0)
170 int mtd_write_buffer(int fd, const char *buf, int offset, int length)
172 lseek(fd, offset, SEEK_SET);
173 write(fd, buf, length);
178 image_check(int imagefd, const char *mtd)
184 while (buflen < sizeof(magic)) {
185 bufread = read(imagefd, buf + buflen, sizeof(magic) - buflen);
192 if (buflen < sizeof(magic)) {
193 fprintf(stdout, "Could not get image magic\n");
197 magic = ((uint32_t *)buf)[0];
199 if (be32_to_cpu(magic) == TRX_MAGIC)
200 imageformat = MTD_IMAGE_FORMAT_TRX;
201 else if (be32_to_cpu(magic) == SEAMA_MAGIC)
202 imageformat = MTD_IMAGE_FORMAT_SEAMA;
204 switch (imageformat) {
205 case MTD_IMAGE_FORMAT_TRX:
207 ret = trx_check(imagefd, mtd, buf, &buflen);
209 case MTD_IMAGE_FORMAT_SEAMA:
213 if (!strcmp(mtd, "firmware"))
222 static int mtd_check(const char *mtd)
228 if (strchr(mtd, ':')) {
234 next = strchr(mtd, ':');
240 fd = mtd_check_open(mtd);
245 buf = malloc(erasesize);
258 mtd_unlock(const char *mtd)
260 struct erase_info_user mtdLockInfo;
265 if (strchr(mtd, ':')) {
271 next = strchr(mtd, ':');
277 fd = mtd_check_open(mtd);
279 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
284 fprintf(stderr, "Unlocking %s ...\n", mtd);
286 mtdLockInfo.start = 0;
287 mtdLockInfo.length = mtdsize;
288 ioctl(fd, MEMUNLOCK, &mtdLockInfo);
300 mtd_erase(const char *mtd)
303 struct erase_info_user mtdEraseInfo;
306 fprintf(stderr, "Erasing %s ...\n", mtd);
308 fd = mtd_check_open(mtd);
310 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
314 mtdEraseInfo.length = erasesize;
316 for (mtdEraseInfo.start = 0;
317 mtdEraseInfo.start < mtdsize;
318 mtdEraseInfo.start += erasesize) {
319 if (mtd_block_is_bad(fd, mtdEraseInfo.start)) {
321 fprintf(stderr, "\nSkipping bad block at 0x%x ", mtdEraseInfo.start);
323 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
324 if(ioctl(fd, MEMERASE, &mtdEraseInfo))
325 fprintf(stderr, "Failed to erase block on %s at 0x%x\n", mtd, mtdEraseInfo.start);
335 mtd_dump(const char *mtd, int part_offset, int size)
337 int ret = 0, offset = 0;
342 fprintf(stderr, "Dumping %s ...\n", mtd);
344 fd = mtd_check_open(mtd);
346 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
354 lseek(fd, part_offset, SEEK_SET);
356 buf = malloc(erasesize);
361 int len = (size > erasesize) ? (erasesize) : (size);
362 int rlen = read(fd, buf, len);
370 if (!rlen || rlen != len)
372 if (mtd_block_is_bad(fd, offset)) {
373 fprintf(stderr, "skipping bad block at 0x%08x\n", offset);
387 mtd_verify(const char *mtd, char *file)
389 uint32_t f_md5[4], m_md5[4];
396 fprintf(stderr, "Verifying %s against %s ...\n", mtd, file);
398 if (stat(file, &s) || md5sum(file, f_md5) < 0) {
399 fprintf(stderr, "Failed to hash %s\n", file);
403 fd = mtd_check_open(mtd);
405 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
412 int len = (s.st_size > sizeof(buf)) ? (sizeof(buf)) : (s.st_size);
413 int rlen = read(fd, buf, len);
423 md5_hash(buf, rlen, &ctx);
425 } while (s.st_size > 0);
427 md5_end(m_md5, &ctx);
429 fprintf(stderr, "%08x%08x%08x%08x - %s\n", m_md5[0], m_md5[1], m_md5[2], m_md5[3], mtd);
430 fprintf(stderr, "%08x%08x%08x%08x - %s\n", f_md5[0], f_md5[1], f_md5[2], f_md5[3], file);
432 ret = memcmp(f_md5, m_md5, sizeof(m_md5));
434 fprintf(stderr, "Success\n");
436 fprintf(stderr, "Failed\n");
444 indicate_writing(const char *mtd)
447 fprintf(stderr, "\nWriting from %s to %s ... ", imagefile, mtd);
450 fprintf(stderr, " [ ]");
454 mtd_write(int imagefd, const char *mtd, char *fis_layout, size_t part_offset)
462 int jffs2_replaced = 0;
463 int skip_bad_blocks = 0;
466 static struct fis_part new_parts[MAX_ARGS];
467 static struct fis_part old_parts[MAX_ARGS];
468 int n_new = 0, n_old = 0;
471 const char *tmp = mtd;
475 memset(&old_parts, 0, sizeof(old_parts));
476 memset(&new_parts, 0, sizeof(new_parts));
479 next = strchr(tmp, ':');
481 next = (char *) tmp + strlen(tmp);
483 memcpy(old_parts[n_old].name, tmp, next - tmp);
489 for (word = strtok_r(fis_layout, ",", &brkt);
491 word = strtok_r(NULL, ",", &brkt)) {
493 tmp = strtok(word, ":");
494 strncpy((char *) new_parts[n_new].name, tmp, sizeof(new_parts[n_new].name) - 1);
496 tmp = strtok(NULL, ":");
500 new_parts[n_new].size = strtoul(tmp, NULL, 0);
502 tmp = strtok(NULL, ":");
506 new_parts[n_new].loadaddr = strtoul(tmp, NULL, 16);
510 ret = fis_validate(old_parts, n_old, new_parts, n_new);
512 fprintf(stderr, "Failed to validate the new FIS partition table\n");
520 if (strchr(mtd, ':')) {
528 next = strchr(mtd, ':');
534 fd = mtd_check_open(mtd);
536 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
539 if (part_offset > 0) {
540 fprintf(stderr, "Seeking on mtd device '%s' to: %zu\n", mtd, part_offset);
541 lseek(fd, part_offset, SEEK_SET);
544 indicate_writing(mtd);
548 /* buffer may contain data already (from trx check or last mtd partition write attempt) */
549 while (buflen < erasesize) {
550 r = read(imagefd, buf + buflen, erasesize - buflen);
552 if ((errno == EINTR) || (errno == EAGAIN))
569 if (buflen < erasesize) {
570 /* Pad block to eraseblock size */
571 memset(&buf[buflen], 0xff, erasesize - buflen);
579 indicate_writing(mtd);
584 if (jffs2file && w >= jffs2_skip_bytes) {
585 if (memcmp(buf, JFFS2_EOF, sizeof(JFFS2_EOF) - 1) == 0) {
587 fprintf(stderr, "\b\b\b ");
589 fprintf(stderr, "\nAppending jffs2 data from %s to %s...", jffs2file, mtd);
590 /* got an EOF marker - this is the place to add some jffs2 data */
591 skip = mtd_replace_jffs2(mtd, fd, e, jffs2file);
594 /* don't add it again */
604 /* no EOF marker, make sure we figure out the last inode number
605 * before appending some data */
606 mtd_parse_jffs2data(buf, jffs2dir);
609 /* need to erase the next block before writing data to it */
612 while (w + buflen > e - skip_bad_blocks) {
614 fprintf(stderr, "\b\b\b[e]");
616 if (mtd_block_is_bad(fd, e)) {
618 fprintf(stderr, "\nSkipping bad block at 0x%08zx ", e);
620 skip_bad_blocks += erasesize;
623 // Move the file pointer along over the bad block.
624 lseek(fd, erasesize, SEEK_CUR);
628 if (mtd_erase_block(fd, e) < 0) {
631 write(fd, buf + offset, e - w);
638 fprintf(stderr, "\b\b\b \n");
641 fprintf(stderr, "Failed to erase block\n");
646 /* erase the chunk */
652 fprintf(stderr, "\b\b\b[w]");
654 if ((result = write(fd, buf + offset, buflen)) < buflen) {
656 fprintf(stderr, "Error writing image.\n");
659 fprintf(stderr, "Insufficient space.\n");
669 if (jffs2_replaced) {
670 switch (imageformat) {
671 case MTD_IMAGE_FORMAT_TRX:
675 case MTD_IMAGE_FORMAT_SEAMA:
677 mtd_fixseama(mtd, 0);
685 fprintf(stderr, "\b\b\b\b ");
688 fprintf(stderr, "\n");
692 if (fis_remap(old_parts, n_old, new_parts, n_new) < 0)
693 fprintf(stderr, "Failed to update the FIS partition table\n");
701 static void usage(void)
703 fprintf(stderr, "Usage: mtd [<options> ...] <command> [<arguments> ...] <device>[:<device>...]\n\n"
704 "The device is in the format of mtdX (eg: mtd4) or its label.\n"
705 "mtd recognizes these commands:\n"
706 " unlock unlock the device\n"
707 " refresh refresh mtd partition\n"
708 " erase erase all data on device\n"
709 " verify <imagefile>|- verify <imagefile> (use - for stdin) to device\n"
710 " write <imagefile>|- write <imagefile> (use - for stdin) to device\n"
711 " jffs2write <file> append <file> to the jffs2 partition on the device\n");
714 " resetbc <device> reset the uboot boot counter\n");
718 " fixtrx fix the checksum in a trx header on first boot\n");
722 " fixseama fix the checksum in a seama header on first boot\n");
725 "Following options are available:\n"
726 " -q quiet mode (once: no [w] on writing,\n"
727 " twice: no status messages)\n"
728 " -n write without first erasing the blocks\n"
729 " -r reboot after successful command\n"
730 " -f force write without trx checks\n"
731 " -e <device> erase <device> before executing the command\n"
732 " -d <name> directory for jffs2write, defaults to \"tmp\"\n"
733 " -j <name> integrate <file> into jffs2 data when writing an image\n"
734 " -s <number> skip the first n bytes when appending data to the jffs2 partiton, defaults to \"0\"\n"
735 " -p write beginning at partition offset\n"
736 " -l <length> the length of data that we want to dump\n");
739 " -o offset offset of the image header in the partition(for fixtrx)\n");
743 " -F <part>[:<size>[:<entrypoint>]][,<part>...]\n"
744 " alter the fis partition table to create new partitions replacing\n"
745 " the partitions provided as argument to the write command\n"
746 " (only valid together with the write command)\n"
749 "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
750 " mtd -r write linux.trx linux\n\n");
754 static void do_reboot(void)
756 fprintf(stderr, "Rebooting ...\n");
759 /* try regular reboot method first */
760 system("/sbin/reboot");
763 /* if we're still alive at this point, force the kernel to reboot */
764 syscall(SYS_reboot,LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,LINUX_REBOOT_CMD_RESTART,NULL);
767 int main (int argc, char **argv)
769 int ch, i, boot, imagefd = 0, force, unlocked;
770 char *erase[MAX_ARGS], *device = NULL;
771 char *fis_layout = NULL;
772 size_t offset = 0, part_offset = 0, dump_len = 0;
792 while ((ch = getopt(argc, argv,
796 "frnqe:d:s:j:p:o:l:")) != -1)
812 jffs2_skip_bytes = strtoul(optarg, 0, 0);
814 fprintf(stderr, "-s: illegal numeric string\n");
823 while ((erase[i] != NULL) && ((i + 1) < MAX_ARGS))
834 part_offset = strtoul(optarg, 0, 0);
836 fprintf(stderr, "-p: illegal numeric string\n");
842 dump_len = strtoul(optarg, 0, 0);
844 fprintf(stderr, "-l: illegal numeric string\n");
850 offset = strtoul(optarg, 0, 0);
852 fprintf(stderr, "-o: illegal numeric string\n");
871 if ((strcmp(argv[0], "unlock") == 0) && (argc == 2)) {
874 } else if ((strcmp(argv[0], "erase") == 0) && (argc == 2)) {
877 } else if (((strcmp(argv[0], "resetbc") == 0) && (argc == 2)) && mtd_resetbc) {
880 } else if (((strcmp(argv[0], "fixtrx") == 0) && (argc == 2)) && mtd_fixtrx) {
883 } else if (((strcmp(argv[0], "fixseama") == 0) && (argc == 2)) && mtd_fixseama) {
886 } else if ((strcmp(argv[0], "verify") == 0) && (argc == 3)) {
890 } else if ((strcmp(argv[0], "dump") == 0) && (argc == 2)) {
893 } else if ((strcmp(argv[0], "write") == 0) && (argc == 3)) {
897 if (strcmp(argv[1], "-") == 0) {
898 imagefile = "<stdin>";
902 if ((imagefd = open(argv[1], O_RDONLY)) < 0) {
903 fprintf(stderr, "Couldn't open image file: %s!\n", imagefile);
908 if (!mtd_check(device)) {
909 fprintf(stderr, "Can't open device for writing!\n");
912 /* check trx file before erasing or writing anything */
913 if (!image_check(imagefd, device) && !force) {
914 fprintf(stderr, "Image check failed.\n");
917 } else if ((strcmp(argv[0], "jffs2write") == 0) && (argc == 3)) {
918 cmd = CMD_JFFS2WRITE;
922 if (!mtd_check(device)) {
923 fprintf(stderr, "Can't open device for writing!\n");
934 while (erase[i] != NULL) {
935 mtd_unlock(erase[i]);
937 if (strcmp(erase[i], device) == 0)
948 mtd_verify(device, imagefile);
951 mtd_dump(device, offset, dump_len);
961 mtd_write(imagefd, device, fis_layout, part_offset);
966 mtd_write_jffs2(device, imagefile, jffs2dir);
970 mtd_fixtrx(device, offset);
980 mtd_fixseama(device, 0);