add 'mtd refresh' command
[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  *                        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  * $Id$
22  *
23  * The code is based on the linux-mtd examples.
24  */
25
26 #include <limits.h>
27 #include <unistd.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <stdint.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
46 #include "mtd.h"
47
48 #define TRX_MAGIC       0x30524448      /* "HDR0" */
49 #define BUFSIZE (16 * 1024)
50 #define MAX_ARGS 8
51
52 #define DEBUG
53
54 #define SYSTYPE_UNKNOWN     0
55 #define SYSTYPE_BROADCOM    1
56 /* to be continued */
57
58 struct trx_header {
59         uint32_t magic;         /* "HDR0" */
60         uint32_t len;           /* Length of file including header */
61         uint32_t crc32;         /* 32-bit CRC from flag_version to end of file */
62         uint32_t flag_version;  /* 0:15 flags, 16:31 version */
63         uint32_t offsets[3];    /* Offsets of partitions from start of header */
64 };
65
66 char buf[BUFSIZE];
67 int buflen;
68 int quiet;
69
70 #ifdef target_brcm
71 int
72 image_check_brcm(int imagefd, const char *mtd)
73 {
74         struct trx_header *trx = (struct trx_header *) buf;
75         struct mtd_info_user mtdInfo;
76         int fd;
77
78         if (strcmp(mtd, "linux") != 0)
79                 return 1;
80         
81         buflen = read(imagefd, buf, 32);
82         if (buflen < 32) {
83                 fprintf(stdout, "Could not get image header, file too small (%ld bytes)\n", buflen);
84                 return 0;
85         }
86
87         if (trx->magic != TRX_MAGIC || trx->len < sizeof(struct trx_header)) {
88                 if (quiet < 2) {
89                         fprintf(stderr, "Bad trx header\n");
90                         fprintf(stderr, "This is not the correct file format; refusing to flash.\n"
91                                         "Please specify the correct file or use -f to force.\n");
92                 }
93                 return 0;
94         }
95
96         /* check if image fits to mtd device */
97         fd = mtd_open(mtd, O_RDWR | O_SYNC);
98         if(fd < 0) {
99                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
100                 exit(1);
101         }
102
103         if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
104                 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
105                 exit(1);
106         }
107                 
108         if(mtdInfo.size < trx->len) {
109                 fprintf(stderr, "Image too big for partition: %s\n", mtd);
110                 close(fd);
111                 return 0;
112         }       
113         
114         close(fd);
115         return 1;
116 }
117 #endif /* target_brcm */
118
119 int
120 image_check(int imagefd, const char *mtd)
121 {
122         int fd, systype;
123         size_t count;
124         char *c;
125         FILE *f;
126
127 #ifdef target_brcm
128         return image_check_brcm(imagefd, mtd);
129 #endif
130 }
131
132 int mtd_check(char *mtd)
133 {
134         struct mtd_info_user mtdInfo;
135         int fd;
136
137         fd = mtd_open(mtd, O_RDWR | O_SYNC);
138         if(fd < 0) {
139                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
140                 return 0;
141         }
142
143         if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
144                 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
145                 close(fd);
146                 return 0;
147         }
148
149         close(fd);
150         return 1;
151 }
152
153 int
154 mtd_unlock(const char *mtd)
155 {
156         int fd;
157         struct mtd_info_user mtdInfo;
158         struct erase_info_user mtdLockInfo;
159
160         fd = mtd_open(mtd, O_RDWR | O_SYNC);
161         if(fd < 0) {
162                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
163                 exit(1);
164         }
165
166         if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
167                 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
168                 close(fd);
169                 exit(1);
170         }
171
172         mtdLockInfo.start = 0;
173         mtdLockInfo.length = mtdInfo.size;
174         if(ioctl(fd, MEMUNLOCK, &mtdLockInfo)) {
175                 close(fd);
176                 return 0;
177         }
178                 
179         close(fd);
180         return 0;
181 }
182
183 int
184 mtd_open(const char *mtd, int flags)
185 {
186         FILE *fp;
187         char dev[PATH_MAX];
188         int i;
189         int ret;
190
191         if ((fp = fopen("/proc/mtd", "r"))) {
192                 while (fgets(dev, sizeof(dev), fp)) {
193                         if (sscanf(dev, "mtd%d:", &i) && strstr(dev, mtd)) {
194                                 snprintf(dev, sizeof(dev), "/dev/mtd/%d", i);
195                                 if ((ret=open(dev, flags))<0) {
196                                         snprintf(dev, sizeof(dev), "/dev/mtd%d", i);
197                                         ret=open(dev, flags);
198                                 }
199                                 fclose(fp);
200                                 return ret;
201                         }
202                 }
203                 fclose(fp);
204         }
205
206         return open(mtd, flags);
207 }
208
209 int
210 mtd_erase(const char *mtd)
211 {
212         int fd;
213         struct mtd_info_user mtdInfo;
214         struct erase_info_user mtdEraseInfo;
215
216         fd = mtd_open(mtd, O_RDWR | O_SYNC);
217         if(fd < 0) {
218                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
219                 exit(1);
220         }
221
222         if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
223                 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
224                 close(fd);
225                 exit(1);
226         }
227
228         mtdEraseInfo.length = mtdInfo.erasesize;
229
230         for (mtdEraseInfo.start = 0;
231                  mtdEraseInfo.start < mtdInfo.size;
232                  mtdEraseInfo.start += mtdInfo.erasesize) {
233                 
234                 ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
235                 if(ioctl(fd, MEMERASE, &mtdEraseInfo))
236                         fprintf(stderr, "Failed to erase block on %s at 0x%x\n", mtd, mtdEraseInfo.start);
237         }               
238
239         close(fd);
240         return 0;
241
242 }
243
244 int
245 mtd_refresh(const char *mtd)
246 {
247         int fd;
248
249         fd = mtd_open(mtd, O_RDWR | O_SYNC);
250         if(fd < 0) {
251                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
252                 exit(1);
253         }
254         if (ioctl(fd, MTDREFRESH, NULL)) {
255                 fprintf(stderr, "Failed to refresh the MTD device\n");
256                 close(fd);
257                 exit(1);
258         }
259         close(fd);
260         return 0;
261 }
262
263 int
264 mtd_write(int imagefd, const char *mtd)
265 {
266         int fd, i, result;
267         size_t r, w, e;
268         struct mtd_info_user mtdInfo;
269         struct erase_info_user mtdEraseInfo;
270         int ret = 0;
271
272         fd = mtd_open(mtd, O_RDWR | O_SYNC);
273         if(fd < 0) {
274                 fprintf(stderr, "Could not open mtd device: %s\n", mtd);
275                 exit(1);
276         }
277
278         if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
279                 fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
280                 close(fd);
281                 exit(1);
282         }
283                 
284         r = w = e = 0;
285         if (!quiet)
286                 fprintf(stderr, " [ ]");
287
288         for (;;) {
289                 /* buffer may contain data already (from trx check) */
290                 r = buflen;
291                 r += read(imagefd, buf + buflen, BUFSIZE - buflen);
292                 w += r;
293
294                 /* EOF */
295                 if (r <= 0) break;
296
297                 /* need to erase the next block before writing data to it */
298                 while (w > e) {
299                         mtdEraseInfo.start = e;
300                         mtdEraseInfo.length = mtdInfo.erasesize;
301
302                         if (!quiet)
303                                 fprintf(stderr, "\b\b\b[e]");
304                         /* erase the chunk */
305                         if (ioctl (fd,MEMERASE,&mtdEraseInfo) < 0) {
306                                 fprintf(stderr, "Erasing mtd failed: %s\n", mtd);
307                                 exit(1);
308                         }
309                         e += mtdInfo.erasesize;
310                 }
311                 
312                 if (!quiet)
313                         fprintf(stderr, "\b\b\b[w]");
314                 
315                 if ((result = write(fd, buf, r)) < r) {
316                         if (result < 0) {
317                                 fprintf(stderr, "Error writing image.\n");
318                                 exit(1);
319                         } else {
320                                 fprintf(stderr, "Insufficient space.\n");
321                                 exit(1);
322                         }
323                 }
324                 
325                 buflen = 0;
326         }
327         if (!quiet)
328                 fprintf(stderr, "\b\b\b\b");
329
330         close(fd);
331         return 0;
332 }
333
334 void usage(void)
335 {
336         fprintf(stderr, "Usage: mtd [<options> ...] <command> [<arguments> ...] <device>\n\n"
337         "The device is in the format of mtdX (eg: mtd4) or its label.\n"
338         "mtd recognizes these commands:\n"
339         "        unlock                  unlock the device\n"
340         "        refresh                 refresh mtd partition\n"
341         "        erase                   erase all data on device\n"
342         "        write <imagefile>|-     write <imagefile> (use - for stdin) to device\n"
343         "Following options are available:\n"
344         "        -q                      quiet mode (once: no [w] on writing,\n"
345         "                                           twice: no status messages)\n"
346         "        -r                      reboot after successful command\n"
347         "        -f                      force write without trx checks\n"
348         "        -e <device>             erase <device> before executing the command\n\n"
349         "Example: To write linux.trx to mtd4 labeled as linux and reboot afterwards\n"
350         "         mtd -r write linux.trx linux\n\n");
351         exit(1);
352 }
353
354 int main (int argc, char **argv)
355 {
356         int ch, i, boot, unlock, imagefd, force, unlocked;
357         char *erase[MAX_ARGS], *device, *imagefile;
358         enum {
359                 CMD_ERASE,
360                 CMD_WRITE,
361                 CMD_UNLOCK,
362                 CMD_REFRESH
363         } cmd;
364         
365         erase[0] = NULL;
366         boot = 0;
367         force = 0;
368         buflen = 0;
369         quiet = 0;
370
371         while ((ch = getopt(argc, argv, "frqe:")) != -1)
372                 switch (ch) {
373                         case 'f':
374                                 force = 1;
375                                 break;
376                         case 'r':
377                                 boot = 1;
378                                 break;
379                         case 'q':
380                                 quiet++;
381                                 break;
382                         case 'e':
383                                 i = 0;
384                                 while ((erase[i] != NULL) && ((i + 1) < MAX_ARGS))
385                                         i++;
386                                         
387                                 erase[i++] = optarg;
388                                 erase[i] = NULL;
389                                 break;
390                         
391                         case '?':
392                         default:
393                                 usage();
394                 }
395         argc -= optind;
396         argv += optind;
397         
398         if (argc < 2)
399                 usage();
400
401         if ((strcmp(argv[0], "unlock") == 0) && (argc == 2)) {
402                 cmd = CMD_UNLOCK;
403                 device = argv[1];
404         } else if ((strcmp(argv[0], "refresh") == 0) && (argc == 2)) {
405                 cmd = CMD_REFRESH;
406                 device = argv[1];
407         } else if ((strcmp(argv[0], "erase") == 0) && (argc == 2)) {
408                 cmd = CMD_ERASE;
409                 device = argv[1];
410         } else if ((strcmp(argv[0], "write") == 0) && (argc == 3)) {
411                 cmd = CMD_WRITE;
412                 device = argv[2];
413         
414                 if (strcmp(argv[1], "-") == 0) {
415                         imagefile = "<stdin>";
416                         imagefd = 0;
417                 } else {
418                         imagefile = argv[1];
419                         if ((imagefd = open(argv[1], O_RDONLY)) < 0) {
420                                 fprintf(stderr, "Couldn't open image file: %s!\n", imagefile);
421                                 exit(1);
422                         }
423                 }
424         
425                 /* check trx file before erasing or writing anything */
426                 if (!image_check(imagefd, device)) {
427                         if (!force) {
428                                 fprintf(stderr, "Image check failed.\n");
429                                 exit(1);
430                         }
431                 } else {
432                         if (!mtd_check(device)) {
433                                 fprintf(stderr, "Can't open device for writing!\n");
434                                 exit(1);
435                         }
436                 }
437         } else {
438                 usage();
439         }
440
441         sync();
442         
443         i = 0;
444         unlocked = 0;
445         while (erase[i] != NULL) {
446                 if (quiet < 2)
447                         fprintf(stderr, "Unlocking %s ...\n", erase[i]);
448                 mtd_unlock(erase[i]);
449                 if (quiet < 2)
450                         fprintf(stderr, "Erasing %s ...\n", erase[i]);
451                 mtd_erase(erase[i]);
452                 if (strcmp(erase[i], device) == 0)
453                         unlocked = 1;
454                 i++;
455         }
456         
457         if (!unlocked) {
458                 if (quiet < 2) 
459                         fprintf(stderr, "Unlocking %s ...\n", device);
460                 mtd_unlock(device);
461         }
462                 
463         switch (cmd) {
464                 case CMD_UNLOCK:
465                         break;
466                 case CMD_ERASE:
467                         if (quiet < 2)
468                                 fprintf(stderr, "Erasing %s ...\n", device);
469                         mtd_erase(device);
470                         break;
471                 case CMD_WRITE:
472                         if (quiet < 2)
473                                 fprintf(stderr, "Writing from %s to %s ... ", imagefile, device);
474                         mtd_write(imagefd, device);
475                         if (quiet < 2)
476                                 fprintf(stderr, "\n");
477                         break;
478                 case CMD_REFRESH:
479                         if (quiet < 2)
480                                 fprintf(stderr, "Refreshing mtd partition %s ... ");
481                         mtd_refresh(device);
482                         if (quiet < 2)
483                                 fprintf(stderr, "\n");
484                         break;
485         }
486
487         sync();
488         
489         if (boot) {
490                 fprintf(stderr, "Rebooting ...\n");
491                 fflush(stderr);
492                 syscall(SYS_reboot,LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,LINUX_REBOOT_CMD_RESTART,NULL);
493         }
494         return 0;
495 }