55a90dfb60b5538c40c454fa431182df17197e7a
[openwrt.git] / tools / firmware-utils / src / mkzynfw.c
1 /*
2  *  $Id$
3  *
4  *  Copyright (C) 2007 OpenWrt.org
5  *  Copyright (C) 2007 Gabor Juhos <juhosg at openwrt.org>
6  *
7  *  This code was based on the information of the ZyXEL's firmware
8  *  image format written by Kolja Waschk, can be found at:
9  *  http://www.ixo.de/info/zyxel_uclinux
10  *
11  *  This program is free software; you can redistribute it and/or modify it
12  *  under the terms of the GNU General Public License version 2 as published
13  *  by the Free Software Foundation.
14  *
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <stdint.h>
20 #include <string.h>
21 #include <unistd.h>     /* for unlink() */
22 #include <libgen.h>
23 #include <getopt.h>     /* for getopt() */
24 #include <stdarg.h>
25 #include <errno.h>
26 #include <sys/stat.h>
27 #include <endian.h>     /* for __BYTE_ORDER */
28 #if defined(__CYGWIN__)
29 #  include <byteswap.h>
30 #endif
31
32 #include "zynos.h"
33
34 #if (__BYTE_ORDER == __LITTLE_ENDIAN)
35 #  define HOST_TO_LE16(x)       (x)
36 #  define HOST_TO_LE32(x)       (x)
37 #  define LE16_TO_HOST(x)       (x)
38 #  define LE32_TO_HOST(x)       (x)
39 #  define HOST_TO_BE16(x)       bswap_16(x)
40 #  define HOST_TO_BE32(x)       bswap_32(x)
41 #  define BE16_TO_HOST(x)       bswap_16(x)
42 #  define BE32_TO_HOST(x)       bswap_32(x)
43 #else
44 #  define HOST_TO_BE16(x)       (x)
45 #  define HOST_TO_BE32(x)       (x)
46 #  define BE16_TO_HOST(x)       (x)
47 #  define BE32_TO_HOST(x)       (x)
48 #  define HOST_TO_LE16(x)       bswap_16(x)
49 #  define HOST_TO_LE32(x)       bswap_32(x)
50 #  define LE16_TO_HOST(x)       bswap_16(x)
51 #  define LE32_TO_HOST(x)       bswap_32(x)
52 #endif
53
54 #define ALIGN(x,y)      (((x)+((y)-1)) & ~((y)-1))
55
56 #define MAX_NUM_BLOCKS  8
57 #define MAX_ARG_COUNT   32
58 #define MAX_ARG_LEN     1024
59 #define FILE_BUF_LEN    (16*1024)
60
61
62 struct csum_state{
63         int             odd;
64         uint32_t        sum;
65         uint32_t        tmp;
66 };
67
68 struct fw_block {
69         uint32_t        align;          /* alignment of this block */
70         char            *file_name;     /* name of the file */
71         uint32_t        file_size;      /* length of the file */
72         char            *mmap_name;     /* name in the MMAP table */
73         int             type;           /* block type */
74         uint32_t        padlen;
75         uint8_t         padc;
76 };
77
78 #define BLOCK_TYPE_BOOTEXT      0
79 #define BLOCK_TYPE_RAW          1
80
81 struct fw_mmap {
82         uint32_t        addr;
83         uint32_t        size;
84         uint32_t        user_addr;
85         uint32_t        user_size;
86 };
87 #define MMAP_DATA_SIZE  1024
88 #define MMAP_ALIGN      16
89
90 struct board_info {
91         char *name;             /* model name */
92         char *desc;             /* description */
93         uint16_t vendor;        /* vendor id */
94         uint16_t model;         /* model id */
95         uint32_t flash_base;    /* flash base address */
96         uint32_t flash_size;    /* board flash size */
97         uint32_t code_start;    /* code start address */
98         uint32_t fw_offs;       /* offset of the firmware within the flash */
99 };
100
101 /*
102  * Globals
103  */
104 char *progname;
105 char *ofname = NULL;
106 int verblevel = 0;
107
108 struct board_info *board = NULL;
109
110 struct fw_block blocks[MAX_NUM_BLOCKS];
111 struct fw_block *bootext_block = NULL;
112 int num_blocks = 0;
113
114 #define ADM5120_FLASH_BASE      0xBFC00000
115 #define ADM5120_CODE_START      0x80008000
116
117 /* TODO: check values for AR7 */
118 #define AR7_FLASH_BASE          0xB0000000
119 #define AR7_CODE_START          0x94008000
120
121 #define ATHEROS_FLASH_BASE      0xBFC00000
122 #define ATHEROS_CODE_START      0x80000800
123
124 #define BOARD(n, d, v, m, fb, fs, cs, fo) { \
125         .name = (n), .desc=(d), \
126         .vendor = (v), .model = (m), \
127         .flash_base = (fb), .flash_size = (fs)<<20, \
128         .code_start = (cs), .fw_offs = (fo) \
129         }
130
131 #define ADMBOARD1(n, d, m, fs) BOARD(n, d, ZYNOS_VENDOR_ID_ZYXEL, m, \
132         ADM5120_FLASH_BASE, fs, ADM5120_CODE_START, 0x8000)
133
134 #define ADMBOARD2(n, d, m, fs) BOARD(n, d, ZYNOS_VENDOR_ID_ZYXEL, m, \
135         ADM5120_FLASH_BASE, fs, ADM5120_CODE_START, 0x10000)
136
137 #define AR7BOARD1(n, d, m, fs) BOARD(n, d, ZYNOS_VENDOR_ID_ZYXEL, m, \
138         AR7_FLASH_BASE, fs, AR7_CODE_START, 0x8000)
139
140 #define ATHEROSBOARD1(n, d, m, fs) BOARD(n, d, ZYNOS_VENDOR_ID_ZYXEL, m, \
141         ATHEROS_FLASH_BASE, fs, ATHEROS_CODE_START, 0x8000)
142
143 static struct board_info boards[] = {
144         /*
145          * Infineon/ADMtek ADM5120 based boards
146          */
147         ADMBOARD2("ES-2024A",   "ZyXEL ES-2024A", ZYNOS_MODEL_ES_2024A, 4),
148         ADMBOARD2("ES-2024PWR", "ZyXEL ES-2024PWR", ZYNOS_MODEL_ES_2024PWR, 4),
149         ADMBOARD2("ES-2108",    "ZyXEL ES-2108", ZYNOS_MODEL_ES_2108, 4),
150         ADMBOARD2("ES-2108-F",  "ZyXEL ES-2108-F", ZYNOS_MODEL_ES_2108_F, 4),
151         ADMBOARD2("ES-2108-G",  "ZyXEL ES-2108-G", ZYNOS_MODEL_ES_2108_G, 4),
152         ADMBOARD2("ES-2108-LC", "ZyXEL ES-2108-LC", ZYNOS_MODEL_ES_2108_LC, 4),
153         ADMBOARD2("ES-2108PWR", "ZyXEL ES-2108PWR", ZYNOS_MODEL_ES_2108PWR, 4),
154         ADMBOARD1("HS-100",     "ZyXEL HomeSafe 100", ZYNOS_MODEL_HS_100, 2),
155         ADMBOARD1("HS-100W",    "ZyXEL HomeSafe 100W", ZYNOS_MODEL_HS_100W, 2),
156         ADMBOARD1("P-334",      "ZyXEL Prestige 334", ZYNOS_MODEL_P_334, 2),
157         ADMBOARD1("P-334U",     "ZyXEL Prestige 334U", ZYNOS_MODEL_P_334U, 4),
158         ADMBOARD1("P-334W",     "ZyXEL Prestige 334W", ZYNOS_MODEL_P_334W, 2),
159         ADMBOARD1("P-334WH",    "ZyXEL Prestige 334WH", ZYNOS_MODEL_P_334WH, 4),
160         ADMBOARD1("P-334WHD",   "ZyXEL Prestige 334WHD", ZYNOS_MODEL_P_334WHD, 4),
161         ADMBOARD1("P-334WT",    "ZyXEL Prestige 334WT", ZYNOS_MODEL_P_334WT, 4),
162         ADMBOARD1("P-335",      "ZyXEL Prestige 335", ZYNOS_MODEL_P_335, 4),
163         ADMBOARD1("P-335Plus",  "ZyXEL Prestige 335Plus", ZYNOS_MODEL_P_335PLUS, 4),
164         ADMBOARD1("P-335U",     "ZyXEL Prestige 335U", ZYNOS_MODEL_P_335U, 4),
165         ADMBOARD1("P-335WT",    "ZyXEL Prestige 335WT", ZYNOS_MODEL_P_335WT, 4),
166
167 #if 0
168         /*
169          * Texas Instruments AR7 based boards
170          */
171         AR7BOARD1("P-660H-61",  "ZyXEL P-660H-61", ZYNOS_MODEL_P_660H_61, 2),
172         AR7BOARD1("P-660H-63",  "ZyXEL P-660H-63", ZYNOS_MODEL_P_660H_63, 2),
173         AR7BOARD1("P-660H-D1",  "ZyXEL P-660H-D1", ZYNOS_MODEL_P_660H_D1, 2),
174         AR7BOARD1("P-660H-D3",  "ZyXEL P-660H-D3", ZYNOS_MODEL_P_660H_D3, 2),
175         AR7BOARD1("P-660HW-61", "ZyXEL P-660HW-61", ZYNOS_MODEL_P_660HW_61, 2),
176         AR7BOARD1("P-660HW-63", "ZyXEL P-660HW-63", ZYNOS_MODEL_P_660HW_63, 2),
177         AR7BOARD1("P-660HW-67", "ZyXEL P-660HW-67", ZYNOS_MODEL_P_660HW_67, 2),
178         AR7BOARD1("P-660HW-D1", "ZyXEL P-660HW-D1", ZYNOS_MODEL_P_660HW_D1, 2),
179         AR7BOARD1("P-660HW-D3", "ZyXEL P-660HW-D3", ZYNOS_MODEL_P_660HW_D3, 2),
180         AR7BOARD1("P-660R-61",  "ZyXEL P-660R-61", ZYNOS_MODEL_P_660R_61, 2),
181         AR7BOARD1("P-660R-61C", "ZyXEL P-660R-61C", ZYNOS_MODEL_P_660R_61C, 2),
182         AR7BOARD1("P-660R-63",  "ZyXEL P-660R-63", ZYNOS_MODEL_P_660R_63, 2),
183         AR7BOARD1("P-660R-63C", "ZyXEL P-660R-63C", ZYNOS_MODEL_P_660R_63C, 2),
184         AR7BOARD1("P-660R-67",  "ZyXEL P-660R-67", ZYNOS_MODEL_P_660R_67, 2),
185         AR7BOARD1("P-660R-D1",  "ZyXEL P-660R-D1", ZYNOS_MODEL_P_660R_D1, 2),
186         AR7BOARD1("P-660R-D3",  "ZyXEL P-660R-D3", ZYNOS_MODEL_P_660R_D3, 2),
187 #endif
188         {
189                 .name           = "O2SURF",
190                 .desc           = "O2 DSL Surf & Phone",
191                 .vendor         = ZYNOS_VENDOR_ID_O2,
192                 .model          = ZYNOS_MODEL_O2SURF,
193                 .flash_base     = AR7_FLASH_BASE,
194                 .flash_size     = 8*1024*1024,
195                 .code_start     = 0x94014000,
196                 .fw_offs        = 0x40000,
197         },
198
199         /*
200 :x
201          */
202         ATHEROSBOARD1("NBG-318S", "ZyXEL NBG-318S", ZYNOS_MODEL_NBG_318S, 4),
203
204         {.name = NULL}
205 };
206
207 /*
208  * Message macros
209  */
210 #define ERR(fmt, ...) do { \
211         fflush(0); \
212         fprintf(stderr, "[%s] *** error: " fmt "\n", \
213                         progname, ## __VA_ARGS__ ); \
214 } while (0)
215
216 #define ERRS(fmt, ...) do { \
217         int save = errno; \
218         fflush(0); \
219         fprintf(stderr, "[%s] *** error: " fmt ", %s\n", \
220                         progname, ## __VA_ARGS__, strerror(save)); \
221 } while (0)
222
223 #define WARN(fmt, ...) do { \
224         fprintf(stderr, "[%s] *** warning: " fmt "\n", \
225                         progname, ## __VA_ARGS__ ); \
226 } while (0)
227
228 #define DBG(lev, fmt, ...) do { \
229         if (verblevel < lev) \
230                 break;\
231         fprintf(stderr, "[%s] " fmt "\n", progname, ## __VA_ARGS__ ); \
232 } while (0)
233
234 #define ERR_FATAL               -1
235 #define ERR_INVALID_IMAGE       -2
236
237 /*
238  * Helper routines
239  */
240 void
241 usage(int status)
242 {
243         FILE *stream = (status != EXIT_SUCCESS) ? stderr : stdout;
244         struct board_info *board;
245
246         fprintf(stream, "Usage: %s [OPTIONS...]\n", progname);
247         fprintf(stream,
248 "\n"
249 "Options:\n"
250 "  -B <board>      create image for the board specified with <board>.\n"
251 "                  valid <board> values:\n"
252         );
253         for (board = boards; board->name != NULL; board++){
254                 fprintf(stream,
255 "                    %-12s= %s\n",
256                  board->name, board->desc);
257         };
258         fprintf(stream,
259 "  -b <file>[:<align>]\n"
260 "                  add boot extension block to the image\n"
261 "  -r <file>[:<align>]\n"
262 "                  add raw block to the image\n"
263 "  -o <file>       write output to the file <file>\n"
264 "  -h              show this screen\n"
265         );
266
267         exit(status);
268 }
269
270
271 /*
272  * argument parsing
273  */
274 int
275 str2u32(char *arg, uint32_t *val)
276 {
277         char *err = NULL;
278         uint32_t t;
279
280         errno=0;
281         t = strtoul(arg, &err, 0);
282         if (errno || (err==arg) || ((err != NULL) && *err)) {
283                 return -1;
284         }
285
286         *val = t;
287         return 0;
288 }
289
290
291 int
292 str2u16(char *arg, uint16_t *val)
293 {
294         char *err = NULL;
295         uint32_t t;
296
297         errno=0;
298         t = strtoul(arg, &err, 0);
299         if (errno || (err==arg) || ((err != NULL) && *err) || (t >= 0x10000)) {
300                 return -1;
301         }
302
303         *val = t & 0xFFFF;
304         return 0;
305 }
306
307 int
308 str2u8(char *arg, uint8_t *val)
309 {
310         char *err = NULL;
311         uint32_t t;
312
313         errno=0;
314         t = strtoul(arg, &err, 0);
315         if (errno || (err==arg) || ((err != NULL) && *err) || (t >= 0x100)) {
316                 return -1;
317         }
318
319         *val = t & 0xFF;
320         return 0;
321 }
322
323 int
324 str2sig(char *arg, uint32_t *sig)
325 {
326         if (strlen(arg) != 4)
327                 return -1;
328
329         *sig = arg[0] | (arg[1] << 8) | (arg[2] << 16) | (arg[3] << 24);
330
331         return 0;
332 }
333
334
335 int
336 parse_arg(char *arg, char *buf, char *argv[])
337 {
338         int res = 0;
339         size_t argl;
340         char *tok;
341         char **ap = &buf;
342         int i;
343
344         memset(argv, 0, MAX_ARG_COUNT * sizeof(void *));
345
346         if ((arg == NULL)) {
347                 /* no arguments */
348                 return 0;
349         }
350
351         argl = strlen(arg);
352         if (argl == 0) {
353                 /* no arguments */
354                 return 0;
355         }
356
357         if (argl >= MAX_ARG_LEN) {
358                 /* argument is too long */
359                 argl = MAX_ARG_LEN-1;
360         }
361
362         memcpy(buf, arg, argl);
363         buf[argl] = '\0';
364
365         for (i = 0; i < MAX_ARG_COUNT; i++) {
366                 tok = strsep(ap, ":");
367                 if (tok == NULL) {
368                         break;
369                 }
370 #if 0
371                 else if (tok[0] == '\0') {
372                         break;
373                 }
374 #endif
375                 argv[i] = tok;
376                 res++;
377         }
378
379         return res;
380 }
381
382
383 int
384 required_arg(char c, char *arg)
385 {
386         if (arg == NULL || *arg != '-')
387                 return 0;
388
389         ERR("option -%c requires an argument\n", c);
390         return -1;
391 }
392
393
394 int
395 is_empty_arg(char *arg)
396 {
397         int ret = 1;
398         if (arg != NULL) {
399                 if (*arg) ret = 0;
400         };
401         return ret;
402 }
403
404
405 void
406 csum_init(struct csum_state *css)
407 {
408         css->odd = 0;
409         css->sum = 0;
410         css->tmp = 0;
411 }
412
413
414 void
415 csum_update(uint8_t *p, uint32_t len, struct csum_state *css)
416 {
417         if (len == 0)
418                 return;
419
420         if (css->odd) {
421                 css->sum += (css->tmp << 8) + p[0];
422                 if (css->sum > 0xFFFF) {
423                         css->sum += 1;
424                         css->sum &= 0xFFFF;
425                 }
426                 css->odd = 0;
427                 len--;
428                 p++;
429         }
430
431         for ( ; len > 1; len -= 2, p +=2 ) {
432                 css->sum  += (p[0] << 8) + p[1];
433                 if (css->sum > 0xFFFF) {
434                         css->sum += 1;
435                         css->sum &= 0xFFFF;
436                 }
437         }
438
439         if (len == 1){
440                 css->tmp = p[0];
441                 css->odd = 1;
442         }
443 }
444
445
446 uint16_t
447 csum_get(struct csum_state *css)
448 {
449         char pad = 0;
450
451         csum_update(&pad, 1, css);
452         return css->sum;
453 }
454
455 uint16_t
456 csum_buf(uint8_t *p, uint32_t len)
457 {
458         struct csum_state css;
459
460         csum_init(&css);
461         csum_update(p, len, &css);
462         return csum_get(&css);
463
464 }
465
466 /*
467  * routines to write data to the output file
468  */
469 int
470 write_out_data(FILE *outfile, uint8_t *data, size_t len,
471                 struct csum_state *css)
472 {
473         errno = 0;
474
475         fwrite(data, len, 1, outfile);
476         if (errno) {
477                 ERR("unable to write output file");
478                 return -1;
479         }
480
481         if (css) {
482                 csum_update(data, len, css);
483         }
484
485         return 0;
486 }
487
488
489 int
490 write_out_padding(FILE *outfile, size_t len, uint8_t padc,
491                  struct csum_state *css)
492 {
493         uint8_t buf[512];
494         size_t buflen = sizeof(buf);
495
496         memset(buf, padc, buflen);
497         while (len > 0) {
498                 if (len < buflen)
499                         buflen = len;
500
501                 if (write_out_data(outfile, buf, buflen, css))
502                         return -1;
503
504                 len -= buflen;
505         }
506
507         return 0;
508 }
509
510
511 int
512 write_out_data_align(FILE *outfile, uint8_t *data, size_t len, size_t align,
513                 struct csum_state *css)
514 {
515         size_t padlen;
516         int res;
517
518         res = write_out_data(outfile, data, len, css);
519         if (res)
520                 return res;
521
522         padlen = ALIGN(len,align) - len;
523         res = write_out_padding(outfile, padlen, 0xFF, css);
524
525         return res;
526 }
527
528
529 int
530 write_out_header(FILE *outfile, struct zyn_rombin_hdr *hdr)
531 {
532         struct zyn_rombin_hdr t;
533
534         errno = 0;
535         if (fseek(outfile, 0, SEEK_SET) != 0) {
536                 ERRS("fseek failed on output file");
537                 return -1;
538         }
539
540         /* setup temporary header fields */
541         memset(&t, 0, sizeof(t));
542         t.addr = HOST_TO_BE32(hdr->addr);
543         memcpy(&t.sig, ROMBIN_SIGNATURE, ROMBIN_SIG_LEN);
544         t.type = hdr->type;
545         t.flags = hdr->flags;
546         t.osize = HOST_TO_BE32(hdr->osize);
547         t.csize = HOST_TO_BE32(hdr->csize);
548         t.ocsum = HOST_TO_BE16(hdr->ocsum);
549         t.ccsum = HOST_TO_BE16(hdr->ccsum);
550         t.mmap_addr = HOST_TO_BE32(hdr->mmap_addr);
551
552         return write_out_data(outfile, (uint8_t *)&t, sizeof(t), NULL);
553 }
554
555
556 int
557 write_out_mmap(FILE *outfile, struct fw_mmap *mmap, struct csum_state *css)
558 {
559         struct zyn_mmt_hdr *mh;
560         uint8_t buf[MMAP_DATA_SIZE];
561         uint32_t user_size;
562         char *data;
563         int res;
564
565         memset(buf, 0, sizeof(buf));
566
567         mh = (struct zyn_mmt_hdr *)buf;
568
569         /* TODO: needs to recreate the memory map too? */
570         mh->count=0;
571
572         /* Build user data section */
573         data = buf+sizeof(*mh);
574         data += sprintf(data, "Vendor 1 %d", board->vendor);
575         *data++ = '\0';
576         data += sprintf(data, "Model 1 %d", BE16_TO_HOST(board->model));
577         *data++ = '\0';
578         /* TODO: make hardware version configurable? */
579         data += sprintf(data, "HwVerRange 2 %d %d", 0, 0);
580         *data++ = '\0';
581
582         user_size = (uint8_t *)data - buf;
583         mh->user_start= HOST_TO_BE32(mmap->addr+sizeof(*mh));
584         mh->user_end= HOST_TO_BE32(mmap->addr+user_size);
585         mh->csum = HOST_TO_BE16(csum_buf(buf+sizeof(*mh), user_size));
586
587         res = write_out_data(outfile, buf, sizeof(buf), css);
588
589         return res;
590 }
591
592
593 int
594 block_stat_file(struct fw_block *block)
595 {
596         struct stat st;
597         int res;
598
599         if (block->file_name == NULL)
600                 return 0;
601
602         res = stat(block->file_name, &st);
603         if (res){
604                 ERRS("stat failed on %s", block->file_name);
605                 return res;
606         }
607
608         block->file_size = st.st_size;
609         return 0;
610 }
611
612
613 int
614 write_out_file(FILE *outfile, char *name, size_t len, struct csum_state *css)
615 {
616         char buf[FILE_BUF_LEN];
617         size_t buflen = sizeof(buf);
618         FILE *f;
619         int res;
620
621         DBG(2, "writing out file, name=%s, len=%d",
622                 name, len);
623
624         errno = 0;
625         f = fopen(name,"r");
626         if (errno) {
627                 ERRS("unable to open file: %s", name);
628                 return -1;
629         }
630
631         while (len > 0) {
632                 if (len < buflen)
633                         buflen = len;
634
635                 /* read data from source file */
636                 errno = 0;
637                 fread(buf, buflen, 1, f);
638                 if (errno != 0) {
639                         ERRS("unable to read from file: %s",name);
640                         res = -1;
641                         break;
642                 }
643
644                 res = write_out_data(outfile, buf, buflen, css);
645                 if (res)
646                         break;
647
648                 len -= buflen;
649         }
650
651         fclose(f);
652         return res;
653 }
654
655
656 int
657 write_out_block(FILE *outfile, struct fw_block *block, struct csum_state *css)
658 {
659         int res;
660
661         if (block == NULL)
662                 return 0;
663
664         if (block->file_name == NULL)
665                 return 0;
666
667         if (block->file_size == 0)
668                 return 0;
669
670         res = write_out_file(outfile, block->file_name,
671                         block->file_size, css);
672         return res;
673 }
674
675
676 int
677 write_out_image(FILE *outfile)
678 {
679         struct fw_block *block;
680         struct fw_mmap mmap;
681         struct zyn_rombin_hdr hdr;
682         struct csum_state css;
683         int i, res;
684         uint32_t offset;
685         uint32_t padlen;
686
687         /* setup header fields */
688         memset(&hdr, 0, sizeof(hdr));
689         hdr.addr = board->code_start;
690         hdr.type = OBJECT_TYPE_BOOTEXT;
691         hdr.flags = ROMBIN_FLAG_OCSUM;
692
693         res = write_out_header(outfile, &hdr);
694         if (res)
695                 return res;
696
697         offset = sizeof(hdr);
698
699         csum_init(&css);
700         res = write_out_block(outfile, bootext_block, &css);
701         if (res)
702                 return res;
703
704         offset += bootext_block->file_size;
705
706         padlen = ALIGN(offset,MMAP_ALIGN) - offset;
707         res = write_out_padding(outfile, padlen, 0xFF, &css);
708         if (res)
709                 return res;
710
711         offset += padlen;
712
713         mmap.addr = board->flash_base + board->fw_offs + offset;
714         hdr.mmap_addr = mmap.addr;
715         res = write_out_mmap(outfile, &mmap, &css);
716         if (res)
717                 return res;
718
719         offset += MMAP_DATA_SIZE;
720         hdr.osize = offset - sizeof(hdr);
721         hdr.ocsum = csum_get(&css);
722
723         for (i=0; i < num_blocks; i++) {
724                 block = &blocks[i];
725
726                 if (block->type == BLOCK_TYPE_BOOTEXT)
727                         continue;
728
729                 padlen = ALIGN(offset,block->align) - offset;
730                 res = write_out_padding(outfile, padlen, 0xFF, NULL);
731                 if (res)
732                         return res;
733                 offset += padlen;
734
735                 res = write_out_block(outfile, block, NULL);
736                 if (res)
737                         return res;
738                 offset += block->file_size;
739         }
740
741         res = write_out_header(outfile, &hdr);
742
743         return res;
744 }
745
746
747 struct board_info *
748 find_board(char *name)
749 {
750         struct board_info *ret;
751         struct board_info *board;
752
753         ret = NULL;
754         for (board = boards; board->name != NULL; board++){
755                 if (strcasecmp(name, board->name) == 0) {
756                         ret = board;
757                         break;
758                 }
759         };
760
761         return ret;
762 }
763
764
765 int
766 parse_opt_board(char ch, char *arg)
767 {
768
769         DBG(1,"parsing board option: -%c %s", ch, arg);
770
771         if (board != NULL) {
772                 ERR("only one board option allowed");
773                 return -1;
774         }
775
776         if (required_arg(ch, arg))
777                 return -1;
778
779         board = find_board(arg);
780         if (board == NULL){
781                 ERR("invalid/unknown board specified: %s", arg);
782                 return -1;
783         }
784
785         return 0;
786 }
787
788
789 int
790 parse_opt_ofname(char ch, char *arg)
791 {
792
793         if (ofname != NULL) {
794                 ERR("only one output file allowed");
795                 return -1;
796         }
797
798         if (required_arg(ch, arg))
799                 return -1;
800
801         ofname = arg;
802
803         return 0;
804 }
805
806
807 int
808 parse_opt_block(char ch, char *arg)
809 {
810         char buf[MAX_ARG_LEN];
811         char *argv[MAX_ARG_COUNT];
812         int argc;
813         char *p;
814         struct fw_block *block;
815         int i;
816
817         if ( num_blocks >= MAX_NUM_BLOCKS ) {
818                 ERR("too many blocks specified");
819                 return -1;
820         }
821
822         block = &blocks[num_blocks++];
823
824         /* setup default field values */
825         block->padc = 0xFF;
826
827         switch(ch) {
828         case 'b':
829                 if (bootext_block) {
830                         ERR("only one boot extension block allowed");
831                         break;
832                 }
833                 block->type = BLOCK_TYPE_BOOTEXT;
834                 bootext_block = block;
835                 break;
836         case 'r':
837                 block->type = BLOCK_TYPE_RAW;
838                 break;
839         }
840
841         argc = parse_arg(arg, buf, argv);
842
843         i = 0;
844         p = argv[i++];
845         if (is_empty_arg(p)) {
846                 ERR("no file specified in %s", arg);
847                 return -1;
848         } else {
849                 block->file_name = strdup(p);
850                 if (block->file_name == NULL) {
851                         ERR("not enough memory");
852                         return -1;
853                 }
854         }
855
856         if(block->type == BLOCK_TYPE_BOOTEXT)
857                 return 0;
858
859         p = argv[i++];
860         if (!is_empty_arg(p)) {
861                 if (str2u32(p, &block->align) != 0) {
862                         ERR("invalid block align in %s", arg);
863                         return -1;
864                 }
865         }
866
867         return 0;
868 }
869
870
871 int
872 calc_block_offsets(int type, uint32_t *offset)
873 {
874         struct fw_block *block;
875         uint32_t next_offs;
876         uint32_t avail;
877         int i, res;
878
879         DBG(1,"calculating block offsets, starting with %lu",
880                 *offset);
881
882         res = 0;
883         for (i = 0; i < num_blocks; i++) {
884                 block = &blocks[i];
885
886                 if (block->type != type)
887                         continue;
888
889                 next_offs = ALIGN(*offset, block->align);
890                 avail = board->flash_size - board->fw_offs - next_offs;
891                 if (next_offs + block->file_size > avail) {
892                         ERR("file %s is too big, offset = %u, size=%u,"
893                                 " align = %u", block->file_name,
894                                 (unsigned)next_offs,
895                                 (unsigned)block->file_size,
896                                 (unsigned)block->align);
897                         res = -1;
898                         break;
899                 }
900
901                 block->padlen = next_offs - *offset;
902                 *offset += block->file_size;
903         }
904
905         return res;
906 }
907
908 int
909 process_blocks(void)
910 {
911         struct fw_block *block;
912         uint32_t offset;
913         int i;
914         int res;
915
916         /* collecting file stats */
917         for (i = 0; i < num_blocks; i++) {
918                 block = &blocks[i];
919                 res = block_stat_file(block);
920                 if (res)
921                         return res;
922         }
923
924         offset = board->fw_offs + bootext_block->file_size;
925         res = calc_block_offsets(BLOCK_TYPE_RAW, &offset);
926
927         return res;
928 }
929
930
931 int
932 main(int argc, char *argv[])
933 {
934         int optinvalid = 0;   /* flag for invalid option */
935         int c;
936         int res = EXIT_FAILURE;
937
938         FILE *outfile;
939
940         progname=basename(argv[0]);
941
942         opterr = 0;  /* could not print standard getopt error messages */
943         while ( 1 ) {
944                 optinvalid = 0;
945
946                 c = getopt(argc, argv, "b:B:ho:r:v");
947                 if (c == -1)
948                         break;
949
950                 switch (c) {
951                 case 'b':
952                 case 'r':
953                         optinvalid = parse_opt_block(c,optarg);
954                         break;
955                 case 'B':
956                         optinvalid = parse_opt_board(c,optarg);
957                         break;
958                 case 'o':
959                         optinvalid = parse_opt_ofname(c,optarg);
960                         break;
961                 case 'v':
962                         verblevel++;
963                         break;
964                 case 'h':
965                         usage(EXIT_SUCCESS);
966                         break;
967                 default:
968                         optinvalid = 1;
969                         break;
970                 }
971                 if (optinvalid != 0 ) {
972                         ERR("invalid option: -%c", optopt);
973                         goto out;
974                 }
975         }
976
977         if (board == NULL) {
978                 ERR("no board specified");
979                 goto out;
980         }
981
982         if (ofname == NULL) {
983                 ERR("no output file specified");
984                 goto out;
985         }
986
987         if (optind < argc) {
988                 ERR("invalid option: %s", argv[optind]);
989                 goto out;
990         }
991
992
993         if (process_blocks() != 0) {
994                 goto out;
995         }
996
997         outfile = fopen(ofname, "w");
998         if (outfile == NULL) {
999                 ERRS("could not open \"%s\" for writing", ofname);
1000                 goto out;
1001         }
1002
1003         if (write_out_image(outfile) != 0)
1004                 goto out_flush;
1005
1006         DBG(1,"Image file %s completed.", ofname);
1007
1008         res = EXIT_SUCCESS;
1009
1010 out_flush:
1011         fflush(outfile);
1012         fclose(outfile);
1013         if (res != EXIT_SUCCESS) {
1014                 unlink(ofname);
1015         }
1016 out:
1017         return res;
1018 }