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