usbvfiod 0.2.0

A vfio-user server for USB pass-through.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
//! Abstraction of the Transfer Request Block (TRB) of a USB3 Host (XHCI) controller.
//!
//! See XHCI specification Section 3.2.7 for an overview on TRB.

use thiserror::Error;
use tracing::warn;

use super::super::pci::constants::xhci::rings::trb_types::{self, *};

/// Dedicated type to indicate that a 16 byte array represents the contents
/// of a Transfer Request Block.
pub type RawTrbBuffer = [u8; 16];

#[derive(Debug)]
pub struct RawTrb {
    pub address: u64,
    pub buffer: RawTrbBuffer,
}

/// Create a zero-initiliated TRB buffer.
pub const fn zeroed_trb_buffer() -> RawTrbBuffer {
    [0; 16]
}

/// Represents a TRB that the XHCI controller can place on the event ring.
///
/// See XHCI specification Section 6.4.2 for detailed event TRB type descriptions.
#[derive(Debug)]
pub enum EventTrb {
    Transfer(TransferEventTrbData),
    CommandCompletion(CommandCompletionEventTrbData),
    PortStatusChange(PortStatusChangeEventTrbData),
    //BandwidthRequest,
    //Doorbell,
    //HostController,
    //DeviceNotification,
    //MfIndexWrap,
}

impl EventTrb {
    /// Generates the byte representation of the TRB.
    ///
    /// The cycle bit's value does not depend on the TRB but on the ring that
    /// the TRB will be placed on.
    ///
    /// # Parameters
    ///
    /// - `cycle_bit`: value to set the cycle bit to. Has to match the ring
    ///   where the caller will write the TRB on.
    pub fn to_bytes(&self, cycle_bit: bool) -> RawTrbBuffer {
        // layout the event-type-specific data
        let mut trb_data = match self {
            Self::Transfer(data) => data.to_bytes(),
            Self::CommandCompletion(data) => data.to_bytes(),
            Self::PortStatusChange(data) => data.to_bytes(),
        };
        // set cycle bit
        trb_data[12] = (trb_data[12] & !0x1) | cycle_bit as u8;

        trb_data
    }
}

/// Stores the relevant data for a Command Completion Event.
///
/// Do not use this struct directly, use EventTrb::new_command_completion_event_trb
/// instead.
#[derive(Debug)]
pub struct CommandCompletionEventTrbData {
    command_trb_pointer: u64,
    command_completion_parameter: u32,
    completion_code: CompletionCode,
    slot_id: u8,
}

impl EventTrb {
    /// Create a new Command Completion Event TRB.
    ///
    /// The XHCI spec describes this structure in Section 6.4.2.2.
    ///
    /// # Parameters
    ///
    /// - `command_trb_pointer`: 64-bit address of the Command TRB that
    ///   generated this event. The address has to be 16-byte-aligned, so the
    ///   lowest four bit have to be 0.
    /// - `command_completion_parameter`: Depends on the associated command.
    ///   This is a 24-bit value, so the highest eight bit are ignored.
    /// - `completion_code`: Encodes the completion status of the associated
    ///   command.
    /// - `slot_id`: The slot associated with command that generated this
    ///   event.
    pub fn new_command_completion_event_trb(
        command_trb_pointer: u64,
        command_completion_parameter: u32,
        completion_code: CompletionCode,
        slot_id: u8,
    ) -> Self {
        assert_eq!(
            0,
            command_trb_pointer & 0x0f,
            "command_trb_pointer has to be 16-byte-aligned."
        );
        assert_eq!(
            0,
            command_completion_parameter & 0xff000000,
            "command_completion_parameter has to be a 24-bit value."
        );
        Self::CommandCompletion(CommandCompletionEventTrbData {
            command_trb_pointer,
            command_completion_parameter,
            completion_code,
            slot_id,
        })
    }
}

impl CommandCompletionEventTrbData {
    fn to_bytes(&self) -> RawTrbBuffer {
        let mut trb = zeroed_trb_buffer();

        trb[0..8].copy_from_slice(&self.command_trb_pointer.to_le_bytes());
        trb[8..11].copy_from_slice(&self.command_completion_parameter.to_le_bytes()[0..3]);
        trb[11] = self.completion_code as u8;
        trb[13] = COMMAND_COMPLETION_EVENT << 2;
        trb[15] = self.slot_id;

        trb
    }
}

/// Stores the relevant data for a Port Status Change Event.
///
/// Do not use this struct directly, use EventTrb::new_port_status_change_event_trb
/// instead.
#[derive(Debug)]
pub struct PortStatusChangeEventTrbData {
    port_id: u8,
}

impl EventTrb {
    /// Create a new Port Status Change Event TRB.
    ///
    /// The XHCI spec describes this structure in Section 6.4.2.3.
    ///
    /// # Parameters
    ///
    /// - `port_id`: The number of the root hub port that generated this
    ///   event.
    pub const fn new_port_status_change_event_trb(port_id: u8) -> Self {
        Self::PortStatusChange(PortStatusChangeEventTrbData { port_id })
    }
}

impl PortStatusChangeEventTrbData {
    const fn to_bytes(&self) -> RawTrbBuffer {
        let mut bytes = zeroed_trb_buffer();

        bytes[3] = self.port_id;
        bytes[11] = CompletionCode::Success as u8;
        bytes[13] = PORT_STATUS_CHANGE_EVENT << 2;

        bytes
    }
}

/// Stores the relevant data for a Transfer Event.
#[derive(Debug)]
pub struct TransferEventTrbData {
    trb_pointer: u64,
    trb_transfer_length: u32,
    completion_code: CompletionCode,
    event_data: bool,
    endpoint_id: u8,
    slot_id: u8,
}

impl EventTrb {
    /// Create a new Transfer Event TRB.
    ///
    /// The XHCI spec describes this structure in Section 6.4.2.1.
    ///
    /// # Parameters
    ///
    /// - `trb_pointer`: Pointer to the transfer even that generated the event.
    /// - `trb_transfer_length`: Residual number of bytes not transferred.
    /// - `completion_code`: Encodes the completion status of the associated
    ///   transfer.
    /// - `event_data`: Whether this event was generated by an Event Data TRB.
    /// - `endpoint_id`: On which endpoint the transfer happened.
    /// - `slot_id`: On which slot the transfer happened.
    pub const fn new_transfer_event_trb(
        trb_pointer: u64,
        trb_transfer_length: u32,
        completion_code: CompletionCode,
        event_data: bool,
        endpoint_id: u8,
        slot_id: u8,
    ) -> Self {
        Self::Transfer(TransferEventTrbData {
            trb_pointer,
            trb_transfer_length,
            completion_code,
            event_data,
            endpoint_id,
            slot_id,
        })
    }
}

impl TransferEventTrbData {
    fn to_bytes(&self) -> RawTrbBuffer {
        let mut trb = zeroed_trb_buffer();

        trb[0..8].copy_from_slice(&self.trb_pointer.to_le_bytes());
        trb[8..11].copy_from_slice(&self.trb_transfer_length.to_le_bytes()[0..3]);
        trb[11] = self.completion_code as u8;
        trb[12] = (self.event_data as u8) << 2;
        trb[13] = TRANSFER_EVENT << 2;
        trb[14] = self.endpoint_id;
        trb[15] = self.slot_id;

        trb
    }
}

/// Encodes the completion code that some event TRBs contain.
///
/// Refer to Table 6-90 in the XHCI specification for detailed descriptions of each code.
#[allow(dead_code)]
#[derive(Debug, Copy, Clone)]
pub enum CompletionCode {
    Invalid = 0,
    Success,
    DataBufferError,
    BabbleDetectedError,
    UsbTransactionError,
    TrbError,
    StallError,
    ResourceError,
    BandwidthError,
    NoSlotsAvailableError,
    InvalidStreamTypeError,
    SlotNotEnabledError,
    EndpointNotEnabledError,
    ShortPacket,
    RingUnderrun,
    RingOverrun,
    VfEventRingFullError,
    ParameterError,
    BandwidthOverrunError,
    ContextStateError,
    NoPingResponseError,
    EventRingFullError,
    IncompatibleDeviceError,
    MissedServiceError,
    CommandRingStopped,
    CommandAborted,
    Stopped,
    StoppedLengthInvalid,
    StoppedShortedPacket,
    MaxExitLatencyTooLargeError,
    Reserved,
    IsochBufferOverrun,
    EventLostError,
    UndefinedError,
    InvalidStreamIdError,
    SecondaryBandwidthError,
    SplitTransactionError,
}

/// A trait for types offering a higher-level view of raw TRB bytes.
///
/// All types representing data of TRBs should implement this trait to be
/// usable by the `parse` function.
trait TrbData: Sized {
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError>;
}

/// A trait for `CommandTrbVariant` and `TransferTrbVariant` to allow access
/// to their `Unrecognized` enum variant.
///
/// This trait allows the `parse` function to construct a `Unrecognized`
/// variant of both `CommandTrbVariant` and `TransferTrbVariant` by only
/// specifying a type parameter (which can be inferred).
trait TrbVariant: Sized {
    fn unrecognized(trb_bytes: RawTrbBuffer, err: TrbParseError) -> Self;
}

impl TrbVariant for CommandTrbVariant {
    fn unrecognized(trb_bytes: RawTrbBuffer, err: TrbParseError) -> Self {
        Self::Unrecognized(trb_bytes, err)
    }
}

impl TrbVariant for TransferTrbVariant {
    fn unrecognized(trb_bytes: RawTrbBuffer, err: TrbParseError) -> Self {
        Self::Unrecognized(trb_bytes, err)
    }
}

/// Glue function to construct a `CommandTrbVariant` or `TransferTrbVariant`
/// from raw TRB bytes.
///
/// This function makes the code of `CommandTrbVariant::parse` and
/// `TransferTrbVariant` quite a bit simpler.
///
/// # Type Parameters
///
/// The data of a TRB is abstracted by putting all type-specific information
/// into a type-specific struct such as `LinkTrbData`, and summarizing all
/// different TRB types in an enum such as `CommandTrbVariant`.
///
/// - `O`: The summarizing enum such as `CommandTrbVariant` (short for
///   "Outer").
/// - `I`: The TRB-type-specific struct such as `LinkTrbData` (short for
///   "Inner").
/// - `F`: Type of matching variant constructor (`F` due to convention).
///
/// # Parameters
///
/// - `variant_constructor`: The variant to be constructed.
/// - `trb_bytes`: The raw TRB data to use for parsing.
///
/// # Example
///
/// `parse(CommandTrbVariant::Link, trb_bytes)`
///
/// which is equivalent to
///
/// `parse<CommandTrbVariant, LinkTrbData, Fn(LinkTrbData) ->
/// CommandTrbVariant>(CommandTrbVariant::Link, trb_bytes)`
fn parse<O, I, F>(variant_constructor: F, trb_bytes: RawTrbBuffer) -> O
where
    O: TrbVariant,
    I: TrbData,
    F: Fn(I) -> O,
{
    I::parse(trb_bytes).map_or_else(|err| O::unrecognized(trb_bytes, err), variant_constructor)
}

/// Represents a TRB that the driver can place on the command ring.
#[derive(Debug, PartialEq, Eq)]
pub struct CommandTrb {
    /// Guest memory address where the driver placed the TRB.
    pub address: u64,
    /// Information specific to the particular command TRB variant.
    pub variant: CommandTrbVariant,
}

/// Represents a TRB that the driver can place on the command ring.
///
/// See XHCI specification Section 6.4.3 for detailed command TRB type descriptions.
#[derive(Debug, PartialEq, Eq)]
pub enum CommandTrbVariant {
    EnableSlot,
    DisableSlot(DisableSlotCommandTrbData),
    AddressDevice(AddressDeviceCommandTrbData),
    ConfigureEndpoint(ConfigureEndpointCommandTrbData),
    EvaluateContext(EvaluateContextCommandTrbData),
    ResetEndpoint(ResetEndpointCommandTrbData),
    StopEndpoint(StopEndpointCommandTrbData),
    SetTrDequeuePointer(SetTrDequeuePointerCommandTrbData),
    ResetDevice(ResetDeviceCommandTrbData),
    ForceHeader,
    NoOp,
    Unrecognized(RawTrbBuffer, TrbParseError),
}

impl CommandTrbVariant {
    /// Parse command-specific TRB data from a 16-byte buffer.
    ///
    /// If any errors occur during parsing, the function returns
    /// `CommandTrbVariant::Unrecognized`. Otherwise, it returns the variant
    /// including all relevant data that was encoded in the TRB buffer.
    ///
    /// # Limitations
    ///
    /// While this function can parse all available Command TRB types, it does
    /// not parse all of them in full detail. If the function returns only the
    /// enum variant without an associated struct, the parsing for the
    /// particular command is not yet implemented. EnableSlotCommand is an
    /// exception, because the TRB does not contain any additional information.
    pub fn parse(bytes: RawTrbBuffer) -> Self {
        let trb_type = bytes[13] >> 2;
        match trb_type {
            // EnableSlotCommand does not contain information apart from the
            // type; thus, no further parsing is necessary and we can just
            // return the enum variant.
            trb_types::ENABLE_SLOT_COMMAND => Self::EnableSlot,
            trb_types::DISABLE_SLOT_COMMAND => parse(Self::DisableSlot, bytes),
            trb_types::ADDRESS_DEVICE_COMMAND => parse(Self::AddressDevice, bytes),
            trb_types::CONFIGURE_ENDPOINT_COMMAND => parse(Self::ConfigureEndpoint, bytes),
            trb_types::EVALUATE_CONTEXT_COMMAND => parse(Self::EvaluateContext, bytes),
            trb_types::RESET_ENDPOINT_COMMAND => parse(Self::ResetEndpoint, bytes),
            trb_types::STOP_ENDPOINT_COMMAND => parse(Self::StopEndpoint, bytes),
            trb_types::SET_TR_DEQUEUE_POINTER_COMMAND => parse(Self::SetTrDequeuePointer, bytes),
            trb_types::RESET_DEVICE_COMMAND => parse(Self::ResetDevice, bytes),
            trb_types::FORCE_EVENT_COMMAND => Self::Unrecognized(
                bytes,
                TrbParseError::UnsupportedOptionalCommand(18, "Force Event Command".to_string()),
            ),
            trb_types::NEGOTIATE_BANDWIDTH_COMMAND => Self::Unrecognized(
                bytes,
                TrbParseError::UnsupportedOptionalCommand(
                    19,
                    "Negotiate Bandwidth Command".to_string(),
                ),
            ),
            trb_types::SET_LATENCY_TOLERANCE_VALUE_COMMAND => Self::Unrecognized(
                bytes,
                TrbParseError::UnsupportedOptionalCommand(
                    20,
                    "Set Latency Tolerance Value Command".to_string(),
                ),
            ),
            trb_types::GET_PORT_BANDWIDTH_COMMAND => Self::Unrecognized(
                bytes,
                TrbParseError::UnsupportedOptionalCommand(
                    21,
                    "Get Port Bandwidth Command".to_string(),
                ),
            ),
            trb_types::FORCE_HEADER_COMMAND => Self::ForceHeader,
            trb_types::NO_OP_COMMAND => Self::NoOp,
            trb_type => Self::Unrecognized(bytes, TrbParseError::UnknownTrbType(trb_type)),
        }
    }
}

/// Link TRB data structure.
///
/// See XHCI specification Section 6.4.4.1 for detailed descriptions
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkTrb {
    /// The address of the next ring segment.
    pub ring_segment_pointer: u64,
    /// The flag that indicates whether to toggle the cycle bit.
    pub toggle_cycle: bool,
}

impl LinkTrb {
    /// Parse data of a Link TRB.
    pub fn parse(trb_bytes: RawTrbBuffer) -> Option<Self> {
        let trb_type = trb_bytes[13] >> 2;
        if trb_type != trb_types::LINK {
            return None;
        }

        // SAFETY: range matches array length
        let rsp_bytes: [u8; 8] = trb_bytes[0..8].try_into().unwrap();
        let mut ring_segment_pointer = u64::from_le_bytes(rsp_bytes);
        let toggle_cycle = trb_bytes[12] & 0x2 != 0;

        // the lowest four bit of the pointer are RsvdZ to ensure 16-byte
        // alignment.
        if ring_segment_pointer & 0xf != 0 {
            warn!("RsvdZ violation in link TRB");
            ring_segment_pointer &= !0xf;
        }

        Some(Self {
            ring_segment_pointer,
            toggle_cycle,
        })
    }
}

/// Disable Slot Command TRB data structure.
///
/// See XHCI specification Section 6.4.3.3 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq)]
pub struct DisableSlotCommandTrbData {
    /// The associated Slot ID
    pub slot_id: u8,
}

impl TrbData for DisableSlotCommandTrbData {
    /// Parse data of a Disable Slot Command TRB.
    ///
    /// Only `CommandTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects all RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::DISABLE_SLOT_COMMAND,
            trb_type,
            "DisableSlotCommandTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        let slot_id = trb_bytes[15];

        Ok(Self { slot_id })
    }
}

/// Address Device Command TRB data structure.
///
/// See XHCI specification Section 6.4.3.4 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct AddressDeviceCommandTrbData {
    /// The address of the input context.
    pub input_context_pointer: u64,
    /// The flag that indicates whether to send a USB SET_ADDRESS request to the
    /// device.
    pub block_set_address_request: bool,
    /// The associated Slot ID
    pub slot_id: u8,
}

impl TrbData for AddressDeviceCommandTrbData {
    /// Parse data of a Address Device Command TRB.
    ///
    /// Only `CommandTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects all RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::ADDRESS_DEVICE_COMMAND,
            trb_type,
            "AddressDeviceCommandTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        // SAFETY: range matches array length
        let icp_bytes: [u8; 8] = trb_bytes[0..8].try_into().unwrap();
        let input_context_pointer = u64::from_le_bytes(icp_bytes);

        // the lowest four bit of the pointer are RsvdZ to ensure 16-byte
        // alignment.
        if input_context_pointer & 0xf != 0 {
            return Err(TrbParseError::RsvdZViolation);
        }

        let block_set_address_request = trb_bytes[13] & 0x2 != 0;
        let slot_id = trb_bytes[15];

        Ok(Self {
            input_context_pointer,
            block_set_address_request,
            slot_id,
        })
    }
}

/// Configure Endpoint Command TRB data structure.
///
/// See XHCI specification Section 6.4.3.5 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct ConfigureEndpointCommandTrbData {
    pub input_context_pointer: u64,
    pub deconfigure: bool,
    pub slot_id: u8,
}

impl TrbData for ConfigureEndpointCommandTrbData {
    /// Parse data of a Configure Endpoint Command TRB.
    ///
    /// Only `CommandTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects all RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::CONFIGURE_ENDPOINT_COMMAND,
            trb_type,
            "ConfigureEndpointCommandTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        // SAFETY: range matches array length
        let icp_bytes: [u8; 8] = trb_bytes[0..8].try_into().unwrap();
        let input_context_pointer = u64::from_le_bytes(icp_bytes);

        // the lowest four bit of the pointer are RsvdZ to ensure 16-byte
        // alignment.
        if input_context_pointer & 0xf != 0 {
            return Err(TrbParseError::RsvdZViolation);
        }

        let deconfigure = trb_bytes[13] & 0x2 != 0;
        let slot_id = trb_bytes[15];

        Ok(Self {
            input_context_pointer,
            deconfigure,
            slot_id,
        })
    }
}

/// Evaluate Context Command TRB data structure.
///
/// See XHCI specification Section 6.4.3.6 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct EvaluateContextCommandTrbData {
    pub input_context_pointer: u64,
    pub slot_id: u8,
}

impl TrbData for EvaluateContextCommandTrbData {
    /// Parse data of a Evaluate Context Command TRB.
    ///
    /// Only `CommandTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects all RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::EVALUATE_CONTEXT_COMMAND,
            trb_type,
            "EvaluateContextCommandTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        // SAFETY: range matches array length
        let icp_bytes: [u8; 8] = trb_bytes[0..8].try_into().unwrap();
        let input_context_pointer = u64::from_le_bytes(icp_bytes);

        // the lowest four bit of the pointer are RsvdZ to ensure 16-byte
        // alignment.
        if input_context_pointer & 0xf != 0 {
            return Err(TrbParseError::RsvdZViolation);
        }

        let slot_id = trb_bytes[15];

        Ok(Self {
            input_context_pointer,
            slot_id,
        })
    }
}

/// Reset Endpoint Command TRB data structure.
///
/// See XHCI specification Section 6.4.3.7 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq)]
pub struct ResetEndpointCommandTrbData {
    pub slot_id: u8,
    pub endpoint_id: u8,
}

impl TrbData for ResetEndpointCommandTrbData {
    /// Parse data of a Reset Endpoint Command TRB.
    ///
    /// Only `CommandTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects all RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::RESET_ENDPOINT_COMMAND,
            trb_type,
            "ResetEndpointCommandTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        let endpoint_id = trb_bytes[14] & 0x1f;
        let slot_id = trb_bytes[15];

        Ok(Self {
            slot_id,
            endpoint_id,
        })
    }
}

/// Stop Endpoint Command TRB data structure.
///
/// See XHCI specification Section 6.4.3.8 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq)]
pub struct StopEndpointCommandTrbData {
    /// The endpoint to stop.
    pub endpoint_id: u8,
    /// The associated Slot ID.
    pub slot_id: u8,
}

impl TrbData for StopEndpointCommandTrbData {
    /// Parse data of a Stop Endpoint Command TRB.
    ///
    /// Only `CommandTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects all RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::STOP_ENDPOINT_COMMAND,
            trb_type,
            "StopEndpointCommandTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        let endpoint_id = trb_bytes[14] & 0x1f;
        let slot_id = trb_bytes[15];

        Ok(Self {
            endpoint_id,
            slot_id,
        })
    }
}

/// Set TR Dequeue Pointer Command TRB data structure.
///
/// See XHCI specification Section 6.4.3.9 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct SetTrDequeuePointerCommandTrbData {
    /// The value of the xHC Consumer Cycle State referenced by the TR Dequeue pointer.
    pub dequeue_cycle_state: bool,
    /// If a stream_id is set, identifies the type of the Stream Context, otherwise 0.
    pub stream_context_type: u8,
    /// Base address to be written to the TR Dequeue Pointer Field in the target Endpoint or Stream Context.
    pub dequeue_pointer: u64,
    /// If streams enabled, identifies the Stream Context that receives the TR Dequeue Pointer.
    pub stream_id: u16,
    /// The target endpoint to receive the new pointer.
    pub endpoint_id: u8,
    /// The associated Slot ID.
    pub slot_id: u8,
}

impl TrbData for SetTrDequeuePointerCommandTrbData {
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let dequeue_cycle_state = trb_bytes[0] & 1 != 0;
        let stream_context_type = trb_bytes[0] & 0xe;

        // SAFETY: range matches array length
        let mut dequeue_pointer_bytes: [u8; 8] = trb_bytes[0..8].try_into().unwrap();
        dequeue_pointer_bytes[0] &= 0xf0;
        let dequeue_pointer = u64::from_le_bytes(dequeue_pointer_bytes);

        // SAFETY: range matches array length
        let stream_id_bytes: [u8; 2] = trb_bytes[11..13].try_into().unwrap();
        let stream_id = u16::from_le_bytes(stream_id_bytes);

        let endpoint_id = trb_bytes[14] & 0x1f;
        let slot_id = trb_bytes[15];

        Ok(Self {
            dequeue_cycle_state,
            stream_context_type,
            dequeue_pointer,
            stream_id,
            endpoint_id,
            slot_id,
        })
    }
}

/// Reset Device Command TRB data structure.
///
/// See XHCI specification Section 6.4.3.10 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq)]
pub struct ResetDeviceCommandTrbData {
    /// The slot ID associated with this command.
    pub slot_id: u8,
}

impl TrbData for ResetDeviceCommandTrbData {
    /// Parse data of a Reset Device Command TRB.
    ///
    /// Only `CommandTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects all RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::RESET_DEVICE_COMMAND,
            trb_type,
            "ResetDeviceCommandTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        let slot_id = trb_bytes[15];

        Ok(Self { slot_id })
    }
}

/// Represents a TRB that the driver can place on a transfer ring.
#[derive(Debug, PartialEq, Eq)]
pub struct TransferTrb {
    /// Guest memory address where the driver placed the TRB.
    pub address: u64,
    /// Information specific to the particular transfer TRB variant.
    pub variant: TransferTrbVariant,
}

/// Represents a TRB that the driver can place on a transfer ring.
///
/// See XHCI specification Section 6.4.1 for detailed transfer TRB type descriptions.
#[derive(Debug, PartialEq, Eq)]
pub enum TransferTrbVariant {
    Normal(NormalTrbData),
    SetupStage(SetupStageTrbData),
    DataStage(DataStageTrbData),
    StatusStage(StatusStageTrbData),
    Isoch,
    EventData(EventDataTrbData),
    NoOp,
    #[allow(unused)]
    Unrecognized(RawTrbBuffer, TrbParseError),
}

impl TransferTrbVariant {
    /// Parse transfer-specific TRB data from a 16-byte buffer.
    ///
    /// If any errors occur during parsing, the function returns
    /// `TransferTrbVariant::Unrecognized`. Otherwise, it returns the variant
    /// including all relevant data that was encoded in the TRB buffer.
    ///
    /// # Limitations
    ///
    /// While this function can parse all available Transfer TRB types, it does
    /// not parse all of them in full detail. If the function returns only the
    /// enum variant without an associated struct, the parsing for the
    /// particular command is not yet implemented.
    pub fn parse(bytes: RawTrbBuffer) -> Self {
        let trb_type = bytes[13] >> 2;
        match trb_type {
            trb_types::NORMAL => parse(Self::Normal, bytes),
            trb_types::SETUP_STAGE => parse(Self::SetupStage, bytes),
            trb_types::DATA_STAGE => parse(Self::DataStage, bytes),
            trb_types::STATUS_STAGE => parse(Self::StatusStage, bytes),
            trb_types::ISOCH => Self::Isoch,
            trb_types::EVENT_DATA => parse(Self::EventData, bytes),
            trb_types::NO_OP => Self::NoOp,
            trb_type => Self::Unrecognized(bytes, TrbParseError::UnknownTrbType(trb_type)),
        }
    }
}

/// Normal TRB data structure (simplified representation).
///
/// This struct contains only the commonly used fields from the Normal TRB.
/// See XHCI specification Section 6.4.1.1 for the complete TRB layout.
#[derive(Debug, PartialEq, Eq)]
pub struct NormalTrbData {
    pub data_pointer: u64,
    pub transfer_length: u32,
    pub chain: bool,
    pub interrupt_on_completion: bool,
    pub immediate_data: bool,
}

impl TrbData for NormalTrbData {
    /// Parse data of a Normal TRB.
    ///
    /// Only `TransferTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::NORMAL,
            trb_type,
            "SetupStageTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        // SAFETY: range matches array length
        let dp_bytes: [u8; 8] = trb_bytes[0..8].try_into().unwrap();
        let data_pointer = u64::from_le_bytes(dp_bytes);

        let tl_bytes: [u8; 4] = [trb_bytes[8], trb_bytes[9], trb_bytes[10] & 0x01, 0];
        let transfer_length = u32::from_le_bytes(tl_bytes);

        let chain = trb_bytes[12] & 0x10 != 0;
        let interrupt_on_completion = trb_bytes[12] & 0x20 != 0;
        let immediate_data = trb_bytes[12] & 0x40 != 0;

        Ok(Self {
            data_pointer,
            transfer_length,
            chain,
            interrupt_on_completion,
            immediate_data,
        })
    }
}

/// Setup Stage TRB data structure.
///
/// See XHCI specification Section 6.4.1.2.1 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq)]
pub struct SetupStageTrbData {
    pub request_type: u8,
    pub request: u8,
    pub value: u16,
    pub index: u16,
    pub length: u16,
    pub interrupt_on_completion: bool,
}

impl TrbData for SetupStageTrbData {
    /// Parse data of a Setup Stage TRB.
    ///
    /// Only `TransferTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::SETUP_STAGE,
            trb_type,
            "SetupStageTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        let request_type = trb_bytes[0];
        let request = trb_bytes[1];
        let value = trb_bytes[2] as u16 + ((trb_bytes[3] as u16) << 8);
        let index = trb_bytes[4] as u16 + ((trb_bytes[5] as u16) << 8);
        let length = trb_bytes[6] as u16 + ((trb_bytes[7] as u16) << 8);
        let interrupt_on_completion = trb_bytes[12] & 0x20 != 0;

        Ok(Self {
            request_type,
            request,
            value,
            index,
            length,
            interrupt_on_completion,
        })
    }
}

/// Data Stage TRB data structure.
///
/// See XHCI specification Section 6.4.1.2.2 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq)]
pub struct DataStageTrbData {
    pub data_pointer: u64,
    pub transfer_length: u16,
    pub chain: bool,
    pub interrupt_on_completion: bool,
    pub immediate_data: bool,
    pub direction: bool,
}

impl TrbData for DataStageTrbData {
    /// Parse data of a Data Stage TRB.
    ///
    /// Only `TransferTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::DATA_STAGE,
            trb_type,
            "DataStageTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        // SAFETY: range matches array length
        let dp_bytes: [u8; 8] = trb_bytes[0..8].try_into().unwrap();
        let data_pointer = u64::from_le_bytes(dp_bytes);

        let tl_bytes: [u8; 2] = trb_bytes[8..10].try_into().unwrap();
        let transfer_length = u16::from_le_bytes(tl_bytes);

        let chain = trb_bytes[12] & 0x10 != 0;
        let interrupt_on_completion = trb_bytes[12] & 0x20 != 0;
        let immediate_data = trb_bytes[12] & 0x40 != 0;
        let direction = trb_bytes[14] & 0x1 != 0;

        Ok(Self {
            data_pointer,
            transfer_length,
            chain,
            interrupt_on_completion,
            immediate_data,
            direction,
        })
    }
}

/// Status Stage TRB data structure.
///
/// See XHCI specification Section 6.4.1.2.3 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq)]
pub struct StatusStageTrbData {
    pub chain: bool,
    pub interrupt_on_completion: bool,
    pub direction: bool,
}

impl TrbData for StatusStageTrbData {
    /// Parse data of a Status Stage TRB.
    ///
    /// Only `TransferTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::STATUS_STAGE,
            trb_type,
            "StatusStageTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        let chain = trb_bytes[12] & 0x10 != 0;
        let interrupt_on_completion = trb_bytes[12] & 0x20 != 0;
        let direction = trb_bytes[14] & 0x1 != 0;

        Ok(Self {
            chain,
            interrupt_on_completion,
            direction,
        })
    }
}

/// Event Data TRB data structure.
///
/// See XHCI specification Section 6.4.4.2 for detailed field descriptions.
#[derive(Debug, PartialEq, Eq)]
pub struct EventDataTrbData {
    pub event_data: u64,
    pub chain: bool,
    pub interrupt_on_completion: bool,
}

impl TrbData for EventDataTrbData {
    /// Parse data of a Event Data TRB.
    ///
    /// Only `TransferTrb::try_from` should call this function.
    ///
    /// # Limitations
    ///
    /// The function currently does not check if the slice respects RsvdZ
    /// fields.
    fn parse(trb_bytes: RawTrbBuffer) -> Result<Self, TrbParseError> {
        let trb_type = trb_bytes[13] >> 2;
        assert_eq!(
            trb_types::EVENT_DATA,
            trb_type,
            "EventDataTrbData::parse called on TRB data with incorrect TRB type ({trb_type:#x})"
        );

        // SAFETY: range matches array length
        let ed_bytes: [u8; 8] = trb_bytes[0..8].try_into().unwrap();
        let event_data = u64::from_le_bytes(ed_bytes);

        let chain = trb_bytes[12] & 0x10 != 0;
        let interrupt_on_completion = trb_bytes[12] & 0x20 != 0;

        Ok(Self {
            event_data,
            chain,
            interrupt_on_completion,
        })
    }
}

/// Custom error type to represent errors in TRB parsing.
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum TrbParseError {
    #[error("TRB type {0} refers to \"{1}\", which is optional and not supported.")]
    UnsupportedOptionalCommand(u8, String),
    #[error("TRB type {0} does not refer to any command.")]
    UnknownTrbType(u8),
    #[error("Detected a non-zero value in a RsvdZ field")]
    RsvdZViolation,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_link_trb() {
        let trb_bytes = [
            0x80, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, 0x00, 0x00, 0x00, 0x02, 0x18,
            0x00, 0x00,
        ];
        let expected = Some(LinkTrb {
            ring_segment_pointer: 0x1122334455667780,
            toggle_cycle: true,
        });
        assert_eq!(LinkTrb::parse(trb_bytes), expected);
    }

    #[test]
    fn parse_enable_slot_command_trb() {
        let trb_bytes = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24,
            0x00, 0x00,
        ];
        let expected = CommandTrbVariant::EnableSlot;
        assert_eq!(CommandTrbVariant::parse(trb_bytes), expected);
    }

    #[test]
    fn parse_address_device_command_trb() {
        let trb_bytes = [
            0x80, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, 0x00, 0x00, 0x00, 0x02, 0x2e,
            0x00, 0x13,
        ];
        let expected = CommandTrbVariant::AddressDevice(AddressDeviceCommandTrbData {
            input_context_pointer: 0x1122334455667780,
            block_set_address_request: true,
            slot_id: 0x13,
        });
        assert_eq!(CommandTrbVariant::parse(trb_bytes), expected);
    }

    #[test]
    fn parse_configure_endpoint_command_trb() {
        let trb_bytes = [
            0x80, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, 0x00, 0x00, 0x00, 0x02, 0x32,
            0x00, 0x13,
        ];
        let expected = CommandTrbVariant::ConfigureEndpoint(ConfigureEndpointCommandTrbData {
            input_context_pointer: 0x1122334455667780,
            deconfigure: true,
            slot_id: 0x13,
        });
        assert_eq!(CommandTrbVariant::parse(trb_bytes), expected);
    }

    #[test]
    fn parse_stop_endpoint_command_trb() {
        let trb_bytes = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c,
            0x02, 0x10,
        ];
        let expected = CommandTrbVariant::StopEndpoint(StopEndpointCommandTrbData {
            endpoint_id: 0x02,
            slot_id: 0x10,
        });
        assert_eq!(CommandTrbVariant::parse(trb_bytes), expected);
    }

    #[test]
    fn parse_reset_endpoint_command_trb() {
        let trb_bytes = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38,
            0x02, 0x10,
        ];
        let expected = CommandTrbVariant::ResetEndpoint(ResetEndpointCommandTrbData {
            endpoint_id: 0x02,
            slot_id: 0x10,
        });
        assert_eq!(CommandTrbVariant::parse(trb_bytes), expected);
    }

    #[test]
    fn command_completion_event_trb() {
        let trb = EventTrb::new_command_completion_event_trb(
            0x1122334455667780,
            0xaabbcc,
            CompletionCode::Success,
            2,
        );
        assert_eq!(
            [
                0x80, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0xcc, 0xbb, 0xaa, 0x01, 0x01, 0x84,
                0x00, 0x02,
            ],
            trb.to_bytes(true),
        );
    }

    #[test]
    fn port_status_change_event_trb() {
        let trb = EventTrb::new_port_status_change_event_trb(2);
        assert_eq!(
            [
                0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x88,
                0x00, 0x00,
            ],
            trb.to_bytes(true),
        );
    }

    #[test]
    fn test_parse_normal_trb() {
        let trb_bytes = [
            0x11, 0x22, 0x44, 0x33, 0x66, 0x55, 0x88, 0x77, 0x12, 0x34, 0x00, 0x00, 0x30, 0x04,
            0x00, 0x00,
        ];
        let expected = TransferTrbVariant::Normal(NormalTrbData {
            data_pointer: 0x7788556633442211,
            transfer_length: 0x3412,
            chain: true,
            interrupt_on_completion: true,
            immediate_data: false,
        });
        assert_eq!(TransferTrbVariant::parse(trb_bytes), expected);
    }

    #[test]
    fn test_parse_setup_stage_trb() {
        let trb_bytes = [
            0x11, 0x22, 0x44, 0x33, 0x66, 0x55, 0x88, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08,
            0x00, 0x00,
        ];
        let expected = TransferTrbVariant::SetupStage(SetupStageTrbData {
            request_type: 0x11,
            request: 0x22,
            value: 0x3344,
            index: 0x5566,
            length: 0x7788,
            interrupt_on_completion: false,
        });
        assert_eq!(TransferTrbVariant::parse(trb_bytes), expected);
    }

    #[test]
    fn test_parse_data_stage_trb() {
        let trb_bytes = [
            0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x10, 0x00, 0x00, 0x00, 0x00, 0x0c,
            0x00, 0x00,
        ];
        let expected = TransferTrbVariant::DataStage(DataStageTrbData {
            data_pointer: 0x1122334455667788,
            transfer_length: 0x0010,
            chain: false,
            interrupt_on_completion: false,
            immediate_data: false,
            direction: false,
        });
        assert_eq!(TransferTrbVariant::parse(trb_bytes), expected);
    }

    #[test]
    fn test_parse_status_stage_trb() {
        let trb_bytes = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x10,
            0x01, 0x00,
        ];
        let expected = TransferTrbVariant::StatusStage(StatusStageTrbData {
            chain: true,
            interrupt_on_completion: true,
            direction: true,
        });
        assert_eq!(TransferTrbVariant::parse(trb_bytes), expected);
    }

    #[test]
    fn test_parse_event_data_trb() {
        let trb_bytes = [
            0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x10, 0x00, 0x00, 0x00, 0x30, 0x1c,
            0x00, 0x00,
        ];
        let expected = TransferTrbVariant::EventData(EventDataTrbData {
            event_data: 0x1122334455667788,
            chain: true,
            interrupt_on_completion: true,
        });
        assert_eq!(TransferTrbVariant::parse(trb_bytes), expected);
    }
}