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;
80 int mtd_open(const char *mtd, bool block)
86 int flags = O_RDWR | O_SYNC;
88 if ((fp = fopen("/proc/mtd", "r"))) {
89 while (fgets(dev, sizeof(dev), fp)) {
90 if (sscanf(dev, "mtd%d:", &i) && strstr(dev, mtd)) {
91 snprintf(dev, sizeof(dev), "/dev/mtd%s/%d", (block ? "block" : ""), i);
92 if ((ret=open(dev, flags))<0) {
93 snprintf(dev, sizeof(dev), "/dev/mtd%s%d", (block ? "block" : ""), i);
103 return open(mtd, flags);
106 int mtd_check_open(const char *mtd)
108 struct mtd_info_user mtdInfo;
111 fd = mtd_open(mtd, false);
113 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
117 if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
118 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
122 mtdsize = mtdInfo.size;
123 erasesize = mtdInfo.erasesize;
128 int mtd_erase_block(int fd, int offset)
130 struct erase_info_user mtdEraseInfo;
132 mtdEraseInfo.start = offset;
133 mtdEraseInfo.length = erasesize;
134 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
135 if (ioctl (fd, MEMERASE, &mtdEraseInfo) < 0)
141 int mtd_write_buffer(int fd, const char *buf, int offset, int length)
143 lseek(fd, offset, SEEK_SET);
144 write(fd, buf, length);
150 image_check(int imagefd, const char *mtd)
154 ret = trx_check(imagefd, mtd, buf, &buflen);
159 static int mtd_check(const char *mtd)
165 if (strchr(mtd, ':')) {
171 next = strchr(mtd, ':');
177 fd = mtd_check_open(mtd);
182 buf = malloc(erasesize);
195 mtd_unlock(const char *mtd)
197 struct erase_info_user mtdLockInfo;
202 if (strchr(mtd, ':')) {
208 next = strchr(mtd, ':');
214 fd = mtd_check_open(mtd);
216 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
221 fprintf(stderr, "Unlocking %s ...\n", mtd);
223 mtdLockInfo.start = 0;
224 mtdLockInfo.length = mtdsize;
225 ioctl(fd, MEMUNLOCK, &mtdLockInfo);
237 mtd_erase(const char *mtd)
240 struct erase_info_user mtdEraseInfo;
243 fprintf(stderr, "Erasing %s ...\n", mtd);
245 fd = mtd_check_open(mtd);
247 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
251 mtdEraseInfo.length = erasesize;
253 for (mtdEraseInfo.start = 0;
254 mtdEraseInfo.start < mtdsize;
255 mtdEraseInfo.start += erasesize) {
257 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
258 if(ioctl(fd, MEMERASE, &mtdEraseInfo))
259 fprintf(stderr, "Failed to erase block on %s at 0x%x\n", mtd, mtdEraseInfo.start);
268 mtd_fixtrx(const char *mtd, size_t offset)
271 struct trx_header *trx;
277 fprintf(stderr, "Trying to fix trx header in %s at 0x%x...\n", mtd, offset);
279 block_offset = offset & ~(erasesize - 1);
280 offset -= block_offset;
282 fd = mtd_check_open(mtd);
284 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
288 if (block_offset + erasesize > mtdsize) {
289 fprintf(stderr, "Offset too large, device size 0x%x\n", mtdsize);
293 buf = malloc(erasesize);
299 res = pread(fd, buf, erasesize, block_offset);
300 if (res != erasesize) {
305 trx = (struct trx_header *) (buf + offset);
306 if (trx->magic != STORE32_LE(0x30524448)) {
307 fprintf(stderr, "No trx magic found\n");
311 if (trx->len == STORE32_LE(erasesize - offset)) {
313 fprintf(stderr, "Header already fixed, exiting\n");
318 trx->len = STORE32_LE(erasesize - offset);
320 trx->crc32 = STORE32_LE(crc32buf((char*) &trx->flag_version, erasesize - offset - 3*4));
321 if (mtd_erase_block(fd, block_offset)) {
322 fprintf(stderr, "Can't erease block at 0x%x (%s)\n", block_offset, strerror(errno));
327 fprintf(stderr, "New crc32: 0x%x, rewriting block\n", trx->crc32);
329 if (pwrite(fd, buf, erasesize, block_offset) != erasesize) {
330 fprintf(stderr, "Error writing block (%s)\n", strerror(errno));
335 fprintf(stderr, "Done.\n");
344 mtd_refresh(const char *mtd)
349 fprintf(stderr, "Refreshing mtd partition %s ... ", mtd);
351 fd = mtd_check_open(mtd);
353 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
357 if (ioctl(fd, MTDREFRESH, NULL)) {
358 fprintf(stderr, "Failed to refresh the MTD device\n");
365 fprintf(stderr, "\n");
371 mtd_write(int imagefd, const char *mtd, char *fis_layout)
380 static struct fis_part new_parts[MAX_ARGS];
381 static struct fis_part old_parts[MAX_ARGS];
382 int n_new = 0, n_old = 0;
385 const char *tmp = mtd;
389 memset(&old_parts, 0, sizeof(old_parts));
390 memset(&new_parts, 0, sizeof(new_parts));
393 next = strchr(tmp, ':');
395 next = (char *) tmp + strlen(tmp);
397 memcpy(old_parts[n_old].name, tmp, next - tmp);
403 for (word = strtok_r(fis_layout, ",", &brkt);
405 word = strtok_r(NULL, ",", &brkt)) {
407 tmp = strtok(word, ":");
408 strncpy((char *) new_parts[n_new].name, tmp, sizeof(new_parts[n_new].name) - 1);
410 tmp = strtok(NULL, ":");
414 new_parts[n_new].size = strtoul(tmp, NULL, 0);
416 tmp = strtok(NULL, ":");
420 new_parts[n_new].loadaddr = strtoul(tmp, NULL, 16);
424 ret = fis_validate(old_parts, n_old, new_parts, n_new);
426 fprintf(stderr, "Failed to validate the new FIS partition table\n");
434 if (strchr(mtd, ':')) {
442 next = strchr(mtd, ':');
448 fd = mtd_check_open(mtd);
450 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
455 fprintf(stderr, "Writing from %s to %s ... ", imagefile, mtd);
459 fprintf(stderr, " [ ]");
462 /* buffer may contain data already (from trx check or last mtd partition write attempt) */
463 while (buflen < erasesize) {
464 r = read(imagefd, buf + buflen, erasesize - buflen);
466 if ((errno == EINTR) || (errno == EAGAIN))
484 if (memcmp(buf, JFFS2_EOF, sizeof(JFFS2_EOF) - 1) == 0) {
486 fprintf(stderr, "\b\b\b ");
488 fprintf(stderr, "\nAppending jffs2 data from %s to %s...", jffs2file, mtd);
489 /* got an EOF marker - this is the place to add some jffs2 data */
490 mtd_replace_jffs2(mtd, fd, e, jffs2file);
493 /* no EOF marker, make sure we figure out the last inode number
494 * before appending some data */
495 mtd_parse_jffs2data(buf, jffs2dir);
498 /* need to erase the next block before writing data to it */
499 while (w + buflen > e) {
501 fprintf(stderr, "\b\b\b[e]");
504 if (mtd_erase_block(fd, e) < 0) {
507 write(fd, buf + offset, e - w);
514 fprintf(stderr, "\b\b\b \n");
517 fprintf(stderr, "Failed to erase block\n");
522 /* erase the chunk */
527 fprintf(stderr, "\b\b\b[w]");
529 if ((result = write(fd, buf + offset, buflen)) < buflen) {
531 fprintf(stderr, "Error writing image.\n");
534 fprintf(stderr, "Insufficient space.\n");
545 fprintf(stderr, "\b\b\b\b ");
549 fprintf(stderr, "\n");
553 if (fis_remap(old_parts, n_old, new_parts, n_new) < 0)
554 fprintf(stderr, "Failed to update the FIS partition table\n");
562 static void usage(void)
564 fprintf(stderr, "Usage: mtd [<options> ...] <command> [<arguments> ...] <device>[:<device>...]\n\n"
565 "The device is in the format of mtdX (eg: mtd4) or its label.\n"
566 "mtd recognizes these commands:\n"
567 " unlock unlock the device\n"
568 " refresh refresh mtd partition\n"
569 " erase erase all data on device\n"
570 " write <imagefile>|- write <imagefile> (use - for stdin) to device\n"
571 " jffs2write <file> append <file> to the jffs2 partition on the device\n"
572 " fixtrx fix the checksum in a trx header on first boot\n"
573 "Following options are available:\n"
574 " -q quiet mode (once: no [w] on writing,\n"
575 " twice: no status messages)\n"
576 " -r reboot after successful command\n"
577 " -f force write without trx checks\n"
578 " -e <device> erase <device> before executing the command\n"
579 " -d <name> directory for jffs2write, defaults to \"tmp\"\n"
580 " -j <name> integrate <file> into jffs2 data when writing an image\n"
581 " -o offset offset of the trx header in the partition (for fixtrx)\n"
583 " -F <part>[:<size>[:<entrypoint>]][,<part>...]\n"
584 " alter the fis partition table to create new partitions replacing\n"
585 " the partitions provided as argument to the write command\n"
586 " (only valid together with the write command)\n"
589 "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
590 " mtd -r write linux.trx linux\n\n");
594 static void do_reboot(void)
596 fprintf(stderr, "Rebooting ...\n");
599 /* try regular reboot method first */
600 system("/sbin/reboot");
603 /* if we're still alive at this point, force the kernel to reboot */
604 syscall(SYS_reboot,LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,LINUX_REBOOT_CMD_RESTART,NULL);
607 int main (int argc, char **argv)
609 int ch, i, boot, imagefd = 0, force, unlocked;
610 char *erase[MAX_ARGS], *device = NULL;
611 char *fis_layout = NULL;
628 while ((ch = getopt(argc, argv,
632 "frqe:d:j:o:")) != -1)
648 while ((erase[i] != NULL) && ((i + 1) < MAX_ARGS))
659 offset = strtoul(optarg, 0, 0);
661 fprintf(stderr, "-o: illegal numeric string\n");
680 if ((strcmp(argv[0], "unlock") == 0) && (argc == 2)) {
683 } else if ((strcmp(argv[0], "refresh") == 0) && (argc == 2)) {
686 } else if ((strcmp(argv[0], "erase") == 0) && (argc == 2)) {
689 } else if ((strcmp(argv[0], "fixtrx") == 0) && (argc == 2)) {
692 } else if ((strcmp(argv[0], "write") == 0) && (argc == 3)) {
696 if (strcmp(argv[1], "-") == 0) {
697 imagefile = "<stdin>";
701 if ((imagefd = open(argv[1], O_RDONLY)) < 0) {
702 fprintf(stderr, "Couldn't open image file: %s!\n", imagefile);
707 if (!mtd_check(device)) {
708 fprintf(stderr, "Can't open device for writing!\n");
711 /* check trx file before erasing or writing anything */
712 if (!image_check(imagefd, device) && !force) {
713 fprintf(stderr, "Image check failed.\n");
716 } else if ((strcmp(argv[0], "jffs2write") == 0) && (argc == 3)) {
717 cmd = CMD_JFFS2WRITE;
721 if (!mtd_check(device)) {
722 fprintf(stderr, "Can't open device for writing!\n");
733 while (erase[i] != NULL) {
734 mtd_unlock(erase[i]);
736 if (strcmp(erase[i], device) == 0)
754 mtd_write(imagefd, device, fis_layout);
759 mtd_write_jffs2(device, imagefile, jffs2dir);
765 mtd_fixtrx(device, offset);