-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsupervisor_service.cpp
More file actions
1858 lines (1748 loc) · 63.1 KB
/
Copy pathsupervisor_service.cpp
File metadata and controls
1858 lines (1748 loc) · 63.1 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 "supervisor_service.h"
#include <cstdio>
#include <cstring>
#include "boot_config.h"
#include "boot_log.h"
#include "ff.h"
#include "fpga_manager_version.h"
#include "golden_images.h"
#include "hardware/adc.h"
#include "hardware/dma.h"
#include "hardware/flash.h"
#include "hardware/pio.h"
#include "hardware/sync.h"
#include "miniz.h"
#include "pico/stdlib.h"
#include "supervisor_spi.pio.h"
namespace {
constexpr uint8_t kRequestMagic = 0xA5;
constexpr uint8_t kResponseMagic = 0x5A;
constexpr uint8_t kProtocolVersion = 1;
constexpr size_t kFrameSize = 256;
constexpr size_t kHeaderSize = 16;
constexpr size_t kMaxPayload = kFrameSize - kHeaderSize;
constexpr uint8_t kFirmwareMajor = FPGA_MANAGER_VERSION_MAJOR;
constexpr uint8_t kFirmwareMinor = FPGA_MANAGER_VERSION_MINOR;
constexpr uint kMisoPin = 0;
constexpr uint kCsPin = 1;
constexpr uint kClockPin = 2;
constexpr uint kMosiPin = 3;
constexpr uint8_t kCommandPoll = 0x00;
constexpr uint8_t kCommandPing = 0x01;
constexpr uint8_t kCommandImageBegin = 0x02;
constexpr uint8_t kCommandImageData = 0x03;
constexpr uint8_t kCommandImageEnd = 0x04;
constexpr uint8_t kCommandImageAbort = 0x05;
constexpr uint8_t kCommandReconfigure = 0x06;
constexpr uint8_t kCommandImageStatus = 0x07;
constexpr uint8_t kCommandCatalogBegin = 0x08;
constexpr uint8_t kCommandCatalogGet = 0x09;
constexpr uint8_t kCommandGetSelection = 0x0a;
constexpr uint8_t kCommandSetSelection = 0x0b;
constexpr uint8_t kCommandReconfigureSelected = 0x0c;
constexpr uint8_t kCommandClearFlash = 0x0d;
constexpr uint8_t kCommandGetBootStatus = 0x0e;
constexpr uint8_t kCommandCopySdToFlash = 0x0f;
constexpr uint8_t kCommandGetBootLog = 0x10;
constexpr uint8_t kCommandCopySdToFlashBegin = 0x11;
constexpr uint8_t kCommandCopySdToFlashStep = 0x12;
constexpr uint8_t kCommandDeleteSdImage = 0x13;
constexpr uint8_t kCommandReconfigureOnce = 0x14;
constexpr uint8_t kCommandRestartSupervisor = 0x15;
constexpr uint8_t kCommandReadSdBegin = 0x16;
constexpr uint8_t kCommandReadSdData = 0x17;
constexpr uint8_t kCommandReadSdEnd = 0x18;
constexpr uint8_t kTargetSdRaw = 0;
constexpr uint8_t kTargetFlashGzip = 2;
constexpr uint8_t kTargetSdNamed = 3;
constexpr uint32_t kFpgaImageSize = 9730652u;
constexpr uint32_t kFlashSlotSize = 2u * 1024u * 1024u;
constexpr uint32_t kCopyEraseStep = 64u * 1024u;
constexpr unsigned kCopyBlocksPerStep = 8;
constexpr size_t kReadSdChunkSize = kMaxPayload - 8;
constexpr uint32_t kMaxSdGzipSize = kFpgaImageSize + 64u * 1024u;
constexpr uintptr_t kXipBase = 0x10000000u;
constexpr uint32_t kMutableFlashStart = 8u * 1024u * 1024u;
constexpr uint32_t kMutableFlashEnd = 16u * 1024u * 1024u;
constexpr uint32_t kFlashSlotOffsets[] = {
0x00800000u, 0x00A00000u, 0x00C00000u, 0x00E00000u
};
static_assert(kFlashSlotOffsets[0] == kMutableFlashStart, "mutable bank start changed");
static_assert(kFlashSlotOffsets[3] + kFlashSlotSize == kMutableFlashEnd,
"mutable bank must remain inside the upper 8 MiB");
constexpr const char* kImagePaths[] = {
"0:/CNTX1/context1.bin",
"0:/CNTX2/context2.bin",
"0:/CNTX3/context3.bin",
"0:/CNTX4/context4.bin",
};
enum Error : uint8_t {
kErrorNone = 0,
kErrorBadMagic = 1,
kErrorProtocol = 2,
kErrorLength = 3,
kErrorUploadActive = 0x10,
kErrorBadTarget = 0x11,
kErrorBadSlot = 0x12,
kErrorFileOpen = 0x13,
kErrorFileWrite = 0x14,
kErrorSize = 0x15,
kErrorCrc = 0x16,
kErrorFlashSize = 0x17,
kErrorNoUpload = 0x18,
kErrorGzip = 0x19,
kErrorFlashVerify = 0x1a,
kErrorMetadata = 0x1b,
kErrorCatalog = 0x20,
kErrorStaleCatalog = 0x21,
kErrorBadSelection = 0x22,
kErrorCopyRead = 0x23,
kErrorBootLog = 0x24,
kErrorDelete = 0x25,
kErrorNoRead = 0x26,
kErrorReadPosition = 0x27,
kErrorContextMismatch = 0x28,
};
enum ImageFormat : uint8_t {
kFormatNone = 0,
kFormatRaw = 1,
kFormatGzip = 2,
};
enum CopyState : uint8_t {
kCopyIdle = 0,
kCopyErasing = 1,
kCopyWriting = 2,
kCopyFinalizing = 3,
kCopyDone = 4,
kCopyFailed = 5,
};
constexpr uint8_t kCatalogFlagSelected = 0x01;
constexpr uint8_t kCatalogFlagRunning = 0x02;
constexpr size_t kCatalogCapacity = 32;
struct CatalogEntry {
BootSource source;
ImageFormat format;
uint32_t size;
char name[kBootPathLength];
};
PIO service_pio = pio1;
int service_sm = -1;
int tx_dma = -1;
int rx_dma = -1;
uint service_offset = 0;
uint8_t request[kFrameSize];
uint8_t response[kFrameSize];
uint32_t tx_words[kFrameSize];
uint32_t rx_words[kFrameSize];
bool sd_available = false;
uint8_t physical_context = 0;
bool upload_active = false;
uint8_t upload_target = 0;
uint8_t upload_slot = 0;
uint32_t upload_expected_size = 0;
uint32_t upload_expected_crc = 0;
uint32_t upload_size = 0;
mz_ulong upload_crc = MZ_CRC32_INIT;
FIL upload_file;
bool upload_file_open = false;
uint8_t flash_page[FLASH_PAGE_SIZE];
uint8_t flash_first_page[FLASH_PAGE_SIZE];
size_t flash_page_used = 0;
uint32_t flash_write_offset = 0;
bool flash_first_page_pending = false;
uint8_t upload_header[10];
size_t upload_header_used = 0;
uint8_t upload_tail[8];
uint8_t last_error = kErrorNone;
char upload_label[kFlashLabelLength];
char upload_destination[kBootPathLength];
char upload_temporary[kBootPathLength];
char upload_backup[kBootPathLength];
uint8_t copy_buffer[1024];
FIL copy_source;
bool copy_source_open = false;
FIL sd_read_source;
bool sd_read_source_open = false;
uint32_t sd_read_size = 0;
uint32_t sd_read_offset = 0;
mz_ulong sd_read_crc = MZ_CRC32_INIT;
uint8_t sd_read_cache[kReadSdChunkSize];
uint32_t sd_read_cache_offset = 0;
uint8_t sd_read_cache_count = 0;
bool sd_read_cache_valid = false;
CopyState copy_state = kCopyIdle;
uint8_t copy_error = kErrorNone;
uint32_t copy_erase_offset = 0;
CatalogEntry catalog[kCatalogCapacity];
uint16_t catalog_count = 0;
uint8_t catalog_context = 0;
uint32_t catalog_generation = 0;
uint8_t command_response[kMaxPayload];
DIR catalog_directory;
FILINFO catalog_file_info;
char catalog_path[kBootPathLength];
bool last_command_valid = false;
uint8_t last_command_sequence = 0;
uint8_t last_command = kCommandPoll;
uint16_t last_command_length = 0;
uint8_t last_command_payload[kMaxPayload];
uint16_t read_le16(const uint8_t* p)
{
return static_cast<uint16_t>(p[0]) |
(static_cast<uint16_t>(p[1]) << 8);
}
uint32_t read_le32(const uint8_t* p)
{
return static_cast<uint32_t>(p[0]) |
(static_cast<uint32_t>(p[1]) << 8) |
(static_cast<uint32_t>(p[2]) << 16) |
(static_cast<uint32_t>(p[3]) << 24);
}
void write_le16(uint8_t* p, uint16_t value)
{
p[0] = static_cast<uint8_t>(value);
p[1] = static_cast<uint8_t>(value >> 8);
}
void write_le32(uint8_t* p, uint32_t value)
{
p[0] = static_cast<uint8_t>(value);
p[1] = static_cast<uint8_t>(value >> 8);
p[2] = static_cast<uint8_t>(value >> 16);
p[3] = static_cast<uint8_t>(value >> 24);
}
char ascii_tolower(char c)
{
return c >= 'A' && c <= 'Z' ? static_cast<char>(c - 'A' + 'a') : c;
}
bool ends_with_casefold(const char* text, const char* suffix)
{
const size_t text_length = std::strlen(text);
const size_t suffix_length = std::strlen(suffix);
if (suffix_length > text_length) {
return false;
}
text += text_length - suffix_length;
for (size_t i = 0; i < suffix_length; ++i) {
if (ascii_tolower(text[i]) != ascii_tolower(suffix[i])) {
return false;
}
}
return true;
}
bool strings_equal_casefold(const char* a, const char* b)
{
while (*a && *b) {
if (ascii_tolower(*a++) != ascii_tolower(*b++)) {
return false;
}
}
return *a == *b;
}
bool valid_image_basename(const char* name)
{
if (!name || !name[0] || name[0] == '.' || std::strstr(name, "..") ||
std::strchr(name, '/') || std::strchr(name, '\\') ||
std::strchr(name, ':')) {
return false;
}
return ends_with_casefold(name, ".gz") || ends_with_casefold(name, ".bin");
}
bool ensure_context_directory(uint8_t context)
{
if (context >= kBootContextCount) {
return false;
}
char directory[16];
const int length = std::snprintf(
directory, sizeof(directory), "0:/CNTX%u",
static_cast<unsigned>(context + 1));
if (length <= 0 || length >= static_cast<int>(sizeof(directory))) {
return false;
}
const FRESULT result = f_mkdir(directory);
if (result == FR_OK) {
std::printf("Created manager SD directory: %s\n", directory);
return true;
}
return result == FR_EXIST;
}
bool prepare_named_upload_paths(uint8_t context, const char* name)
{
if (context >= kBootContextCount || !valid_image_basename(name)) {
return false;
}
const int destination_length = std::snprintf(
upload_destination, sizeof(upload_destination), "0:/CNTX%u/%s",
static_cast<unsigned>(context + 1), name);
const int temporary_length = std::snprintf(
upload_temporary, sizeof(upload_temporary), "0:/CNTX%u/.%s.upload",
static_cast<unsigned>(context + 1), name);
const int backup_length = std::snprintf(
upload_backup, sizeof(upload_backup), "0:/CNTX%u/.%s.old",
static_cast<unsigned>(context + 1), name);
return destination_length > 0 && temporary_length > 0 && backup_length > 0 &&
destination_length < static_cast<int>(sizeof(upload_destination)) &&
temporary_length < static_cast<int>(sizeof(upload_temporary)) &&
backup_length < static_cast<int>(sizeof(upload_backup));
}
bool add_catalog_entry(BootSource source, ImageFormat format, uint32_t size,
const char* name)
{
if (catalog_count >= kCatalogCapacity || !name ||
std::strlen(name) >= sizeof(catalog[0].name)) {
return false;
}
CatalogEntry& entry = catalog[catalog_count++];
entry.source = source;
entry.format = format;
entry.size = size;
std::snprintf(entry.name, sizeof(entry.name), "%s", name);
return true;
}
bool flash_slot_has_gzip(uint8_t context)
{
const uint8_t* data = reinterpret_cast<const uint8_t*>(
kXipBase + kFlashSlotOffsets[context]);
return data[0] == 0x1f && data[1] == 0x8b && data[2] == 8 &&
(data[3] & 0xe0) == 0;
}
bool valid_sd_selection_path(uint8_t context, const char* path)
{
if (!path || !path[0] || std::strstr(path, "..") != nullptr ||
(!ends_with_casefold(path, ".gz") && !ends_with_casefold(path, ".bin"))) {
return false;
}
char prefix[16];
std::snprintf(prefix, sizeof(prefix), "CNTX%u/",
static_cast<unsigned>(context + 1));
const char* relative = path;
if (relative[0] == '0' && relative[1] == ':' && relative[2] == '/') {
relative += 3;
} else if (relative[0] == '/') {
++relative;
}
for (size_t i = 0; prefix[i]; ++i) {
if (!relative[i] || ascii_tolower(relative[i]) != ascii_tolower(prefix[i])) {
return false;
}
}
return true;
}
void rebuild_catalog(uint8_t context)
{
const absolute_time_t scan_start = get_absolute_time();
uint16_t directory_entries = 0;
uint16_t sd_images = 0;
std::printf("Catalog scan start: context %u\n",
static_cast<unsigned>(context + 1));
catalog_count = 0;
catalog_context = context;
++catalog_generation;
if (catalog_generation == 0) {
++catalog_generation;
}
const GoldenImageInfo* golden = golden_image_for_context(context);
add_catalog_entry(BootSource::Auto, kFormatNone, 0,
golden ? "Automatic (SD, flash, golden)"
: "Automatic (SD, flash)");
if (sd_available) {
char directory[16];
std::snprintf(directory, sizeof(directory), "CNTX%u",
static_cast<unsigned>(context + 1));
if (f_opendir(&catalog_directory, directory) == FR_OK) {
for (;;) {
// Reserve room for the replaceable flash slot and, in
// the recovery context, the immutable golden entry.
const size_t reserved_entries = golden ? 2 : 1;
if (catalog_count >= kCatalogCapacity - reserved_entries) {
break;
}
FRESULT result = f_readdir(&catalog_directory,
&catalog_file_info);
if (result != FR_OK || catalog_file_info.fname[0] == '\0') {
if (result != FR_OK) {
std::printf("Catalog readdir failed: %u\n",
static_cast<unsigned>(result));
}
break;
}
++directory_entries;
// Dotfiles are conventionally hidden even when the FAT hidden
// attribute was not set by the host that created them. Keep
// both forms of hidden metadata, and FAT system files, out of
// the user-facing core catalog.
if (catalog_file_info.fname[0] == '.' ||
(catalog_file_info.fattrib & (AM_DIR | AM_HID | AM_SYS)) != 0) {
continue;
}
ImageFormat format = kFormatNone;
if (ends_with_casefold(catalog_file_info.fname, ".gz")) {
format = kFormatGzip;
} else if (ends_with_casefold(catalog_file_info.fname, ".bin")) {
format = kFormatRaw;
} else {
continue;
}
int length = std::snprintf(catalog_path, sizeof(catalog_path),
"%s/%s", directory,
catalog_file_info.fname);
if (length > 0 &&
length < static_cast<int>(sizeof(catalog_path))) {
if (add_catalog_entry(
BootSource::Sd, format,
static_cast<uint32_t>(catalog_file_info.fsize),
catalog_path)) {
++sd_images;
}
}
}
f_closedir(&catalog_directory);
} else {
std::printf("Catalog opendir failed: %s\n", directory);
}
}
if (flash_slot_has_gzip(context)) {
FlashSlotInfo slot = boot_config_flash_slot(context);
char label[kFlashLabelLength];
if (slot.valid && slot.label[0]) {
std::snprintf(label, sizeof(label), "%s", slot.label);
} else {
std::snprintf(label, sizeof(label), "Flash slot %u (unlabelled)",
static_cast<unsigned>(context + 1));
}
add_catalog_entry(BootSource::Flash, kFormatGzip,
slot.valid ? slot.compressed_size : 0, label);
}
if (golden) {
add_catalog_entry(BootSource::Golden, kFormatGzip,
static_cast<uint32_t>(golden_image_size(*golden)),
golden->label);
}
const int64_t scan_us =
absolute_time_diff_us(scan_start, get_absolute_time());
std::printf(
"Catalog scan complete: %u entries (%u directory, %u SD images), "
"%lld us\n",
static_cast<unsigned>(catalog_count),
static_cast<unsigned>(directory_entries),
static_cast<unsigned>(sd_images), scan_us);
}
uint8_t catalog_flags(const CatalogEntry& entry)
{
uint8_t flags = 0;
const BootSelection& selection = boot_config_selection(catalog_context);
if (selection.source == entry.source &&
(entry.source != BootSource::Sd ||
strings_equal_casefold(selection.path, entry.name))) {
flags |= kCatalogFlagSelected;
}
const BootRuntimeStatus& running = boot_runtime_status();
if (running.valid && running.context == catalog_context &&
running.source == entry.source &&
(entry.source != BootSource::Sd ||
strings_equal_casefold(running.path, entry.name))) {
flags |= kCatalogFlagRunning;
}
return flags;
}
uint8_t sample_adc(uint channel)
{
adc_select_input(channel);
return static_cast<uint8_t>(adc_read() >> 4);
}
uint8_t status_byte()
{
uint8_t status = 0x01;
if (upload_active) {
status |= 0x02;
}
if (sd_available) {
status |= 0x04;
}
if (upload_active && upload_target == kTargetFlashGzip) {
status |= 0x08;
}
if (sd_read_source_open) {
status |= 0x10;
}
if (last_error != kErrorNone) {
status |= 0x80;
}
return status;
}
void prepare_response(uint8_t sequence)
{
std::memset(response, 0, sizeof(response));
response[0] = kResponseMagic;
response[1] = kProtocolVersion;
response[2] = sequence;
response[3] = status_byte();
response[4] = last_error;
response[7] = static_cast<uint8_t>(kMaxPayload);
response[8] = static_cast<uint8_t>(kMaxPayload >> 8);
response[9] = sample_adc(0);
response[10] = sample_adc(1);
response[11] = sample_adc(2);
response[12] = sample_adc(3);
response[13] = kFirmwareMajor;
response[14] = kFirmwareMinor;
}
void reset_transport()
{
pio_sm_set_enabled(service_pio, service_sm, false);
pio_sm_clear_fifos(service_pio, service_sm);
pio_sm_restart(service_pio, service_sm);
pio_sm_set_enabled(service_pio, service_sm, true);
}
void transfer_frame()
{
for (size_t i = 0; i < kFrameSize; ++i) {
tx_words[i] = static_cast<uint32_t>(response[i]) << 24;
rx_words[i] = 0;
}
reset_transport();
dma_channel_config tx_config = dma_channel_get_default_config(tx_dma);
channel_config_set_transfer_data_size(&tx_config, DMA_SIZE_32);
channel_config_set_read_increment(&tx_config, true);
channel_config_set_write_increment(&tx_config, false);
channel_config_set_dreq(&tx_config, pio_get_dreq(service_pio, service_sm, true));
dma_channel_configure(tx_dma, &tx_config, &service_pio->txf[service_sm],
tx_words, kFrameSize, false);
dma_channel_config rx_config = dma_channel_get_default_config(rx_dma);
channel_config_set_transfer_data_size(&rx_config, DMA_SIZE_32);
channel_config_set_read_increment(&rx_config, false);
channel_config_set_write_increment(&rx_config, true);
channel_config_set_dreq(&rx_config, pio_get_dreq(service_pio, service_sm, false));
dma_channel_configure(rx_dma, &rx_config, rx_words,
&service_pio->rxf[service_sm], kFrameSize, false);
dma_start_channel_mask((1u << tx_dma) | (1u << rx_dma));
dma_channel_wait_for_finish_blocking(rx_dma);
while (!gpio_get(kCsPin)) {
tight_loop_contents();
}
dma_channel_abort(tx_dma);
for (size_t i = 0; i < kFrameSize; ++i) {
request[i] = static_cast<uint8_t>(rx_words[i]);
}
}
void close_upload_file()
{
if (upload_file_open) {
f_close(&upload_file);
upload_file_open = false;
}
}
void abort_upload()
{
close_upload_file();
if (upload_target == kTargetSdRaw && upload_slot < 4) {
char temporary[96];
std::snprintf(temporary, sizeof(temporary), "%s.upload", kImagePaths[upload_slot]);
f_unlink(temporary);
} else if (upload_target == kTargetSdNamed && upload_temporary[0]) {
f_unlink(upload_temporary);
}
upload_active = false;
flash_page_used = 0;
flash_first_page_pending = false;
}
bool program_and_verify_flash_page(uint32_t offset, const uint8_t* page)
{
const uint32_t flash_offset = kFlashSlotOffsets[upload_slot] + offset;
uint32_t interrupts = save_and_disable_interrupts();
flash_range_program(flash_offset, page, FLASH_PAGE_SIZE);
restore_interrupts(interrupts);
const uint8_t* readback = reinterpret_cast<const uint8_t*>(kXipBase + flash_offset);
if (std::memcmp(readback, page, FLASH_PAGE_SIZE) != 0) {
last_error = kErrorFlashVerify;
return false;
}
return true;
}
bool flash_program_page()
{
if (flash_page_used == 0) {
return true;
}
std::memset(flash_page + flash_page_used, 0xFF, FLASH_PAGE_SIZE - flash_page_used);
if (flash_write_offset == 0) {
std::memcpy(flash_first_page, flash_page, FLASH_PAGE_SIZE);
flash_first_page_pending = true;
} else if (!program_and_verify_flash_page(flash_write_offset, flash_page)) {
return false;
}
flash_write_offset += FLASH_PAGE_SIZE;
flash_page_used = 0;
return true;
}
bool flash_commit_first_page()
{
if (!flash_first_page_pending) {
last_error = kErrorFlashVerify;
return false;
}
if (!program_and_verify_flash_page(0, flash_first_page)) {
return false;
}
flash_first_page_pending = false;
return true;
}
void capture_upload_bytes(const uint8_t* payload, size_t length)
{
for (size_t i = 0; i < length && upload_header_used < sizeof(upload_header); ++i) {
upload_header[upload_header_used++] = payload[i];
}
if (length >= sizeof(upload_tail)) {
std::memcpy(upload_tail, payload + length - sizeof(upload_tail), sizeof(upload_tail));
return;
}
for (size_t i = 0; i < length; ++i) {
std::memmove(upload_tail, upload_tail + 1, sizeof(upload_tail) - 1);
upload_tail[sizeof(upload_tail) - 1] = payload[i];
}
}
bool uploaded_gzip_shape_valid()
{
return upload_size >= 18 && upload_header_used == sizeof(upload_header) &&
upload_header[0] == 0x1f && upload_header[1] == 0x8b &&
upload_header[2] == 8 && (upload_header[3] & 0xe0) == 0 &&
read_le32(upload_tail + 4) == kFpgaImageSize;
}
bool begin_upload(const uint8_t* payload, size_t length)
{
if (upload_active) {
last_error = kErrorUploadActive;
return false;
}
if (length < 10) {
last_error = kErrorLength;
return false;
}
upload_label[0] = '\0';
if (length > 10) {
const size_t label_length = payload[10];
if (length != 11 + label_length || label_length == 0 ||
label_length >= sizeof(upload_label)) {
last_error = kErrorLength;
return false;
}
std::memcpy(upload_label, payload + 11, label_length);
upload_label[label_length] = '\0';
}
upload_target = payload[0];
upload_slot = payload[1];
upload_expected_size = read_le32(payload + 2);
upload_expected_crc = read_le32(payload + 6);
upload_size = 0;
upload_crc = MZ_CRC32_INIT;
flash_page_used = 0;
flash_write_offset = 0;
flash_first_page_pending = false;
upload_header_used = 0;
upload_destination[0] = '\0';
upload_temporary[0] = '\0';
upload_backup[0] = '\0';
std::memset(upload_header, 0, sizeof(upload_header));
std::memset(upload_tail, 0, sizeof(upload_tail));
if (upload_slot >= 4) {
last_error = kErrorBadSlot;
return false;
}
if (!upload_label[0] && upload_target == kTargetFlashGzip) {
std::snprintf(upload_label, sizeof(upload_label), "Uploaded flash slot %u",
static_cast<unsigned>(upload_slot + 1));
}
if (upload_target == kTargetSdRaw) {
if (!sd_available) {
last_error = kErrorBadTarget;
return false;
}
if (!ensure_context_directory(upload_slot)) {
last_error = kErrorFileOpen;
return false;
}
char temporary[96];
std::snprintf(temporary, sizeof(temporary), "%s.upload", kImagePaths[upload_slot]);
if (f_open(&upload_file, temporary, FA_CREATE_ALWAYS | FA_WRITE) != FR_OK) {
last_error = kErrorFileOpen;
return false;
}
upload_file_open = true;
} else if (upload_target == kTargetSdNamed) {
if (!sd_available) {
last_error = kErrorBadTarget;
return false;
}
if (!prepare_named_upload_paths(upload_slot, upload_label)) {
last_error = kErrorBadSelection;
return false;
}
if ((ends_with_casefold(upload_label, ".bin") &&
upload_expected_size != kFpgaImageSize) ||
(ends_with_casefold(upload_label, ".gz") &&
(upload_expected_size < 18 ||
upload_expected_size > kMaxSdGzipSize))) {
last_error = kErrorSize;
return false;
}
if (!ensure_context_directory(upload_slot)) {
last_error = kErrorFileOpen;
return false;
}
f_unlink(upload_temporary);
if (f_open(&upload_file, upload_temporary,
FA_CREATE_ALWAYS | FA_WRITE) != FR_OK) {
last_error = kErrorFileOpen;
return false;
}
upload_file_open = true;
} else if (upload_target == kTargetFlashGzip) {
if (upload_expected_size < 18 || upload_expected_size > kFlashSlotSize) {
last_error = kErrorFlashSize;
return false;
}
uint32_t interrupts = save_and_disable_interrupts();
flash_range_erase(kFlashSlotOffsets[upload_slot], kFlashSlotSize);
restore_interrupts(interrupts);
} else {
last_error = kErrorBadTarget;
return false;
}
upload_active = true;
last_error = kErrorNone;
return true;
}
bool write_upload(const uint8_t* payload, size_t length)
{
if (!upload_active) {
last_error = kErrorNoUpload;
return false;
}
if (upload_size + length > upload_expected_size) {
last_error = kErrorSize;
return false;
}
if (upload_target == kTargetSdRaw || upload_target == kTargetSdNamed) {
UINT written = 0;
if (f_write(&upload_file, payload, static_cast<UINT>(length), &written) != FR_OK ||
written != length) {
last_error = kErrorFileWrite;
return false;
}
if (upload_target == kTargetSdNamed &&
ends_with_casefold(upload_label, ".gz")) {
capture_upload_bytes(payload, length);
}
} else {
capture_upload_bytes(payload, length);
size_t consumed = 0;
while (consumed < length) {
size_t room = FLASH_PAGE_SIZE - flash_page_used;
size_t amount = length - consumed;
if (amount > room) {
amount = room;
}
std::memcpy(flash_page + flash_page_used, payload + consumed, amount);
flash_page_used += amount;
consumed += amount;
if (flash_page_used == FLASH_PAGE_SIZE) {
if (!flash_program_page()) {
return false;
}
}
}
}
upload_crc = mz_crc32(upload_crc, payload, length);
upload_size += static_cast<uint32_t>(length);
last_error = kErrorNone;
return true;
}
bool finish_sd_upload()
{
if (f_sync(&upload_file) != FR_OK) {
last_error = kErrorFileWrite;
close_upload_file();
return false;
}
close_upload_file();
char temporary[96];
char backup[96];
char compressed[96];
std::snprintf(temporary, sizeof(temporary), "%s.upload", kImagePaths[upload_slot]);
std::snprintf(backup, sizeof(backup), "%s.old", kImagePaths[upload_slot]);
f_unlink(backup);
f_rename(kImagePaths[upload_slot], backup);
if (f_rename(temporary, kImagePaths[upload_slot]) != FR_OK) {
f_rename(backup, kImagePaths[upload_slot]);
last_error = kErrorFileWrite;
return false;
}
f_unlink(backup);
std::snprintf(compressed, sizeof(compressed), "%s.gz", kImagePaths[upload_slot]);
f_unlink(compressed);
return true;
}
bool finish_named_sd_upload()
{
if (f_sync(&upload_file) != FR_OK) {
last_error = kErrorFileWrite;
close_upload_file();
return false;
}
close_upload_file();
f_unlink(upload_backup);
const FRESULT backup_result = f_rename(upload_destination, upload_backup);
if (backup_result != FR_OK && backup_result != FR_NO_FILE) {
last_error = kErrorFileWrite;
return false;
}
if (f_rename(upload_temporary, upload_destination) != FR_OK) {
if (backup_result == FR_OK) {
f_rename(upload_backup, upload_destination);
}
last_error = kErrorFileWrite;
return false;
}
f_unlink(upload_backup);
return true;
}
bool finish_upload()
{
if (!upload_active) {
last_error = kErrorNoUpload;
return false;
}
if (upload_size != upload_expected_size) {
std::printf("Upload size mismatch: received %lu, expected %lu\n",
static_cast<unsigned long>(upload_size),
static_cast<unsigned long>(upload_expected_size));
last_error = kErrorSize;
return false;
}
if (static_cast<uint32_t>(upload_crc) != upload_expected_crc) {
last_error = kErrorCrc;
return false;
}
if ((upload_target == kTargetFlashGzip ||
(upload_target == kTargetSdNamed &&
ends_with_casefold(upload_label, ".gz"))) &&
!uploaded_gzip_shape_valid()) {
last_error = kErrorGzip;
return false;
}
bool ok = true;
if (upload_target == kTargetSdRaw) {
ok = finish_sd_upload();
} else if (upload_target == kTargetSdNamed) {
ok = finish_named_sd_upload();
} else {
ok = flash_program_page() && flash_commit_first_page();
if (ok && !boot_config_set_flash_slot(upload_slot, upload_size,
upload_expected_crc,
upload_label)) {
last_error = kErrorMetadata;
ok = false;
}
}
if (ok) {
upload_active = false;
last_error = kErrorNone;
}
return ok;
}
void close_copy_source()
{
if (copy_source_open) {
f_close(©_source);
copy_source_open = false;
}
}
void fail_incremental_copy(uint8_t error)
{
close_copy_source();
copy_error = error;
copy_state = kCopyFailed;
abort_upload();
}
bool begin_incremental_sd_to_flash_copy(uint8_t context, const char* path)
{
if (upload_active) {
last_error = kErrorUploadActive;
return false;
}
if (!sd_available || context >= kBootContextCount ||
!valid_sd_selection_path(context, path) ||
!ends_with_casefold(path, ".gz")) {
last_error = kErrorBadSelection;
return false;
}
if (f_open(©_source, path, FA_READ) != FR_OK) {
last_error = kErrorFileOpen;
return false;
}
copy_source_open = true;
const FSIZE_t source_size = f_size(©_source);
if (source_size < 18 || source_size > kFlashSlotSize) {
close_copy_source();
last_error = kErrorFlashSize;
return false;
}
const char* basename = std::strrchr(path, '/');
basename = basename ? basename + 1 : path;
if (!basename[0] || std::strlen(basename) >= sizeof(upload_label)) {
close_copy_source();
last_error = kErrorBadSelection;
return false;
}
upload_target = kTargetFlashGzip;
upload_slot = context;
upload_expected_size = static_cast<uint32_t>(source_size);
upload_expected_crc = 0;
upload_size = 0;
upload_crc = MZ_CRC32_INIT;
flash_page_used = 0;
flash_write_offset = 0;
flash_first_page_pending = false;
upload_header_used = 0;
std::memset(upload_header, 0, sizeof(upload_header));
std::memset(upload_tail, 0, sizeof(upload_tail));
std::snprintf(upload_label, sizeof(upload_label), "%s", basename);
upload_active = true;
copy_state = kCopyErasing;
copy_error = kErrorNone;
copy_erase_offset = 0;
last_error = kErrorNone;
return true;
}
void step_incremental_sd_to_flash_copy()
{
if (copy_state == kCopyErasing) {
if (copy_erase_offset == kFlashSlotSize) {
copy_state = kCopyWriting;
return;
}
const uint32_t offset = kFlashSlotOffsets[upload_slot] + copy_erase_offset;