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.
30 #include <sys/ioctl.h>
31 #include <sys/syscall.h>
36 #include <sys/ioctl.h>
37 #include <sys/types.h>
38 #include <sys/param.h>
39 #include <sys/mount.h>
41 #include <sys/reboot.h>
42 #include <linux/reboot.h>
43 #include <mtd/mtd-user.h>
47 #include <libubox/md5.h>
50 #define JFFS2_DEFAULT_DIR "" /* directory name without /, empty means root dir */
52 static char *buf = NULL;
53 static char *imagefile = NULL;
54 static char *jffs2file = NULL, *jffs2dir = JFFS2_DEFAULT_DIR;
55 static int buflen = 0;
60 int jffs2_skip_bytes=0;
63 int mtd_open(const char *mtd, bool block)
69 int flags = O_RDWR | O_SYNC;
71 if ((fp = fopen("/proc/mtd", "r"))) {
72 while (fgets(dev, sizeof(dev), fp)) {
73 if (sscanf(dev, "mtd%d:", &i) && strstr(dev, mtd)) {
74 snprintf(dev, sizeof(dev), "/dev/mtd%s/%d", (block ? "block" : ""), i);
75 if ((ret=open(dev, flags))<0) {
76 snprintf(dev, sizeof(dev), "/dev/mtd%s%d", (block ? "block" : ""), i);
86 return open(mtd, flags);
89 int mtd_check_open(const char *mtd)
91 struct mtd_info_user mtdInfo;
94 fd = mtd_open(mtd, false);
96 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
100 if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
101 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
105 mtdsize = mtdInfo.size;
106 erasesize = mtdInfo.erasesize;
107 mtdtype = mtdInfo.type;
112 int mtd_block_is_bad(int fd, int offset)
117 if (mtdtype == MTD_NANDFLASH)
119 r = ioctl(fd, MEMGETBADBLOCK, &o);
122 fprintf(stderr, "Failed to get erase block status\n");
129 int mtd_erase_block(int fd, int offset)
131 struct erase_info_user mtdEraseInfo;
133 mtdEraseInfo.start = offset;
134 mtdEraseInfo.length = erasesize;
135 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
136 if (ioctl (fd, MEMERASE, &mtdEraseInfo) < 0)
142 int mtd_write_buffer(int fd, const char *buf, int offset, int length)
144 lseek(fd, offset, SEEK_SET);
145 write(fd, buf, length);
151 image_check(int imagefd, const char *mtd)
155 ret = trx_check(imagefd, mtd, buf, &buflen);
161 static int mtd_check(const char *mtd)
167 if (strchr(mtd, ':')) {
173 next = strchr(mtd, ':');
179 fd = mtd_check_open(mtd);
184 buf = malloc(erasesize);
197 mtd_unlock(const char *mtd)
199 struct erase_info_user mtdLockInfo;
204 if (strchr(mtd, ':')) {
210 next = strchr(mtd, ':');
216 fd = mtd_check_open(mtd);
218 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
223 fprintf(stderr, "Unlocking %s ...\n", mtd);
225 mtdLockInfo.start = 0;
226 mtdLockInfo.length = mtdsize;
227 ioctl(fd, MEMUNLOCK, &mtdLockInfo);
239 mtd_erase(const char *mtd)
242 struct erase_info_user mtdEraseInfo;
245 fprintf(stderr, "Erasing %s ...\n", mtd);
247 fd = mtd_check_open(mtd);
249 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
253 mtdEraseInfo.length = erasesize;
255 for (mtdEraseInfo.start = 0;
256 mtdEraseInfo.start < mtdsize;
257 mtdEraseInfo.start += erasesize) {
258 if (mtd_block_is_bad(fd, mtdEraseInfo.start)) {
260 fprintf(stderr, "\nSkipping bad block at 0x%x ", mtdEraseInfo.start);
262 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
263 if(ioctl(fd, MEMERASE, &mtdEraseInfo))
264 fprintf(stderr, "Failed to erase block on %s at 0x%x\n", mtd, mtdEraseInfo.start);
274 mtd_verify(const char *mtd, char *file)
276 uint32_t f_md5[4], m_md5[4];
283 fprintf(stderr, "Verifying %s against %s ...\n", mtd, file);
285 if (stat(file, &s) || md5sum(file, f_md5)) {
286 fprintf(stderr, "Failed to hash %s\n", file);
290 fd = mtd_check_open(mtd);
292 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
299 int len = (s.st_size > sizeof(buf)) ? (sizeof(buf)) : (s.st_size);
300 int rlen = read(fd, buf, len);
310 md5_hash(buf, rlen, &ctx);
312 } while (s.st_size > 0);
314 md5_end(m_md5, &ctx);
316 fprintf(stderr, "%08x%08x%08x%08x - %s\n", m_md5[0], m_md5[1], m_md5[2], m_md5[3], mtd);
317 fprintf(stderr, "%08x%08x%08x%08x - %s\n", f_md5[0], f_md5[1], f_md5[2], f_md5[3], file);
319 ret = memcmp(f_md5, m_md5, sizeof(m_md5));
321 fprintf(stderr, "Success\n");
323 fprintf(stderr, "Failed\n");
331 indicate_writing(const char *mtd)
334 fprintf(stderr, "\nWriting from %s to %s ... ", imagefile, mtd);
337 fprintf(stderr, " [ ]");
341 mtd_write(int imagefd, const char *mtd, char *fis_layout, size_t part_offset)
349 int jffs2_replaced = 0;
350 int skip_bad_blocks = 0;
353 static struct fis_part new_parts[MAX_ARGS];
354 static struct fis_part old_parts[MAX_ARGS];
355 int n_new = 0, n_old = 0;
358 const char *tmp = mtd;
362 memset(&old_parts, 0, sizeof(old_parts));
363 memset(&new_parts, 0, sizeof(new_parts));
366 next = strchr(tmp, ':');
368 next = (char *) tmp + strlen(tmp);
370 memcpy(old_parts[n_old].name, tmp, next - tmp);
376 for (word = strtok_r(fis_layout, ",", &brkt);
378 word = strtok_r(NULL, ",", &brkt)) {
380 tmp = strtok(word, ":");
381 strncpy((char *) new_parts[n_new].name, tmp, sizeof(new_parts[n_new].name) - 1);
383 tmp = strtok(NULL, ":");
387 new_parts[n_new].size = strtoul(tmp, NULL, 0);
389 tmp = strtok(NULL, ":");
393 new_parts[n_new].loadaddr = strtoul(tmp, NULL, 16);
397 ret = fis_validate(old_parts, n_old, new_parts, n_new);
399 fprintf(stderr, "Failed to validate the new FIS partition table\n");
407 if (strchr(mtd, ':')) {
415 next = strchr(mtd, ':');
421 fd = mtd_check_open(mtd);
423 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
426 if (part_offset > 0) {
427 fprintf(stderr, "Seeking on mtd device '%s' to: %zu\n", mtd, part_offset);
428 lseek(fd, part_offset, SEEK_SET);
431 indicate_writing(mtd);
435 /* buffer may contain data already (from trx check or last mtd partition write attempt) */
436 while (buflen < erasesize) {
437 r = read(imagefd, buf + buflen, erasesize - buflen);
439 if ((errno == EINTR) || (errno == EAGAIN))
456 if (buflen < erasesize) {
457 /* Pad block to eraseblock size */
458 memset(&buf[buflen], 0xff, erasesize - buflen);
466 indicate_writing(mtd);
471 if (jffs2file && w >= jffs2_skip_bytes) {
472 if (memcmp(buf, JFFS2_EOF, sizeof(JFFS2_EOF) - 1) == 0) {
474 fprintf(stderr, "\b\b\b ");
476 fprintf(stderr, "\nAppending jffs2 data from %s to %s...", jffs2file, mtd);
477 /* got an EOF marker - this is the place to add some jffs2 data */
478 skip = mtd_replace_jffs2(mtd, fd, e, jffs2file);
481 /* don't add it again */
491 /* no EOF marker, make sure we figure out the last inode number
492 * before appending some data */
493 mtd_parse_jffs2data(buf, jffs2dir);
496 /* need to erase the next block before writing data to it */
499 while (w + buflen > e - skip_bad_blocks) {
501 fprintf(stderr, "\b\b\b[e]");
503 if (mtd_block_is_bad(fd, e)) {
505 fprintf(stderr, "\nSkipping bad block at 0x%08x ", e);
507 skip_bad_blocks += erasesize;
510 // Move the file pointer along over the bad block.
511 lseek(fd, erasesize, SEEK_CUR);
515 if (mtd_erase_block(fd, e) < 0) {
518 write(fd, buf + offset, e - w);
525 fprintf(stderr, "\b\b\b \n");
528 fprintf(stderr, "Failed to erase block\n");
533 /* erase the chunk */
539 fprintf(stderr, "\b\b\b[w]");
541 if ((result = write(fd, buf + offset, buflen)) < buflen) {
543 fprintf(stderr, "Error writing image.\n");
546 fprintf(stderr, "Insufficient space.\n");
556 if (jffs2_replaced && trx_fixup) {
561 fprintf(stderr, "\b\b\b\b ");
565 fprintf(stderr, "\n");
569 if (fis_remap(old_parts, n_old, new_parts, n_new) < 0)
570 fprintf(stderr, "Failed to update the FIS partition table\n");
578 static void usage(void)
580 fprintf(stderr, "Usage: mtd [<options> ...] <command> [<arguments> ...] <device>[:<device>...]\n\n"
581 "The device is in the format of mtdX (eg: mtd4) or its label.\n"
582 "mtd recognizes these commands:\n"
583 " unlock unlock the device\n"
584 " refresh refresh mtd partition\n"
585 " erase erase all data on device\n"
586 " verify <imagefile>|- verify <imagefile> (use - for stdin) to device\n"
587 " write <imagefile>|- write <imagefile> (use - for stdin) to device\n"
588 " jffs2write <file> append <file> to the jffs2 partition on the device\n");
591 " fixtrx fix the checksum in a trx header on first boot\n");
595 " fixseama fix the checksum in a seama header on first boot\n");
598 "Following options are available:\n"
599 " -q quiet mode (once: no [w] on writing,\n"
600 " twice: no status messages)\n"
601 " -n write without first erasing the blocks\n"
602 " -r reboot after successful command\n"
603 " -f force write without trx checks\n"
604 " -e <device> erase <device> before executing the command\n"
605 " -d <name> directory for jffs2write, defaults to \"tmp\"\n"
606 " -j <name> integrate <file> into jffs2 data when writing an image\n"
607 " -s <number> skip the first n bytes when appending data to the jffs2 partiton, defaults to \"0\"\n"
608 " -p write beginning at partition offset\n");
611 " -o offset offset of the image header in the partition(for fixtrx)\n");
615 " -F <part>[:<size>[:<entrypoint>]][,<part>...]\n"
616 " alter the fis partition table to create new partitions replacing\n"
617 " the partitions provided as argument to the write command\n"
618 " (only valid together with the write command)\n"
621 "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
622 " mtd -r write linux.trx linux\n\n");
626 static void do_reboot(void)
628 fprintf(stderr, "Rebooting ...\n");
631 /* try regular reboot method first */
632 system("/sbin/reboot");
635 /* if we're still alive at this point, force the kernel to reboot */
636 syscall(SYS_reboot,LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,LINUX_REBOOT_CMD_RESTART,NULL);
639 int main (int argc, char **argv)
641 int ch, i, boot, imagefd = 0, force, unlocked;
642 char *erase[MAX_ARGS], *device = NULL;
643 char *fis_layout = NULL;
644 size_t offset = 0, part_offset = 0;
662 while ((ch = getopt(argc, argv,
666 "frnqe:d:s:j:p:o:")) != -1)
682 jffs2_skip_bytes = strtoul(optarg, 0, 0);
684 fprintf(stderr, "-s: illegal numeric string\n");
693 while ((erase[i] != NULL) && ((i + 1) < MAX_ARGS))
704 part_offset = strtoul(optarg, 0, 0);
706 fprintf(stderr, "-p: illegal numeric string\n");
712 fprintf(stderr, "-o: is not available on this platform\n");
716 offset = strtoul(optarg, 0, 0);
718 fprintf(stderr, "-o: illegal numeric string\n");
737 if ((strcmp(argv[0], "unlock") == 0) && (argc == 2)) {
740 } else if ((strcmp(argv[0], "erase") == 0) && (argc == 2)) {
743 } else if (((strcmp(argv[0], "fixtrx") == 0) && (argc == 2)) && mtd_fixtrx) {
746 } else if (((strcmp(argv[0], "fixseama") == 0) && (argc == 2)) && mtd_fixseama) {
749 } else if ((strcmp(argv[0], "verify") == 0) && (argc == 3)) {
753 } else if ((strcmp(argv[0], "write") == 0) && (argc == 3)) {
757 if (strcmp(argv[1], "-") == 0) {
758 imagefile = "<stdin>";
762 if ((imagefd = open(argv[1], O_RDONLY)) < 0) {
763 fprintf(stderr, "Couldn't open image file: %s!\n", imagefile);
768 if (!mtd_check(device)) {
769 fprintf(stderr, "Can't open device for writing!\n");
772 /* check trx file before erasing or writing anything */
773 if (!image_check(imagefd, device) && !force) {
774 fprintf(stderr, "Image check failed.\n");
777 } else if ((strcmp(argv[0], "jffs2write") == 0) && (argc == 3)) {
778 cmd = CMD_JFFS2WRITE;
782 if (!mtd_check(device)) {
783 fprintf(stderr, "Can't open device for writing!\n");
794 while (erase[i] != NULL) {
795 mtd_unlock(erase[i]);
797 if (strcmp(erase[i], device) == 0)
808 mtd_verify(device, imagefile);
818 mtd_write(imagefd, device, fis_layout, part_offset);
823 mtd_write_jffs2(device, imagefile, jffs2dir);
827 mtd_fixtrx(device, offset);
831 mtd_fixseama(device, 0);