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