92873ca19b775eb84bb714d1cfc0e643b7ef78a4
[openwrt/openwrt.git] / package / mtd / src / mtd.c
1 /*
2 * mtd - simple memory technology device manipulation tool
3 *
4 * Copyright (C) 2005 Waldemar Brodkorb <wbx@dass-it.de>,
5 * Copyright (C) 2005-2009 Felix Fietkau <nbd@openwrt.org>
6 *
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.
10 *
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.
15 *
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.
19 *
20 *
21 * The code is based on the linux-mtd examples.
22 */
23
24 #include <limits.h>
25 #include <unistd.h>
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <stdint.h>
29 #include <signal.h>
30 #include <sys/ioctl.h>
31 #include <sys/syscall.h>
32 #include <fcntl.h>
33 #include <errno.h>
34 #include <error.h>
35 #include <time.h>
36 #include <string.h>
37 #include <sys/ioctl.h>
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/mount.h>
41 #include <sys/stat.h>
42 #include <sys/reboot.h>
43 #include <linux/reboot.h>
44 #include <mtd/mtd-user.h>
45 #include "fis.h"
46 #include "mtd.h"
47
48 #ifndef MTDREFRESH
49 #define MTDREFRESH _IO('M', 50)
50 #endif
51
52 #define MAX_ARGS 8
53 #define JFFS2_DEFAULT_DIR "" /* directory name without /, empty means root dir */
54
55 static char *buf = NULL;
56 static char *imagefile = NULL;
57 static char *jffs2file = NULL, *jffs2dir = JFFS2_DEFAULT_DIR;
58 static int buflen = 0;
59 int quiet;
60 int no_erase;
61 int mtdsize = 0;
62 int erasesize = 0;
63
64 int mtd_open(const char *mtd, bool block)
65 {
66 FILE *fp;
67 char dev[PATH_MAX];
68 int i;
69 int ret;
70 int flags = O_RDWR | O_SYNC;
71
72 if ((fp = fopen("/proc/mtd", "r"))) {
73 while (fgets(dev, sizeof(dev), fp)) {
74 if (sscanf(dev, "mtd%d:", &i) && strstr(dev, mtd)) {
75 snprintf(dev, sizeof(dev), "/dev/mtd%s/%d", (block ? "block" : ""), i);
76 if ((ret=open(dev, flags))<0) {
77 snprintf(dev, sizeof(dev), "/dev/mtd%s%d", (block ? "block" : ""), i);
78 ret=open(dev, flags);
79 }
80 fclose(fp);
81 return ret;
82 }
83 }
84 fclose(fp);
85 }
86
87 return open(mtd, flags);
88 }
89
90 int mtd_check_open(const char *mtd)
91 {
92 struct mtd_info_user mtdInfo;
93 int fd;
94
95 fd = mtd_open(mtd, false);
96 if(fd < 0) {
97 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
98 return -1;
99 }
100
101 if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
102 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
103 close(fd);
104 return -1;
105 }
106 mtdsize = mtdInfo.size;
107 erasesize = mtdInfo.erasesize;
108
109 return fd;
110 }
111
112 int mtd_erase_block(int fd, int offset)
113 {
114 struct erase_info_user mtdEraseInfo;
115
116 mtdEraseInfo.start = offset;
117 mtdEraseInfo.length = erasesize;
118 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
119 if (ioctl (fd, MEMERASE, &mtdEraseInfo) < 0)
120 return -1;
121
122 return 0;
123 }
124
125 int mtd_write_buffer(int fd, const char *buf, int offset, int length)
126 {
127 lseek(fd, offset, SEEK_SET);
128 write(fd, buf, length);
129 return 0;
130 }
131
132
133 static int
134 image_check(int imagefd, const char *mtd)
135 {
136 int ret = 1;
137 if (trx_check) {
138 ret = trx_check(imagefd, mtd, buf, &buflen);
139 }
140 return ret;
141 }
142
143 static int mtd_check(const char *mtd)
144 {
145 char *next = NULL;
146 char *str = NULL;
147 int fd;
148
149 if (strchr(mtd, ':')) {
150 str = strdup(mtd);
151 mtd = str;
152 }
153
154 do {
155 next = strchr(mtd, ':');
156 if (next) {
157 *next = 0;
158 next++;
159 }
160
161 fd = mtd_check_open(mtd);
162 if (fd < 0)
163 return 0;
164
165 if (!buf)
166 buf = malloc(erasesize);
167
168 close(fd);
169 mtd = next;
170 } while (next);
171
172 if (str)
173 free(str);
174
175 return 1;
176 }
177
178 static int
179 mtd_unlock(const char *mtd)
180 {
181 struct erase_info_user mtdLockInfo;
182 char *next = NULL;
183 char *str = NULL;
184 int fd;
185
186 if (strchr(mtd, ':')) {
187 str = strdup(mtd);
188 mtd = str;
189 }
190
191 do {
192 next = strchr(mtd, ':');
193 if (next) {
194 *next = 0;
195 next++;
196 }
197
198 fd = mtd_check_open(mtd);
199 if(fd < 0) {
200 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
201 exit(1);
202 }
203
204 if (quiet < 2)
205 fprintf(stderr, "Unlocking %s ...\n", mtd);
206
207 mtdLockInfo.start = 0;
208 mtdLockInfo.length = mtdsize;
209 ioctl(fd, MEMUNLOCK, &mtdLockInfo);
210 close(fd);
211 mtd = next;
212 } while (next);
213
214 if (str)
215 free(str);
216
217 return 0;
218 }
219
220 static int
221 mtd_erase(const char *mtd)
222 {
223 int fd;
224 struct erase_info_user mtdEraseInfo;
225
226 if (quiet < 2)
227 fprintf(stderr, "Erasing %s ...\n", mtd);
228
229 fd = mtd_check_open(mtd);
230 if(fd < 0) {
231 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
232 exit(1);
233 }
234
235 mtdEraseInfo.length = erasesize;
236
237 for (mtdEraseInfo.start = 0;
238 mtdEraseInfo.start < mtdsize;
239 mtdEraseInfo.start += erasesize) {
240
241 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
242 if(ioctl(fd, MEMERASE, &mtdEraseInfo))
243 fprintf(stderr, "Failed to erase block on %s at 0x%x\n", mtd, mtdEraseInfo.start);
244 }
245
246 close(fd);
247 return 0;
248
249 }
250
251 static int
252 mtd_refresh(const char *mtd)
253 {
254 int fd;
255
256 if (quiet < 2)
257 fprintf(stderr, "Refreshing mtd partition %s ... ", mtd);
258
259 fd = mtd_check_open(mtd);
260 if(fd < 0) {
261 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
262 exit(1);
263 }
264
265 if (ioctl(fd, MTDREFRESH, NULL)) {
266 fprintf(stderr, "Failed to refresh the MTD device\n");
267 close(fd);
268 exit(1);
269 }
270 close(fd);
271
272 if (quiet < 2)
273 fprintf(stderr, "\n");
274
275 return 0;
276 }
277
278 static void
279 indicate_writing(const char *mtd)
280 {
281 if (quiet < 2)
282 fprintf(stderr, "\nWriting from %s to %s ... ", imagefile, mtd);
283
284 if (!quiet)
285 fprintf(stderr, " [ ]");
286 }
287
288 static int
289 mtd_write(int imagefd, const char *mtd, char *fis_layout, size_t part_offset)
290 {
291 char *next = NULL;
292 char *str = NULL;
293 int fd, result;
294 ssize_t r, w, e;
295 ssize_t skip = 0;
296 uint32_t offset = 0;
297
298 #ifdef FIS_SUPPORT
299 static struct fis_part new_parts[MAX_ARGS];
300 static struct fis_part old_parts[MAX_ARGS];
301 int n_new = 0, n_old = 0;
302
303 if (fis_layout) {
304 const char *tmp = mtd;
305 char *word, *brkt;
306 int ret;
307
308 memset(&old_parts, 0, sizeof(old_parts));
309 memset(&new_parts, 0, sizeof(new_parts));
310
311 do {
312 next = strchr(tmp, ':');
313 if (!next)
314 next = (char *) tmp + strlen(tmp);
315
316 memcpy(old_parts[n_old].name, tmp, next - tmp);
317
318 n_old++;
319 tmp = next + 1;
320 } while(*next);
321
322 for (word = strtok_r(fis_layout, ",", &brkt);
323 word;
324 word = strtok_r(NULL, ",", &brkt)) {
325
326 tmp = strtok(word, ":");
327 strncpy((char *) new_parts[n_new].name, tmp, sizeof(new_parts[n_new].name) - 1);
328
329 tmp = strtok(NULL, ":");
330 if (!tmp)
331 goto next;
332
333 new_parts[n_new].size = strtoul(tmp, NULL, 0);
334
335 tmp = strtok(NULL, ":");
336 if (!tmp)
337 goto next;
338
339 new_parts[n_new].loadaddr = strtoul(tmp, NULL, 16);
340 next:
341 n_new++;
342 }
343 ret = fis_validate(old_parts, n_old, new_parts, n_new);
344 if (ret < 0) {
345 fprintf(stderr, "Failed to validate the new FIS partition table\n");
346 exit(1);
347 }
348 if (ret == 0)
349 fis_layout = NULL;
350 }
351 #endif
352
353 if (strchr(mtd, ':')) {
354 str = strdup(mtd);
355 mtd = str;
356 }
357
358 r = 0;
359
360 resume:
361 next = strchr(mtd, ':');
362 if (next) {
363 *next = 0;
364 next++;
365 }
366
367 fd = mtd_check_open(mtd);
368 if(fd < 0) {
369 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
370 exit(1);
371 }
372
373 if (part_offset > 0) {
374 fprintf(stderr, "Seeking on mtd device '%s' to: %u\n", mtd, part_offset);
375 lseek(fd, part_offset, SEEK_SET);
376 }
377
378 indicate_writing(mtd);
379
380 w = e = 0;
381 for (;;) {
382 /* buffer may contain data already (from trx check or last mtd partition write attempt) */
383 while (buflen < erasesize) {
384 r = read(imagefd, buf + buflen, erasesize - buflen);
385 if (r < 0) {
386 if ((errno == EINTR) || (errno == EAGAIN))
387 continue;
388 else {
389 perror("read");
390 break;
391 }
392 }
393
394 if (r == 0)
395 break;
396
397 buflen += r;
398 }
399
400 if (buflen == 0)
401 break;
402
403 if (skip > 0) {
404 skip -= buflen;
405 buflen = 0;
406 if (skip <= 0)
407 indicate_writing(mtd);
408
409 continue;
410 }
411
412 if (jffs2file) {
413 if (memcmp(buf, JFFS2_EOF, sizeof(JFFS2_EOF) - 1) == 0) {
414 if (!quiet)
415 fprintf(stderr, "\b\b\b ");
416 if (quiet < 2)
417 fprintf(stderr, "\nAppending jffs2 data from %s to %s...", jffs2file, mtd);
418 /* got an EOF marker - this is the place to add some jffs2 data */
419 skip = mtd_replace_jffs2(mtd, fd, e, jffs2file);
420
421 /* don't add it again */
422 jffs2file = NULL;
423
424 w += skip;
425 e += skip;
426 skip -= buflen;
427 buflen = 0;
428 offset = 0;
429 continue;
430 }
431 /* no EOF marker, make sure we figure out the last inode number
432 * before appending some data */
433 mtd_parse_jffs2data(buf, jffs2dir);
434 }
435
436 /* need to erase the next block before writing data to it */
437 if(!no_erase)
438 {
439 while (w + buflen > e) {
440 if (!quiet)
441 fprintf(stderr, "\b\b\b[e]");
442
443
444 if (mtd_erase_block(fd, e) < 0) {
445 if (next) {
446 if (w < e) {
447 write(fd, buf + offset, e - w);
448 offset = e - w;
449 }
450 w = 0;
451 e = 0;
452 close(fd);
453 mtd = next;
454 fprintf(stderr, "\b\b\b \n");
455 goto resume;
456 } else {
457 fprintf(stderr, "Failed to erase block\n");
458 exit(1);
459 }
460 }
461
462 /* erase the chunk */
463 e += erasesize;
464 }
465 }
466
467 if (!quiet)
468 fprintf(stderr, "\b\b\b[w]");
469
470 if ((result = write(fd, buf + offset, buflen)) < buflen) {
471 if (result < 0) {
472 fprintf(stderr, "Error writing image.\n");
473 exit(1);
474 } else {
475 fprintf(stderr, "Insufficient space.\n");
476 exit(1);
477 }
478 }
479 w += buflen;
480
481 buflen = 0;
482 offset = 0;
483 }
484
485 if (!quiet)
486 fprintf(stderr, "\b\b\b\b ");
487
488 done:
489 if (quiet < 2)
490 fprintf(stderr, "\n");
491
492 #ifdef FIS_SUPPORT
493 if (fis_layout) {
494 if (fis_remap(old_parts, n_old, new_parts, n_new) < 0)
495 fprintf(stderr, "Failed to update the FIS partition table\n");
496 }
497 #endif
498
499 close(fd);
500 return 0;
501 }
502
503 static void usage(void)
504 {
505 fprintf(stderr, "Usage: mtd [<options> ...] <command> [<arguments> ...] <device>[:<device>...]\n\n"
506 "The device is in the format of mtdX (eg: mtd4) or its label.\n"
507 "mtd recognizes these commands:\n"
508 " unlock unlock the device\n"
509 " refresh refresh mtd partition\n"
510 " erase erase all data on device\n"
511 " write <imagefile>|- write <imagefile> (use - for stdin) to device\n"
512 " jffs2write <file> append <file> to the jffs2 partition on the device\n");
513 if (mtd_fixtrx) {
514 fprintf(stderr,
515 " fixtrx fix the checksum in a trx header on first boot\n");
516 }
517 fprintf(stderr,
518 "Following options are available:\n"
519 " -q quiet mode (once: no [w] on writing,\n"
520 " twice: no status messages)\n"
521 " -n write without first erasing the blocks\n"
522 " -r reboot after successful command\n"
523 " -f force write without trx checks\n"
524 " -e <device> erase <device> before executing the command\n"
525 " -d <name> directory for jffs2write, defaults to \"tmp\"\n"
526 " -j <name> integrate <file> into jffs2 data when writing an image\n"
527 " -p write beginning at partition offset\n");
528 if (mtd_fixtrx) {
529 fprintf(stderr,
530 " -o offset offset of the image header in the partition(for fixtrx)\n");
531 }
532 fprintf(stderr,
533 #ifdef FIS_SUPPORT
534 " -F <part>[:<size>[:<entrypoint>]][,<part>...]\n"
535 " alter the fis partition table to create new partitions replacing\n"
536 " the partitions provided as argument to the write command\n"
537 " (only valid together with the write command)\n"
538 #endif
539 "\n"
540 "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
541 " mtd -r write linux.trx linux\n\n");
542 exit(1);
543 }
544
545 static void do_reboot(void)
546 {
547 fprintf(stderr, "Rebooting ...\n");
548 fflush(stderr);
549
550 /* try regular reboot method first */
551 system("/sbin/reboot");
552 sleep(2);
553
554 /* if we're still alive at this point, force the kernel to reboot */
555 syscall(SYS_reboot,LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,LINUX_REBOOT_CMD_RESTART,NULL);
556 }
557
558 int main (int argc, char **argv)
559 {
560 int ch, i, boot, imagefd = 0, force, unlocked;
561 char *erase[MAX_ARGS], *device = NULL;
562 char *fis_layout = NULL;
563 size_t offset = 0, part_offset = 0;
564 enum {
565 CMD_ERASE,
566 CMD_WRITE,
567 CMD_UNLOCK,
568 CMD_REFRESH,
569 CMD_JFFS2WRITE,
570 CMD_FIXTRX,
571 } cmd = -1;
572
573 erase[0] = NULL;
574 boot = 0;
575 force = 0;
576 buflen = 0;
577 quiet = 0;
578 no_erase = 0;
579
580 while ((ch = getopt(argc, argv,
581 #ifdef FIS_SUPPORT
582 "F:"
583 #endif
584 "frnqe:d:j:p:o:")) != -1)
585 switch (ch) {
586 case 'f':
587 force = 1;
588 break;
589 case 'r':
590 boot = 1;
591 break;
592 case 'n':
593 no_erase = 1;
594 break;
595 case 'j':
596 jffs2file = optarg;
597 break;
598 case 'q':
599 quiet++;
600 break;
601 case 'e':
602 i = 0;
603 while ((erase[i] != NULL) && ((i + 1) < MAX_ARGS))
604 i++;
605
606 erase[i++] = optarg;
607 erase[i] = NULL;
608 break;
609 case 'd':
610 jffs2dir = optarg;
611 break;
612 case 'p':
613 errno = 0;
614 part_offset = strtoul(optarg, 0, 0);
615 if (errno) {
616 fprintf(stderr, "-p: illegal numeric string\n");
617 usage();
618 }
619 break;
620 case 'o':
621 if (!mtd_fixtrx) {
622 fprintf(stderr, "-o: is not available on this platform\n");
623 usage();
624 }
625 errno = 0;
626 offset = strtoul(optarg, 0, 0);
627 if (errno) {
628 fprintf(stderr, "-o: illegal numeric string\n");
629 usage();
630 }
631 break;
632 #ifdef FIS_SUPPORT
633 case 'F':
634 fis_layout = optarg;
635 break;
636 #endif
637 case '?':
638 default:
639 usage();
640 }
641 argc -= optind;
642 argv += optind;
643
644 if (argc < 2)
645 usage();
646
647 if ((strcmp(argv[0], "unlock") == 0) && (argc == 2)) {
648 cmd = CMD_UNLOCK;
649 device = argv[1];
650 } else if ((strcmp(argv[0], "refresh") == 0) && (argc == 2)) {
651 cmd = CMD_REFRESH;
652 device = argv[1];
653 } else if ((strcmp(argv[0], "erase") == 0) && (argc == 2)) {
654 cmd = CMD_ERASE;
655 device = argv[1];
656 } else if (((strcmp(argv[0], "fixtrx") == 0) && (argc == 2)) && mtd_fixtrx) {
657 cmd = CMD_FIXTRX;
658 device = argv[1];
659 } else if ((strcmp(argv[0], "write") == 0) && (argc == 3)) {
660 cmd = CMD_WRITE;
661 device = argv[2];
662
663 if (strcmp(argv[1], "-") == 0) {
664 imagefile = "<stdin>";
665 imagefd = 0;
666 } else {
667 imagefile = argv[1];
668 if ((imagefd = open(argv[1], O_RDONLY)) < 0) {
669 fprintf(stderr, "Couldn't open image file: %s!\n", imagefile);
670 exit(1);
671 }
672 }
673
674 if (!mtd_check(device)) {
675 fprintf(stderr, "Can't open device for writing!\n");
676 exit(1);
677 }
678 /* check trx file before erasing or writing anything */
679 if (!image_check(imagefd, device) && !force) {
680 fprintf(stderr, "Image check failed.\n");
681 exit(1);
682 }
683 } else if ((strcmp(argv[0], "jffs2write") == 0) && (argc == 3)) {
684 cmd = CMD_JFFS2WRITE;
685 device = argv[2];
686
687 imagefile = argv[1];
688 if (!mtd_check(device)) {
689 fprintf(stderr, "Can't open device for writing!\n");
690 exit(1);
691 }
692 } else {
693 usage();
694 }
695
696 sync();
697
698 i = 0;
699 unlocked = 0;
700 while (erase[i] != NULL) {
701 mtd_unlock(erase[i]);
702 mtd_erase(erase[i]);
703 if (strcmp(erase[i], device) == 0)
704 unlocked = 1;
705 i++;
706 }
707
708 switch (cmd) {
709 case CMD_UNLOCK:
710 if (!unlocked)
711 mtd_unlock(device);
712 break;
713 case CMD_ERASE:
714 if (!unlocked)
715 mtd_unlock(device);
716 mtd_erase(device);
717 break;
718 case CMD_WRITE:
719 if (!unlocked)
720 mtd_unlock(device);
721 mtd_write(imagefd, device, fis_layout, part_offset);
722 break;
723 case CMD_JFFS2WRITE:
724 if (!unlocked)
725 mtd_unlock(device);
726 mtd_write_jffs2(device, imagefile, jffs2dir);
727 break;
728 case CMD_REFRESH:
729 mtd_refresh(device);
730 break;
731 case CMD_FIXTRX:
732 if (mtd_fixtrx) {
733 mtd_fixtrx(device, offset);
734 }
735 break;
736 }
737
738 sync();
739
740 if (boot)
741 do_reboot();
742
743 return 0;
744 }