ar71xx: Unifi AP Pro sysupgrade patch
[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 int jffs2_skip_bytes=0;
59
60 int mtd_open(const char *mtd, bool block)
61 {
62         FILE *fp;
63         char dev[PATH_MAX];
64         int i;
65         int ret;
66         int flags = O_RDWR | O_SYNC;
67
68         if ((fp = fopen("/proc/mtd", "r"))) {
69                 while (fgets(dev, sizeof(dev), fp)) {
70                         if (sscanf(dev, "mtd%d:", &i) && strstr(dev, mtd)) {
71                                 snprintf(dev, sizeof(dev), "/dev/mtd%s/%d", (block ? "block" : ""), i);
72                                 if ((ret=open(dev, flags))<0) {
73                                         snprintf(dev, sizeof(dev), "/dev/mtd%s%d", (block ? "block" : ""), i);
74                                         ret=open(dev, flags);
75                                 }
76                                 fclose(fp);
77                                 return ret;
78                         }
79                 }
80                 fclose(fp);
81         }
82
83         return open(mtd, flags);
84 }
85
86 int mtd_check_open(const char *mtd)
87 {
88         struct mtd_info_user mtdInfo;
89         int fd;
90
91         fd = mtd_open(mtd, false);
92         if(fd < 0) {
93                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
94                 return -1;
95         }
96
97         if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
98                 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
99                 close(fd);
100                 return -1;
101         }
102         mtdsize = mtdInfo.size;
103         erasesize = mtdInfo.erasesize;
104
105         return fd;
106 }
107
108 int mtd_erase_block(int fd, int offset)
109 {
110         struct erase_info_user mtdEraseInfo;
111
112         mtdEraseInfo.start = offset;
113         mtdEraseInfo.length = erasesize;
114         ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
115         if (ioctl (fd, MEMERASE, &mtdEraseInfo) < 0)
116                 return -1;
117
118         return 0;
119 }
120
121 int mtd_write_buffer(int fd, const char *buf, int offset, int length)
122 {
123         lseek(fd, offset, SEEK_SET);
124         write(fd, buf, length);
125         return 0;
126 }
127
128
129 static int
130 image_check(int imagefd, const char *mtd)
131 {
132         int ret = 1;
133         if (trx_check) {
134           ret = trx_check(imagefd, mtd, buf, &buflen);
135         }
136
137         return ret;
138 }
139
140 static int mtd_check(const char *mtd)
141 {
142         char *next = NULL;
143         char *str = NULL;
144         int fd;
145
146         if (strchr(mtd, ':')) {
147                 str = strdup(mtd);
148                 mtd = str;
149         }
150
151         do {
152                 next = strchr(mtd, ':');
153                 if (next) {
154                         *next = 0;
155                         next++;
156                 }
157
158                 fd = mtd_check_open(mtd);
159                 if (fd < 0)
160                         return 0;
161
162                 if (!buf)
163                         buf = malloc(erasesize);
164
165                 close(fd);
166                 mtd = next;
167         } while (next);
168
169         if (str)
170                 free(str);
171
172         return 1;
173 }
174
175 static int
176 mtd_unlock(const char *mtd)
177 {
178         struct erase_info_user mtdLockInfo;
179         char *next = NULL;
180         char *str = NULL;
181         int fd;
182
183         if (strchr(mtd, ':')) {
184                 str = strdup(mtd);
185                 mtd = str;
186         }
187
188         do {
189                 next = strchr(mtd, ':');
190                 if (next) {
191                         *next = 0;
192                         next++;
193                 }
194
195                 fd = mtd_check_open(mtd);
196                 if(fd < 0) {
197                         fprintf(stderr, "Could not open mtd device: %s\n", mtd);
198                         exit(1);
199                 }
200
201                 if (quiet < 2)
202                         fprintf(stderr, "Unlocking %s ...\n", mtd);
203
204                 mtdLockInfo.start = 0;
205                 mtdLockInfo.length = mtdsize;
206                 ioctl(fd, MEMUNLOCK, &mtdLockInfo);
207                 close(fd);
208                 mtd = next;
209         } while (next);
210
211         if (str)
212                 free(str);
213
214         return 0;
215 }
216
217 static int
218 mtd_erase(const char *mtd)
219 {
220         int fd;
221         struct erase_info_user mtdEraseInfo;
222
223         if (quiet < 2)
224                 fprintf(stderr, "Erasing %s ...\n", mtd);
225
226         fd = mtd_check_open(mtd);
227         if(fd < 0) {
228                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
229                 exit(1);
230         }
231
232         mtdEraseInfo.length = erasesize;
233
234         for (mtdEraseInfo.start = 0;
235                  mtdEraseInfo.start < mtdsize;
236                  mtdEraseInfo.start += erasesize) {
237
238                 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
239                 if(ioctl(fd, MEMERASE, &mtdEraseInfo))
240                         fprintf(stderr, "Failed to erase block on %s at 0x%x\n", mtd, mtdEraseInfo.start);
241         }
242
243         close(fd);
244         return 0;
245
246 }
247
248 static void
249 indicate_writing(const char *mtd)
250 {
251         if (quiet < 2)
252                 fprintf(stderr, "\nWriting from %s to %s ... ", imagefile, mtd);
253
254         if (!quiet)
255                 fprintf(stderr, " [ ]");
256 }
257
258 static int
259 mtd_write(int imagefd, const char *mtd, char *fis_layout, size_t part_offset)
260 {
261         char *next = NULL;
262         char *str = NULL;
263         int fd, result;
264         ssize_t r, w, e;
265         ssize_t skip = 0;
266         uint32_t offset = 0;
267         int jffs2_replaced = 0;
268
269 #ifdef FIS_SUPPORT
270         static struct fis_part new_parts[MAX_ARGS];
271         static struct fis_part old_parts[MAX_ARGS];
272         int n_new = 0, n_old = 0;
273
274         if (fis_layout) {
275                 const char *tmp = mtd;
276                 char *word, *brkt;
277                 int ret;
278
279                 memset(&old_parts, 0, sizeof(old_parts));
280                 memset(&new_parts, 0, sizeof(new_parts));
281
282                 do {
283                         next = strchr(tmp, ':');
284                         if (!next)
285                                 next = (char *) tmp + strlen(tmp);
286
287                         memcpy(old_parts[n_old].name, tmp, next - tmp);
288
289                         n_old++;
290                         tmp = next + 1;
291                 } while(*next);
292
293                 for (word = strtok_r(fis_layout, ",", &brkt);
294                      word;
295                          word = strtok_r(NULL, ",", &brkt)) {
296
297                         tmp = strtok(word, ":");
298                         strncpy((char *) new_parts[n_new].name, tmp, sizeof(new_parts[n_new].name) - 1);
299
300                         tmp = strtok(NULL, ":");
301                         if (!tmp)
302                                 goto next;
303
304                         new_parts[n_new].size = strtoul(tmp, NULL, 0);
305
306                         tmp = strtok(NULL, ":");
307                         if (!tmp)
308                                 goto next;
309
310                         new_parts[n_new].loadaddr = strtoul(tmp, NULL, 16);
311 next:
312                         n_new++;
313                 }
314                 ret = fis_validate(old_parts, n_old, new_parts, n_new);
315                 if (ret < 0) {
316                         fprintf(stderr, "Failed to validate the new FIS partition table\n");
317                         exit(1);
318                 }
319                 if (ret == 0)
320                         fis_layout = NULL;
321         }
322 #endif
323
324         if (strchr(mtd, ':')) {
325                 str = strdup(mtd);
326                 mtd = str;
327         }
328
329         r = 0;
330
331 resume:
332         next = strchr(mtd, ':');
333         if (next) {
334                 *next = 0;
335                 next++;
336         }
337
338         fd = mtd_check_open(mtd);
339         if(fd < 0) {
340                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
341                 exit(1);
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 && w >= jffs2_skip_bytes) {
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         "        -s <number>             skip the first n bytes when appending data to the jffs2 partiton, defaults to \"0\"\n"
507         "        -p                      write beginning at partition offset\n");
508         if (mtd_fixtrx) {
509             fprintf(stderr,
510         "        -o offset               offset of the image header in the partition(for fixtrx)\n");
511     }
512         fprintf(stderr,
513 #ifdef FIS_SUPPORT
514         "        -F <part>[:<size>[:<entrypoint>]][,<part>...]\n"
515         "                                alter the fis partition table to create new partitions replacing\n"
516         "                                the partitions provided as argument to the write command\n"
517         "                                (only valid together with the write command)\n"
518 #endif
519         "\n"
520         "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
521         "         mtd -r write linux.trx linux\n\n");
522         exit(1);
523 }
524
525 static void do_reboot(void)
526 {
527         fprintf(stderr, "Rebooting ...\n");
528         fflush(stderr);
529
530         /* try regular reboot method first */
531         system("/sbin/reboot");
532         sleep(2);
533
534         /* if we're still alive at this point, force the kernel to reboot */
535         syscall(SYS_reboot,LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,LINUX_REBOOT_CMD_RESTART,NULL);
536 }
537
538 int main (int argc, char **argv)
539 {
540         int ch, i, boot, imagefd = 0, force, unlocked;
541         char *erase[MAX_ARGS], *device = NULL;
542         char *fis_layout = NULL;
543         size_t offset = 0, part_offset = 0;
544         enum {
545                 CMD_ERASE,
546                 CMD_WRITE,
547                 CMD_UNLOCK,
548                 CMD_JFFS2WRITE,
549                 CMD_FIXTRX,
550                 CMD_FIXSEAMA,
551         } cmd = -1;
552
553         erase[0] = NULL;
554         boot = 0;
555         force = 0;
556         buflen = 0;
557         quiet = 0;
558         no_erase = 0;
559
560         while ((ch = getopt(argc, argv,
561 #ifdef FIS_SUPPORT
562                         "F:"
563 #endif
564                         "frnqe:d:s:j:p:o:")) != -1)
565                 switch (ch) {
566                         case 'f':
567                                 force = 1;
568                                 break;
569                         case 'r':
570                                 boot = 1;
571                                 break;
572                         case 'n':
573                                 no_erase = 1;
574                                 break;
575                         case 'j':
576                                 jffs2file = optarg;
577                                 break;
578                         case 's':
579                                 errno = 0;
580                                 jffs2_skip_bytes = strtoul(optarg, 0, 0);
581                                 if (errno) {
582                                                 fprintf(stderr, "-s: illegal numeric string\n");
583                                                 usage();
584                                 }
585                                 break;
586                         case 'q':
587                                 quiet++;
588                                 break;
589                         case 'e':
590                                 i = 0;
591                                 while ((erase[i] != NULL) && ((i + 1) < MAX_ARGS))
592                                         i++;
593
594                                 erase[i++] = optarg;
595                                 erase[i] = NULL;
596                                 break;
597                         case 'd':
598                                 jffs2dir = optarg;
599                                 break;
600                         case 'p':
601                                 errno = 0;
602                                 part_offset = strtoul(optarg, 0, 0);
603                                 if (errno) {
604                                         fprintf(stderr, "-p: illegal numeric string\n");
605                                         usage();
606                                 }
607                                 break;
608                         case 'o':
609                                 if (!mtd_fixtrx) {
610                                         fprintf(stderr, "-o: is not available on this platform\n");
611                                         usage();
612                                 }
613                                 errno = 0;
614                                 offset = strtoul(optarg, 0, 0);
615                                 if (errno) {
616                                         fprintf(stderr, "-o: illegal numeric string\n");
617                                         usage();
618                                 }
619                                 break;
620 #ifdef FIS_SUPPORT
621                         case 'F':
622                                 fis_layout = optarg;
623                                 break;
624 #endif
625                         case '?':
626                         default:
627                                 usage();
628                 }
629         argc -= optind;
630         argv += optind;
631
632         if (argc < 2)
633                 usage();
634
635         if ((strcmp(argv[0], "unlock") == 0) && (argc == 2)) {
636                 cmd = CMD_UNLOCK;
637                 device = argv[1];
638         } else if ((strcmp(argv[0], "erase") == 0) && (argc == 2)) {
639                 cmd = CMD_ERASE;
640                 device = argv[1];
641         } else if (((strcmp(argv[0], "fixtrx") == 0) && (argc == 2)) && mtd_fixtrx) {
642                 cmd = CMD_FIXTRX;
643                 device = argv[1];
644         } else if (((strcmp(argv[0], "fixseama") == 0) && (argc == 2)) && mtd_fixseama) {
645                 cmd = CMD_FIXSEAMA;
646                 device = argv[1];
647         } else if ((strcmp(argv[0], "write") == 0) && (argc == 3)) {
648                 cmd = CMD_WRITE;
649                 device = argv[2];
650
651                 if (strcmp(argv[1], "-") == 0) {
652                         imagefile = "<stdin>";
653                         imagefd = 0;
654                 } else {
655                         imagefile = argv[1];
656                         if ((imagefd = open(argv[1], O_RDONLY)) < 0) {
657                                 fprintf(stderr, "Couldn't open image file: %s!\n", imagefile);
658                                 exit(1);
659                         }
660                 }
661
662                 if (!mtd_check(device)) {
663                         fprintf(stderr, "Can't open device for writing!\n");
664                         exit(1);
665                 }
666                 /* check trx file before erasing or writing anything */
667                 if (!image_check(imagefd, device) && !force) {
668                         fprintf(stderr, "Image check failed.\n");
669                         exit(1);
670                 }
671         } else if ((strcmp(argv[0], "jffs2write") == 0) && (argc == 3)) {
672                 cmd = CMD_JFFS2WRITE;
673                 device = argv[2];
674
675                 imagefile = argv[1];
676                 if (!mtd_check(device)) {
677                         fprintf(stderr, "Can't open device for writing!\n");
678                         exit(1);
679                 }
680         } else {
681                 usage();
682         }
683
684         sync();
685
686         i = 0;
687         unlocked = 0;
688         while (erase[i] != NULL) {
689                 mtd_unlock(erase[i]);
690                 mtd_erase(erase[i]);
691                 if (strcmp(erase[i], device) == 0)
692                         unlocked = 1;
693                 i++;
694         }
695
696         switch (cmd) {
697                 case CMD_UNLOCK:
698                         if (!unlocked)
699                                 mtd_unlock(device);
700                         break;
701                 case CMD_ERASE:
702                         if (!unlocked)
703                                 mtd_unlock(device);
704                         mtd_erase(device);
705                         break;
706                 case CMD_WRITE:
707                         if (!unlocked)
708                                 mtd_unlock(device);
709                         mtd_write(imagefd, device, fis_layout, part_offset);
710                         break;
711                 case CMD_JFFS2WRITE:
712                         if (!unlocked)
713                                 mtd_unlock(device);
714                         mtd_write_jffs2(device, imagefile, jffs2dir);
715                         break;
716                 case CMD_FIXTRX:
717                     if (mtd_fixtrx) {
718                             mtd_fixtrx(device, offset);
719             }
720                 case CMD_FIXSEAMA:
721                         if (mtd_fixseama)
722                             mtd_fixseama(device, 0);
723                         break;
724         }
725
726         sync();
727
728         if (boot)
729                 do_reboot();
730
731         return 0;
732 }