-
Notifications
You must be signed in to change notification settings - Fork 3
/
sp_to_mgs.rs
1562 lines (1449 loc) · 51.5 KB
/
sp_to_mgs.rs
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Types for messages sent from SPs to MGS.
use crate::tlv;
use crate::BadRequestReason;
use crate::PowerState;
use crate::RotResponse;
use crate::RotSlotId;
use crate::SensorResponse;
use crate::SpComponent;
use crate::StartupOptions;
use crate::UnlockChallenge;
use crate::UpdateId;
use bitflags::bitflags;
use core::fmt;
use hubpack::SerializedSize;
use serde::Deserialize;
use serde::Serialize;
use serde_repr::Deserialize_repr;
use serde_repr::Serialize_repr;
pub mod ignition;
pub mod measurement;
pub mod monorail_port_status;
pub use ignition::IgnitionState;
pub use measurement::Measurement;
use ignition::IgnitionError;
use measurement::MeasurementHeader;
use monorail_port_status::{PortStatus, PortStatusError};
use ignition::LinkEvents;
#[derive(
Debug, Clone, Copy, SerializedSize, Serialize, Deserialize, PartialEq, Eq,
)]
pub enum SpRequest {
/// Data traveling from an SP-attached component (in practice, a CPU) on the
/// component's serial console.
///
/// Note that SP -> MGS serial console messages are currently _not_
/// acknowledged or retried; they are purely "fire and forget" from the SP's
/// point of view. Once it sends data in a packet, it discards it from its
/// local buffer.
SerialConsole {
component: SpComponent,
/// Offset of the first byte in this packet's data starting from 0 when
/// the serial console session was attached.
offset: u64,
},
/// Request a single packet-worth of a host phase 2 image (identified by
/// `hash`) starting at `offset`.
HostPhase2Data { hash: [u8; 32], offset: u64 },
}
#[derive(
Debug,
Clone,
Copy,
PartialEq,
SerializedSize,
Serialize,
Deserialize,
strum_macros::IntoStaticStr,
)]
#[strum(serialize_all = "snake_case")]
pub enum SpResponse {
Discover(DiscoverResponse),
IgnitionState(IgnitionState),
/// `BulkIgnitionState` is followed by a TLV-encoded set of
/// [`ignition::IgnitionState`]s.
BulkIgnitionState(TlvPage),
IgnitionCommandAck,
SpState(SpStateV1),
SpUpdatePrepareAck,
ComponentUpdatePrepareAck,
UpdateChunkAck,
UpdateStatus(UpdateStatus),
UpdateAbortAck,
SerialConsoleAttachAck,
SerialConsoleWriteAck {
furthest_ingested_offset: u64,
},
SerialConsoleDetachAck,
PowerState(PowerState),
SetPowerStateAck,
ResetPrepareAck,
// There is intentionally no `ResetTriggerAck` response; the expected
// "response" to `ResetTrigger` is an SP reset, which won't allow for
// acks to be sent.
/// An `Inventory` response is followed by a TLV-encoded set of
/// [`DeviceDescriptionHeader`]s.
Inventory(TlvPage),
Error(SpError),
StartupOptions(StartupOptions),
SetStartupOptionsAck,
/// A `ComponentDetails` response is followed by a TLV-encoded set of
/// informational structures (see [`ComponentDetails`]).
ComponentDetails(TlvPage),
IgnitionLinkEvents(LinkEvents),
/// A `BulkIgnitionLinkEvents` response is followed by a TLV-encoded set of
/// [`ignition::LinkEvents`]s.
BulkIgnitionLinkEvents(TlvPage),
ClearIgnitionLinkEventsAck,
ComponentClearStatusAck,
ComponentActiveSlot(u16),
ComponentSetActiveSlotAck,
SerialConsoleBreakAck,
SendHostNmiAck,
SetIpccKeyLookupValueAck,
ComponentSetAndPersistActiveSlotAck,
/// The packet contains trailing caboose data
CabooseValue,
SerialConsoleKeepAliveAck,
ResetComponentPrepareAck,
ResetComponentTriggerAck,
SwitchDefaultImageAck,
ComponentActionAck,
SpStateV2(SpStateV2),
ReadSensor(SensorResponse),
CurrentTime(u64),
ReadRot(RotResponse),
/// The packet contains trailing lock information
VpdLockState,
DisableComponentWatchdogAck,
ComponentWatchdogSupportedAck,
SpStateV3(SpStateV3),
RotBootInfo(RotBootInfo),
/// Response to a data-bearing component action
ComponentAction(ComponentActionResponse),
}
/// Identifier for one of of an SP's KSZ8463 management-network-facing ports.
#[derive(
Clone,
Copy,
Debug,
PartialEq,
Eq,
Hash,
Serialize_repr,
Deserialize_repr,
SerializedSize,
)]
#[repr(u8)]
pub enum SpPort {
One = 1,
Two = 2,
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct DiscoverResponse {
/// Which SP port received the `Discover` request.
pub sp_port: SpPort,
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct ImageVersion {
pub epoch: u32,
pub version: u32,
}
#[derive(
Debug, Copy, Clone, PartialEq, Eq, Deserialize, Serialize, SerializedSize,
)]
pub enum ImageError {
/// Image has not been sanity checked (internal use)
Unchecked = 1,
/// First page of image is erased.
FirstPageErased,
/// Some pages in the image are erased.
PartiallyProgrammed,
/// The NXP image offset + length caused a wrapping add.
InvalidLength,
/// The header flash page is erased.
HeaderNotProgrammed,
/// A bootloader image is too short.
BootloaderTooSmall,
/// A required ImageHeader is missing.
BadMagic,
/// The image size in ImageHeader is unreasonable.
HeaderImageSize,
/// total_image_length in ImageHeader is not properly aligned.
UnalignedLength,
/// Some NXP image types are not supported.
UnsupportedType,
/// Wrong format reset vector.
ResetVectorNotThumb2,
/// Reset vector points outside of image execution range.
ResetVector,
/// Signature check on image failed.
Signature,
}
/// This is quasi-deprecated in that it will only be returned by SPs with images
/// older than the introduction of `SpStateV2`.
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct SpStateV1 {
pub hubris_archive_id: [u8; 8],
// Serial and revision are only 11 bytes in practice; we have plenty of room
// so we'll leave the fields wider in case we grow it in the future. The
// values are 0-padded.
pub serial_number: [u8; 32],
pub model: [u8; 32],
pub revision: u32,
pub base_mac_address: [u8; 6],
pub version: ImageVersion,
pub power_state: PowerState,
pub rot: Result<RotState, RotError>,
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct SpStateV2 {
pub hubris_archive_id: [u8; 8],
// Serial and revision are only 11 bytes in practice; we have plenty of room
// so we'll leave the fields wider in case we grow it in the future. The
// values are 0-padded.
pub serial_number: [u8; 32],
pub model: [u8; 32],
pub revision: u32,
pub base_mac_address: [u8; 6],
pub power_state: PowerState,
pub rot: Result<RotStateV2, RotError>,
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct SpStateV3 {
pub hubris_archive_id: [u8; 8],
// Serial and revision are only 11 bytes in practice; we have plenty of room
// so we'll leave the fields wider in case we grow it in the future. The
// values are 0-padded.
pub serial_number: [u8; 32],
pub model: [u8; 32],
pub revision: u32,
pub base_mac_address: [u8; 6],
pub power_state: PowerState,
}
type Digest256 = [u8; 32];
trait HexDisplayableArray {
// fn display(&self) -> fmt::Display;
fn display(&self) -> HexStringDisplay;
}
impl HexDisplayableArray for Digest256 {
fn display(&self) -> HexStringDisplay<'_> {
HexStringDisplay(&self[..])
}
}
struct HexStringDisplay<'a>(&'a [u8]);
impl<'a> fmt::Display for HexStringDisplay<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "\"")?;
for b in self.0.iter() {
write!(f, "{:02x}", b)?;
}
write!(f, "\"")?;
Ok(())
}
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, SerializedSize,
)]
pub struct RotImageDetails {
pub digest: Digest256,
pub version: ImageVersion,
}
impl RotImageDetails {
pub fn display(&self) -> RotImageDetailsDisplay<'_> {
RotImageDetailsDisplay(self)
}
}
/// This class exists for faux-mgs to nicely display the Firmware ID (FWID).
#[derive(Clone, Debug)]
#[must_use = "this struct does nothing unless displayed"]
pub struct RotImageDetailsDisplay<'a>(pub &'a RotImageDetails);
impl<'a> fmt::Display for RotImageDetailsDisplay<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = self.0;
writeln!(f, "digest: {}, ", s.digest.display())?;
writeln!(f, "version: {:?}, ", s.version)?;
Ok(())
}
}
/// The boot time details dumped by Stage0 into Hubris on the RoT
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct RotBootState {
pub active: RotSlotId,
pub slot_a: Option<RotImageDetails>,
pub slot_b: Option<RotImageDetails>,
}
impl RotBootState {
pub fn display(&self) -> RotBootStateDisplay<'_> {
RotBootStateDisplay(self)
}
}
/// This class exists for faux-mgs to nicely display the Firmware ID (FWID).
#[derive(Clone, Debug)]
#[must_use = "this struct does nothing unless displayed"]
pub struct RotBootStateDisplay<'a>(pub &'a RotBootState);
impl<'a> fmt::Display for RotBootStateDisplay<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = self.0;
writeln!(f, "active: {:?}, ", s.active)?;
write!(f, "slot_a: ")?;
match s.slot_a {
Some(details) => {
writeln!(
f,
"Some(RotImageDetails{{ {} }}),",
&RotImageDetailsDisplay(&details)
)?;
}
None => writeln!(f, "None,")?,
};
write!(f, "slot_b: ")?;
match s.slot_b {
Some(details) => {
writeln!(
f,
"Some(RotImageDetails{{ {} }}),",
&RotImageDetailsDisplay(&details)
)?;
}
None => writeln!(f, "None,")?,
};
Ok(())
}
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct RotUpdateDetails {
pub boot_state: RotBootState,
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct RotState {
pub rot_updates: RotUpdateDetails,
}
impl RotState {
pub fn display(&self) -> RotStateDisplay<'_> {
RotStateDisplay(self)
}
}
/// This class exists for faux-mgs to nicely display the Firmware ID (FWID).
#[derive(Clone, Debug)]
#[must_use = "this struct does nothing unless displayed"]
pub struct RotStateDisplay<'a>(pub &'a RotState);
impl<'a> fmt::Display for RotStateDisplay<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = self.0.rot_updates.boot_state;
writeln!(
f,
"RotState {{ rot_updates: RotUpdateDetails {{ boot_state: RotBootState {{ {} }} }} }}",
&RotBootStateDisplay(&s)
)?;
Ok(())
}
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct RotStateV2 {
/// The slot of the currently running image
pub active: RotSlotId,
/// The persistent boot preference written into the current authoritative
/// CFPA page (ping or pong).
pub persistent_boot_preference: RotSlotId,
/// The persistent boot preference written into the CFPA scratch page that
/// will become the persistent boot preference in the authoritative CFPA
/// page upon reboot, unless CFPA update of the authoritative page fails for
/// some reason.
pub pending_persistent_boot_preference: Option<RotSlotId>,
/// Override persistent preference selection for a single boot
///
/// This is a magic ram value that is cleared by bootleby
pub transient_boot_preference: Option<RotSlotId>,
/// Sha3-256 Digest of Slot A in Flash
pub slot_a_sha3_256_digest: Option<[u8; 32]>,
/// Sha3-256 Digest of Slot B in Flash
pub slot_b_sha3_256_digest: Option<[u8; 32]>,
}
impl RotStateV2 {
pub fn display(&self) -> RotStateV2Display<'_> {
RotStateV2Display(self)
}
}
/// This class exists for faux-mgs to nicely display the Firmware ID (FWID).
#[derive(Clone, Debug)]
#[must_use = "this struct does nothing unless displayed"]
pub struct RotStateV2Display<'a>(pub &'a RotStateV2);
impl<'a> fmt::Display for RotStateV2Display<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = self.0;
writeln!(f, "RotStateV2 {{")?;
writeln!(f, "active: {:?}, ", s.active)?;
writeln!(
f,
"persistent_boot_preference: {:?}, ",
s.persistent_boot_preference
)?;
writeln!(
f,
"pending_persistent_boot_preference: {:?}, ",
s.pending_persistent_boot_preference
)?;
writeln!(
f,
"transient_boot_preference: {:?}, ",
s.transient_boot_preference
)?;
write!(f, "slot_a_sha3_256_digest: ")?;
match s.slot_a_sha3_256_digest {
Some(digest) => {
writeln!(f, "Some({}), ", digest.display())?;
}
None => writeln!(f, "None, ")?,
};
write!(f, "slot_b_sha3_256_digest: ")?;
match s.slot_b_sha3_256_digest {
Some(digest) => {
writeln!(f, "Some({}), ", digest.display())?;
}
None => writeln!(f, "None, ")?,
};
writeln!(f, "}}")?;
Ok(())
}
}
impl fmt::Display for RotStateV2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "{}", &RotStateV2Display(self))?;
Ok(())
}
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub enum Fwid {
Sha3_256(Digest256),
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct RotStateV3 {
/// The slot of the currently running image
pub active: RotSlotId,
/// The persistent boot preference written into the current authoritative
/// CFPA page (ping or pong).
pub persistent_boot_preference: RotSlotId,
/// The persistent boot preference written into the CFPA scratch page that
/// will become the persistent boot preference in the authoritative CFPA
/// page upon reboot, unless CFPA update of the authoritative page fails for
/// some reason.
pub pending_persistent_boot_preference: Option<RotSlotId>,
/// Override persistent preference selection for a single boot
///
/// This corresponds to a magic ram value that is cleared by bootleby
pub transient_boot_preference: Option<RotSlotId>,
/// Sha3-256 Digest of Slot A in Flash
pub slot_a_fwid: Fwid,
/// Sha3-256 Digest of Slot B in Flash
pub slot_b_fwid: Fwid,
/// Sha3-256 Digest of Bootloader in Flash at boot time
pub stage0_fwid: Fwid,
/// Sha3-256 Digest of Staged Bootloader in Flash at boot time
pub stage0next_fwid: Fwid,
/// Flash Slot A status at last RoT reset
pub slot_a_status: Result<(), ImageError>,
/// Slot B status at last RoT reset
pub slot_b_status: Result<(), ImageError>,
/// Stage0 (bootloader) status at last RoT reset
pub stage0_status: Result<(), ImageError>,
/// Stage0Next status at last RoT reset
pub stage0next_status: Result<(), ImageError>,
}
impl RotStateV3 {
pub fn display(&self) -> RotStateV3Display<'_> {
RotStateV3Display(self)
}
}
#[derive(Clone, Debug)]
#[must_use = "this struct does nothing unless displayed"]
pub struct RotStateV3Display<'a>(pub &'a RotStateV3);
impl<'a> fmt::Display for RotStateV3Display<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = self.0;
writeln!(f, "RotStateV3 {{")?;
writeln!(f, "active: {:?}, ", s.active)?;
writeln!(
f,
"persistent_boot_preference: {:?}, ",
s.persistent_boot_preference
)?;
writeln!(
f,
"pending_persistent_boot_preference: {:?}, ",
s.pending_persistent_boot_preference
)?;
writeln!(
f,
"transient_boot_preference: {:?}, ",
s.transient_boot_preference
)?;
match s.slot_a_fwid {
Fwid::Sha3_256(digest) => writeln!(
f,
"slot_a_fwid: Fwid::Sha3_256({}), ",
digest.display()
)?,
}
match s.slot_b_fwid {
Fwid::Sha3_256(digest) => writeln!(
f,
"slot_b_fwid: Fwid::Sha3_256({}), ",
digest.display()
)?,
}
match s.stage0_fwid {
Fwid::Sha3_256(digest) => writeln!(
f,
"stage0_fwid: Fwid::Sha3_256({}), ",
digest.display()
)?,
}
match s.stage0next_fwid {
Fwid::Sha3_256(digest) => writeln!(
f,
"stage0next_fwid: Fwid::Sha3_256({}), ",
digest.display()
)?,
}
writeln!(f, "slot_a_status: {:?}, ", s.slot_a_status)?;
writeln!(f, "slot_b_status: {:?}, ", s.slot_b_status)?;
writeln!(f, "stage0_status: {:?}, ", s.stage0_status)?;
writeln!(f, "stage0next_status: {:?} ", s.stage0next_status)?;
write!(f, "}}")?;
Ok(())
}
}
/// `rot_boot_info` and versioned_rot_boot_info` are used to
/// implement backward/forward compatible Hubris update flows.
///
/// The end goal is to flush out old images from the customer base
/// and spares so that the older APIs can be deprecated and removed.
///
/// A to-be-implemented rollback-protection feature will keep old
/// versions from being reintroduced.
/// [Issue 222](https://github.com/oxidecomputer/management-gateway-service/issues/222)
///
/// Until then, the management-gateway-service needs to continue to
/// handle old versions of SP and RoT firmware update flows.
///
/// MGS will always need to handle SP and RoT version skew during update as
/// well as being exposed to spares loaded with SP and RoT images that are
/// newer than the running MGS version.
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub enum RotBootInfo {
V1(RotState),
V2(RotStateV2),
V3(RotStateV3),
}
impl RotBootInfo {
/// update HIGHEST_KNOWN_VERSION when the next RotBootInfo variant is added.
pub const HIGHEST_KNOWN_VERSION: u8 = 3;
pub fn display(&self) -> RotBootInfoDisplay<'_> {
RotBootInfoDisplay(self)
}
}
#[derive(Clone, Debug)]
#[must_use = "this struct does nothing unless displayed"]
pub struct RotBootInfoDisplay<'a>(pub &'a RotBootInfo);
impl<'a> fmt::Display for RotBootInfoDisplay<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, " RotBootInfo {{")?;
match self.0 {
RotBootInfo::V1(rotstate) => {
write!(f, " V1({})", &RotStateDisplay(rotstate))?;
}
// Use a helper on V2 to display a human readable FWID
RotBootInfo::V2(rotstate) => {
write!(f, " V2({})", &RotStateV2Display(rotstate))?;
}
// Use helper on V3 to display a human readable FWID
RotBootInfo::V3(rotstate) => {
write!(f, " V3({})", &RotStateV3Display(rotstate))?;
}
}
writeln!(f, "}}")?;
Ok(())
}
}
/// Metadata describing a single page (out of a larger list) of TLV-encoded
/// structures returned by the SP.
///
/// Always followed by trailing data containing a sequence of [`tlv`]-encoded
/// structures (e.g., [`DeviceDescriptionHeader`], [`ComponentDetails`]).
#[derive(
Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, SerializedSize,
)]
pub struct TlvPage {
/// First encoded structure present in this packet.
pub offset: u32,
/// Total number of structures in this data set.
pub total: u32,
}
/// Types of component details that can be included in the TLV-encoded data of
/// an [`SpResponse::ComponentDetails(_)`] message.
///
/// Note that `ComponentDetails` itself does not implement the relevant serde
/// serialization traits; it only serves as an organizing collection of the
/// possible types contained in a component details message. Each TLV-encoded
/// struct corresponds to one of these cases.
#[derive(Debug, Clone)]
pub enum ComponentDetails {
PortStatus(Result<PortStatus, PortStatusError>),
Measurement(Measurement),
}
impl ComponentDetails {
pub fn tag(&self) -> tlv::Tag {
match self {
ComponentDetails::PortStatus(_) => PortStatus::TAG,
ComponentDetails::Measurement(_) => MeasurementHeader::TAG,
}
}
pub fn serialize(&self, buf: &mut [u8]) -> hubpack::error::Result<usize> {
match self {
ComponentDetails::PortStatus(p) => hubpack::serialize(buf, p),
ComponentDetails::Measurement(m) => {
let header = MeasurementHeader::from(m);
// Serialize the header...
let n = hubpack::serialize(buf, &header)?;
let buf = &mut buf[n..];
// ... then append the name if we have room.
if buf.len() < m.name.len() {
Err(hubpack::error::Error::Overrun)
} else {
buf[..m.name.len()].copy_from_slice(m.name.as_bytes());
Ok(n + m.name.len())
}
}
}
}
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub enum ComponentActionResponse {
Ack,
Monorail(MonorailComponentActionResponse),
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub enum MonorailComponentActionResponse {
RequestChallenge(UnlockChallenge),
}
/// Header for the description of a single device.
///
/// Always packed into a [`tlv`] triple containing:
///
/// ```text
/// [
/// DeviceDescriptionHeader::TAG
/// | length
/// | hubpack-serialized DeviceDescriptionHeader
/// | device
/// | description
/// ]
/// ```
///
/// where `device` and `description` are UTF8 strings whose lengths are included
/// in the `DeviceDescriptionHeader`.
#[derive(
Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, SerializedSize,
)]
pub struct DeviceDescriptionHeader {
pub component: SpComponent,
pub device_len: u32,
pub description_len: u32,
pub capabilities: DeviceCapabilities,
pub presence: DevicePresence,
}
impl DeviceDescriptionHeader {
pub const TAG: tlv::Tag = tlv::Tag(*b"DSC0");
}
#[derive(
Default,
Debug,
Clone,
Copy,
PartialEq,
Eq,
SerializedSize,
Serialize,
Deserialize,
)]
#[repr(transparent)]
pub struct DeviceCapabilities(u32);
bitflags! {
impl DeviceCapabilities: u32 {
const UPDATEABLE = 1 << 0;
const HAS_MEASUREMENT_CHANNELS = 1 << 1;
const HAS_SERIAL_CONSOLE = 1 << 2;
const IS_LED = 1 << 3;
// MGS has a placeholder API for powering off an individual component;
// do we want to keep that? If so, add a bit for "can be powered on and
// off".
}
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, SerializedSize,
)]
pub enum DevicePresence {
Present,
NotPresent,
Failed,
Unavailable,
Timeout,
Error,
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub enum UpdateStatus {
/// The SP has no update status.
None,
/// Returned when the SP is still preparing to apply the update with the
/// given ID (e.g., erasing a target flash slot).
Preparing(UpdatePreparationStatus),
/// Special status only applicable to SP updates: the SP has finished
/// scanning its auxiliary flash slots, and we now know whether we need to
/// send the aux flash image.
///
/// This state is only applicable to (a) the `SP_ITSELF` component when (b)
/// the update preparation message sent by MGS indicates an aux flash image
/// is present.
SpUpdateAuxFlashChckScan {
id: UpdateId,
/// If true, MGS will not send the aux flash image and will only send
/// the SP image.
found_match: bool,
/// Total size of the update to be applied.
///
/// This is not directly relevant to this state, but is used by MGS to
/// convert this state (which only it knows about) into an `InProgress`
/// state to return to its callers.
total_size: u32,
},
/// Returned when an update is currently in progress.
InProgress(UpdateInProgressStatus),
/// Returned when an update has completed.
///
/// The SP has no concept of time, so we cannot indicate how recently this
/// update completed. The SP will continue to return this status until a new
/// update starts (or the status is reset some other way, such as an SP
/// reboot).
Complete(UpdateId),
/// Returned when an update has been aborted.
///
/// The SP has no concept of time, so we cannot indicate how recently this
/// abort happened. The SP will continue to return this status until a new
/// update starts (or the status is reset some other way, such as an SP
/// reboot).
Aborted(UpdateId),
/// Returned when an update has failed on the SP.
///
/// The SP has no concept of time, so we cannot indicate how recently this
/// abort happened. The SP will continue to return this status until a new
/// update starts (or the status is reset some other way, such as an SP
/// reboot).
Failed { id: UpdateId, code: u32 },
/// Returned when an update to the RoT has failed.
///
/// The SP has no concept of time, so we cannot indicate how recently this
/// abort happened. The SP will continue to return this status until a new
/// update starts (or the status is reset some other way, such as an SP
/// reboot).
RotError { id: UpdateId, error: RotError },
}
/// Current state when the SP is preparing to apply an update.
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct UpdatePreparationStatus {
pub id: UpdateId,
pub progress: Option<UpdatePreparationProgress>,
}
/// Current progress of preparing for an update.
///
/// The initial values reported by the SP should have `current=0` and `total`
/// defined in some SP-specific unit. `current` should advance toward `total`;
/// once `current == total` preparation is complete, and the SP should return
/// `UpdateStatus::InProgress` instead.
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct UpdatePreparationProgress {
pub current: u32,
pub total: u32,
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, SerializedSize, Serialize, Deserialize,
)]
pub struct UpdateInProgressStatus {
pub id: UpdateId,
pub bytes_received: u32,
pub total_size: u32,
}
#[derive(
Debug, Clone, Copy, PartialEq, SerializedSize, Serialize, Deserialize,
)]
pub enum SpError {
/// The SP is busy; retry the request mometarily.
///
/// E.g., the request requires communicating on a USART whose FIFO is
/// currently full.
Busy,
/// The request from MGS was invalid.
BadRequest(BadRequestReason),
/// The [`RequestKind`] is not supported by the receiving SP; e.g., asking an
/// SP without an attached ignition controller for ignition state.
RequestUnsupportedForSp,
/// The [`RequestKind`] is not supported by the receiving component of the
/// SP; e.g., asking for the serial console of a component that does not
/// have one.
RequestUnsupportedForComponent,
/// An ignition-related error.
Ignition(IgnitionError),
/// Cannot write to the serial console because it is not attached.
SerialConsoleNotAttached,
/// Cannot attach to the serial console because another MGS instance is
/// already attached.
SerialConsoleAlreadyAttached,
/// An update cannot be started while another component is being updated.
OtherComponentUpdateInProgress(SpComponent),
/// An update has not been prepared yet.
UpdateNotPrepared,
/// An update-related message arrived at the SP, but its update ID does not
/// match the update ID the SP is currently processing.
InvalidUpdateId {
sp_update_id: UpdateId,
},
/// An update is already in progress with the specified amount of data
/// already provided. MGS should resume the update at that offset.
UpdateInProgress(UpdateStatus),
/// Received an invalid update chunk; the in-progress update must be
/// aborted and restarted.
InvalidUpdateChunk,
/// An update operation failed with the associated code.
UpdateFailed(u32),
/// An update is not possible at this time (e.g., the target slot is locked
/// by another device).
UpdateSlotBusy,
/// An error occurred getting or setting the power state.
PowerStateError(u32),
/// Received a `ResetTrigger` request without first receiving a
/// `ResetPrepare` request. This can be used to detect a successful
/// reset.
ResetTriggerWithoutPrepare,
/// Request mentioned a slot number for a component that does not have that
/// slot.
InvalidSlotForComponent,
/// The requested operation on the component failed with the associated
/// code.
ComponentOperationFailed(u32),
/// The update exceeds our slot capacity
UpdateIsTooLarge,
/// Setting requested IPCC key/value failed.
SetIpccKeyLookupValueFailed(IpccKeyLookupValueError),
/// The image does not have a caboose
NoCaboose,
/// The given key is not available in the caboose
NoSuchCabooseKey([u8; 4]),
/// The given caboose value would overflow the trailing packet data
CabooseValueOverflow(u32),
CabooseReadError,
BadCabooseChecksum,
/// The new image does not have a caboose with the `BORD` key
ImageBoardUnknown,
/// The new image has a `BORD` key that does not match the current image
ImageBoardMismatch,
/// Received a `ResetComponentTrigger` request without first receiving a
/// `ResetComponentPrepare` request. This can be used to detect a successful
/// reset on the SP_ITSELF. Not used for the ROT where the SP observes
/// the RoT reset and can report success.
ResetComponentTriggerWithoutPrepare,
/// There will be policy violations for some requests:
/// - No image in SlotId (what suitability checks are needed?)
/// - Lower epoch than current in SlotId
SwitchDefaultImageError(u32),
// --------------------------------------
// *** That new hotness below here ***
// --------------------------------------
//
// New nested variants, one for each hubris API are below We will likely
// create a new Error variant so we can deprecate some of redundant
// variants above.
Sprot(SprotProtocolError),
Spi(SpiError),
Sprockets(SprocketsError),
Update(UpdateError),
Sensor(SensorError),
Vpd(VpdError),
Watchdog(WatchdogError),
Monorail(MonorailError),
}
impl fmt::Display for SpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Busy => {
write!(f, "SP busy")
}
Self::BadRequest(reason) => {
write!(f, "bad request: {reason:?}")
}
Self::RequestUnsupportedForSp => {
write!(f, "unsupported request for this SP")
}
Self::RequestUnsupportedForComponent => {
write!(f, "unsupported request for this SP component")
}