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
58 #if !defined(__BYTE_ORDER)
59 #error "Unknown byte order"
62 #if __BYTE_ORDER == __BIG_ENDIAN
63 #define cpu_to_be32(x) (x)
64 #define be32_to_cpu(x) (x)
65 #elif __BYTE_ORDER == __LITTLE_ENDIAN
66 #define cpu_to_be32(x) bswap_32(x)
67 #define be32_to_cpu(x) bswap_32(x)
69 #error "Unsupported endianness"
72 enum mtd_image_format {
73 MTD_IMAGE_FORMAT_UNKNOWN,
75 MTD_IMAGE_FORMAT_SEAMA,
78 static char *buf = NULL;
79 static char *imagefile = NULL;
80 static enum mtd_image_format imageformat = MTD_IMAGE_FORMAT_UNKNOWN;
81 static char *jffs2file = NULL, *jffs2dir = JFFS2_DEFAULT_DIR;
82 static int buflen = 0;
87 int jffs2_skip_bytes=0;
90 int mtd_open(const char *mtd, bool block)
96 int flags = O_RDWR | O_SYNC;
99 snprintf(name, sizeof(name), "\"%s\"", mtd);
100 if ((fp = fopen("/proc/mtd", "r"))) {
101 while (fgets(dev, sizeof(dev), fp)) {
102 if (sscanf(dev, "mtd%d:", &i) && strstr(dev, name)) {
103 snprintf(dev, sizeof(dev), "/dev/mtd%s/%d", (block ? "block" : ""), i);
104 if ((ret=open(dev, flags))<0) {
105 snprintf(dev, sizeof(dev), "/dev/mtd%s%d", (block ? "block" : ""), i);
106 ret=open(dev, flags);
115 return open(mtd, flags);
118 int mtd_check_open(const char *mtd)
120 struct mtd_info_user mtdInfo;
123 fd = mtd_open(mtd, false);
125 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
129 if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
130 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
134 mtdsize = mtdInfo.size;
135 erasesize = mtdInfo.erasesize;
136 mtdtype = mtdInfo.type;
141 int mtd_block_is_bad(int fd, int offset)
146 if (mtdtype == MTD_NANDFLASH)
148 r = ioctl(fd, MEMGETBADBLOCK, &o);
151 fprintf(stderr, "Failed to get erase block status\n");
158 int mtd_erase_block(int fd, int offset)
160 struct erase_info_user mtdEraseInfo;
162 mtdEraseInfo.start = offset;
163 mtdEraseInfo.length = erasesize;
164 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
165 if (ioctl (fd, MEMERASE, &mtdEraseInfo) < 0)
171 int mtd_write_buffer(int fd, const char *buf, int offset, int length)
173 lseek(fd, offset, SEEK_SET);
174 write(fd, buf, length);
179 image_check(int imagefd, const char *mtd)
185 while (buflen < sizeof(magic)) {
186 bufread = read(imagefd, buf + buflen, sizeof(magic) - buflen);
193 if (buflen < sizeof(magic)) {
194 fprintf(stdout, "Could not get image magic\n");
198 magic = ((uint32_t *)buf)[0];
200 if (be32_to_cpu(magic) == TRX_MAGIC)
201 imageformat = MTD_IMAGE_FORMAT_TRX;
202 else if (be32_to_cpu(magic) == SEAMA_MAGIC)
203 imageformat = MTD_IMAGE_FORMAT_SEAMA;
205 switch (imageformat) {
206 case MTD_IMAGE_FORMAT_TRX:
208 ret = trx_check(imagefd, mtd, buf, &buflen);
210 case MTD_IMAGE_FORMAT_SEAMA:
214 if (!strcmp(mtd, "firmware"))
223 static int mtd_check(const char *mtd)
229 if (strchr(mtd, ':')) {
235 next = strchr(mtd, ':');
241 fd = mtd_check_open(mtd);
246 buf = malloc(erasesize);
259 mtd_unlock(const char *mtd)
261 struct erase_info_user mtdLockInfo;
266 if (strchr(mtd, ':')) {
272 next = strchr(mtd, ':');
278 fd = mtd_check_open(mtd);
280 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
285 fprintf(stderr, "Unlocking %s ...\n", mtd);
287 mtdLockInfo.start = 0;
288 mtdLockInfo.length = mtdsize;
289 ioctl(fd, MEMUNLOCK, &mtdLockInfo);
301 mtd_erase(const char *mtd)
304 struct erase_info_user mtdEraseInfo;
307 fprintf(stderr, "Erasing %s ...\n", mtd);
309 fd = mtd_check_open(mtd);
311 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
315 mtdEraseInfo.length = erasesize;
317 for (mtdEraseInfo.start = 0;
318 mtdEraseInfo.start < mtdsize;
319 mtdEraseInfo.start += erasesize) {
320 if (mtd_block_is_bad(fd, mtdEraseInfo.start)) {
322 fprintf(stderr, "\nSkipping bad block at 0x%x ", mtdEraseInfo.start);
324 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
325 if(ioctl(fd, MEMERASE, &mtdEraseInfo))
326 fprintf(stderr, "Failed to erase block on %s at 0x%x\n", mtd, mtdEraseInfo.start);
336 mtd_dump(const char *mtd, int part_offset, int size)
338 int ret = 0, offset = 0;
343 fprintf(stderr, "Dumping %s ...\n", mtd);
345 fd = mtd_check_open(mtd);
347 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
355 lseek(fd, part_offset, SEEK_SET);
357 buf = malloc(erasesize);
362 int len = (size > erasesize) ? (erasesize) : (size);
363 int rlen = read(fd, buf, len);
371 if (!rlen || rlen != len)
373 if (mtd_block_is_bad(fd, offset)) {
374 fprintf(stderr, "skipping bad block at 0x%08x\n", offset);
388 mtd_verify(const char *mtd, char *file)
390 uint32_t f_md5[4], m_md5[4];
397 fprintf(stderr, "Verifying %s against %s ...\n", mtd, file);
399 if (stat(file, &s) || md5sum(file, f_md5) < 0) {
400 fprintf(stderr, "Failed to hash %s\n", file);
404 fd = mtd_check_open(mtd);
406 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
413 int len = (s.st_size > sizeof(buf)) ? (sizeof(buf)) : (s.st_size);
414 int rlen = read(fd, buf, len);
424 md5_hash(buf, rlen, &ctx);
426 } while (s.st_size > 0);
428 md5_end(m_md5, &ctx);
430 fprintf(stderr, "%08x%08x%08x%08x - %s\n", m_md5[0], m_md5[1], m_md5[2], m_md5[3], mtd);
431 fprintf(stderr, "%08x%08x%08x%08x - %s\n", f_md5[0], f_md5[1], f_md5[2], f_md5[3], file);
433 ret = memcmp(f_md5, m_md5, sizeof(m_md5));
435 fprintf(stderr, "Success\n");
437 fprintf(stderr, "Failed\n");
445 indicate_writing(const char *mtd)
448 fprintf(stderr, "\nWriting from %s to %s ... ", imagefile, mtd);
451 fprintf(stderr, " [ ]");
455 mtd_write(int imagefd, const char *mtd, char *fis_layout, size_t part_offset)
463 int jffs2_replaced = 0;
464 int skip_bad_blocks = 0;
467 static struct fis_part new_parts[MAX_ARGS];
468 static struct fis_part old_parts[MAX_ARGS];
469 int n_new = 0, n_old = 0;
472 const char *tmp = mtd;
476 memset(&old_parts, 0, sizeof(old_parts));
477 memset(&new_parts, 0, sizeof(new_parts));
480 next = strchr(tmp, ':');
482 next = (char *) tmp + strlen(tmp);
484 memcpy(old_parts[n_old].name, tmp, next - tmp);
490 for (word = strtok_r(fis_layout, ",", &brkt);
492 word = strtok_r(NULL, ",", &brkt)) {
494 tmp = strtok(word, ":");
495 strncpy((char *) new_parts[n_new].name, tmp, sizeof(new_parts[n_new].name) - 1);
497 tmp = strtok(NULL, ":");
501 new_parts[n_new].size = strtoul(tmp, NULL, 0);
503 tmp = strtok(NULL, ":");
507 new_parts[n_new].loadaddr = strtoul(tmp, NULL, 16);
511 ret = fis_validate(old_parts, n_old, new_parts, n_new);
513 fprintf(stderr, "Failed to validate the new FIS partition table\n");
521 if (strchr(mtd, ':')) {
529 next = strchr(mtd, ':');
535 fd = mtd_check_open(mtd);
537 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
540 if (part_offset > 0) {
541 fprintf(stderr, "Seeking on mtd device '%s' to: %zu\n", mtd, part_offset);
542 lseek(fd, part_offset, SEEK_SET);
545 indicate_writing(mtd);
549 /* buffer may contain data already (from trx check or last mtd partition write attempt) */
550 while (buflen < erasesize) {
551 r = read(imagefd, buf + buflen, erasesize - buflen);
553 if ((errno == EINTR) || (errno == EAGAIN))
570 if (buflen < erasesize) {
571 /* Pad block to eraseblock size */
572 memset(&buf[buflen], 0xff, erasesize - buflen);
580 indicate_writing(mtd);
585 if (jffs2file && w >= jffs2_skip_bytes) {
586 if (memcmp(buf, JFFS2_EOF, sizeof(JFFS2_EOF) - 1) == 0) {
588 fprintf(stderr, "\b\b\b ");
590 fprintf(stderr, "\nAppending jffs2 data from %s to %s..\n.", jffs2file, mtd);
591 /* got an EOF marker - this is the place to add some jffs2 data */
592 skip = mtd_replace_jffs2(mtd, fd, e, jffs2file);
595 /* don't add it again */
605 /* no EOF marker, make sure we figure out the last inode number
606 * before appending some data */
607 mtd_parse_jffs2data(buf, jffs2dir);
610 /* need to erase the next block before writing data to it */
613 while (w + buflen > e - skip_bad_blocks) {
615 fprintf(stderr, "\b\b\b[e]");
617 if (mtd_block_is_bad(fd, e)) {
619 fprintf(stderr, "\nSkipping bad block at 0x%08zx ", e);
621 skip_bad_blocks += erasesize;
624 // Move the file pointer along over the bad block.
625 lseek(fd, erasesize, SEEK_CUR);
629 if (mtd_erase_block(fd, e) < 0) {
632 write(fd, buf + offset, e - w);
639 fprintf(stderr, "\b\b\b \n");
642 fprintf(stderr, "Failed to erase block\n");
647 /* erase the chunk */
653 fprintf(stderr, "\b\b\b[w]");
655 if ((result = write(fd, buf + offset, buflen)) < buflen) {
657 fprintf(stderr, "Error writing image.\n");
660 fprintf(stderr, "Insufficient space.\n");
670 if (jffs2_replaced) {
671 switch (imageformat) {
672 case MTD_IMAGE_FORMAT_TRX:
676 case MTD_IMAGE_FORMAT_SEAMA:
678 mtd_fixseama(mtd, 0, 0);
686 fprintf(stderr, "\b\b\b\b ");
689 fprintf(stderr, "\n");
693 if (fis_remap(old_parts, n_old, new_parts, n_new) < 0)
694 fprintf(stderr, "Failed to update the FIS partition table\n");
702 static void usage(void)
704 fprintf(stderr, "Usage: mtd [<options> ...] <command> [<arguments> ...] <device>[:<device>...]\n\n"
705 "The device is in the format of mtdX (eg: mtd4) or its label.\n"
706 "mtd recognizes these commands:\n"
707 " unlock unlock the device\n"
708 " refresh refresh mtd partition\n"
709 " erase erase all data on device\n"
710 " verify <imagefile>|- verify <imagefile> (use - for stdin) to device\n"
711 " write <imagefile>|- write <imagefile> (use - for stdin) to device\n"
712 " jffs2write <file> append <file> to the jffs2 partition on the device\n");
715 " resetbc <device> reset the uboot boot counter\n");
719 " fixtrx fix the checksum in a trx header on first boot\n");
723 " fixseama fix the checksum in a seama header on first boot\n");
726 "Following options are available:\n"
727 " -q quiet mode (once: no [w] on writing,\n"
728 " twice: no status messages)\n"
729 " -n write without first erasing the blocks\n"
730 " -r reboot after successful command\n"
731 " -f force write without trx checks\n"
732 " -e <device> erase <device> before executing the command\n"
733 " -d <name> directory for jffs2write, defaults to \"tmp\"\n"
734 " -j <name> integrate <file> into jffs2 data when writing an image\n"
735 " -s <number> skip the first n bytes when appending data to the jffs2 partiton, defaults to \"0\"\n"
736 " -p <number> write beginning at partition offset\n"
737 " -l <length> the length of data that we want to dump\n");
740 " -o offset offset of the image header in the partition(for fixtrx)\n");
742 if (mtd_fixtrx || mtd_fixseama) {
744 " -c datasize amount of data to be used for checksum calculation (for fixtrx / fixseama)\n");
748 " -F <part>[:<size>[:<entrypoint>]][,<part>...]\n"
749 " alter the fis partition table to create new partitions replacing\n"
750 " the partitions provided as argument to the write command\n"
751 " (only valid together with the write command)\n"
754 "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
755 " mtd -r write linux.trx linux\n\n");
759 static void do_reboot(void)
761 fprintf(stderr, "Rebooting ...\n");
764 /* try regular reboot method first */
765 system("/sbin/reboot");
768 /* if we're still alive at this point, force the kernel to reboot */
769 syscall(SYS_reboot,LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,LINUX_REBOOT_CMD_RESTART,NULL);
772 int main (int argc, char **argv)
774 int ch, i, boot, imagefd = 0, force, unlocked;
775 char *erase[MAX_ARGS], *device = NULL;
776 char *fis_layout = NULL;
777 size_t offset = 0, data_size = 0, part_offset = 0, dump_len = 0;
797 while ((ch = getopt(argc, argv,
801 "frnqe:d:s:j:p:o:c:l:")) != -1)
817 jffs2_skip_bytes = strtoul(optarg, 0, 0);
819 fprintf(stderr, "-s: illegal numeric string\n");
828 while ((erase[i] != NULL) && ((i + 1) < MAX_ARGS))
839 part_offset = strtoul(optarg, 0, 0);
841 fprintf(stderr, "-p: illegal numeric string\n");
847 dump_len = strtoul(optarg, 0, 0);
849 fprintf(stderr, "-l: illegal numeric string\n");
855 offset = strtoul(optarg, 0, 0);
857 fprintf(stderr, "-o: illegal numeric string\n");
863 data_size = strtoul(optarg, 0, 0);
865 fprintf(stderr, "-c: illegal numeric string\n");
884 if ((strcmp(argv[0], "unlock") == 0) && (argc == 2)) {
887 } else if ((strcmp(argv[0], "erase") == 0) && (argc == 2)) {
890 } else if (((strcmp(argv[0], "resetbc") == 0) && (argc == 2)) && mtd_resetbc) {
893 } else if (((strcmp(argv[0], "fixtrx") == 0) && (argc == 2)) && mtd_fixtrx) {
896 } else if (((strcmp(argv[0], "fixseama") == 0) && (argc == 2)) && mtd_fixseama) {
899 } else if ((strcmp(argv[0], "verify") == 0) && (argc == 3)) {
903 } else if ((strcmp(argv[0], "dump") == 0) && (argc == 2)) {
906 } else if ((strcmp(argv[0], "write") == 0) && (argc == 3)) {
910 if (strcmp(argv[1], "-") == 0) {
911 imagefile = "<stdin>";
915 if ((imagefd = open(argv[1], O_RDONLY)) < 0) {
916 fprintf(stderr, "Couldn't open image file: %s!\n", imagefile);
921 if (!mtd_check(device)) {
922 fprintf(stderr, "Can't open device for writing!\n");
925 /* check trx file before erasing or writing anything */
926 if (!image_check(imagefd, device) && !force) {
927 fprintf(stderr, "Image check failed.\n");
930 } else if ((strcmp(argv[0], "jffs2write") == 0) && (argc == 3)) {
931 cmd = CMD_JFFS2WRITE;
935 if (!mtd_check(device)) {
936 fprintf(stderr, "Can't open device for writing!\n");
947 while (erase[i] != NULL) {
948 mtd_unlock(erase[i]);
950 if (strcmp(erase[i], device) == 0)
961 mtd_verify(device, imagefile);
964 mtd_dump(device, offset, dump_len);
974 mtd_write(imagefd, device, fis_layout, part_offset);
979 mtd_write_jffs2(device, imagefile, jffs2dir);
983 mtd_fixtrx(device, offset, data_size);
993 mtd_fixseama(device, 0, data_size);