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