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