Merge branch 'master' of git://git.denx.de/u-boot-sunxi
[oweals/u-boot.git] / tools / imx8image.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright 2018 NXP
4  *
5  * Peng Fan <peng.fan@nxp.com>
6  */
7
8 #include "imx8image.h"
9
10 static int p_idx;
11 static int sector_size;
12 static soc_type_t soc;
13 static int container = -1;
14 static int32_t core_type = CFG_CORE_INVALID;
15 static bool emmc_fastboot;
16 static image_t param_stack[IMG_STACK_SIZE];
17 static uint8_t fuse_version;
18 static uint16_t sw_version;
19 static uint32_t custom_partition;
20 static uint32_t scfw_flags;
21
22 int imx8image_check_params(struct image_tool_params *params)
23 {
24         return 0;
25 }
26
27 static void imx8image_set_header(void *ptr, struct stat *sbuf, int ifd,
28                                  struct image_tool_params *params)
29 {
30 }
31
32 static void imx8image_print_header(const void *ptr)
33 {
34 }
35
36 static int imx8image_check_image_types(uint8_t type)
37 {
38         return (type == IH_TYPE_IMX8IMAGE) ? EXIT_SUCCESS : EXIT_FAILURE;
39 }
40
41 static table_entry_t imx8image_cmds[] = {
42         {CMD_BOOT_FROM,         "BOOT_FROM",            "boot command",       },
43         {CMD_FUSE_VERSION,      "FUSE_VERSION",         "fuse version",       },
44         {CMD_SW_VERSION,        "SW_VERSION",           "sw version",         },
45         {CMD_MSG_BLOCK,         "MSG_BLOCK",            "msg block",          },
46         {CMD_FILEOFF,           "FILEOFF",              "fileoff",            },
47         {CMD_FLAG,              "FLAG",                 "flag",       },
48         {CMD_APPEND,            "APPEND",               "append a container", },
49         {CMD_PARTITION,         "PARTITION",            "new partition",      },
50         {CMD_SOC_TYPE,          "SOC_TYPE",             "soc type",           },
51         {CMD_CONTAINER,         "CONTAINER",            "new container",      },
52         {CMD_IMAGE,             "IMAGE",                "new image",          },
53         {CMD_DATA,              "DATA",                 "new data",           },
54         {-1,                    "",                     "",                   },
55 };
56
57 static table_entry_t imx8image_core_entries[] = {
58         {CFG_SCU,       "SCU",                  "scu core",     },
59         {CFG_M40,       "M40",                  "M4 core 0",    },
60         {CFG_M41,       "M41",                  "M4 core 1",    },
61         {CFG_A35,       "A35",                  "A35 core",     },
62         {CFG_A53,       "A53",                  "A53 core",     },
63         {CFG_A72,       "A72",                  "A72 core",     },
64         {-1,            "",                     "",             },
65 };
66
67 static table_entry_t imx8image_sector_size[] = {
68         {0x400,         "sd",                   "sd/emmc",},
69         {0x400,         "emmc_fastboot",        "emmc fastboot",},
70         {0x400,         "fspi",                 "flexspi",      },
71         {0x1000,        "nand_4k",              "nand 4K",      },
72         {0x2000,        "nand_8k",              "nand 8K",      },
73         {0x4000,        "nand_16k",             "nand 16K",     },
74         {-1,            "",                     "Invalid",      },
75 };
76
77 static void parse_cfg_cmd(image_t *param_stack, int32_t cmd, char *token,
78                           char *name, int lineno)
79 {
80         switch (cmd) {
81         case CMD_BOOT_FROM:
82                 sector_size = get_table_entry_id(imx8image_sector_size,
83                                                  "imximage boot option",
84                                                  token);
85                 if (!strncmp("emmc_fastboot", token, 13))
86                         emmc_fastboot = true;
87                 break;
88         case CMD_FUSE_VERSION:
89                 fuse_version = (uint8_t)(strtoll(token, NULL, 0) & 0xFF);
90                 break;
91         case CMD_SW_VERSION:
92                 sw_version = (uint8_t)(strtoll(token, NULL, 0) & 0xFFFF);
93                 break;
94         case CMD_FILEOFF:
95                 param_stack[p_idx].option = FILEOFF;
96                 param_stack[p_idx++].dst = (uint32_t)strtoll(token, NULL, 0);
97                 break;
98         case CMD_MSG_BLOCK:
99                 param_stack[p_idx].option = MSG_BLOCK;
100                 param_stack[p_idx].filename = token;
101                 break;
102         case CMD_FLAG:
103                 param_stack[p_idx].option = FLAG;
104                 param_stack[p_idx++].entry = (uint32_t)strtoll(token, NULL, 0);
105                 break;
106         case CMD_APPEND:
107                 param_stack[p_idx].option = APPEND;
108                 param_stack[p_idx++].filename = token;
109                 break;
110         case CMD_PARTITION:
111                 param_stack[p_idx].option = PARTITION;
112                 param_stack[p_idx++].entry = (uint32_t)strtoll(token, NULL, 0);
113                 break;
114         case CMD_SOC_TYPE:
115                 if (!strncmp(token, "IMX8QX", 6)) {
116                         soc = QX;
117                 } else if (!strncmp(token, "IMX8QM", 6)) {
118                         soc = QM;
119                 } else {
120                         fprintf(stderr, "Unknown CMD_SOC_TYPE");
121                         exit(EXIT_FAILURE);
122                 }
123                 break;
124         case CMD_IMAGE:
125         case CMD_DATA:
126                 core_type = get_table_entry_id(imx8image_core_entries,
127                                                "imx8image core entries",
128                                                token);
129                 if (core_type < 0) {
130                         fprintf(stderr, "Wrong IMAGE core_type %s\n", token);
131                         exit(EXIT_FAILURE);
132                 }
133                 break;
134         default:
135                 break;
136         }
137 }
138
139 static void parse_cfg_fld(image_t *param_stack, int32_t *cmd, char *token,
140                           char *name, int lineno, int fld)
141 {
142         switch (fld) {
143         case CFG_COMMAND:
144                 *cmd = get_table_entry_id(imx8image_cmds, "imx8image cmds",
145                                           token);
146                 if (*cmd < 0) {
147                         fprintf(stderr, "Error: %s[%d] - Invalid command (%s)\n", name, lineno, token);
148                         exit(EXIT_FAILURE);
149                 }
150
151                 if (*cmd == CMD_CONTAINER) {
152                         fprintf(stdout, "New Container: \t%d\n", ++container);
153                         param_stack[p_idx++].option = NEW_CONTAINER;
154                 }
155                 break;
156         case CFG_CORE_TYPE:
157                 parse_cfg_cmd(param_stack, *cmd, token, name, lineno);
158                 break;
159         case CFG_IMAGE_NAME:
160                 if (*cmd == CMD_MSG_BLOCK) {
161                         if (!strncmp(token, "fuse", 4)) {
162                                 param_stack[p_idx].ext = SC_R_OTP;
163                         } else if (!strncmp(token, "debug", 5)) {
164                                 param_stack[p_idx].ext = SC_R_DEBUG;
165                         } else if (!strncmp(token, "field", 5)) {
166                                 param_stack[p_idx].ext = SC_R_ROM_0;
167                         } else {
168                                 fprintf(stderr, "MSG type not found %s\n", token);
169                                 exit(EXIT_FAILURE);
170                         }
171                         break;
172                 }
173                 switch (core_type) {
174                 case CFG_SCU:
175                         param_stack[p_idx].option = SCFW;
176                         param_stack[p_idx++].filename = token;
177                         break;
178                 case CFG_M40:
179                         param_stack[p_idx].option = M40;
180                         param_stack[p_idx].ext = 0;
181                         param_stack[p_idx].filename = token;
182                         break;
183                 case CFG_M41:
184                         param_stack[p_idx].option = M41;
185                         param_stack[p_idx].ext = 1;
186                         param_stack[p_idx].filename = token;
187                         break;
188                 case CFG_A35:
189                         param_stack[p_idx].ext = CORE_CA35;
190                         param_stack[p_idx].option =
191                                 (*cmd == CMD_DATA) ? DATA : AP;
192                         param_stack[p_idx].filename = token;
193                         break;
194                 case CFG_A53:
195                         param_stack[p_idx].ext = CORE_CA53;
196                         param_stack[p_idx].option =
197                                 (*cmd == CMD_DATA) ? DATA : AP;
198                         param_stack[p_idx].filename = token;
199                         break;
200                 case CFG_A72:
201                         param_stack[p_idx].ext = CORE_CA72;
202                         param_stack[p_idx].option =
203                                 (*cmd == CMD_DATA) ? DATA : AP;
204                         param_stack[p_idx].filename = token;
205                         break;
206                 }
207                 break;
208         case CFG_LOAD_ADDR:
209                 if (*cmd == CMD_MSG_BLOCK) {
210                         param_stack[p_idx++].entry =
211                                 (uint32_t)strtoll(token, NULL, 0);
212                         break;
213                 }
214                 switch (core_type) {
215                 case CFG_SCU:
216                         break;
217                 case CFG_M40:
218                 case CFG_M41:
219                 case CFG_A35:
220                 case CFG_A53:
221                 case CFG_A72:
222                         param_stack[p_idx++].entry =
223                                 (uint32_t)strtoll(token, NULL, 0);
224                         break;
225                 }
226         default:
227                 break;
228         }
229 }
230
231 static uint32_t parse_cfg_file(image_t *param_stack, char *name)
232 {
233         FILE *fd = NULL;
234         char *line = NULL;
235         char *token, *saveptr1, *saveptr2;
236         int lineno = 0;
237         int fld;
238         size_t len;
239         int32_t cmd;
240
241         fd = fopen(name, "r");
242         if (fd == 0) {
243                 fprintf(stderr, "Error: %s - Can't open cfg file\n", name);
244                 exit(EXIT_FAILURE);
245         }
246
247         /*
248          * Very simple parsing, line starting with # are comments
249          * and are dropped
250          */
251         while ((getline(&line, &len, fd)) > 0) {
252                 lineno++;
253
254                 token = strtok_r(line, "\r\n", &saveptr1);
255                 if (!token)
256                         continue;
257
258                 /* Check inside the single line */
259                 for (fld = CFG_COMMAND, cmd = CFG_INVALID,
260                      line = token; ; line = NULL, fld++) {
261                         token = strtok_r(line, " \t", &saveptr2);
262                         if (!token)
263                                 break;
264
265                         /* Drop all text starting with '#' as comments */
266                         if (token[0] == '#')
267                                 break;
268
269                         parse_cfg_fld(param_stack, &cmd, token, name, lineno,
270                                       fld);
271                 }
272         }
273
274         return 0;
275 }
276
277 static void check_file(struct stat *sbuf, char *filename)
278 {
279         int tmp_fd  = open(filename, O_RDONLY | O_BINARY);
280
281         if (tmp_fd < 0) {
282                 fprintf(stderr, "%s: Can't open: %s\n",
283                         filename, strerror(errno));
284                 exit(EXIT_FAILURE);
285         }
286
287         if (fstat(tmp_fd, sbuf) < 0) {
288                 fprintf(stderr, "%s: Can't stat: %s\n",
289                         filename, strerror(errno));
290                 exit(EXIT_FAILURE);
291         }
292
293         close(tmp_fd);
294 }
295
296 static void copy_file_aligned(int ifd, const char *datafile, int offset,
297                               int align)
298 {
299         int dfd;
300         struct stat sbuf;
301         unsigned char *ptr;
302         uint8_t zeros[0x4000];
303         int size;
304
305         if (align > 0x4000) {
306                 fprintf(stderr, "Wrong alignment requested %d\n", align);
307                 exit(EXIT_FAILURE);
308         }
309
310         memset(zeros, 0, sizeof(zeros));
311
312         dfd = open(datafile, O_RDONLY | O_BINARY);
313         if (dfd < 0) {
314                 fprintf(stderr, "Can't open %s: %s\n",
315                         datafile, strerror(errno));
316                 exit(EXIT_FAILURE);
317         }
318
319         if (fstat(dfd, &sbuf) < 0) {
320                 fprintf(stderr, "Can't stat %s: %s\n",
321                         datafile, strerror(errno));
322                 exit(EXIT_FAILURE);
323         }
324
325         if (sbuf.st_size == 0)
326                 goto close;
327
328         ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, dfd, 0);
329         if (ptr == MAP_FAILED) {
330                 fprintf(stderr, "Can't read %s: %s\n",
331                         datafile, strerror(errno));
332                 exit(EXIT_FAILURE);
333         }
334
335         size = sbuf.st_size;
336         lseek(ifd, offset, SEEK_SET);
337         if (write(ifd, ptr, size) != size) {
338                 fprintf(stderr, "Write error %s\n", strerror(errno));
339                 exit(EXIT_FAILURE);
340         }
341
342         align = ALIGN(size, align) - size;
343
344         if (write(ifd, (char *)&zeros, align) != align) {
345                 fprintf(stderr, "Write error: %s\n", strerror(errno));
346                 exit(EXIT_FAILURE);
347         }
348
349         munmap((void *)ptr, sbuf.st_size);
350 close:
351         close(dfd);
352 }
353
354 static void copy_file (int ifd, const char *datafile, int pad, int offset)
355 {
356         int dfd;
357         struct stat sbuf;
358         unsigned char *ptr;
359         int tail;
360         int zero = 0;
361         uint8_t zeros[4096];
362         int size;
363
364         memset(zeros, 0, sizeof(zeros));
365
366         dfd = open(datafile, O_RDONLY | O_BINARY);
367         if (dfd < 0) {
368                 fprintf(stderr, "Can't open %s: %s\n",
369                         datafile, strerror(errno));
370                 exit(EXIT_FAILURE);
371         }
372
373         if (fstat(dfd, &sbuf) < 0) {
374                 fprintf(stderr, "Can't stat %s: %s\n",
375                         datafile, strerror(errno));
376                 exit(EXIT_FAILURE);
377         }
378
379         if (sbuf.st_size == 0)
380                 goto close;
381
382         ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, dfd, 0);
383         if (ptr == MAP_FAILED) {
384                 fprintf(stderr, "Can't read %s: %s\n",
385                         datafile, strerror(errno));
386                 exit(EXIT_FAILURE);
387         }
388
389         size = sbuf.st_size;
390         lseek(ifd, offset, SEEK_SET);
391         if (write(ifd, ptr, size) != size) {
392                 fprintf(stderr, "Write error %s\n",
393                         strerror(errno));
394                 exit(EXIT_FAILURE);
395         }
396
397         tail = size % 4;
398         pad = pad - size;
399         if (pad == 1 && tail != 0) {
400                 if (write(ifd, (char *)&zero, 4 - tail) != 4 - tail) {
401                         fprintf(stderr, "Write error on %s\n",
402                                 strerror(errno));
403                         exit(EXIT_FAILURE);
404                 }
405         } else if (pad > 1) {
406                 while (pad > 0) {
407                         int todo = sizeof(zeros);
408
409                         if (todo > pad)
410                                 todo = pad;
411                         if (write(ifd, (char *)&zeros, todo) != todo) {
412                                 fprintf(stderr, "Write error: %s\n",
413                                         strerror(errno));
414                                 exit(EXIT_FAILURE);
415                         }
416                         pad -= todo;
417                 }
418         }
419
420         munmap((void *)ptr, sbuf.st_size);
421 close:
422         close(dfd);
423 }
424
425 uint64_t read_dcd_offset(char *filename)
426 {
427         int dfd;
428         struct stat sbuf;
429         uint8_t *ptr;
430         uint64_t offset = 0;
431
432         dfd = open(filename, O_RDONLY | O_BINARY);
433         if (dfd < 0) {
434                 fprintf(stderr, "Can't open %s: %s\n", filename, strerror(errno));
435                 exit(EXIT_FAILURE);
436         }
437
438         if (fstat(dfd, &sbuf) < 0) {
439                 fprintf(stderr, "Can't stat %s: %s\n", filename, strerror(errno));
440                 exit(EXIT_FAILURE);
441         }
442
443         ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, dfd, 0);
444         if (ptr == MAP_FAILED) {
445                 fprintf(stderr, "Can't read %s: %s\n", filename, strerror(errno));
446                 exit(EXIT_FAILURE);
447         }
448
449         offset = *(uint32_t *)(ptr + DCD_ENTRY_ADDR_IN_SCFW);
450
451         munmap((void *)ptr, sbuf.st_size);
452         close(dfd);
453
454         return offset;
455 }
456
457 static void set_image_hash(boot_img_t *img, char *filename, uint32_t hash_type)
458 {
459         FILE *fp = NULL;
460         char sha_command[512];
461         char hash[2 * HASH_MAX_LEN + 1];
462         int i, ret;
463
464         if (img->size == 0)
465                 sprintf(sha_command, "sha%dsum /dev/null", hash_type);
466         else
467                 sprintf(sha_command, "dd if=/dev/zero of=tmp_pad bs=%d count=1;\
468                         dd if=\'%s\' of=tmp_pad conv=notrunc;\
469                         sha%dsum tmp_pad; rm -f tmp_pad",
470                         img->size, filename, hash_type);
471
472         switch (hash_type) {
473         case HASH_TYPE_SHA_256:
474                 img->hab_flags |= IMG_FLAG_HASH_SHA256;
475                 break;
476         case HASH_TYPE_SHA_384:
477                 img->hab_flags |= IMG_FLAG_HASH_SHA384;
478                 break;
479         case HASH_TYPE_SHA_512:
480                 img->hab_flags |= IMG_FLAG_HASH_SHA512;
481                 break;
482         default:
483                 fprintf(stderr, "Wrong hash type selected (%d) !!!\n\n",
484                         hash_type);
485                 exit(EXIT_FAILURE);
486                 break;
487         }
488         memset(img->hash, 0, HASH_MAX_LEN);
489
490         fp = popen(sha_command, "r");
491         if (!fp) {
492                 fprintf(stderr, "Failed to run command hash\n");
493                 exit(EXIT_FAILURE);
494         }
495
496         if (!fgets(hash, hash_type / 4 + 1, fp)) {
497                 fprintf(stderr, "Failed to hash file: %s\n", filename);
498                 exit(EXIT_FAILURE);
499         }
500
501         for (i = 0; i < strlen(hash) / 2; i++) {
502                 ret = sscanf(hash + 2 * i, "%02hhx", &img->hash[i]);
503                 if (ret < 0) {
504                         fprintf(stderr, "Failed sscanf hash: %d\n", ret);
505                         exit(EXIT_FAILURE);
506                 }
507         }
508
509         pclose(fp);
510 }
511
512 static void set_image_array_entry(flash_header_v3_t *container,
513                                   soc_type_t soc, const image_t *image_stack,
514                                   uint32_t offset, uint32_t size,
515                                   char *tmp_filename, bool dcd_skip)
516 {
517         uint64_t entry = image_stack->entry;
518         uint64_t core = image_stack->ext;
519         uint32_t meta;
520         char *tmp_name = "";
521         option_type_t type = image_stack->option;
522         boot_img_t *img = &container->img[container->num_images];
523
524         img->offset = offset;  /* Is re-adjusted later */
525         img->size = size;
526
527         set_image_hash(img, tmp_filename, IMAGE_HASH_ALGO_DEFAULT);
528
529         switch (type) {
530         case SECO:
531                 img->hab_flags |= IMG_TYPE_SECO;
532                 img->hab_flags |= CORE_SECO << BOOT_IMG_FLAGS_CORE_SHIFT;
533                 tmp_name = "SECO";
534                 img->dst = 0x20C00000;
535                 img->entry = 0x20000000;
536                 break;
537         case AP:
538                 if (soc == QX && core == CORE_CA35) {
539                         meta = IMAGE_A35_DEFAULT_META(custom_partition);
540                 } else if (soc == QM && core == CORE_CA53) {
541                         meta = IMAGE_A53_DEFAULT_META(custom_partition);
542                 } else if (soc == QM && core == CORE_CA72) {
543                         meta = IMAGE_A72_DEFAULT_META(custom_partition);
544                 } else {
545                         fprintf(stderr, "Error: invalid AP core id: %lu\n",
546                                 core);
547                         exit(EXIT_FAILURE);
548                 }
549                 img->hab_flags |= IMG_TYPE_EXEC;
550                 /* On B0, only core id = 4 is valid */
551                 img->hab_flags |= CORE_CA53 << BOOT_IMG_FLAGS_CORE_SHIFT;
552                 tmp_name = "AP";
553                 img->dst = entry;
554                 img->entry = entry;
555                 img->meta = meta;
556                 custom_partition = 0;
557                 break;
558         case M40:
559         case M41:
560                 if (core == 0) {
561                         core = CORE_CM4_0;
562                         meta = IMAGE_M4_0_DEFAULT_META(custom_partition);
563                 } else if (core == 1) {
564                         core = CORE_CM4_1;
565                         meta = IMAGE_M4_1_DEFAULT_META(custom_partition);
566                 } else {
567                         fprintf(stderr, "Error: invalid m4 core id: %lu\n", core);
568                         exit(EXIT_FAILURE);
569                 }
570                 img->hab_flags |= IMG_TYPE_EXEC;
571                 img->hab_flags |= core << BOOT_IMG_FLAGS_CORE_SHIFT;
572                 tmp_name = "M4";
573                 if ((entry & 0x7) != 0) {
574                         fprintf(stderr, "\n\nWarning: M4 Destination address is not 8 byte aligned\n\n");
575                         exit(EXIT_FAILURE);
576                 }
577                 img->dst = entry;
578                 img->entry = entry;
579                 img->meta = meta;
580                 custom_partition = 0;
581                 break;
582         case DATA:
583                 img->hab_flags |= IMG_TYPE_DATA;
584                 img->hab_flags |= CORE_CA35 << BOOT_IMG_FLAGS_CORE_SHIFT;
585                 tmp_name = "DATA";
586                 img->dst = entry;
587                 break;
588         case MSG_BLOCK:
589                 img->hab_flags |= IMG_TYPE_DATA;
590                 img->hab_flags |= CORE_CA35 << BOOT_IMG_FLAGS_CORE_SHIFT;
591                 img->meta = core << BOOT_IMG_META_MU_RID_SHIFT;
592                 tmp_name = "MSG_BLOCK";
593                 img->dst = entry;
594                 break;
595         case SCFW:
596                 img->hab_flags |= scfw_flags & 0xFFFF0000;
597                 img->hab_flags |= IMG_TYPE_EXEC;
598                 img->hab_flags |= CORE_SC << BOOT_IMG_FLAGS_CORE_SHIFT;
599                 tmp_name = "SCFW";
600                 img->dst = 0x1FFE0000;
601                 img->entry = 0x1FFE0000;
602
603                 /* Lets add the DCD now */
604                 if (!dcd_skip) {
605                         container->num_images++;
606                         img = &container->img[container->num_images];
607                         img->hab_flags |= IMG_TYPE_DCD_DDR;
608                         img->hab_flags |= CORE_SC << BOOT_IMG_FLAGS_CORE_SHIFT;
609                         set_image_hash(img, "/dev/null",
610                                        IMAGE_HASH_ALGO_DEFAULT);
611                         img->offset = offset + img->size;
612                         img->entry = read_dcd_offset(tmp_filename);
613                         img->dst = img->entry - 1;
614                 }
615                 break;
616         default:
617                 fprintf(stderr, "unrecognized image type (%d)\n", type);
618                 exit(EXIT_FAILURE);
619         }
620
621         fprintf(stdout, "%s file_offset = 0x%x size = 0x%x\n", tmp_name, offset, size);
622
623         container->num_images++;
624 }
625
626 void set_container(flash_header_v3_t *container,  uint16_t sw_version,
627                    uint32_t alignment, uint32_t flags, uint16_t fuse_version)
628 {
629         container->sig_blk_hdr.tag = 0x90;
630         container->sig_blk_hdr.length = sizeof(sig_blk_hdr_t);
631         container->sw_version = sw_version;
632         container->padding = alignment;
633         container->fuse_version = fuse_version;
634         container->flags = flags;
635         fprintf(stdout, "container flags: 0x%x\n", container->flags);
636 }
637
638 static int get_container_image_start_pos(image_t *image_stack, uint32_t align)
639 {
640         image_t *img_sp = image_stack;
641         /*8K total container header*/
642         int file_off = CONTAINER_IMAGE_ARRAY_START_OFFSET;
643         FILE *fd = NULL;
644         flash_header_v3_t header;
645         int ret;
646
647         while (img_sp->option != NO_IMG) {
648                 if (img_sp->option == APPEND) {
649                         fd = fopen(img_sp->filename, "r");
650                         if (!fd) {
651                                 fprintf(stderr, "Fail open first container file %s\n", img_sp->filename);
652                                 exit(EXIT_FAILURE);
653                         }
654
655                         ret = fread(&header, sizeof(header), 1, fd);
656                         if (ret != 1)
657                                 printf("Failure Read header %d\n", ret);
658
659                         fclose(fd);
660
661                         if (header.tag != IVT_HEADER_TAG_B0) {
662                                 fprintf(stderr, "header tag missmatched \n");
663                                 exit(EXIT_FAILURE);
664                         } else {
665                                 file_off +=
666                                         header.img[header.num_images - 1].size;
667                                 file_off = ALIGN(file_off, align);
668                         }
669                 }
670
671                 img_sp++;
672         }
673
674         return file_off;
675 }
676
677 static void set_imx_hdr_v3(imx_header_v3_t *imxhdr, uint32_t cont_id)
678 {
679         flash_header_v3_t *fhdr_v3 = &imxhdr->fhdr[cont_id];
680
681         /* Set magic number, Only >= B0 supported */
682         fhdr_v3->tag = IVT_HEADER_TAG_B0;
683         fhdr_v3->version = IVT_VERSION_B0;
684 }
685
686 static uint8_t *flatten_container_header(imx_header_v3_t *imx_header,
687                                          uint8_t containers_count,
688                                          uint32_t *size_out,
689                                          uint32_t file_offset)
690 {
691         uint8_t *flat = NULL;
692         uint8_t *ptr = NULL;
693         uint16_t size = 0;
694         int i, j;
695
696         /* Compute size of all container headers */
697         for (i = 0; i < containers_count; i++) {
698                 flash_header_v3_t *container = &imx_header->fhdr[i];
699
700                 container->sig_blk_offset = HEADER_IMG_ARRAY_OFFSET +
701                         container->num_images * IMG_ARRAY_ENTRY_SIZE;
702
703                 container->length = HEADER_IMG_ARRAY_OFFSET +
704                         (IMG_ARRAY_ENTRY_SIZE * container->num_images) +
705                         sizeof(sig_blk_hdr_t);
706
707                 /* Print info needed by CST to sign the container header */
708                 fprintf(stdout, "CST: CONTAINER %d offset: 0x%x\n",
709                         i, file_offset + size);
710                 fprintf(stdout, "CST: CONTAINER %d: Signature Block: offset is at 0x%x\n", i,
711                         file_offset + size + container->length -
712                         SIGNATURE_BLOCK_HEADER_LENGTH);
713
714                 size += ALIGN(container->length, container->padding);
715         }
716
717         flat = calloc(size, sizeof(uint8_t));
718         if (!flat) {
719                 fprintf(stderr, "Failed to allocate memory (%d)\n", size);
720                 exit(EXIT_FAILURE);
721         }
722
723         ptr = flat;
724         *size_out = size;
725
726         for (i = 0; i < containers_count; i++) {
727                 flash_header_v3_t *container = &imx_header->fhdr[i];
728                 uint32_t container_start_offset = ptr - flat;
729
730                 /* Append container header */
731                 append(ptr, container, HEADER_IMG_ARRAY_OFFSET);
732
733                 /* Adjust images offset to start from container headers start */
734                 for (j = 0; j < container->num_images; j++) {
735                         container->img[j].offset -=
736                                 container_start_offset + file_offset;
737                 }
738                 /* Append each image array entry */
739                 for (j = 0; j < container->num_images; j++)
740                         append(ptr, &container->img[j], sizeof(boot_img_t));
741
742                 append(ptr, &container->sig_blk_hdr, sizeof(sig_blk_hdr_t));
743
744                 /* Padding for container (if necessary) */
745                 ptr += ALIGN(container->length, container->padding) -
746                         container->length;
747         }
748
749         return flat;
750 }
751
752 static int build_container(soc_type_t soc, uint32_t sector_size,
753                            bool emmc_fastboot, image_t *image_stack,
754                            bool dcd_skip, uint8_t fuse_version,
755                            uint16_t sw_version, int ofd)
756 {
757         static imx_header_v3_t imx_header;
758         image_t *img_sp = image_stack;
759         int file_off;
760         uint8_t *tmp;
761         struct stat sbuf;
762         char *tmp_filename = NULL;
763         uint32_t size = 0;
764         uint32_t file_padding = 0;
765
766         int container = -1;
767         int cont_img_count = 0; /* indexes to arrange the container */
768
769         memset((char *)&imx_header, 0, sizeof(imx_header_v3_t));
770
771         if (!image_stack) {
772                 fprintf(stderr, "Empty image stack ");
773                 exit(EXIT_FAILURE);
774         }
775
776         if (soc == QX)
777                 fprintf(stdout, "Platform:\ti.MX8QXP B0\n");
778         else if (soc == QM)
779                 fprintf(stdout, "Platform:\ti.MX8QM B0\n");
780
781         set_imx_hdr_v3(&imx_header, 0);
782         set_imx_hdr_v3(&imx_header, 1);
783
784         file_off = get_container_image_start_pos(image_stack, sector_size);
785         fprintf(stdout, "container image offset (aligned):%x\n", file_off);
786
787         /* step through image stack and generate the header */
788         img_sp = image_stack;
789
790         /* stop once we reach null terminator */
791         while (img_sp->option != NO_IMG) {
792                 switch (img_sp->option) {
793                 case AP:
794                 case M40:
795                 case M41:
796                 case SCFW:
797                 case DATA:
798                 case MSG_BLOCK:
799                         check_file(&sbuf, img_sp->filename);
800                         tmp_filename = img_sp->filename;
801                         set_image_array_entry(&imx_header.fhdr[container],
802                                               soc, img_sp, file_off,
803                                               ALIGN(sbuf.st_size, sector_size),
804                                               tmp_filename, dcd_skip);
805                         img_sp->src = file_off;
806
807                         file_off += ALIGN(sbuf.st_size, sector_size);
808                         cont_img_count++;
809                         break;
810
811                 case SECO:
812                         check_file(&sbuf, img_sp->filename);
813                         tmp_filename = img_sp->filename;
814                         set_image_array_entry(&imx_header.fhdr[container],
815                                               soc,
816                                               img_sp,
817                                               file_off,
818                                               sbuf.st_size,
819                                               tmp_filename, dcd_skip);
820                         img_sp->src = file_off;
821
822                         file_off += sbuf.st_size;
823                         cont_img_count++;
824                         break;
825
826                 case NEW_CONTAINER:
827                         container++;
828                         set_container(&imx_header.fhdr[container], sw_version,
829                                       CONTAINER_ALIGNMENT,
830                                       CONTAINER_FLAGS_DEFAULT,
831                                       fuse_version);
832                         /* reset img count when moving to new container */
833                         cont_img_count = 0;
834                         scfw_flags = 0;
835                         break;
836
837                 case APPEND:
838                         /*
839                          * nothing to do here, the container is appended
840                          * in the output
841                          */
842                         break;
843                 case FLAG:
844                         /*
845                          * override the flags for scfw in current container
846                          * mask off bottom 16 bits.
847                          */
848                         scfw_flags = img_sp->entry & 0xFFFF0000;
849                         break;
850                 case FILEOFF:
851                         if (file_off > img_sp->dst) {
852                                 fprintf(stderr, "FILEOFF address less than current file offset!!!\n");
853                                 exit(EXIT_FAILURE);
854                         }
855                         if (img_sp->dst != ALIGN(img_sp->dst, sector_size)) {
856                                 fprintf(stderr, "FILEOFF address is not aligned to sector size!!!\n");
857                                 exit(EXIT_FAILURE);
858                         }
859                         file_off = img_sp->dst;
860                         break;
861                 case PARTITION:
862                         /*
863                          * keep custom partition until next executable image
864                          * use a global var for default behaviour
865                          */
866                         custom_partition = img_sp->entry;
867                         break;
868                 default:
869                         fprintf(stderr, "unrecognized option in input stack (%d)\n", img_sp->option);
870                         exit(EXIT_FAILURE);
871                 }
872                 img_sp++; /* advance index */
873         }
874
875         /* Append container (if specified) */
876         img_sp = image_stack;
877         do {
878                 if (img_sp->option == APPEND) {
879                         copy_file(ofd, img_sp->filename, 0, 0);
880                         file_padding += FIRST_CONTAINER_HEADER_LENGTH;
881                 }
882                 img_sp++;
883         } while (img_sp->option != NO_IMG);
884
885         /* Add padding or skip appended container */
886         lseek(ofd, file_padding, SEEK_SET);
887
888         /* Note: Image offset are not contained in the image */
889         tmp = flatten_container_header(&imx_header, container + 1, &size,
890                                        file_padding);
891         /* Write image header */
892         if (write(ofd, tmp, size) != size) {
893                 fprintf(stderr, "error writing image hdr\n");
894                 exit(EXIT_FAILURE);
895         }
896
897         /* Clean-up memory used by the headers */
898         free(tmp);
899
900         /*
901          * step through the image stack again this time copying
902          * images to final bin, stop once we reach null terminator.
903          */
904         img_sp = image_stack;
905         while (img_sp->option != NO_IMG) {
906                 if (img_sp->option == M40 || img_sp->option == M41 ||
907                     img_sp->option == AP || img_sp->option == DATA ||
908                     img_sp->option == SCD || img_sp->option == SCFW ||
909                     img_sp->option == SECO || img_sp->option == MSG_BLOCK) {
910                         copy_file_aligned(ofd, img_sp->filename, img_sp->src,
911                                           sector_size);
912                 }
913                 img_sp++;
914         }
915
916         return 0;
917 }
918
919 int imx8image_copy_image(int outfd, struct image_tool_params *mparams)
920 {
921         image_t *img_sp = param_stack;
922
923         /*
924          * SECO FW is a container image, this is to calculate the
925          * 2nd container offset.
926          */
927         fprintf(stdout, "parsing %s\n", mparams->imagename);
928         parse_cfg_file(img_sp, mparams->imagename);
929
930         if (sector_size == 0) {
931                 fprintf(stderr, "Wrong sector size\n");
932                 exit(EXIT_FAILURE);
933         }
934
935         fprintf(stdout, "CONTAINER Sector size:\t%08x\n", sector_size);
936         fprintf(stdout, "CONTAINER FUSE VERSION:\t0x%02x\n", fuse_version);
937         fprintf(stdout, "CONTAINER SW VERSION:\t0x%04x\n", sw_version);
938
939         build_container(soc, sector_size, emmc_fastboot,
940                         img_sp, false, fuse_version, sw_version, outfd);
941
942         return 0;
943 }
944
945 /*
946  * imx8image parameters
947  */
948 U_BOOT_IMAGE_TYPE(
949         imx8image,
950         "NXP i.MX8 Boot Image support",
951         0,
952         NULL,
953         imx8image_check_params,
954         NULL,
955         imx8image_print_header,
956         imx8image_set_header,
957         NULL,
958         imx8image_check_image_types,
959         NULL,
960         NULL
961 );