-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfpga_mgr.cpp
More file actions
1291 lines (1170 loc) · 41.7 KB
/
Copy pathfpga_mgr.cpp
File metadata and controls
1291 lines (1170 loc) · 41.7 KB
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
#include <array>
#include <cstdint>
#include <cstring>
#include <stdio.h>
//
#include "f_util.h"
#include "ff.h"
#include "hardware/dma.h"
#include "hardware/gpio.h"
#include "hardware/pio.h"
#include "hardware/structs/sio.h"
#include "hardware/watchdog.h"
#include "hardware/xosc.h"
#include "pico/stdlib.h"
#include "rtc.h"
//
#include "boot_config.h"
#include "boot_log.h"
#include "fpga_manager_version.h"
#include "fpga_out.pio.h"
#include "golden_images.h"
#include "hardware/clocks.h"
#include "hw_config.h"
#include "miniz.h"
#include "supervisor_service.h"
// Set to 0 to use legacy GPIO bit-bang path for FPGA programming.
#ifndef USE_PIO_FPGA
#define USE_PIO_FPGA 1
#endif
#ifndef FPGA_PIO_CLKDIV
#define FPGA_PIO_CLKDIV 1.0f
#endif
#ifndef K2_BOARD_REVISION
#define K2_BOARD_REVISION "unknown"
#endif
// datasheet for information on which other pins can be used.
#define UART_ID uart1
#define BAUD_RATE 115200
#define DATA_BITS 8
#define STOP_BITS 1
#define PARITY UART_PARITY_NONE
#define UART_TX_PIN 24
#define UART_RX_PIN 25
#define SPI_SUPER_MISO_i 0 // SPI0
#define SPI_SUPER_CSn_i 1 // SPI0
#define SPI_SUPER_SCLK_i 2 // SPI0
#define SPI_SUPER_MOSI_o 3 // SPI0
#define FPGA_CONFIG_PRG 4 // Output - Pulse to begin Sequence
#define FPGA_SYSTEM_RSTn 5 // Output
#define FPGA_CONFIG_CCLK 6 // Output
#define FPGA_CONFIG_INITn 7 // Input
// Output
#define FPGA_BUS_D0 8
#define FPGA_BUS_D1 9
#define FPGA_BUS_D2 10
#define FPGA_BUS_D3 11
#define FPGA_BUS_D4 12
#define FPGA_BUS_D5 13
#define FPGA_BUS_D6 14
#define FPGA_BUS_D7 15
// Input
#define F256K2_CONTEXT_SW0 16
#define F256K2_CONTEXT_SW1 17
#define SPI_SD_SD1 21 // Not used now
#define SPI_SD_SD2 22 // Not used Now
// UART Definition
#define COM_TX_PIN 24 // UART1
#define COM_RX_PIN 25 // UART1
#define ADC0 26
#define ADC1 27
#define ADC2 28
#define ADC3 29
#define FPGA_SIZE 9730652
#define BUFFER_SIZE 32768
#define GZ_IN_BUF_SIZE 2048
#define FPGA_DATA_MASK 0x0000FF00u
#define FPGA_CCLK_MASK (1u << FPGA_CONFIG_CCLK)
#define FPGA_INIT_TIMEOUT_MS 100
#define RESET_HOLD_SAMPLE_MS 100
#define RESET_HOLD_SECONDS 5
#define RESET_HOLD_TICKS ((RESET_HOLD_SECONDS * 1000) / RESET_HOLD_SAMPLE_MS)
// Prototypes
void f256k2_context_man_init_io(void);
static inline void f256k2_Set_FPGA_Data_Port(unsigned char Value);
bool f256k2_init_prg_fpga(void);
bool f256k2_prg_block_fpga(const uint8_t* ptr, unsigned int len);
bool program_fpga_from_file(FIL* fil);
bool program_fpga_from_gz_file(const char* path);
bool program_fpga_from_file_path(const char* path);
bool program_fpga_from_gz_file_path(const char* gz_path);
// External FPGA gzip blobs are stored in flash at fixed addresses.
#define FPGA_FLASH_GZIP_BASE0 0x10800000u
#define FPGA_FLASH_GZIP_BASE1 0x10A00000u
#define FPGA_FLASH_GZIP_BASE2 0x10C00000u
#define FPGA_FLASH_GZIP_BASE3 0x10E00000u
#define FPGA_FLASH_SLOT_SIZE (2 * 1024 * 1024u)
typedef struct {
const char* base_path;
const char* update_filename;
const char* fallback_filename;
uint32_t flash_base;
} fpga_image_info_t;
static const fpga_image_info_t fpga_images[] = {
{ "CNTX1", "context1.bin", "CFP95600C.bin", FPGA_FLASH_GZIP_BASE0 },
{ "CNTX2", "context2.bin", "CFP95616E.bin", FPGA_FLASH_GZIP_BASE1 },
{ "CNTX3", "context3.bin", "f256k2t9.bin", FPGA_FLASH_GZIP_BASE2 },
{ "CNTX4", "context4.bin", "foenix138.bin", FPGA_FLASH_GZIP_BASE3 },
};
static void ensure_manager_sd_context_directories()
{
for (const fpga_image_info_t& image : fpga_images) {
const FRESULT result = f_mkdir(image.base_path);
if (result == FR_OK) {
printf("Created manager SD directory: %s\n", image.base_path);
boot_logf("Created SD directory: %s", image.base_path);
} else if (result != FR_EXIST) {
printf("Manager SD directory unavailable: %s (FatFs %u)\n",
image.base_path, static_cast<unsigned>(result));
boot_logf("SD directory failed: %s (%u)", image.base_path,
static_cast<unsigned>(result));
}
}
}
typedef enum {
FPGA_METHOD_NONE = 0,
FPGA_METHOD_SD_GZIP,
FPGA_METHOD_SD_RAW,
FPGA_METHOD_FLASH_GZIP,
FPGA_METHOD_GOLDEN_GZIP,
} fpga_method_t;
static std::array fpga_method_names {
"none",
"SD gzip",
"SD raw",
"FLASH gzip",
"GOLDEN gzip",
};
static_assert(FPGA_METHOD_GOLDEN_GZIP == fpga_method_names.size() - 1);
fpga_method_t program_fpga_from_sd_card(const fpga_image_info_t* info, uint8_t slot);
fpga_method_t program_fpga_from_sd_path(const char* path, uint8_t slot);
fpga_method_t program_fpga_from_flash_slot(const fpga_image_info_t* info, uint8_t slot);
bool program_fpga_from_gz_data(const uint8_t* data, size_t len, bool allow_ff_padding);
fpga_method_t program_fpga_from_golden_slot(unsigned char sw_choice);
fpga_method_t program_selected_context(uint8_t slot, bool sd_mounted,
bool force_golden);
fpga_method_t program_transient_context(uint8_t slot, bool sd_mounted,
BootSource source, const char* path);
bool reset_hold_timer_callback(struct repeating_timer* timer);
void start_reset_hold_monitor(void);
unsigned char Buffer0[BUFFER_SIZE];
static uint8_t gzip_file_buffer[GZ_IN_BUF_SIZE];
static struct repeating_timer reset_hold_timer;
static volatile unsigned int reset_hold_ticks = 0;
static volatile bool reset_hold_armed = false;
bool reset_hold_timer_callback(struct repeating_timer* timer)
{
(void)timer;
if (gpio_get(FPGA_SYSTEM_RSTn)) {
reset_hold_ticks = 0;
reset_hold_armed = true;
return true;
}
if (!reset_hold_armed) {
return true;
}
if (++reset_hold_ticks >= RESET_HOLD_TICKS) {
watchdog_reboot(0, 0, 0);
return false;
}
return true;
}
void start_reset_hold_monitor(void)
{
reset_hold_ticks = 0;
reset_hold_armed = false;
if (!add_repeating_timer_ms(-RESET_HOLD_SAMPLE_MS, reset_hold_timer_callback,
NULL, &reset_hold_timer)) {
printf("Warning: RESET hold monitor unavailable\n");
}
}
#if USE_PIO_FPGA
static PIO fpga_pio = pio0;
static int fpga_sm = -1;
static int fpga_dma_chan = -1;
static uint fpga_pio_offset = 0;
static bool fpga_pio_inited = false;
static void fpga_pio_init(void)
{
if (fpga_pio_inited) {
return;
}
fpga_sm = pio_claim_unused_sm(fpga_pio, true);
fpga_dma_chan = dma_claim_unused_channel(true);
fpga_pio_offset = pio_add_program(fpga_pio, &fpga_out_program);
pio_sm_config cfg = fpga_out_program_get_default_config(fpga_pio_offset);
sm_config_set_out_pins(&cfg, FPGA_BUS_D0, 8);
sm_config_set_sideset_pins(&cfg, FPGA_CONFIG_CCLK);
sm_config_set_out_shift(&cfg, true, true, 8);
sm_config_set_fifo_join(&cfg, PIO_FIFO_JOIN_TX);
sm_config_set_clkdiv(&cfg, FPGA_PIO_CLKDIV);
pio_sm_set_consecutive_pindirs(fpga_pio, fpga_sm, FPGA_BUS_D0, 8, true);
pio_sm_set_consecutive_pindirs(fpga_pio, fpga_sm, FPGA_CONFIG_CCLK, 1, true);
pio_sm_init(fpga_pio, fpga_sm, fpga_pio_offset, &cfg);
pio_sm_set_enabled(fpga_pio, fpga_sm, true);
fpga_pio_inited = true;
}
static void fpga_pio_reset(void)
{
fpga_pio_init();
pio_sm_clear_fifos(fpga_pio, fpga_sm);
pio_sm_restart(fpga_pio, fpga_sm);
}
static void fpga_pio_begin(void)
{
fpga_pio_reset();
}
static void fpga_pio_set_gpio_mode(void)
{
for (uint i = 0; i < 8; i++) {
gpio_set_function(FPGA_BUS_D0 + i, GPIO_FUNC_SIO);
gpio_set_dir(FPGA_BUS_D0 + i, GPIO_OUT);
}
gpio_set_function(FPGA_CONFIG_CCLK, GPIO_FUNC_SIO);
gpio_set_dir(FPGA_CONFIG_CCLK, GPIO_OUT);
}
static void fpga_pio_set_pio_mode(void)
{
for (uint i = 0; i < 8; i++) {
pio_gpio_init(fpga_pio, FPGA_BUS_D0 + i);
}
pio_gpio_init(fpga_pio, FPGA_CONFIG_CCLK);
}
static void fpga_pio_enable(bool enable)
{
if (!fpga_pio_inited) {
return;
}
if (enable) {
fpga_pio_set_pio_mode();
} else {
fpga_pio_set_gpio_mode();
}
pio_sm_set_enabled(fpga_pio, fpga_sm, enable);
}
#endif
static char ascii_tolower(char c)
{
if (c >= 'A' && c <= 'Z') {
return (char)(c - 'A' + 'a');
}
return c;
}
static bool starts_with_casefold(const char* text, const char* prefix)
{
if (!text || !prefix) {
return false;
}
while (*prefix) {
if (*text == '\0' || ascii_tolower(*text) != ascii_tolower(*prefix)) {
return false;
}
++text;
++prefix;
}
return true;
}
static bool ends_with_casefold(const char* text, const char* suffix)
{
if (!text || !suffix) {
return false;
}
size_t text_len = strlen(text);
size_t suffix_len = strlen(suffix);
if (suffix_len > text_len) {
return false;
}
const char* tail = text + (text_len - suffix_len);
for (size_t i = 0; i < suffix_len; i++) {
if (ascii_tolower(tail[i]) != ascii_tolower(suffix[i])) {
return false;
}
}
return true;
}
static int compare_casefold(const char* a, const char* b)
{
while (*a && *b) {
char ca = ascii_tolower(*a);
char cb = ascii_tolower(*b);
if (ca != cb) {
return (ca < cb) ? -1 : 1;
}
++a;
++b;
}
if (*a == *b) {
return 0;
}
return (*a == '\0') ? -1 : 1;
}
static bool find_wildbits_image(const char* dir, const char* suffix, char* out_path, size_t out_path_size)
{
if (!dir || !suffix || !out_path || out_path_size == 0) {
return false;
}
DIR dp;
FILINFO fno;
FRESULT fr = f_opendir(&dp, dir);
if (fr != FR_OK) {
return false;
}
bool found = false;
char best_name[256];
best_name[0] = '\0';
for (;;) {
fr = f_readdir(&dp, &fno);
if (fr != FR_OK || fno.fname[0] == '\0') {
break;
}
if (fno.fattrib & AM_DIR) {
continue;
}
if (!starts_with_casefold(fno.fname, "Wildbits")) {
continue;
}
if (!ends_with_casefold(fno.fname, suffix)) {
continue;
}
if (!found || compare_casefold(fno.fname, best_name) > 0) {
int name_len = snprintf(best_name, sizeof(best_name), "%s", fno.fname);
if (name_len <= 0 || name_len >= (int)sizeof(best_name)) {
continue;
}
found = true;
}
}
if (found) {
int written = snprintf(out_path, out_path_size, "%s/%s", dir, best_name);
if (written <= 0 || written >= (int)out_path_size) {
found = false;
}
}
f_closedir(&dp);
return found;
}
// See FatFs - Generic FAT Filesystem Module, "Application Interface",
// http://elm-chan.org/fsw/ff/00index_e.html
int main()
{
// set_sys_clock_khz(266000, true);
stdio_init_all();
boot_log_reset();
boot_logf("Manager Rev%s firmware %s", K2_BOARD_REVISION,
FPGA_MANAGER_VERSION_STRING);
xosc_init(); // #define PICO_XOSC_STARTUP_DELAY_MULTIPLIER 64
time_init();
// stdio_uart_init_full(uart1, BAUD_RATE, UART_TX_PIN, -1); // Setup STDIO to Terminal UART (to be removed later)
f256k2_context_man_init_io(); // Go Init all the GPIOs I will need
boot_config_init();
// Holding the active-low system reset for at least 500 ms during manager
// startup forces recovery. Only physical context 1 has an embedded image.
bool force_golden = !gpio_get(FPGA_SYSTEM_RSTn);
sleep_ms(500);
force_golden = force_golden && !gpio_get(FPGA_SYSTEM_RSTn);
absolute_time_t start = get_absolute_time();
// read the DIP switches to select the FPGA context to program
uint8_t dip_switches = ((gpio_get_all() & 0x00030000) >> 16) & 0x03;
if (dip_switches >= std::size(fpga_images)) {
panic("Slot index %u is out of range\n", dip_switches);
}
printf("Selected slot index (0-3): %u\n", dip_switches);
boot_logf("Boot context %u", static_cast<unsigned>(dip_switches + 1));
fpga_method_t method = FPGA_METHOD_NONE;
// mount the SD card
sd_card_t* pSD = sd_get_by_num(0);
if (!pSD) {
panic("Invalid hardware config, see 'hw_config.c' implementation\n");
}
FRESULT fr = f_mount(&pSD->fatfs, pSD->pcName, 1);
bool sd_mounted = (fr == FR_OK);
if (sd_mounted) {
boot_logf("Manager SD mounted");
ensure_manager_sd_context_directories();
} else {
boot_logf("Manager SD mount failed: %u", static_cast<unsigned>(fr));
}
method = program_selected_context(dip_switches, sd_mounted, force_golden);
if (method == FPGA_METHOD_NONE) {
panic("No usable FPGA image; select context 1 for recovery\n");
}
// measure programming time
int64_t fpga_us = absolute_time_diff_us(start, get_absolute_time());
printf("=== Wildbits FPGA Manager ===\n");
printf("Board : Rev%s\n", K2_BOARD_REVISION);
printf("Firmware : %s\n", FPGA_MANAGER_VERSION_STRING);
printf("Method : %s\n", fpga_method_names[method]);
printf("Time : %lldms\n", fpga_us / 1000);
printf("Core Slot: %d\n", dip_switches);
printf("=============================\n");
// Keep clk_sys unchanged so UART baud and other clock-derived peripheral
// settings remain valid after FPGA programming.
supervisor_service_init(sd_mounted, dip_switches);
start_reset_hold_monitor();
bool reconfigure_armed = false;
SupervisorReconfigureRequest reconfigure_request{};
for (;;) {
SupervisorReconfigureRequest request{};
bool requested = supervisor_service_once(&request);
// The transaction above sends the response prepared for the previous
// request. Waiting one transaction guarantees that RECONFIGURE is
// acknowledged before the FPGA disappears from the supervisor bus.
if (reconfigure_armed) {
if (reconfigure_request.restart) {
printf("RP2040 restart requested through supervisor mailbox\n");
watchdog_reboot(0, 0, 0);
while (true) {
tight_loop_contents();
}
}
boot_logf("Runtime reconfigure context %u%s",
static_cast<unsigned>(reconfigure_request.context + 1),
reconfigure_request.transient ? " (one-shot)" : "");
fpga_method_t next = reconfigure_request.transient
? program_transient_context(
reconfigure_request.context, sd_mounted,
static_cast<BootSource>(reconfigure_request.source),
reconfigure_request.path)
: program_selected_context(
reconfigure_request.context, sd_mounted, false);
printf("Runtime reconfigure slot %u%s: %s\n",
reconfigure_request.context,
reconfigure_request.transient ? " (one-shot)" : "",
fpga_method_names[next]);
reconfigure_armed = false;
}
if (requested) {
reconfigure_request = request;
reconfigure_armed = true;
}
}
}
struct gzip_source_t {
FIL* file;
const uint8_t* memory;
size_t memory_size;
size_t memory_pos;
size_t file_pos;
size_t file_len;
bool read_error;
};
static uint32_t read_le32_bytes(const uint8_t* p)
{
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
static bool gzip_source_read_byte(gzip_source_t* source, uint8_t* out)
{
if (source->memory) {
if (source->memory_pos >= source->memory_size) {
return false;
}
*out = source->memory[source->memory_pos++];
return true;
}
if (source->file_pos >= source->file_len) {
UINT read = 0;
FRESULT result = f_read(source->file, gzip_file_buffer,
sizeof(gzip_file_buffer), &read);
if (result != FR_OK) {
source->read_error = true;
return false;
}
source->file_pos = 0;
source->file_len = read;
if (read == 0) {
return false;
}
}
*out = gzip_file_buffer[source->file_pos++];
return true;
}
static bool gzip_source_supply(gzip_source_t* source, mz_stream* stream)
{
if (stream->avail_in != 0) {
return true;
}
if (source->memory) {
if (source->memory_pos >= source->memory_size) {
return false;
}
size_t available = source->memory_size - source->memory_pos;
stream->next_in = source->memory + source->memory_pos;
stream->avail_in = static_cast<unsigned int>(available);
source->memory_pos += available;
return true;
}
if (source->file_pos >= source->file_len) {
UINT read = 0;
FRESULT result = f_read(source->file, gzip_file_buffer,
sizeof(gzip_file_buffer), &read);
if (result != FR_OK) {
source->read_error = true;
return false;
}
source->file_pos = 0;
source->file_len = read;
}
if (source->file_pos >= source->file_len) {
return false;
}
stream->next_in = gzip_file_buffer + source->file_pos;
stream->avail_in = static_cast<unsigned int>(source->file_len - source->file_pos);
source->file_pos = source->file_len;
return true;
}
static bool gzip_skip_header(gzip_source_t* source)
{
mz_ulong header_crc = MZ_CRC32_INIT;
auto read_header_byte = [&](uint8_t* out) -> bool {
if (!gzip_source_read_byte(source, out)) {
return false;
}
header_crc = mz_crc32(header_crc, out, 1);
return true;
};
uint8_t header[10];
for (uint8_t& byte : header) {
if (!read_header_byte(&byte)) {
return false;
}
}
if (header[0] != 0x1f || header[1] != 0x8b || header[2] != 8 ||
(header[3] & 0xe0) != 0) {
return false;
}
const uint8_t flags = header[3];
if (flags & 0x04) {
uint8_t lo = 0, hi = 0;
if (!read_header_byte(&lo) || !read_header_byte(&hi)) {
return false;
}
uint16_t length = (uint16_t)lo | ((uint16_t)hi << 8);
while (length-- != 0) {
uint8_t ignored = 0;
if (!read_header_byte(&ignored)) {
return false;
}
}
}
for (uint8_t optional_flag : {uint8_t{0x08}, uint8_t{0x10}}) {
if (flags & optional_flag) {
uint8_t byte = 0;
do {
if (!read_header_byte(&byte)) {
return false;
}
} while (byte != 0);
}
}
if (flags & 0x02) {
uint8_t lo = 0, hi = 0;
uint16_t expected_header_crc = 0;
if (!gzip_source_read_byte(source, &lo) ||
!gzip_source_read_byte(source, &hi)) {
return false;
}
expected_header_crc = (uint16_t)lo | ((uint16_t)hi << 8);
if (expected_header_crc != static_cast<uint16_t>(header_crc)) {
return false;
}
}
return true;
}
static bool gzip_read_after_stream(gzip_source_t* source, mz_stream* stream,
uint8_t* out)
{
if (stream->avail_in != 0) {
*out = *stream->next_in++;
--stream->avail_in;
return true;
}
return gzip_source_read_byte(source, out);
}
static bool gzip_trailing_data_ok(gzip_source_t* source, mz_stream* stream,
bool allow_ff_padding)
{
uint8_t byte = 0;
while (gzip_read_after_stream(source, stream, &byte)) {
if (!allow_ff_padding || byte != 0xff) {
return false;
}
}
return !source->read_error;
}
static inline void pulse_fpga_config_clock()
{
gpio_put(FPGA_CONFIG_CCLK, 0);
gpio_put(FPGA_CONFIG_CCLK, 1);
}
static bool wait_for_fpga_init(bool high)
{
const absolute_time_t deadline = make_timeout_time_ms(FPGA_INIT_TIMEOUT_MS);
do {
pulse_fpga_config_clock();
if (gpio_get(FPGA_CONFIG_INITn) == high) {
return true;
}
} while (!time_reached(deadline));
return false;
}
static bool finish_fpga_programming()
{
#if USE_PIO_FPGA
fpga_pio_enable(false);
#endif
gpio_set_dir(FPGA_SYSTEM_RSTn, GPIO_OUT);
for (unsigned int k = 0; k < 100; ++k) {
pulse_fpga_config_clock();
}
const bool init_high = gpio_get(FPGA_CONFIG_INITn);
gpio_set_dir(FPGA_SYSTEM_RSTn, GPIO_IN);
if (!init_high) {
printf("FPGA configuration failed: INITn is low after startup clocks\n");
boot_logf("Reject: FPGA INIT_B low after startup clocks");
return false;
}
printf("FPGA configuration accepted: INITn remained high\n");
return true;
}
static bool program_fpga_from_gzip_source(gzip_source_t* source,
bool allow_ff_padding)
{
if (!gzip_skip_header(source)) {
printf("gzip header error\n");
boot_logf("Reject: invalid gzip header");
return false;
}
mz_stream stream{};
int result = mz_inflateInit2(&stream, -MZ_DEFAULT_WINDOW_BITS);
if (result != MZ_OK) {
printf("inflate init failed: %d\n", result);
boot_logf("Reject: gzip inflate init error %d", result);
return false;
}
mz_ulong output_crc = MZ_CRC32_INIT;
uint32_t output_size = 0;
if (!f256k2_init_prg_fpga()) {
mz_inflateEnd(&stream);
return false;
}
for (;;) {
if (!gzip_source_supply(source, &stream)) {
printf(source->read_error ? "gzip read failed\n" : "gzip truncated\n");
boot_logf(source->read_error ? "Reject: gzip read failed"
: "Reject: gzip stream truncated");
mz_inflateEnd(&stream);
return false;
}
stream.next_out = Buffer0;
stream.avail_out = BUFFER_SIZE;
result = mz_inflate(&stream, MZ_NO_FLUSH);
size_t produced = BUFFER_SIZE - stream.avail_out;
if (produced > FPGA_SIZE - output_size) {
printf("gzip output exceeds FPGA image size\n");
boot_logf("Reject: gzip output exceeds FPGA size");
mz_inflateEnd(&stream);
return false;
}
if (produced != 0) {
output_crc = mz_crc32(output_crc, Buffer0, produced);
output_size += static_cast<uint32_t>(produced);
if (!f256k2_prg_block_fpga(Buffer0,
static_cast<unsigned int>(produced))) {
mz_inflateEnd(&stream);
return false;
}
}
if (result == MZ_STREAM_END) {
uint8_t trailer[8];
bool trailer_ok = true;
for (uint8_t& byte : trailer) {
if (!gzip_read_after_stream(source, &stream, &byte)) {
trailer_ok = false;
break;
}
}
if (!trailer_ok) {
printf("gzip trailer is truncated\n");
boot_logf("Reject: gzip trailer truncated");
mz_inflateEnd(&stream);
return false;
}
if (read_le32_bytes(trailer) != output_crc) {
printf("gzip CRC mismatch\n");
boot_logf("Reject: gzip CRC mismatch");
mz_inflateEnd(&stream);
return false;
}
if (read_le32_bytes(trailer + 4) != output_size) {
printf("gzip trailer size mismatch\n");
boot_logf("Reject: gzip trailer size mismatch");
mz_inflateEnd(&stream);
return false;
}
if (output_size != FPGA_SIZE) {
printf("FPGA image size mismatch: %u\n",
static_cast<unsigned>(output_size));
boot_logf("Reject: FPGA size %u, expected %u",
static_cast<unsigned>(output_size),
static_cast<unsigned>(FPGA_SIZE));
mz_inflateEnd(&stream);
return false;
}
if (!gzip_trailing_data_ok(source, &stream, allow_ff_padding)) {
printf("unexpected data after gzip member\n");
boot_logf(allow_ff_padding
? "Reject: data after gzip member is not erased"
: "Reject: unexpected data after gzip member");
mz_inflateEnd(&stream);
return false;
}
mz_inflateEnd(&stream);
return finish_fpga_programming();
}
if (result != MZ_OK) {
printf("inflate failed: %d\n", result);
boot_logf("Reject: gzip inflate error %d", result);
mz_inflateEnd(&stream);
return false;
}
}
}
bool program_fpga_from_gz_file(const char* path)
{
char gz_path[256];
int written = snprintf(gz_path, sizeof(gz_path), "%s.gz", path);
if (written <= 0 || written >= (int)sizeof(gz_path)) {
printf("gzip path too long\n");
return false;
}
return program_fpga_from_gz_file_path(gz_path);
}
bool program_fpga_from_gz_file_path(const char* gz_path)
{
FIL fil;
FRESULT fr = f_open(&fil, gz_path, FA_READ);
if (fr != FR_OK) {
return false;
}
printf("Programming from SD (gzip): %s\n", gz_path);
gzip_source_t source{&fil, nullptr, 0, 0, 0, 0, false};
bool ok = program_fpga_from_gzip_source(&source, false);
f_close(&fil);
return ok;
}
bool program_fpga_from_gz_data(const uint8_t* data, size_t len, bool allow_ff_padding)
{
if (!data || len < 18 || (data[0] == 0xff && data[1] == 0xff)) {
return false;
}
gzip_source_t source{nullptr, data, len, 0, 0, 0, false};
return program_fpga_from_gzip_source(&source, allow_ff_padding);
}
bool program_fpga_from_file_path(const char* path)
{
FIL fil;
FRESULT fr = f_open(&fil, path, FA_READ);
if (fr != FR_OK) {
return false;
}
printf("Programming from SD (raw): %s\n", path);
bool ok = program_fpga_from_file(&fil);
f_close(&fil);
return ok;
}
fpga_method_t program_fpga_from_sd_path(const char* path, uint8_t slot)
{
if (!path || slot >= std::size(fpga_images)) {
return FPGA_METHOD_NONE;
}
boot_logf("Try SD: %s", path);
fpga_method_t method = FPGA_METHOD_NONE;
if (ends_with_casefold(path, ".gz")) {
if (program_fpga_from_gz_file_path(path)) {
method = FPGA_METHOD_SD_GZIP;
}
} else if (ends_with_casefold(path, ".bin")) {
if (program_fpga_from_file_path(path)) {
method = FPGA_METHOD_SD_RAW;
}
} else {
printf("Selected SD image has unsupported extension: %s\n", path);
}
if (method != FPGA_METHOD_NONE) {
boot_runtime_set(slot, BootSource::Sd, path);
boot_logf("Loaded SD: %s", path);
} else {
boot_logf("SD attempt failed: %s", path);
}
return method;
}
fpga_method_t program_fpga_from_sd_card(const fpga_image_info_t* info, uint8_t slot)
{
char update_path[256];
char fallback_path[256];
char wildbits_path[256];
int written = snprintf(update_path, sizeof(update_path), "%s/%s",
info->base_path, info->update_filename);
if (written <= 0 || written >= (int)sizeof(update_path)) {
printf("Update path too long\n");
return FPGA_METHOD_NONE;
}
written = snprintf(fallback_path, sizeof(fallback_path), "%s/%s",
info->base_path, info->fallback_filename);
if (written <= 0 || written >= (int)sizeof(fallback_path)) {
printf("Fallback path too long\n");
return FPGA_METHOD_NONE;
}
printf("FPGA image base path: %s, update file: %s\n",
info->base_path, info->update_filename);
fpga_method_t method = program_fpga_from_sd_path(update_path, slot);
if (method != FPGA_METHOD_NONE) {
return method;
}
printf("Searching %s for Wildbits*.{gz,bin}\n", info->base_path);
if (find_wildbits_image(info->base_path, ".gz", wildbits_path, sizeof(wildbits_path))) {
printf("Selected Wildbits gzip image: %s\n", wildbits_path);
method = program_fpga_from_sd_path(wildbits_path, slot);
if (method != FPGA_METHOD_NONE) {
return method;
}
printf("Wildbits gzip failed, continuing fallback\n");
}
if (find_wildbits_image(info->base_path, ".bin", wildbits_path, sizeof(wildbits_path))) {
printf("Selected Wildbits raw image: %s\n", wildbits_path);
method = program_fpga_from_sd_path(wildbits_path, slot);
if (method != FPGA_METHOD_NONE) {
return method;
}
printf("Wildbits raw failed, continuing fallback\n");
}
printf("Trying legacy names (.gz -> .bin) from %s\n", fallback_path);
if (program_fpga_from_gz_file(fallback_path)) {
char gzip_path[260];
snprintf(gzip_path, sizeof(gzip_path), "%s.gz", fallback_path);
boot_runtime_set(slot, BootSource::Sd, gzip_path);
boot_logf("Loaded SD: %s", gzip_path);
return FPGA_METHOD_SD_GZIP;
}
if (program_fpga_from_file_path(fallback_path)) {
boot_runtime_set(slot, BootSource::Sd, fallback_path);
boot_logf("Loaded SD: %s", fallback_path);
return FPGA_METHOD_SD_RAW;
}
return FPGA_METHOD_NONE;
}
fpga_method_t program_fpga_from_flash_slot(const fpga_image_info_t* info, uint8_t slot)
{
if (info->flash_base == 0u) {
printf("No flash address specified for slot %u\n", (unsigned)(slot));
return FPGA_METHOD_NONE;
}
printf("Programming from flash (gzip slot %u)\n", (unsigned)(slot));
boot_logf("Try FLASH slot %u", static_cast<unsigned>(slot + 1));
const uint8_t* data = reinterpret_cast<const uint8_t*>(info->flash_base);
if (program_fpga_from_gz_data(data, FPGA_FLASH_SLOT_SIZE, true)) {
FlashSlotInfo flash = boot_config_flash_slot(slot);
char fallback_label[32];
snprintf(fallback_label, sizeof(fallback_label), "flash slot %u",
static_cast<unsigned>(slot + 1));
const char* label =
flash.valid && flash.label[0] ? flash.label : fallback_label;
boot_runtime_set(slot, BootSource::Flash, label);
boot_logf("Loaded FLASH: %s", label);
return FPGA_METHOD_FLASH_GZIP;
}
boot_logf("FLASH slot %u failed", static_cast<unsigned>(slot + 1));
return FPGA_METHOD_NONE;
}
fpga_method_t program_fpga_from_golden_slot(unsigned char sw_choice)
{
const unsigned int slot = sw_choice & 0x03;
const GoldenImageInfo* image = golden_image_for_context(slot);
if (!image) {
printf("No embedded recovery image for context %u; use context 1\n",
static_cast<unsigned>(slot + 1));
boot_logf("No GOLDEN for context %u; use context 1",
static_cast<unsigned>(slot + 1));
return FPGA_METHOD_NONE;
}
const size_t length = golden_image_size(*image);
printf("Programming embedded golden %s for context %u (%u bytes)\n",
image->label, static_cast<unsigned>(slot + 1),
static_cast<unsigned int>(length));
boot_logf("Try GOLDEN: %s", image->label);
if (program_fpga_from_gz_data(image->start, length, false)) {
boot_runtime_set(slot, BootSource::Golden, image->label);
boot_logf("Loaded GOLDEN: %s", image->label);
return FPGA_METHOD_GOLDEN_GZIP;
}
return FPGA_METHOD_NONE;
}
static fpga_method_t program_context_selection(uint8_t slot, bool sd_mounted,
const BootSelection& selection,
bool transient)