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