arm: K3: Add basic support for J721S2 SoC definition
[platform/kernel/u-boot.git] / tools / rkcommon.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2015 Google,  Inc
4  * Written by Simon Glass <sjg@chromium.org>
5  *
6  * (C) 2017 Theobroma Systems Design und Consulting GmbH
7  *
8  * Helper functions for Rockchip images
9  */
10
11 #include "imagetool.h"
12 #include <image.h>
13 #include <u-boot/sha256.h>
14 #include <rc4.h>
15 #include "mkimage.h"
16 #include "rkcommon.h"
17
18 enum {
19         RK_MAGIC                = 0x0ff0aa55,
20         RK_MAGIC_V2             = 0x534E4B52,
21 };
22
23 enum {
24         RK_HEADER_V1    = 1,
25         RK_HEADER_V2    = 2,
26 };
27
28 enum hash_type {
29         HASH_NONE       = 0,
30         HASH_SHA256     = 1,
31         HASH_SHA512     = 2,
32 };
33
34 /**
35  * struct image_entry
36  *
37  * @size_and_off:       [31:16]image size;[15:0]image offset
38  * @address:    default as 0xFFFFFFFF
39  * @flag:       no use
40  * @counter:    no use
41  * @hash:       hash of image
42  *
43  */
44 struct image_entry {
45         uint32_t size_and_off;
46         uint32_t address;
47         uint32_t flag;
48         uint32_t counter;
49         uint8_t reserved[8];
50         uint8_t hash[64];
51 };
52
53 /**
54  * struct header0_info_v2 - v2 header block for rockchip BootRom
55  *
56  * This is stored at SD card block 64 (where each block is 512 bytes)
57  *
58  * @magic:      Magic (must be RK_MAGIC_V2)
59  * @size_and_nimage:    [31:16]number of images;[15:0]
60  *                      offset to hash field of header(unit as 4Byte)
61  * @boot_flag:  [3:0]hash type(0:none,1:sha256,2:sha512)
62  * @signature:  hash or signature for header info
63  *
64  */
65 struct header0_info_v2 {
66         uint32_t magic;
67         uint8_t reserved[4];
68         uint32_t size_and_nimage;
69         uint32_t boot_flag;
70         uint8_t reserved1[104];
71         struct image_entry images[4];
72         uint8_t reserved2[1064];
73         uint8_t hash[512];
74 };
75
76 /**
77  * struct header0_info - header block for boot ROM
78  *
79  * This is stored at SD card block 64 (where each block is 512 bytes, or at
80  * the start of SPI flash. It is encoded with RC4.
81  *
82  * @magic:              Magic (must be RK_MAGIC)
83  * @disable_rc4:        0 to use rc4 for boot image,  1 to use plain binary
84  * @init_offset:        Offset in blocks of the SPL code from this header
85  *                      block. E.g. 4 means 2KB after the start of this header.
86  * Other fields are not used by U-Boot
87  */
88 struct header0_info {
89         uint32_t magic;
90         uint8_t reserved[4];
91         uint32_t disable_rc4;
92         uint16_t init_offset;
93         uint8_t reserved1[492];
94         uint16_t init_size;
95         uint16_t init_boot_size;
96         uint8_t reserved2[2];
97 };
98
99 /**
100  * struct header1_info
101  */
102 struct header1_info {
103         uint32_t magic;
104 };
105
106 /**
107  * struct spl_info - spl info for each chip
108  *
109  * @imagename:          Image name(passed by "mkimage -n")
110  * @spl_hdr:            Boot ROM requires a 4-bytes spl header
111  * @spl_size:           Spl size(include extra 4-bytes spl header)
112  * @spl_rc4:            RC4 encode the SPL binary (same key as header)
113  * @header_ver:         header block version
114  */
115 struct spl_info {
116         const char *imagename;
117         const char *spl_hdr;
118         const uint32_t spl_size;
119         const bool spl_rc4;
120         const uint32_t header_ver;
121 };
122
123 static struct spl_info spl_infos[] = {
124         { "px30", "RK33", 0x2800, false, RK_HEADER_V1 },
125         { "rk3036", "RK30", 0x1000, false, RK_HEADER_V1 },
126         { "rk3128", "RK31", 0x1800, false, RK_HEADER_V1 },
127         { "rk3188", "RK31", 0x8000 - 0x800, true, RK_HEADER_V1 },
128         { "rk322x", "RK32", 0x8000 - 0x1000, false, RK_HEADER_V1 },
129         { "rk3288", "RK32", 0x8000, false, RK_HEADER_V1 },
130         { "rk3308", "RK33", 0x40000 - 0x1000, false, RK_HEADER_V1 },
131         { "rk3328", "RK32", 0x8000 - 0x1000, false, RK_HEADER_V1 },
132         { "rk3368", "RK33", 0x8000 - 0x1000, false, RK_HEADER_V1 },
133         { "rk3399", "RK33", 0x30000 - 0x2000, false, RK_HEADER_V1 },
134         { "rv1108", "RK11", 0x1800, false, RK_HEADER_V1 },
135         { "rk3568", "RK35", 0x14000 - 0x1000, false, RK_HEADER_V2 },
136 };
137
138 /**
139  * struct spl_params - spl params parsed in check_params()
140  *
141  * @init_file:          Init data file path
142  * @init_size:          Aligned size of init data in bytes
143  * @boot_file:          Boot data file path
144  * @boot_size:          Aligned size of boot data in bytes
145  */
146
147 struct spl_params {
148         char *init_file;
149         uint32_t init_size;
150         char *boot_file;
151         uint32_t boot_size;
152 };
153
154 static struct spl_params spl_params = { 0 };
155
156 static unsigned char rc4_key[16] = {
157         124, 78, 3, 4, 85, 5, 9, 7,
158         45, 44, 123, 56, 23, 13, 23, 17
159 };
160
161 static struct spl_info *rkcommon_get_spl_info(char *imagename)
162 {
163         int i;
164
165         if (!imagename)
166                 return NULL;
167
168         for (i = 0; i < ARRAY_SIZE(spl_infos); i++)
169                 if (!strncmp(imagename, spl_infos[i].imagename, 6))
170                         return spl_infos + i;
171
172         return NULL;
173 }
174
175 static int rkcommon_get_aligned_size(struct image_tool_params *params,
176                                      const char *fname)
177 {
178         int size;
179
180         size = imagetool_get_filesize(params, fname);
181         if (size < 0)
182                 return -1;
183
184         /*
185          * Pad to a 2KB alignment, as required for init/boot size by the ROM
186          * (see https://lists.denx.de/pipermail/u-boot/2017-May/293268.html)
187          */
188         return ROUND(size, RK_SIZE_ALIGN);
189 }
190
191 int rkcommon_check_params(struct image_tool_params *params)
192 {
193         int i, size;
194
195         /*
196          * If this is a operation (list or extract), the don't require
197          * imagename to be set.
198          */
199         if (params->lflag || params->iflag)
200                 return EXIT_SUCCESS;
201
202         if (!rkcommon_get_spl_info(params->imagename))
203                 goto err_spl_info;
204
205         spl_params.init_file = params->datafile;
206
207         spl_params.boot_file = strchr(spl_params.init_file, ':');
208         if (spl_params.boot_file) {
209                 *spl_params.boot_file = '\0';
210                 spl_params.boot_file += 1;
211         }
212
213         size = rkcommon_get_aligned_size(params, spl_params.init_file);
214         if (size < 0)
215                 return EXIT_FAILURE;
216         spl_params.init_size = size;
217
218         /* Boot file is optional, and only for back-to-bootrom functionality. */
219         if (spl_params.boot_file) {
220                 size = rkcommon_get_aligned_size(params, spl_params.boot_file);
221                 if (size < 0)
222                         return EXIT_FAILURE;
223                 spl_params.boot_size = size;
224         }
225
226         if (spl_params.init_size > rkcommon_get_spl_size(params)) {
227                 fprintf(stderr,
228                         "Error: SPL image is too large (size %#x than %#x)\n",
229                         spl_params.init_size, rkcommon_get_spl_size(params));
230                 return EXIT_FAILURE;
231         }
232
233         return EXIT_SUCCESS;
234
235 err_spl_info:
236         fprintf(stderr, "ERROR: imagename (%s) is not supported!\n",
237                 params->imagename ? params->imagename : "NULL");
238
239         fprintf(stderr, "Available imagename:");
240         for (i = 0; i < ARRAY_SIZE(spl_infos); i++)
241                 fprintf(stderr, "\t%s", spl_infos[i].imagename);
242         fprintf(stderr, "\n");
243
244         return EXIT_FAILURE;
245 }
246
247 const char *rkcommon_get_spl_hdr(struct image_tool_params *params)
248 {
249         struct spl_info *info = rkcommon_get_spl_info(params->imagename);
250
251         /*
252          * info would not be NULL, because of we checked params before.
253          */
254         return info->spl_hdr;
255 }
256
257 int rkcommon_get_spl_size(struct image_tool_params *params)
258 {
259         struct spl_info *info = rkcommon_get_spl_info(params->imagename);
260
261         /*
262          * info would not be NULL, because of we checked params before.
263          */
264         return info->spl_size;
265 }
266
267 bool rkcommon_need_rc4_spl(struct image_tool_params *params)
268 {
269         struct spl_info *info = rkcommon_get_spl_info(params->imagename);
270
271         /*
272          * info would not be NULL, because of we checked params before.
273          */
274         return info->spl_rc4;
275 }
276
277 bool rkcommon_is_header_v2(struct image_tool_params *params)
278 {
279         struct spl_info *info = rkcommon_get_spl_info(params->imagename);
280
281         return (info->header_ver == RK_HEADER_V2);
282 }
283
284 static void do_sha256_hash(uint8_t *buf, uint32_t size, uint8_t *out)
285 {
286         sha256_context ctx;
287
288         sha256_starts(&ctx);
289         sha256_update(&ctx, buf, size);
290         sha256_finish(&ctx, out);
291 }
292
293 static void rkcommon_set_header0(void *buf, struct image_tool_params *params)
294 {
295         struct header0_info *hdr = buf;
296         uint32_t init_boot_size;
297
298         memset(buf, '\0', RK_INIT_OFFSET * RK_BLK_SIZE);
299         hdr->magic = cpu_to_le32(RK_MAGIC);
300         hdr->disable_rc4 = cpu_to_le32(!rkcommon_need_rc4_spl(params));
301         hdr->init_offset = cpu_to_le16(RK_INIT_OFFSET);
302         hdr->init_size   = cpu_to_le16(spl_params.init_size / RK_BLK_SIZE);
303
304         /*
305          * init_boot_size needs to be set, as it is read by the BootROM
306          * to determine the size of the next-stage bootloader (e.g. U-Boot
307          * proper), when used with the back-to-bootrom functionality.
308          *
309          * see https://lists.denx.de/pipermail/u-boot/2017-May/293267.html
310          * for a more detailed explanation by Andy Yan
311          */
312         if (spl_params.boot_file)
313                 init_boot_size = spl_params.init_size + spl_params.boot_size;
314         else
315                 init_boot_size = spl_params.init_size + RK_MAX_BOOT_SIZE;
316         hdr->init_boot_size = cpu_to_le16(init_boot_size / RK_BLK_SIZE);
317
318         rc4_encode(buf, RK_BLK_SIZE, rc4_key);
319 }
320
321 static void rkcommon_set_header0_v2(void *buf, struct image_tool_params *params)
322 {
323         struct header0_info_v2 *hdr = buf;
324         uint32_t sector_offset, image_sector_count;
325         uint32_t image_size_array[2];
326         uint8_t *image_ptr = NULL;
327         int i;
328
329         printf("Image Type:   Rockchip %s boot image\n",
330                 rkcommon_get_spl_hdr(params));
331         memset(buf, '\0', RK_INIT_OFFSET * RK_BLK_SIZE);
332         hdr->magic   = cpu_to_le32(RK_MAGIC_V2);
333         hdr->size_and_nimage = cpu_to_le32((2 << 16) + 384);
334         hdr->boot_flag = cpu_to_le32(HASH_SHA256);
335         sector_offset = 4;
336         image_size_array[0] = spl_params.init_size;
337         image_size_array[1] = spl_params.boot_size;
338
339         for (i = 0; i < 2; i++) {
340                 image_sector_count = image_size_array[i] / RK_BLK_SIZE;
341                 hdr->images[i].size_and_off = cpu_to_le32((image_sector_count
342                                                         << 16) + sector_offset);
343                 hdr->images[i].address = 0xFFFFFFFF;
344                 hdr->images[i].counter = cpu_to_le32(i + 1);
345                 image_ptr = buf + sector_offset * RK_BLK_SIZE;
346                 do_sha256_hash(image_ptr, image_size_array[i],
347                                hdr->images[i].hash);
348                 sector_offset = sector_offset + image_sector_count;
349         }
350
351         do_sha256_hash(buf, (void *)hdr->hash - buf, hdr->hash);
352 }
353
354 void rkcommon_set_header(void *buf,  struct stat *sbuf,  int ifd,
355                          struct image_tool_params *params)
356 {
357         struct header1_info *hdr = buf + RK_SPL_HDR_START;
358
359         if (rkcommon_is_header_v2(params)) {
360                 rkcommon_set_header0_v2(buf, params);
361         } else {
362                 rkcommon_set_header0(buf, params);
363
364                 /* Set up the SPL name (i.e. copy spl_hdr over) */
365                 if (memcmp(&hdr->magic, "RSAK", 4))
366                         memcpy(&hdr->magic, rkcommon_get_spl_hdr(params), RK_SPL_HDR_SIZE);
367
368                 if (rkcommon_need_rc4_spl(params))
369                         rkcommon_rc4_encode_spl(buf, RK_SPL_HDR_START,
370                                                 spl_params.init_size);
371
372                 if (spl_params.boot_file) {
373                         if (rkcommon_need_rc4_spl(params))
374                                 rkcommon_rc4_encode_spl(buf + RK_SPL_HDR_START,
375                                                         spl_params.init_size,
376                                                         spl_params.boot_size);
377                 }
378         }
379 }
380
381 static inline unsigned int rkcommon_offset_to_spi(unsigned int offset)
382 {
383         /*
384          * While SD/MMC images use a flat addressing, SPI images are padded
385          * to use the first 2K of every 4K sector only.
386          */
387         return ((offset & ~0x7ff) << 1) + (offset & 0x7ff);
388 }
389
390 static int rkcommon_parse_header(const void *buf, struct header0_info *header0,
391                                  struct spl_info **spl_info)
392 {
393         unsigned int hdr1_offset;
394         struct header1_info *hdr1_sdmmc, *hdr1_spi;
395         int i;
396
397         if (spl_info)
398                 *spl_info = NULL;
399
400         /*
401          * The first header (hdr0) is always RC4 encoded, so try to decrypt
402          * with the well-known key.
403          */
404         memcpy((void *)header0, buf, sizeof(struct header0_info));
405         rc4_encode((void *)header0, sizeof(struct header0_info), rc4_key);
406
407         if (le32_to_cpu(header0->magic) != RK_MAGIC)
408                 return -EPROTO;
409
410         /* We don't support RC4 encoded image payloads here, yet... */
411         if (le32_to_cpu(header0->disable_rc4) == 0)
412                 return -ENOSYS;
413
414         hdr1_offset = le16_to_cpu(header0->init_offset) * RK_BLK_SIZE;
415         hdr1_sdmmc = (struct header1_info *)(buf + hdr1_offset);
416         hdr1_spi = (struct header1_info *)(buf +
417                                            rkcommon_offset_to_spi(hdr1_offset));
418
419         for (i = 0; i < ARRAY_SIZE(spl_infos); i++) {
420                 if (!memcmp(&hdr1_sdmmc->magic, spl_infos[i].spl_hdr,
421                             RK_SPL_HDR_SIZE)) {
422                         if (spl_info)
423                                 *spl_info = &spl_infos[i];
424                         return IH_TYPE_RKSD;
425                 } else if (!memcmp(&hdr1_spi->magic, spl_infos[i].spl_hdr,
426                                    RK_SPL_HDR_SIZE)) {
427                         if (spl_info)
428                                 *spl_info = &spl_infos[i];
429                         return IH_TYPE_RKSPI;
430                 }
431         }
432
433         return -1;
434 }
435
436 static int rkcommon_parse_header_v2(const void *buf, struct header0_info_v2 *header)
437 {
438         memcpy((void *)header, buf, sizeof(struct header0_info_v2));
439
440         if (le32_to_cpu(header->magic) != RK_MAGIC_V2)
441                 return -EPROTO;
442
443         return 0;
444 }
445
446 int rkcommon_verify_header(unsigned char *buf, int size,
447                            struct image_tool_params *params)
448 {
449         struct header0_info header0;
450         struct spl_info *img_spl_info, *spl_info;
451         int ret;
452
453         ret = rkcommon_parse_header(buf, &header0, &img_spl_info);
454
455         /* If this is the (unimplemented) RC4 case, then rewrite the result */
456         if (ret == -ENOSYS)
457                 return 0;
458
459         if (ret < 0)
460                 return ret;
461
462         /*
463          * If no 'imagename' is specified via the commandline (e.g. if this is
464          * 'dumpimage -l' w/o any further constraints), we accept any spl_info.
465          */
466         if (params->imagename == NULL)
467                 return 0;
468
469         /* Match the 'imagename' against the 'spl_hdr' found */
470         spl_info = rkcommon_get_spl_info(params->imagename);
471         if (spl_info && img_spl_info)
472                 return strcmp(spl_info->spl_hdr, img_spl_info->spl_hdr);
473
474         return -ENOENT;
475 }
476
477 void rkcommon_print_header(const void *buf)
478 {
479         struct header0_info header0;
480         struct header0_info_v2 header0_v2;
481         struct spl_info *spl_info;
482         uint8_t image_type;
483         int ret, boot_size, init_size;
484
485         if ((*(uint32_t *)buf) == RK_MAGIC_V2) {
486                 ret = rkcommon_parse_header_v2(buf, &header0_v2);
487
488                 if (ret < 0) {
489                         fprintf(stderr, "Error: image verification failed\n");
490                         return;
491                 }
492
493                 init_size = header0_v2.images[0].size_and_off >> 16;
494                 init_size = init_size * RK_BLK_SIZE;
495                 boot_size = header0_v2.images[1].size_and_off >> 16;
496                 boot_size = boot_size * RK_BLK_SIZE;
497         } else {
498                 ret = rkcommon_parse_header(buf, &header0, &spl_info);
499
500                 /* If this is the (unimplemented) RC4 case, then fail silently */
501                 if (ret == -ENOSYS)
502                         return;
503
504                 if (ret < 0) {
505                         fprintf(stderr, "Error: image verification failed\n");
506                         return;
507                 }
508
509                 image_type = ret;
510                 init_size = header0.init_size * RK_BLK_SIZE;
511                 boot_size = header0.init_boot_size * RK_BLK_SIZE - init_size;
512
513                 printf("Image Type:   Rockchip %s (%s) boot image\n",
514                        spl_info->spl_hdr,
515                        (image_type == IH_TYPE_RKSD) ? "SD/MMC" : "SPI");
516         }
517
518         printf("Init Data Size: %d bytes\n", init_size);
519
520         if (boot_size != RK_MAX_BOOT_SIZE)
521                 printf("Boot Data Size: %d bytes\n", boot_size);
522 }
523
524 void rkcommon_rc4_encode_spl(void *buf, unsigned int offset, unsigned int size)
525 {
526         unsigned int remaining = size;
527
528         while (remaining > 0) {
529                 int step = (remaining > RK_BLK_SIZE) ? RK_BLK_SIZE : remaining;
530
531                 rc4_encode(buf + offset, step, rc4_key);
532                 offset += RK_BLK_SIZE;
533                 remaining -= step;
534         }
535 }
536
537 int rkcommon_vrec_header(struct image_tool_params *params,
538                          struct image_type_params *tparams)
539 {
540         /*
541          * The SPL image looks as follows:
542          *
543          * 0x0    header0 (see rkcommon.c)
544          * 0x800  spl_name ('RK30', ..., 'RK33')
545          *        (start of the payload for AArch64 payloads: we expect the
546          *        first 4 bytes to be available for overwriting with our
547          *        spl_name)
548          * 0x804  first instruction to be executed
549          *        (start of the image/payload for 32bit payloads)
550          *
551          * For AArch64 (ARMv8) payloads, natural alignment (8-bytes) is
552          * required for its sections (so the image we receive needs to
553          * have the first 4 bytes reserved for the spl_name).  Reserving
554          * these 4 bytes is done using the BOOT0_HOOK infrastructure.
555          *
556          * The header is always at 0x800 (as we now use a payload
557          * prepadded using the boot0 hook for all targets): the first
558          * 4 bytes of these images can safely be overwritten using the
559          * boot magic.
560          */
561         tparams->header_size = RK_SPL_HDR_START;
562
563         /* Allocate, clear and install the header */
564         tparams->hdr = malloc(tparams->header_size);
565         if (!tparams->hdr) {
566                 fprintf(stderr, "%s: Can't alloc header: %s\n",
567                         params->cmdname, strerror(errno));
568                 exit(EXIT_FAILURE);
569         }
570         memset(tparams->hdr, 0, tparams->header_size);
571
572         /*
573          * We need to store the original file-size (i.e. before padding), as
574          * imagetool does not set this during its adjustment of file_size.
575          */
576         params->orig_file_size = tparams->header_size +
577                 spl_params.init_size + spl_params.boot_size;
578
579         params->file_size = ROUND(params->orig_file_size, RK_SIZE_ALIGN);
580
581         /* Ignoring pad len, since we are using our own copy_image() */
582         return 0;
583 }
584
585 static int pad_file(struct image_tool_params *params, int ifd, int pad)
586 {
587         uint8_t zeros[4096];
588
589         memset(zeros, 0, sizeof(zeros));
590
591         while (pad > 0) {
592                 int todo = sizeof(zeros);
593
594                 if (todo > pad)
595                         todo = pad;
596                 if (write(ifd, (char *)&zeros, todo) != todo) {
597                         fprintf(stderr, "%s: Write error on %s: %s\n",
598                                 params->cmdname, params->imagefile,
599                                 strerror(errno));
600                         return -1;
601                 }
602                 pad -= todo;
603         }
604
605         return 0;
606 }
607
608 static int copy_file(struct image_tool_params *params, int ifd,
609                      const char *file, int padded_size)
610 {
611         int dfd;
612         struct stat sbuf;
613         unsigned char *ptr;
614         int size;
615
616         if (params->vflag)
617                 fprintf(stderr, "Adding Image %s\n", file);
618
619         dfd = open(file, O_RDONLY | O_BINARY);
620         if (dfd < 0) {
621                 fprintf(stderr, "%s: Can't open %s: %s\n",
622                         params->cmdname, file, strerror(errno));
623                 return -1;
624         }
625
626         if (fstat(dfd, &sbuf) < 0) {
627                 fprintf(stderr, "%s: Can't stat %s: %s\n",
628                         params->cmdname, file, strerror(errno));
629                 goto err_close;
630         }
631
632         if (params->vflag)
633                 fprintf(stderr, "Size %u(pad to %u)\n",
634                         (int)sbuf.st_size, padded_size);
635
636         ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, dfd, 0);
637         if (ptr == MAP_FAILED) {
638                 fprintf(stderr, "%s: Can't read %s: %s\n",
639                         params->cmdname, file, strerror(errno));
640                 goto err_munmap;
641         }
642
643         size = sbuf.st_size;
644         if (write(ifd, ptr, size) != size) {
645                 fprintf(stderr, "%s: Write error on %s: %s\n",
646                         params->cmdname, params->imagefile, strerror(errno));
647                 goto err_munmap;
648         }
649
650         munmap((void *)ptr, sbuf.st_size);
651         close(dfd);
652         return pad_file(params, ifd, padded_size - size);
653
654 err_munmap:
655         munmap((void *)ptr, sbuf.st_size);
656 err_close:
657         close(dfd);
658         return -1;
659 }
660
661 int rockchip_copy_image(int ifd, struct image_tool_params *params)
662 {
663         int ret;
664
665         ret = copy_file(params, ifd, spl_params.init_file,
666                         spl_params.init_size);
667         if (ret)
668                 return ret;
669
670         if (spl_params.boot_file) {
671                 ret = copy_file(params, ifd, spl_params.boot_file,
672                                 spl_params.boot_size);
673                 if (ret)
674                         return ret;
675         }
676
677         return pad_file(params, ifd,
678                         params->file_size - params->orig_file_size);
679 }