forked from Mellanox/mlxbf-bootctl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mlxbf-bootctl.c
1472 lines (1246 loc) · 39.9 KB
/
mlxbf-bootctl.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2017-2018, Mellanox Technologies Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define _GNU_SOURCE // asprintf
#include <errno.h>
#include <getopt.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include <linux/major.h>
/* Boot FIFO constants */
#define BOOT_FIFO_ADDR 0x0408
#define SEGMENT_HEADER_LEN 8
#define MAX_SEG_LEN ((1 << 20) - SEGMENT_HEADER_LEN)
#define SEGMENT_IS_END (1UL << 63)
/* File size limits */
#define INPUT_BFB_MAX_SIZE (20 * 1024 * 1024)
#define MMC_BOOT_PARTITION_MAX_SIZE (4 * 1024 * 1024)
/* DMI constants */
#define DMI_TABLE_PATH "/sys/firmware/dmi/tables/DMI"
#define DMI_PROCESSOR_INFO_TYPE 4
#define DMI_PROCESSOR_VERSION_STR_MAX_SIZE 100
/* PSC APP image ID */
#define PSC_APP_IMG_ID 39
/* Record size of irot signature db. */
#define PSC_APP_IROT_SIG_REC_LEN 104
/* TLV based PSC APP sub-image header. */
typedef struct __attribute__((__packed__)) {
#define PSC_APP_TYPE_IROT_SIGNATURE_DB 0x1
uint8_t type; /* sub-image type */
uint32_t length; /* sub-image payload length */
uint8_t unused[3];
} psc_app_img_hdr_t;
/* Other constants */
#define MAX_VERSIONS_COUNT 256
void die(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
putc('\n', stderr);
va_end(ap);
exit(1);
}
/*
* BFB image header.
*
* This definition is extracted from file
* atf/plat/mellanox/common/include/drivers/io/bluefield_boot.h
*/
#define BFB_IMGHDR_MAGIC 0x13026642 /* "Bf^B^S" */
typedef struct {
unsigned long magic:32;
unsigned long major:4;
unsigned long minor:4;
unsigned long reserved:4;
unsigned long next_img_ver:4;
unsigned long cur_img_ver:4;
unsigned long hdr_len:4;
unsigned long image_id:8;
unsigned long image_len:32;
unsigned long image_crc:32;
unsigned long following_images:64;
} boot_image_header_t;
ssize_t read_or_die(const char* filename, int fd, void* buf, size_t count);
#ifndef OUTPUT_ONLY
#include <linux/mmc/ioctl.h>
/*
* The Linux MMC driver doesn't export its ioctl command values, so we
* copy them from include/linux/mmc/mmc.h and include/linux/mmc/core.h.
*/
#define MMC_SWITCH 6 /* ac [31:0] See below R1b */
#define MMC_SEND_EXT_CSD 8 /* adtc R1 */
#define MMC_RSP_PRESENT (1 << 0)
#define MMC_RSP_CRC (1 << 2) /* expect valid crc */
#define MMC_RSP_BUSY (1 << 3) /* card may send busy */
#define MMC_RSP_OPCODE (1 << 4) /* response contains opcode */
#define MMC_RSP_SPI_S1 (1 << 7) /* one status byte */
#define MMC_RSP_SPI_BUSY (1 << 10) /* card may send busy */
#define MMC_RSP_SPI_R1 (MMC_RSP_SPI_S1)
#define MMC_RSP_R1 (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE)
#define MMC_RSP_R1B (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE|MMC_RSP_BUSY)
#define MMC_RSP_SPI_R1B (MMC_RSP_SPI_S1|MMC_RSP_SPI_BUSY)
#define MMC_CMD_AC (0 << 5)
#define MMC_CMD_ADTC (1 << 5)
#define MMC_SWITCH_MODE_WRITE_BYTE 0x03 /* Set target to value */
#define EXT_CSD_CMD_SET_NORMAL (1<<0)
/* EXT_CSD register offset. */
#define EXT_CSD_RST_N 162 /* R/W */
#define EXT_CSD_BOOT_BUS_WIDTH 177 /* R/W */
#define EXT_CSD_PART_CONFIG 179 /* R/W */
#define EXT_CSD_BOOT_SIZE_MULT 226 /* R/W */
/* BOOT_BUS_WIDTH register definition. */
#define EXT_CSD_BOOT_BUS_WIDTH_MASK_ALL 0x7
#define EXT_CSD_BOOT_BUS_WIDTH_MASK 0x3
#define EXT_CSD_BOOT_BUS_WIDTH_RESET_MASK 0x4
#define EXT_CSD_BOOT_BUS_WIDTH_X8 0x6
/* EXT_CSD_RST_N register definition. */
#define EXT_CSD_RST_N_MASK 0x3
#define EXT_CSD_RST_N_ENABLE 0x1
/* Program constants */
#define EMMC_MIN_BOOT_SIZE 0x20000
#define EMMC_BLOCK_SIZE 512
#define SYS_PATH1 "/sys/bus/platform/devices/MLNXBF04:00/driver"
#define SYS_PATH2 "/sys/bus/platform/devices/MLNXBF04:00"
#define SECOND_RESET_ACTION_PATH "second_reset_action"
#define POST_RESET_WDOG_PATH "post_reset_wdog"
#define LIFECYCLE_STATE_PATH "lifecycle_state"
#define SECURE_BOOT_FUSE_STATE_PATH "secure_boot_fuse_state"
/* Program variables */
const char *mmc_path = "/dev/mmcblk0";
/* PSC cert update filtering info */
static uint8_t psc_cert_update; /* whether cert need update. */
static uint64_t psc_cert_key; /* cert signature lookup key */
/* Run an MMC_IOC_CMD ioctl on mmc_path */
void mmc_command(struct mmc_ioc_cmd *idata)
{
static int mmc_fd = -1;
if (mmc_fd < 0)
{
mmc_fd = open(mmc_path, O_RDWR);
if (mmc_fd < 0)
die("%s: %m", mmc_path);
}
if (ioctl(mmc_fd, MMC_IOC_CMD, idata) < 0)
die("%s: mmc ioctl: %m", mmc_path);
}
uint8_t* get_ext_csd(void)
{
static uint8_t ext_csd[EMMC_BLOCK_SIZE]
__attribute__((aligned(EMMC_BLOCK_SIZE))) = { 0 };
struct mmc_ioc_cmd idata = {
.write_flag = 0,
.opcode = MMC_SEND_EXT_CSD,
.arg = 0,
.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC,
.blksz = EMMC_BLOCK_SIZE,
.blocks = 1
};
mmc_ioc_cmd_set_data(idata, ext_csd);
mmc_command(&idata);
return ext_csd;
}
/* Return the current partition (0 or 1) that we will boot from. */
int get_boot_partition(void)
{
uint8_t *ext_csd = get_ext_csd();
int part = ((ext_csd[EXT_CSD_PART_CONFIG] >> 3) & 0x7) - 1;
/* Set part to 0 by default if it is -1 (boot disabled). */
if (part < 0 || part > 1)
part = 0;
return part;
}
/* Set which partition to boot from. */
void set_boot_partition(int part)
{
int value = ((part + 1) & 0x7) << 3; /* Adjust for 1-based numbering */
struct mmc_ioc_cmd idata = {
.write_flag = 1,
.opcode = MMC_SWITCH,
.arg = ((MMC_SWITCH_MODE_WRITE_BYTE << 24) |
(EXT_CSD_PART_CONFIG << 16) |
(value << 8) |
EXT_CSD_CMD_SET_NORMAL),
.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC
};
mmc_command(&idata);
}
/* Get the boot partition size */
uint64_t get_boot_partition_size(void)
{
uint64_t part_size;
uint8_t *ext_csd = get_ext_csd();
part_size = (ext_csd[EXT_CSD_BOOT_SIZE_MULT]) *
EMMC_MIN_BOOT_SIZE;
return part_size;
}
/* Return the current boot bus width. */
int get_boot_bus_width(void)
{
uint8_t *ext_csd = get_ext_csd();
return ext_csd[EXT_CSD_BOOT_BUS_WIDTH] & EXT_CSD_BOOT_BUS_WIDTH_MASK_ALL;
}
/* Set the boot-bus-width to 8-bit mode in ECSD. */
void set_boot_bus_width(void)
{
uint8_t *ext_csd = get_ext_csd();
int value = (ext_csd[EXT_CSD_BOOT_BUS_WIDTH] &
~EXT_CSD_BOOT_BUS_WIDTH_MASK_ALL) | EXT_CSD_BOOT_BUS_WIDTH_X8;
struct mmc_ioc_cmd idata = {
.write_flag = 1,
.opcode = MMC_SWITCH,
.arg = ((MMC_SWITCH_MODE_WRITE_BYTE << 24) |
(EXT_CSD_BOOT_BUS_WIDTH << 16) |
(value << 8) |
EXT_CSD_CMD_SET_NORMAL),
.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC
};
mmc_command(&idata);
}
void enable_rst_n(void)
{
uint8_t *ext_csd = get_ext_csd();
int value = (ext_csd[EXT_CSD_RST_N] & ~EXT_CSD_RST_N_MASK) |
EXT_CSD_RST_N_ENABLE;
struct mmc_ioc_cmd idata = {
.write_flag = 1,
.opcode = MMC_SWITCH,
.arg = ((MMC_SWITCH_MODE_WRITE_BYTE << 24) |
(EXT_CSD_RST_N << 16) |
(value << 8) |
EXT_CSD_CMD_SET_NORMAL),
.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC
};
mmc_command(&idata);
}
FILE *open_sysfs(const char *name, const char *attr)
{
FILE *f;
char path[PATH_MAX];
sprintf(path, "%s/%s", SYS_PATH1, name);
f = fopen(path, attr);
if (f == NULL) {
sprintf(path, "%s/%s", SYS_PATH2, name);
f = fopen(path, attr);
}
if (f == NULL) {
if (errno == ENOENT) {
fprintf(stderr, "cannot find required sysfs path %s\n", path);
die("please load mlxbf_bootctl kernel driver");
}
die("%s: %m", name);
}
return f;
}
int get_watchdog(void)
{
FILE *f = open_sysfs(POST_RESET_WDOG_PATH, "r");
int watchdog;
if (fscanf(f, "%d", &watchdog) != 1)
die("%s: failed to read integer", POST_RESET_WDOG_PATH);
fclose(f);
return watchdog;
}
void set_watchdog(int interval)
{
FILE *f = open_sysfs(POST_RESET_WDOG_PATH, "w");
if (fprintf(f, "%d\n", interval) < 0)
die("%s: failed to set watchdog to '%d'", POST_RESET_WDOG_PATH, interval);
fclose(f);
}
void set_second_reset_action(const char *action)
{
FILE *f = open_sysfs(SECOND_RESET_ACTION_PATH, "w");
if (fprintf(f, "%s\n", action) < 0)
die("%s: failed to set action to '%s'", SECOND_RESET_ACTION_PATH, action);
fclose(f);
}
// Return the (malloced) string describing the lifecycle state (w line return)
char *get_lifecycle_state(void)
{
FILE *f = open_sysfs(LIFECYCLE_STATE_PATH, "r");
char *buf = NULL;
size_t len = 0;
if (getline(&buf, &len, f) == -1)
die("%s: failed to get lifecycle state", LIFECYCLE_STATE_PATH);
fclose(f);
return buf;
}
// Return number of remaining free secure boot fuse versions
int get_free_sbfuse_slots(void)
{
int free_slot = 0;
FILE *f = open_sysfs(SECURE_BOOT_FUSE_STATE_PATH, "r");
char *buf = NULL, *p;
size_t len = 0;
while (getline(&buf, &len, f) != -1)
{
p = buf;
while ((p = strstr(p, "Free")) != NULL) {
free_slot++;
p += strlen("Free");
}
}
free(buf);
fclose(f);
return free_slot;
}
void show_status(void)
{
// Display the default boot partition
int part = get_boot_partition();
printf("primary: %sboot%d\n", mmc_path, part);
printf("backup: %sboot%d\n", mmc_path, part ^ 1);
// Display the boot bus width setting
int boot_bus_width = get_boot_bus_width();
printf("boot-bus-width: x%d\n",
(boot_bus_width & EXT_CSD_BOOT_BUS_WIDTH_MASK) ?
(boot_bus_width & EXT_CSD_BOOT_BUS_WIDTH_MASK) * 4 : 1);
printf("reset to x1 after reboot: %s\n",
(boot_bus_width & EXT_CSD_BOOT_BUS_WIDTH_RESET_MASK)? "FALSE" : "TRUE");
// Display the watchdog value
int watchdog = get_watchdog();
printf("watchdog-swap: ");
if (watchdog == 0)
printf("disabled\n");
else
printf("%d\n", watchdog);
// Display the secure boot fuse states
char *lifecycle_state = get_lifecycle_state();
printf("lifecycle state: %s", lifecycle_state);
free(lifecycle_state);
printf("secure boot key free slots: %d\n", get_free_sbfuse_slots());
}
// Get the version of hardware we're currently running on.
// If it can't be found, this will return -1.
int get_hw_version(void) {
const char *dmi_file = DMI_TABLE_PATH;
int dmi_fd = open(dmi_file, O_RDONLY);
if (dmi_fd < 0) {
fprintf(stderr, "warn: %s: %m, disable version filtering\n", dmi_file);
return -1;
}
struct stat st;
if (fstat(dmi_fd, &st) < 0)
die("%s: stat: %m", dmi_file);
void *dmi_buf = malloc(st.st_size);
if (dmi_buf == NULL)
die("out of memory");
int n_bytes = 0;
n_bytes = read_or_die(dmi_file, dmi_fd, dmi_buf, st.st_size);
if (n_bytes != st.st_size)
die("%s: could not read DMI table", dmi_file);
if (close(dmi_fd) < 0)
die("%s: close: %m", dmi_file);
// Now, skip along table until we reach the processor info
int bytes_left = st.st_size;
void *idx = dmi_buf;
uint8_t table_size = 0;
while (bytes_left > 0) {
uint8_t table_type = *((uint8_t*)idx);
table_size = *((uint8_t*)idx + 1);
// Break if we hit the processor table.
if (table_type == DMI_PROCESSOR_INFO_TYPE)
break;
// Otherwise, skip to next table.
idx += table_size;
bytes_left -= table_size;
bool first_str = true;
// We might need to skip over strings, too.
while (bytes_left > 0) {
// If idx is over two 0 bytes, we're at the end, so
// advance to the next table.
if (*(uint16_t*)idx == 0) {
idx += sizeof(uint16_t);
bytes_left -= sizeof(uint16_t);
break;
} else {
// Skip a string. Note the first iteration will
// place the index at the beginning of the string,
// whereas all further iterations place the index at
// the NULL terminator.
if (!first_str) {
idx++;
bytes_left--;
}
first_str = false;
while (*(char*)idx && bytes_left > 0) {
idx++;
bytes_left--;
}
}
}
}
if (bytes_left <= 0) {
fprintf(stderr, "warning: could not find BlueField SoC revision\n");
free(dmi_buf);
return -1;
}
// Now idx is at processor version table - we can read the
// string now. SMBIOS tables append all strings to the end
// of the structure, and refer to them by their order.
// First string is 1, second is 2, etc.
uint8_t soc_ver_snum = *(uint8_t*)(idx + 0x10);
if (soc_ver_snum == 0) {
fprintf(stderr, "warning: found DMI processor ver field, but it's NULL\n");
free(dmi_buf);
return -1;
}
idx += table_size;
bytes_left -= table_size;
// Skip strings until we hit the desired one.
char version_string[DMI_PROCESSOR_VERSION_STR_MAX_SIZE] = {0};
bool first_str = true;
while (soc_ver_snum-- > 1 && bytes_left > 0) {
if (*(uint16_t*)idx == 0) {
fprintf(stderr, "warning: DMI processor ver specifies string that does not exist.\n");
free(dmi_buf);
return -1;
} else {
if (!first_str) {
idx++;
bytes_left--;
}
first_str = false;
// Skip a string.
while (*(char*)idx && bytes_left > 0) {
idx++;
bytes_left--;
}
}
}
idx++;
bytes_left--;
// Finally, actually copy the string.
strncpy(
version_string,
idx,
bytes_left < DMI_PROCESSOR_VERSION_STR_MAX_SIZE - 1 ? bytes_left : DMI_PROCESSOR_VERSION_STR_MAX_SIZE - 1
);
// Extract version
int version = -1;
if (1 != sscanf(version_string, "Mellanox BlueField-%d", &version))
fprintf(stderr, "warning: Unknown SoC revision");
// BlueField 1 is v0, BF2 is v1, etc.
version--;
free(dmi_buf);
return version;
}
/* Find substring within a buffer. */
static char* find_str(char *buf, int buf_len, const char *str)
{
int len;
char *p = buf, *find;
while ((p - buf) < buf_len) {
len = strlen(p);
find = strstr(p, str);
if (find)
return find;
p += len + 1;
}
return NULL;
}
/*
* Handle the IROT signature DB and returns the offset of the record which
* matches the key 'psc_cert_key', or return value < 0 in case of error case
* or not found.
*/
static int handle_irot_sig_db(uint8_t *buf, uint32_t buf_len)
{
uint32_t idx0, idx1, idx;
uint64_t data64;
/* Ignore sig db if not patch is needed. */
if (!psc_cert_update)
return -1;
/* Sanity check. */
if (buf_len % PSC_APP_IROT_SIG_REC_LEN)
return -EINVAL;
/* Binary search on the sorted records within range [idx0, idx1]. */
idx0 = 0;
idx1 = buf_len / PSC_APP_IROT_SIG_REC_LEN - 1;
/* Binary search to find the record. */
for(;;) {
idx = (idx0 + idx1) / 2;
data64 = *(uint64_t *)(buf + idx * PSC_APP_IROT_SIG_REC_LEN);
if (data64 < psc_cert_key) {
if (idx0 == idx)
break;
else
idx0 = idx;
} else if (data64 == psc_cert_key) {
break;
} else {
if (idx1 == idx)
break;
else
idx1 = idx;
}
}
return (data64 == psc_cert_key) ? idx : -1;
}
/*
* Filter the PSC APP image.
* For the IROT signature DB, only up to one record is needed if matching the
* lookup key.
*/
size_t filter_psc_app_image(void *image, size_t img_size)
{
psc_app_img_hdr_t *hdr;
size_t adjust_len = 0, len = 0;
int idx;
while (len < img_size) {
hdr = (psc_app_img_hdr_t *)(image + len);
if (len + sizeof(*hdr) + hdr->length > img_size)
die("corrupted image\n");
if (len != adjust_len) {
memmove(image + adjust_len, image + len, sizeof(*hdr) + hdr->length);
hdr = (psc_app_img_hdr_t *)(image + adjust_len);
}
len += sizeof(*hdr) + hdr->length;
if (hdr->type != PSC_APP_TYPE_IROT_SIGNATURE_DB) {
adjust_len += sizeof(*hdr) + hdr->length;
continue;
}
idx = handle_irot_sig_db((uint8_t *)&hdr[1], hdr->length);
if (idx >= 0) {
memmove((uint8_t *)&hdr[1],
(uint8_t *)&hdr[1] + idx * PSC_APP_IROT_SIG_REC_LEN,
PSC_APP_IROT_SIG_REC_LEN);
hdr->length = PSC_APP_IROT_SIG_REC_LEN;
adjust_len += sizeof(*hdr) + PSC_APP_IROT_SIG_REC_LEN;
}
}
return adjust_len;
}
static uint32_t crc32_update(uint32_t crc, uint8_t *p, unsigned int len)
{
int i;
while (len--) {
crc ^= *p++;
for (i = 0; i < 8; i++)
crc = (crc >> 1) ^ ((crc & 1) ? 0xedb88320 : 0);
}
return crc;
}
#else
/* Dummy max partition size for OUTPUT_ONLY */
uint64_t get_boot_partition_size(void)
{
return INPUT_BFB_MAX_SIZE;
}
#endif // OUTPUT_ONLY
// Read as much as possible despite EINTR or partial reads, and die on error.
ssize_t read_or_die(const char* filename, int fd, void* buf, size_t count)
{
ssize_t n = 0;
while (count > 0)
{
ssize_t rc = read(fd, buf, count);
if (rc < 0)
{
if (errno == EINTR)
continue;
die("%s: can't read: %m", filename);
}
if (rc == 0)
break;
n += rc;
buf += rc;
count -= rc;
}
return n;
}
// Write everything passed in despite EINTR or partial reads, and die on error.
ssize_t write_or_die(const char* filename,
int fd, const void* buf, size_t count)
{
ssize_t n = count;
while (count > 0)
{
ssize_t rc = write(fd, buf, count);
if (rc < 0)
{
if (errno == EINTR)
continue;
die("%s: can't write: %m", filename);
}
if (rc == 0)
die("%s: write returned zero", filename);
buf += rc;
count -= rc;
}
return n;
}
/*
* Generate the boot stream segment header.
*
* is_end: 1 if this segment is the last segment of the boot code, else 0.
* channel: The channel number to write to.
* address: The register address to write to.
* length: The length of this segment in bytes; max is MAX_SEG_LEN.
*
* We ignore endian issues here since if the tool is built natively,
* this is likely correct anyway, and if built cross, we don't have a
* way to know the endianness of the arm cores anyway.
*/
uint64_t gen_seg_header(int is_end, int channel, int address, size_t length)
{
return (((is_end & 0x1UL) << 63) |
((channel & 0xfUL) << 45) |
((address & 0xfff8UL) << 29) |
(((length + SEGMENT_HEADER_LEN) >> 3) & 0x1ffffUL));
}
uint64_t get_segment_length(uint64_t segheader)
{
uint64_t length = (segheader & 0x1ffffUL) << 3;
if (length == 0)
length = MAX_SEG_LEN;
else
length -= SEGMENT_HEADER_LEN;
return length;
}
void read_bootstream(const char *bootstream, const char *bootfile,
uint64_t part_size)
{
// Copy the contents of the bootfile device to a bootstream
printf("Copy bootstream from %s to %s\n", bootfile, bootstream);
int ifd = open(bootfile, O_RDONLY);
if (ifd < 0)
die("%s: %m", bootfile);
int ofd = open(bootstream, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (ofd < 0)
die("%s: %m", bootstream);
char *buf = malloc(MAX_SEG_LEN);
if (buf == NULL)
die("out of memory");
uint64_t header;
// Read and discard the header word
read_or_die(bootfile, ifd, &header, sizeof(header));
uint64_t segheader = 0, total_size = 0;
while (!(segheader & SEGMENT_IS_END))
{
read_or_die(bootfile, ifd, &segheader, sizeof(segheader));
uint64_t seg_size = get_segment_length(segheader);
read_or_die(bootfile, ifd, buf, seg_size);
write_or_die(bootstream, ofd, buf, seg_size);
total_size += seg_size;
if (total_size > part_size)
die("No valid bfb present");
}
if (close(ifd) < 0)
die("%s: close: %m", bootstream);
if (close(ofd) < 0)
die("%s: close: %m", bootfile);
free(buf);
}
// Read a header from a boot stream. This will consume the
// entire header, verify it, and return the header
// structure.
size_t read_bootstream_header(const char *bootstream, int ifd, boot_image_header_t *hdr) {
int n;
uint64_t data;
// Read and verify the image header.
n = read_or_die(bootstream, ifd, hdr, sizeof(*hdr));
if (n != sizeof(*hdr))
die("Unable to read next header, n=%d", n);
n = hdr->hdr_len - sizeof(*hdr) / sizeof(uint64_t);
if (n < 0)
die("Invalid header length %d, n=%d", hdr->hdr_len, n);
// Drain the rest of header.
while (n--) {
if (read_or_die(bootstream, ifd, &data, sizeof(data)) != sizeof(data))
die("Not enough data for header");
}
return hdr->hdr_len * sizeof(uint64_t);
}
// Correct the following_images and next_img_ver fields in a BFB buffer.
// Note this assumes a well-formed BFB stream in the buffer.
void correct_bootstream_headers(void *buf, int num_images) {
uint64_t fi_map = 0;
void *idx = buf;
boot_image_header_t *hdr;
int img_size = 0;
int pad_size = 0;
if (num_images <= 0)
die("%s: num_images must be at least 1", __FUNCTION__);
// Markers to find images next time
void **images = malloc(num_images * sizeof(void*));
if (images == NULL)
die("out of memory");
// Iterate once to build fi_map and mark image starts
for (int i = 0; i < num_images; i++) {
hdr = (boot_image_header_t*) idx;
// Build image maps
fi_map |= 1UL << hdr->image_id;
images[i] = idx;
// Skip to next image
img_size = hdr->image_len;
pad_size = (img_size % 8) ? (8 - img_size % 8) : 0;
idx += img_size + pad_size + hdr->hdr_len * sizeof(uint64_t);
}
boot_image_header_t *prev_hdr;
// Now we can iterate over the images directly and fixup
// the fields that need it
for (int i = 0; i < num_images; i++) {
hdr = (boot_image_header_t*) images[i];
// Update image bitmap. Note that on the last
// image of a series of versions, this will be wrong,
// and will be corrected next iteration.
hdr->following_images = fi_map;
if (i > 0) {
prev_hdr = (boot_image_header_t*) images[i-1];
if (prev_hdr->image_id == hdr->image_id) {
// Update next_img_ver as long as we haven't gone to
// a new image ID.
prev_hdr->next_img_ver = hdr->cur_img_ver;
} else {
// If next image ID is different, then update
// fi_map, and correct the previous image.
fi_map &= ~(1UL << prev_hdr->image_id);
prev_hdr->following_images = fi_map;
// We also set prev_hdr's next_img_ver to 0 since
// there are no more images of that version.
prev_hdr->next_img_ver = 0;
}
}
}
// Edge case: Handle last image.
hdr = (boot_image_header_t*)images[num_images-1];
hdr->following_images = 0;
hdr->next_img_ver = 0;
free(images);
}
// Tell whether we should write an image to the boot
// partition, based on a version number.
// We do this conservatively, so we don't accidentally
// filter out something common.
bool should_install_image(boot_image_header_t *hdr, int version, uint8_t *max_versions) {
bool install = false;
// version < 0 indicates filtering should be off. All
// images will be installed in this case.
if (version < 0)
return true;
// If version filtering is on, check max_versions is valid
if (max_versions == NULL)
die("internal: max_versions is NULL");
#ifndef OUTPUT_ONLY
if ((hdr->image_id == PSC_APP_IMG_ID) && !psc_cert_update)
return false;
#endif
// The logic to decide what to install and what not to install
// is based on BlueField 1, 2, 3, <X> chips each possibly having
// their own version of a specific image while at the same time
// also using "shared" images. A shared image is defined as an
// image with a version of 0 AND there are no other higher
// versions in the bootstream (i.e. images with a version > 0).
// If the version matches OR the image is a shared image, install it.
if ((hdr->cur_img_ver == version) || (max_versions[hdr->image_id] == 0)) {
install = true;
}
return install;
}
// Find the maximum version image for each image ID.
// max_versions must be a 256 element array. Each element of max_versions
// corresponds to a maximum version: max_versions[img_id] = max_img_ver
void find_max_versions(const char *bootstream, uint8_t *max_versions) {
if (max_versions == NULL)
die("%s: internal: max_versions is NULL", bootstream);
int ifd = open(bootstream, O_RDONLY);
if (ifd < 0)
die("%s: %m", bootstream);
struct stat st;
if (fstat(ifd, &st) < 0)
die("%s: stat: %m", bootstream);
int bytes_left = st.st_size;
// Initialize max_versions
memset (max_versions, 0, MAX_VERSIONS_COUNT * sizeof(uint8_t));
boot_image_header_t hdr;
size_t hdr_size;
size_t pad_size;
size_t img_size;
size_t n_bytes;
while (bytes_left > 0) {
hdr_size = read_bootstream_header(bootstream, ifd, &hdr);
bytes_left -= hdr_size;
img_size = hdr.image_len;
pad_size = (img_size % 8) ? (8 - img_size % 8) : 0;
// update max_versions if needed
if (hdr.cur_img_ver > max_versions[hdr.image_id])
max_versions[hdr.image_id] = hdr.cur_img_ver;
// Skip image
n_bytes = lseek(ifd, img_size + pad_size, SEEK_CUR);
if (n_bytes < 0)
die("%s: Could not skip filtered image: %m", bootstream);
bytes_left -= img_size + pad_size;
}
close (ifd);
}
// Read a bootstream to an internal buffer, optionally filtering out images
// of a given version. Supply -1 to version to turn this behavior off.
size_t read_bootstream_to_buffer(const char *bootstream, void *buf, int buf_size, int version)
{
int ifd = open(bootstream, O_RDONLY);
if (ifd < 0)
die("%s: %m", bootstream);
struct stat st;
if (fstat(ifd, &st) < 0)
die("%s: stat: %m", bootstream);
int bytes_left = st.st_size;
// If no version filtering requested and file is too large for the
// buffer, error out.
if (version < 0 && bytes_left > buf_size) {
die("%s: Boot stream file is too large", bootstream);
}
uint8_t max_versions[MAX_VERSIONS_COUNT];
find_max_versions(bootstream, max_versions);
void *idx = buf; // Index along buffer
size_t n_bytes = 0, n_bytes_adjust = 0;
boot_image_header_t hdr;
size_t hdr_size; // Size of the image header, including reserved words
size_t pad_size;
size_t img_size;
int num_images = 0;
// Otherwise, we'll need to read the whole file and filter it to tell
// whether stream will fit.
while (bytes_left > 0) {
hdr_size = read_bootstream_header(bootstream, ifd, &hdr);
bytes_left -= hdr_size;
img_size = hdr.image_len;
pad_size = (img_size % 8) ? (8 - img_size % 8) : 0;
// Check whether the version should be included.