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>
37 #include <sys/ioctl.h>
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/mount.h>
42 #include <sys/reboot.h>
43 #include <linux/reboot.h>
50 #define JFFS2_DEFAULT_DIR "" /* directory name without /, empty means root dir */
52 #if __BYTE_ORDER == __BIG_ENDIAN
53 #define STORE32_LE(X) ((((X) & 0x000000FF) << 24) | (((X) & 0x0000FF00) << 8) | (((X) & 0x00FF0000) >> 8) | (((X) & 0xFF000000) >> 24))
54 #elif __BYTE_ORDER == __LITTLE_ENDIAN
55 #define STORE32_LE(X) (X)
57 #error unkown endianness!
60 ssize_t pread(int fd, void *buf, size_t count, off_t offset);
61 ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
63 #define TRX_MAGIC 0x30524448 /* "HDR0" */
65 uint32_t magic; /* "HDR0" */
66 uint32_t len; /* Length of file including header */
67 uint32_t crc32; /* 32-bit CRC from flag_version to end of file */
68 uint32_t flag_version; /* 0:15 flags, 16:31 version */
69 uint32_t offsets[3]; /* Offsets of partitions from start of header */
72 static char *buf = NULL;
73 static char *imagefile = NULL;
74 static char *jffs2file = NULL, *jffs2dir = JFFS2_DEFAULT_DIR;
75 static int buflen = 0;
81 int mtd_open(const char *mtd, bool block)
87 int flags = O_RDWR | O_SYNC;
89 if ((fp = fopen("/proc/mtd", "r"))) {
90 while (fgets(dev, sizeof(dev), fp)) {
91 if (sscanf(dev, "mtd%d:", &i) && strstr(dev, mtd)) {
92 snprintf(dev, sizeof(dev), "/dev/mtd%s/%d", (block ? "block" : ""), i);
93 if ((ret=open(dev, flags))<0) {
94 snprintf(dev, sizeof(dev), "/dev/mtd%s%d", (block ? "block" : ""), i);
104 return open(mtd, flags);
107 int mtd_check_open(const char *mtd)
109 struct mtd_info_user mtdInfo;
112 fd = mtd_open(mtd, false);
114 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
118 if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
119 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
123 mtdsize = mtdInfo.size;
124 erasesize = mtdInfo.erasesize;
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);
160 static int mtd_check(const char *mtd)
166 if (strchr(mtd, ':')) {
172 next = strchr(mtd, ':');
178 fd = mtd_check_open(mtd);
183 buf = malloc(erasesize);
196 mtd_unlock(const char *mtd)
198 struct erase_info_user mtdLockInfo;
203 if (strchr(mtd, ':')) {
209 next = strchr(mtd, ':');
215 fd = mtd_check_open(mtd);
217 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
222 fprintf(stderr, "Unlocking %s ...\n", mtd);
224 mtdLockInfo.start = 0;
225 mtdLockInfo.length = mtdsize;
226 ioctl(fd, MEMUNLOCK, &mtdLockInfo);
238 mtd_erase(const char *mtd)
241 struct erase_info_user mtdEraseInfo;
244 fprintf(stderr, "Erasing %s ...\n", mtd);
246 fd = mtd_check_open(mtd);
248 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
252 mtdEraseInfo.length = erasesize;
254 for (mtdEraseInfo.start = 0;
255 mtdEraseInfo.start < mtdsize;
256 mtdEraseInfo.start += erasesize) {
258 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
259 if(ioctl(fd, MEMERASE, &mtdEraseInfo))
260 fprintf(stderr, "Failed to erase block on %s at 0x%x\n", mtd, mtdEraseInfo.start);
269 mtd_fixtrx(const char *mtd, size_t offset)
272 struct trx_header *trx;
278 fprintf(stderr, "Trying to fix trx header in %s at 0x%x...\n", mtd, offset);
280 block_offset = offset & ~(erasesize - 1);
281 offset -= block_offset;
283 fd = mtd_check_open(mtd);
285 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
289 if (block_offset + erasesize > mtdsize) {
290 fprintf(stderr, "Offset too large, device size 0x%x\n", mtdsize);
294 buf = malloc(erasesize);
300 res = pread(fd, buf, erasesize, block_offset);
301 if (res != erasesize) {
306 trx = (struct trx_header *) (buf + offset);
307 if (trx->magic != STORE32_LE(0x30524448)) {
308 fprintf(stderr, "No trx magic found\n");
312 if (trx->len == STORE32_LE(erasesize - offset)) {
314 fprintf(stderr, "Header already fixed, exiting\n");
319 trx->len = STORE32_LE(erasesize - offset);
321 trx->crc32 = STORE32_LE(crc32buf((char*) &trx->flag_version, erasesize - offset - 3*4));
322 if (mtd_erase_block(fd, block_offset)) {
323 fprintf(stderr, "Can't erease block at 0x%x (%s)\n", block_offset, strerror(errno));
328 fprintf(stderr, "New crc32: 0x%x, rewriting block\n", trx->crc32);
330 if (pwrite(fd, buf, erasesize, block_offset) != erasesize) {
331 fprintf(stderr, "Error writing block (%s)\n", strerror(errno));
336 fprintf(stderr, "Done.\n");
345 mtd_refresh(const char *mtd)
350 fprintf(stderr, "Refreshing mtd partition %s ... ", mtd);
352 fd = mtd_check_open(mtd);
354 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
358 if (ioctl(fd, MTDREFRESH, NULL)) {
359 fprintf(stderr, "Failed to refresh the MTD device\n");
366 fprintf(stderr, "\n");
372 indicate_writing(const char *mtd)
375 fprintf(stderr, "\nWriting from %s to %s ... ", imagefile, mtd);
378 fprintf(stderr, " [ ]");
382 mtd_write(int imagefd, const char *mtd, char *fis_layout)
392 static struct fis_part new_parts[MAX_ARGS];
393 static struct fis_part old_parts[MAX_ARGS];
394 int n_new = 0, n_old = 0;
397 const char *tmp = mtd;
401 memset(&old_parts, 0, sizeof(old_parts));
402 memset(&new_parts, 0, sizeof(new_parts));
405 next = strchr(tmp, ':');
407 next = (char *) tmp + strlen(tmp);
409 memcpy(old_parts[n_old].name, tmp, next - tmp);
415 for (word = strtok_r(fis_layout, ",", &brkt);
417 word = strtok_r(NULL, ",", &brkt)) {
419 tmp = strtok(word, ":");
420 strncpy((char *) new_parts[n_new].name, tmp, sizeof(new_parts[n_new].name) - 1);
422 tmp = strtok(NULL, ":");
426 new_parts[n_new].size = strtoul(tmp, NULL, 0);
428 tmp = strtok(NULL, ":");
432 new_parts[n_new].loadaddr = strtoul(tmp, NULL, 16);
436 ret = fis_validate(old_parts, n_old, new_parts, n_new);
438 fprintf(stderr, "Failed to validate the new FIS partition table\n");
446 if (strchr(mtd, ':')) {
454 next = strchr(mtd, ':');
460 fd = mtd_check_open(mtd);
462 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
466 indicate_writing(mtd);
470 /* buffer may contain data already (from trx check or last mtd partition write attempt) */
471 while (buflen < erasesize) {
472 r = read(imagefd, buf + buflen, erasesize - buflen);
474 if ((errno == EINTR) || (errno == EAGAIN))
495 indicate_writing(mtd);
501 if (memcmp(buf, JFFS2_EOF, sizeof(JFFS2_EOF) - 1) == 0) {
503 fprintf(stderr, "\b\b\b ");
505 fprintf(stderr, "\nAppending jffs2 data from %s to %s...", jffs2file, mtd);
506 /* got an EOF marker - this is the place to add some jffs2 data */
507 skip = mtd_replace_jffs2(mtd, fd, e, jffs2file);
516 /* no EOF marker, make sure we figure out the last inode number
517 * before appending some data */
518 mtd_parse_jffs2data(buf, jffs2dir);
521 /* need to erase the next block before writing data to it */
524 while (w + buflen > e) {
526 fprintf(stderr, "\b\b\b[e]");
529 if (mtd_erase_block(fd, e) < 0) {
532 write(fd, buf + offset, e - w);
539 fprintf(stderr, "\b\b\b \n");
542 fprintf(stderr, "Failed to erase block\n");
547 /* erase the chunk */
553 fprintf(stderr, "\b\b\b[w]");
555 if ((result = write(fd, buf + offset, buflen)) < buflen) {
557 fprintf(stderr, "Error writing image.\n");
560 fprintf(stderr, "Insufficient space.\n");
571 fprintf(stderr, "\b\b\b\b ");
575 fprintf(stderr, "\n");
579 if (fis_remap(old_parts, n_old, new_parts, n_new) < 0)
580 fprintf(stderr, "Failed to update the FIS partition table\n");
588 static void usage(void)
590 fprintf(stderr, "Usage: mtd [<options> ...] <command> [<arguments> ...] <device>[:<device>...]\n\n"
591 "The device is in the format of mtdX (eg: mtd4) or its label.\n"
592 "mtd recognizes these commands:\n"
593 " unlock unlock the device\n"
594 " refresh refresh mtd partition\n"
595 " erase erase all data on device\n"
596 " write <imagefile>|- write <imagefile> (use - for stdin) to device\n"
597 " jffs2write <file> append <file> to the jffs2 partition on the device\n"
598 " fixtrx fix the checksum in a trx header on first boot\n"
599 "Following options are available:\n"
600 " -q quiet mode (once: no [w] on writing,\n"
601 " twice: no status messages)\n"
602 " -n write without first erasing the blocks\n"
603 " -r reboot after successful command\n"
604 " -f force write without trx checks\n"
605 " -e <device> erase <device> before executing the command\n"
606 " -d <name> directory for jffs2write, defaults to \"tmp\"\n"
607 " -j <name> integrate <file> into jffs2 data when writing an image\n"
608 " -o offset offset of the trx header in the partition (for fixtrx)\n"
610 " -F <part>[:<size>[:<entrypoint>]][,<part>...]\n"
611 " alter the fis partition table to create new partitions replacing\n"
612 " the partitions provided as argument to the write command\n"
613 " (only valid together with the write command)\n"
616 "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
617 " mtd -r write linux.trx linux\n\n");
621 static void do_reboot(void)
623 fprintf(stderr, "Rebooting ...\n");
626 /* try regular reboot method first */
627 system("/sbin/reboot");
630 /* if we're still alive at this point, force the kernel to reboot */
631 syscall(SYS_reboot,LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,LINUX_REBOOT_CMD_RESTART,NULL);
634 int main (int argc, char **argv)
636 int ch, i, boot, imagefd = 0, force, unlocked;
637 char *erase[MAX_ARGS], *device = NULL;
638 char *fis_layout = NULL;
656 while ((ch = getopt(argc, argv,
660 "frnqe:d:j:o:")) != -1)
679 while ((erase[i] != NULL) && ((i + 1) < MAX_ARGS))
690 offset = strtoul(optarg, 0, 0);
692 fprintf(stderr, "-o: illegal numeric string\n");
711 if ((strcmp(argv[0], "unlock") == 0) && (argc == 2)) {
714 } else if ((strcmp(argv[0], "refresh") == 0) && (argc == 2)) {
717 } else if ((strcmp(argv[0], "erase") == 0) && (argc == 2)) {
720 } else if ((strcmp(argv[0], "fixtrx") == 0) && (argc == 2)) {
723 } else if ((strcmp(argv[0], "write") == 0) && (argc == 3)) {
727 if (strcmp(argv[1], "-") == 0) {
728 imagefile = "<stdin>";
732 if ((imagefd = open(argv[1], O_RDONLY)) < 0) {
733 fprintf(stderr, "Couldn't open image file: %s!\n", imagefile);
738 if (!mtd_check(device)) {
739 fprintf(stderr, "Can't open device for writing!\n");
742 /* check trx file before erasing or writing anything */
743 if (!image_check(imagefd, device) && !force) {
744 fprintf(stderr, "Image check failed.\n");
747 } else if ((strcmp(argv[0], "jffs2write") == 0) && (argc == 3)) {
748 cmd = CMD_JFFS2WRITE;
752 if (!mtd_check(device)) {
753 fprintf(stderr, "Can't open device for writing!\n");
764 while (erase[i] != NULL) {
765 mtd_unlock(erase[i]);
767 if (strcmp(erase[i], device) == 0)
785 mtd_write(imagefd, device, fis_layout);
790 mtd_write_jffs2(device, imagefile, jffs2dir);
796 mtd_fixtrx(device, offset);