forked from CodeConstruct/nvme-mi-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev.rs
More file actions
2213 lines (1988 loc) · 84.6 KB
/
dev.rs
File metadata and controls
2213 lines (1988 loc) · 84.6 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
// SPDX-License-Identifier: GPL-3.0-only
/*
* Copyright (c) 2025 Code Construct
*/
use deku::prelude::*;
use flagset::FlagSet;
use heapless::Vec;
use log::debug;
use mctp::{AsyncRespChannel, MsgIC};
use crate::{
CommandEffect, CommandEffectError, Controller, ControllerError, ControllerType, Discriminant,
MAX_CONTROLLERS, MAX_NAMESPACES, NamespaceId, NamespaceIdDisposition, SubsystemError,
nvme::{
AdminFormatNvmConfiguration, AdminGetLogPageLidRequestType,
AdminGetLogPageSupportedLogPagesResponse, AdminIdentifyActiveNamespaceIdListResponse,
AdminIdentifyAllocatedNamespaceIdListResponse, AdminIdentifyCnsRequestType,
AdminIdentifyControllerResponse,
AdminIdentifyNamespaceIdentificationDescriptorListResponse,
AdminIdentifyNvmIdentifyNamespaceResponse, AdminIoCqeGenericCommandStatus,
AdminIoCqeStatus, AdminIoCqeStatusType, AdminSanitizeConfiguration, ControllerListResponse,
LidSupportedAndEffectsDataStructure, LidSupportedAndEffectsFlags, LogPageAttributes,
NamespaceIdentifierType, SanitizeAction, SanitizeOperationStatus, SanitizeState,
SanitizeStateInformation, SanitizeStatus, SanitizeStatusLogPageResponse,
SmartHealthInformationLogPageResponse,
mi::{
AdminCommandRequestHeader, AdminCommandResponseHeader, AdminFormatNvmRequest,
AdminNamespaceAttachmentRequest, AdminNamespaceManagementRequest, AdminSanitizeRequest,
CompositeControllerStatusDataStructureResponse, CompositeControllerStatusFlagSet,
ControllerFunctionAndReportingFlags, ControllerHealthDataStructure,
ControllerHealthStatusPollResponse, ControllerInformationResponse,
ControllerPropertyFlags, MessageType, NvmSubsystemHealthDataStructureResponse,
NvmSubsystemInformationResponse, NvmeManagementResponse, NvmeMiCommandRequestHeader,
NvmeMiCommandRequestType, NvmeMiDataStructureManagementResponse,
NvmeMiDataStructureRequestType, PcieCommandRequestHeader, PciePortDataResponse,
PortInformationResponse, TwoWirePortDataResponse,
},
},
pcie::PciDeviceFunctionConfigurationSpace,
wire::{WireString, WireVec},
};
use crate::Encode;
use crate::RequestHandler;
use super::{
AdminCommandRequestType, AdminGetLogPageRequest, AdminIdentifyRequest,
GetHealthStatusChangeResponse, GetMctpTransmissionUnitSizeResponse,
GetSmbusI2cFrequencyResponse, MessageHeader, NvmeMiConfigurationGetRequest,
NvmeMiConfigurationIdentifierRequestType, NvmeMiConfigurationSetRequest,
NvmeMiDataStructureRequest, ResponseStatus,
};
const ISCSI: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISCSI);
const MAX_FRAGMENTS: usize = 6;
async fn send_response(resp: &mut impl AsyncRespChannel, bufs: &[&[u8]]) {
let mut digest = ISCSI.digest();
digest.update(&[0x80 | 0x04]);
for s in bufs {
digest.update(s);
}
let icv = digest.finalize().to_le_bytes();
let Ok(mut bufs) = Vec::<&[u8], MAX_FRAGMENTS>::from_slice(bufs) else {
debug!("Failed to gather buffers into vec");
return;
};
if bufs.push(icv.as_slice()).is_err() {
debug!("Failed to apply integrity check to response");
return;
}
if let Err(e) = resp.send_vectored(MsgIC(true), bufs.as_slice()).await {
debug!("Failed to send NVMe-MI response: {e:?}");
}
}
impl RequestHandler for MessageHeader {
type Ctx = Self;
async fn handle<A, C>(
&self,
ctx: &Self::Ctx,
mep: &mut crate::ManagementEndpoint,
subsys: &mut crate::Subsystem,
rest: &[u8],
resp: &mut C,
app: A,
) -> Result<(), ResponseStatus>
where
A: AsyncFnMut(CommandEffect) -> Result<(), CommandEffectError>,
C: AsyncRespChannel,
{
debug!("{self:x?}");
// TODO: Command and Feature Lockdown handling
// TODO: Handle subsystem reset, section 8.1, v2.0
let Ok(nmimt) = ctx.nmimt() else {
return Err(ResponseStatus::InvalidCommandOpcode);
};
match nmimt {
MessageType::NvmeMiCommand => {
match &NvmeMiCommandRequestHeader::from_bytes((rest, 0)) {
Ok(((rest, _), ch)) => ch.handle(ch, mep, subsys, rest, resp, app).await,
Err(err) => {
debug!("Unable to parse NVMeMICommandHeader from message buffer: {err:?}");
// TODO: This is a bad assumption: Can see DekuError::InvalidParam too
Err(ResponseStatus::InvalidCommandSize)
}
}
}
MessageType::NvmeAdminCommand => {
match &AdminCommandRequestHeader::from_bytes((rest, 0)) {
Ok(((rest, _), ch)) => ch.handle(ch, mep, subsys, rest, resp, app).await,
Err(err) => {
debug!("Unable to parse AdminCommandHeader from message buffer: {err:?}");
// TODO: This is a bad assumption: Can see DekuError::InvalidParam too
Err(ResponseStatus::InvalidCommandSize)
}
}
}
MessageType::PcieCommand => {
match &PcieCommandRequestHeader::from_bytes((rest, 0)) {
Ok(((rest, _), ch)) => ch.handle(ch, mep, subsys, rest, resp, app).await,
Err(err) => {
debug!(
"Unable to parse PcieCommandRequestHeader from message buffer: {err:?}"
);
// TODO: This is a bad assumption: Can see DekuError::InvalidParam too
Err(ResponseStatus::InvalidCommandSize)
}
}
}
_ => {
debug!("Unimplemented NMINT: {:?}", ctx.nmimt());
Err(ResponseStatus::InternalError)
}
}
}
}
impl RequestHandler for NvmeMiCommandRequestHeader {
type Ctx = Self;
async fn handle<A, C>(
&self,
ctx: &Self::Ctx,
mep: &mut crate::ManagementEndpoint,
subsys: &mut crate::Subsystem,
rest: &[u8],
resp: &mut C,
app: A,
) -> Result<(), ResponseStatus>
where
A: AsyncFnMut(CommandEffect) -> Result<(), CommandEffectError>,
C: AsyncRespChannel,
{
debug!("{self:x?}");
match &self.body {
NvmeMiCommandRequestType::ReadNvmeMiDataStructure(ds) => {
ds.handle(self, mep, subsys, rest, resp, app).await
}
NvmeMiCommandRequestType::NvmSubsystemHealthStatusPoll(shsp) => {
// 5.6, Figure 108, v2.0
if !rest.is_empty() {
debug!("Lost coherence decoding {:?}", ctx.opcode);
return Err(ResponseStatus::InvalidCommandSize);
}
let mh = MessageHeader::respond(MessageType::NvmeMiCommand).encode()?;
let mr = NvmeManagementResponse {
status: ResponseStatus::Success,
}
.encode()?;
// Implementation-specific strategy is to pick the first controller.
let ctlr = subsys
.ctlrs
.first()
.expect("Device needs at least one controller");
let Some(port) = subsys.ports.iter().find(|p| p.id == ctlr.port) else {
panic!(
"Inconsistent port association for controller {:?}: {:?}",
ctlr.id, ctlr.port
);
};
let crate::PortType::Pcie(pprt) = port.typ else {
panic!("Non-PCIe port associated with controller {:?}", ctlr.id);
};
// Derive ASCBT from spare vs capacity
if ctlr.spare > ctlr.capacity {
debug!(
"spare capacity {} exceeds drive capacity {}",
ctlr.spare, ctlr.capacity
);
return Err(ResponseStatus::InternalError);
}
// Derive TTC from operating range comparison
assert!(ctlr.temp_range.kind == crate::UnitKind::Kelvin);
// Derive CTEMP from controller temperature via conversions
// Clamp to Figure 108, NVMe MI v2.0 requirements
let clamped = ctlr
.temp
.clamp(ctlr.temp_range.lower, ctlr.temp_range.upper);
// Convert to celcius from kelvin
let celcius: i32 = clamped as i32 - 273;
// Convert to unsigned representation of two's-complement value
let ctemp = if celcius < 0 {
celcius + u8::MAX as i32 + 1
} else {
celcius
};
debug_assert!(ctemp <= u8::MAX.into());
// Derive PLDU from write age and expected lifespan
let pdlu = core::cmp::min(255, 100 * ctlr.write_age / ctlr.write_lifespan);
let nvmshds = NvmSubsystemHealthDataStructureResponse {
nss: (subsys.health.nss.atf as u8) << 7
| (subsys.health.nss.sfm as u8) << 6
| (subsys.health.nss.df as u8) << 5
| (subsys.health.nss.rnr as u8) << 4
| ((pprt.cls != crate::nvme::mi::PcieLinkSpeed::Inactive) as u8) << 3 // P0LA
| (false as u8) << 2, // P1LA
#[allow(clippy::nonminimal_bool)]
sw: (!false as u8) << 5 // PMRRO
| (!false as u8) << 4 // VMBF
| (!ctlr.ro as u8) << 3 // AMRO
| (!subsys.health.nss.rd as u8) << 2 // NDR
| (!(ctlr.temp_range.lower <= ctlr.temp && ctlr.temp <= ctlr.temp_range.upper) as u8) << 1 // TTC
| (!((100 * ctlr.spare / ctlr.capacity) < ctlr.spare_range.lower) as u8),
ctemp: ctemp as u8,
pldu: pdlu as u8,
}
.encode()?;
let ccs = CompositeControllerStatusDataStructureResponse {
ccsf: mep.ccsf.0.bits(),
}
.encode()?;
// CS: See Figure 106, NVMe MI v2.0
if (shsp.dword1 & (1u32 << 31)) != 0 {
mep.ccsf.0.clear();
}
send_response(resp, &[&mh.0, &mr.0, &nvmshds.0, &ccs.0]).await;
Ok(())
}
NvmeMiCommandRequestType::ControllerHealthStatusPoll(req) => {
// MI v2.0, 5.3
if !rest.is_empty() {
debug!("Lost coherence decoding {:?}", ctx.opcode);
return Err(ResponseStatus::InvalidCommandSize);
}
if !req
.functions
.0
.contains(ControllerFunctionAndReportingFlags::All)
{
debug!("TODO: Implement support for property-based selectors");
return Err(ResponseStatus::InternalError);
}
if req.functions.0.contains(
ControllerFunctionAndReportingFlags::Incf
| ControllerFunctionAndReportingFlags::Incpf
| ControllerFunctionAndReportingFlags::Incvf,
) {
debug!("TODO: Implement support for function-base selectors");
return Err(ResponseStatus::InternalError);
}
assert!(MAX_CONTROLLERS <= u8::MAX as usize);
if req.maxrent < MAX_CONTROLLERS as u8 {
debug!("TODO: Implement response entry constraint");
return Err(ResponseStatus::InternalError);
}
if req.sctlid > 0 {
debug!("TODO: Implement starting controller ID constraint");
return Err(ResponseStatus::InternalError);
}
let mh = MessageHeader::respond(MessageType::NvmeMiCommand).encode()?;
let mut chspr = ControllerHealthStatusPollResponse {
status: ResponseStatus::Success,
rent: 0,
body: WireVec::new(),
};
for ctlr in &subsys.ctlrs {
chspr
.body
.push(ControllerHealthDataStructure {
ctlid: ctlr.id.0,
csts: ctlr.csts.into(),
ctemp: ctlr.temp,
pdlu: core::cmp::min(255, 100 * ctlr.write_age / ctlr.write_lifespan)
as u8,
spare: <u8>::try_from(100 * ctlr.spare / ctlr.capacity)
.map_err(|_| ResponseStatus::InternalError)?
.clamp(0, 100),
cwarn: {
let mut fs = FlagSet::empty();
if ctlr.spare < ctlr.spare_range.lower {
fs |= crate::nvme::mi::CriticalWarningFlags::St;
}
if ctlr.temp < ctlr.temp_range.lower
|| ctlr.temp > ctlr.temp_range.upper
{
fs |= crate::nvme::mi::CriticalWarningFlags::Taut;
}
// TODO: RD
if ctlr.ro {
fs |= crate::nvme::mi::CriticalWarningFlags::Ro;
}
// TODO: VMBF
// TODO: PMRRO
fs.into()
},
chsc: {
let mecs = &mut mep.mecss[ctlr.id.0 as usize];
let fs = mecs.chscf;
if req.properties.0.contains(ControllerPropertyFlags::Ccf) {
mecs.chscf.clear();
// TODO: Clear NAC, FA, TCIDA in controller health
}
fs.into()
},
})
.map_err(|_| {
debug!("Failed to push ControllerHealthDataStructure");
ResponseStatus::InternalError
})?;
}
chspr.update()?;
let chspr = chspr.encode()?;
send_response(resp, &[&mh.0, &chspr.0[..chspr.1]]).await;
Ok(())
}
NvmeMiCommandRequestType::ConfigurationSet(cid) => {
cid.handle(ctx, mep, subsys, rest, resp, app).await
}
NvmeMiCommandRequestType::ConfigurationGet(cid) => {
cid.handle(ctx, mep, subsys, rest, resp, app).await
}
_ => {
debug!("Unimplemented OPCODE: {:?}", ctx.opcode);
Err(ResponseStatus::InternalError)
}
}
}
}
impl RequestHandler for NvmeMiConfigurationSetRequest {
type Ctx = NvmeMiCommandRequestHeader;
async fn handle<A, C>(
&self,
_ctx: &Self::Ctx,
mep: &mut crate::ManagementEndpoint,
subsys: &mut crate::Subsystem,
rest: &[u8],
resp: &mut C,
mut app: A,
) -> Result<(), ResponseStatus>
where
A: AsyncFnMut(CommandEffect) -> Result<(), CommandEffectError>,
C: AsyncRespChannel,
{
match &self.body {
NvmeMiConfigurationIdentifierRequestType::Reserved => {
Err(ResponseStatus::InvalidParameter)
}
NvmeMiConfigurationIdentifierRequestType::SmbusI2cFrequency(sifr) => {
if !rest.is_empty() {
debug!("Lost synchronisation when decoding ConfigurationSet SmbusI2cFrequency");
return Err(ResponseStatus::InvalidCommandSize);
}
let Some(port) = subsys.ports.get_mut(sifr.dw0_portid as usize) else {
debug!("Unrecognised port ID: {}", sifr.dw0_portid);
return Err(ResponseStatus::InvalidParameter);
};
let crate::PortType::TwoWire(twprt) = &mut port.typ else {
debug!("Port {} is not a TwoWire port: {:?}", sifr.dw0_portid, port);
return Err(ResponseStatus::InvalidParameter);
};
if sifr.dw0_sfreq > twprt.msmbfreq {
debug!("Unsupported SMBus frequency: {:?}", sifr.dw0_sfreq);
return Err(ResponseStatus::InvalidParameter);
}
app(CommandEffect::SetSmbusFreq {
port_id: port.id,
freq: sifr.dw0_sfreq,
})
.await?;
twprt.smbfreq = sifr.dw0_sfreq;
let mh = MessageHeader::respond(MessageType::NvmeMiCommand).encode()?;
// Success
let status = [0u8; 4];
send_response(resp, &[&mh.0, &status]).await;
Ok(())
}
NvmeMiConfigurationIdentifierRequestType::HealthStatusChange(hscr) => {
if !rest.is_empty() {
debug!(
"Lost synchronisation when decoding ConfigurationSet HealthStatusChange"
);
return Err(ResponseStatus::InvalidCommandSize);
}
let Ok(clear) = FlagSet::<super::HealthStatusChangeFlags>::new(hscr.dw1) else {
debug!(
"Invalid composite controller status flags in request: {}",
hscr.dw1
);
return Err(ResponseStatus::InvalidParameter);
};
let clear: super::CompositeControllerStatusFlagSet = clear.into();
mep.ccsf.0 -= clear.0;
let mh = MessageHeader::respond(MessageType::NvmeMiCommand).encode()?;
// Success
let status = [0u8; 4];
send_response(resp, &[&mh.0, &status]).await;
Ok(())
}
NvmeMiConfigurationIdentifierRequestType::MctpTransmissionUnitSize(mtusr) => {
if !rest.is_empty() {
debug!(
"Lost synchronisation when decoding ConfigurationSet MCTPTransmissionUnitSize"
);
return Err(ResponseStatus::InvalidCommandSize);
}
let Some(port) = subsys.ports.get_mut(mtusr.dw0_portid as usize) else {
debug!("Unrecognised port ID: {}", mtusr.dw0_portid);
return Err(ResponseStatus::InvalidParameter);
};
app(CommandEffect::SetMtu {
port_id: port.id,
mtus: mtusr.dw1_mtus as usize,
})
.await?;
port.mtus = mtusr.dw1_mtus;
let mh = MessageHeader::respond(MessageType::NvmeMiCommand).encode()?;
let status = [0u8; 4];
send_response(resp, &[&mh.0, &status]).await;
Ok(())
}
NvmeMiConfigurationIdentifierRequestType::AsynchronousEvent => todo!(),
}
}
}
impl RequestHandler for NvmeMiConfigurationGetRequest {
type Ctx = NvmeMiCommandRequestHeader;
async fn handle<A, C>(
&self,
_ctx: &Self::Ctx,
_mep: &mut crate::ManagementEndpoint,
subsys: &mut crate::Subsystem,
rest: &[u8],
resp: &mut C,
_app: A,
) -> Result<(), ResponseStatus>
where
A: AsyncFnMut(CommandEffect) -> Result<(), CommandEffectError>,
C: AsyncRespChannel,
{
match &self.body {
NvmeMiConfigurationIdentifierRequestType::Reserved => {
Err(ResponseStatus::InvalidParameter)
}
NvmeMiConfigurationIdentifierRequestType::SmbusI2cFrequency(sifr) => {
if !rest.is_empty() {
debug!("Lost synchronisation when decoding ConfigurationGet SMBusI2CFrequency");
return Err(ResponseStatus::InvalidCommandSize);
}
let Some(port) = subsys.ports.get(sifr.dw0_portid as usize) else {
debug!("Unrecognised port ID: {}", sifr.dw0_portid);
return Err(ResponseStatus::InvalidParameter);
};
let crate::PortType::TwoWire(twprt) = port.typ else {
debug!("Port {} is not a TwoWire port: {:?}", sifr.dw0_portid, port);
return Err(ResponseStatus::InvalidParameter);
};
let mh = MessageHeader::respond(MessageType::NvmeMiCommand).encode()?;
let fr = GetSmbusI2cFrequencyResponse {
status: ResponseStatus::Success,
mr_sfreq: twprt.smbfreq,
}
.encode()?;
send_response(resp, &[&mh.0, &fr.0]).await;
Ok(())
}
NvmeMiConfigurationIdentifierRequestType::HealthStatusChange(_) => {
// MI v2.0, 5.1.2
if !rest.is_empty() {
debug!(
"Lost synchronisation when decoding ConfigurationGet HealthStatusChange"
);
return Err(ResponseStatus::InvalidCommandSize);
}
let mh = MessageHeader::respond(MessageType::NvmeMiCommand).encode()?;
let hscr = GetHealthStatusChangeResponse {
status: ResponseStatus::Success,
}
.encode()?;
send_response(resp, &[&mh.0, &hscr.0]).await;
Ok(())
}
NvmeMiConfigurationIdentifierRequestType::MctpTransmissionUnitSize(mtusr) => {
if !rest.is_empty() {
debug!(
"Lost synchronisation when decoding ConfigurationGet MCTPTransmissionUnitSize"
);
return Err(ResponseStatus::InvalidCommandSize);
}
let Some(port) = subsys.ports.get(mtusr.dw0_portid as usize) else {
debug!("Unrecognised port ID: {}", mtusr.dw0_portid);
return Err(ResponseStatus::InvalidParameter);
};
let mh = MessageHeader::respond(MessageType::NvmeMiCommand).encode()?;
let fr = GetMctpTransmissionUnitSizeResponse {
status: ResponseStatus::Success,
mr_mtus: port.mtus,
}
.encode()?;
send_response(resp, &[&mh.0, &fr.0]).await;
Ok(())
}
NvmeMiConfigurationIdentifierRequestType::AsynchronousEvent => todo!(),
}
}
}
impl RequestHandler for NvmeMiDataStructureRequest {
type Ctx = NvmeMiCommandRequestHeader;
async fn handle<A, C>(
&self,
_ctx: &Self::Ctx,
_mep: &mut crate::ManagementEndpoint,
subsys: &mut crate::Subsystem,
rest: &[u8],
resp: &mut C,
_app: A,
) -> Result<(), ResponseStatus>
where
A: AsyncFnMut(CommandEffect) -> Result<(), CommandEffectError>,
C: AsyncRespChannel,
{
if !rest.is_empty() {
debug!("Lost coherence decoding NVMe-MI message");
return Err(ResponseStatus::InvalidCommandInputDataSize);
}
let mh = MessageHeader::respond(MessageType::NvmeMiCommand).encode()?;
match self.body {
NvmeMiDataStructureRequestType::NvmSubsystemInformation => {
assert!(!subsys.ports.is_empty(), "Need at least one port defined");
// See 5.7.1, 5.1.1 of v2.0
assert!(
subsys.ports.len() < u8::MAX as usize,
"Too many ports defined: {}",
subsys.ports.len()
);
// See 5.7.1 of v2.0
let nvmsi = NvmSubsystemInformationResponse {
nump: subsys.ports.len() as u8 - 1,
mjr: subsys.mi.mjr,
mnr: subsys.mi.mnr,
nnsc: subsys.caps.sre.into(),
}
.encode()?;
debug_assert!(nvmsi.0.len() <= u16::MAX as usize);
let dsmr = NvmeMiDataStructureManagementResponse {
status: ResponseStatus::Success,
rdl: nvmsi.0.len() as u16,
}
.encode()?;
send_response(resp, &[&mh.0, &dsmr.0, &nvmsi.0]).await;
Ok(())
}
NvmeMiDataStructureRequestType::PortInformation => {
let Some(port) = subsys.ports.iter().find(|p| p.id.0 == self.portid) else {
// TODO: Propagate PEL
return Err(ResponseStatus::InvalidParameter);
};
let pi = PortInformationResponse {
// FIXME: Change prttyp to crate::nvme::mi::PortType
prttyp: Into::<crate::nvme::mi::PortType>::into(&port.typ).id(),
prtcap: (port.caps.aems as u8) << 1 | (port.caps.ciaps as u8),
mmtus: port.mmtus,
mebs: port.mebs,
}
.encode()?;
match port.typ {
crate::PortType::Pcie(pprt) => {
let ppd = PciePortDataResponse {
pciemps: pprt.mps.into(),
pcieslsv: 0x3fu8,
pciecls: pprt.cls.into(),
pciemlw: pprt.mlw.into(),
pcienlw: pprt.nlw.into(),
pciepn: port.id.0,
}
.encode()?;
debug_assert!(pi.0.len() + ppd.0.len() <= u16::MAX as usize);
let dsmr = NvmeMiDataStructureManagementResponse {
status: ResponseStatus::Success,
rdl: (pi.0.len() + ppd.0.len()) as u16,
}
.encode()?;
send_response(resp, &[&mh.0, &dsmr.0, &pi.0, &ppd.0]).await;
Ok(())
}
crate::PortType::TwoWire(twprt) => {
let twpd = TwoWirePortDataResponse {
cvpdaddr: twprt.cvpdaddr,
mvpdfreq: twprt.mvpdfreq.id(),
cmeaddr: twprt.cmeaddr,
twprt: (twprt.i3csprt as u8) << 7 | twprt.msmbfreq.id() & 3,
nvmebm: twprt.nvmebms.into(),
}
.encode()?;
debug_assert!((pi.0.len() + twpd.0.len()) <= u16::MAX as usize);
let dsmr = NvmeMiDataStructureManagementResponse {
status: ResponseStatus::Success,
rdl: (pi.0.len() + twpd.0.len()) as u16,
}
.encode()?;
send_response(resp, &[&mh.0, &dsmr.0, &pi.0, &twpd.0]).await;
Ok(())
}
_ => {
debug!("Unimplemented port type: {:?}", port.typ);
Err(ResponseStatus::InternalError)
}
}
}
NvmeMiDataStructureRequestType::ControllerList => {
assert!(
subsys.ctlrs.len() <= 2047,
"Invalid number of controllers in drive model: {}",
subsys.ctlrs.len()
);
let mut cl = ControllerListResponse::new();
for ctlr in subsys
.ctlrs
.iter()
// Section 5.7.3, NVMe MI v2.0
.filter(|c| c.id.0 >= self.ctrlid)
{
if let Err(id) = cl.ids.push(ctlr.id.0) {
debug!("Failed to push controller ID {id}");
return Err(ResponseStatus::InternalError);
};
}
// NVMeSubsystemInformation and PortInformation are defined to
// be a minimum of 32 bytes in v2.0 of the NVMe specification.
// ControllerList in the NVMe MI v2.0 specification defers to
// Figure 137 in v2.1 of the NVMe base specification, which
// says "Unused entries are zero-filled". The motivation
// for padding out to 32 bytes for NVMeSubsystemInformation
// and PortInformation messages is unclear wrt whether
// ControllerList should be similarly padded or dynamically
// sized, given it can extend to 4096 bytes.
//
// Assume it's always dynamically sized appropriate for the
// requested controllers for now. mi-mctp seems okay with this.
//
// Note that for zero or even numbers of controllers in the
// response the MIC falls out of natural alignment.
cl.update()?;
let cl = cl.encode()?;
let rdl = cl.1 as u16;
let dsmr = NvmeMiDataStructureManagementResponse {
status: ResponseStatus::Success,
rdl,
}
.encode()?;
send_response(resp, &[&mh.0, &dsmr.0, &cl.0[..cl.1]]).await;
Ok(())
}
NvmeMiDataStructureRequestType::ControllerInformation => {
let Some(ctlr) = subsys.ctlrs.iter().find(|c| c.id.0 == self.ctrlid) else {
debug!("Unknown controller ID: {:?}", self.ctrlid);
return Err(ResponseStatus::InvalidParameter);
};
let Some(port) = subsys.ports.iter().find(|p| p.id == ctlr.port) else {
panic!(
"Inconsistent port association for controller {:?}: {:?}",
ctlr.id, ctlr.port
);
};
let crate::PortType::Pcie(pprt) = port.typ else {
panic!("Non-PCIe port associated with controller {:?}", ctlr.id);
};
let ci = ControllerInformationResponse {
portid: ctlr.port.0,
prii: 1,
pri: pprt.b << 8 | pprt.d << 4 | pprt.f,
pcivid: subsys.info.pci_vid,
pcidid: subsys.info.pci_did,
pcisvid: subsys.info.pci_svid,
pcisdid: subsys.info.pci_sdid,
pciesn: pprt.seg,
}
.encode()?;
debug_assert!(ci.0.len() < u16::MAX as usize);
let dsmr = NvmeMiDataStructureManagementResponse {
status: ResponseStatus::Success,
rdl: ci.0.len() as u16,
}
.encode()?;
send_response(resp, &[&mh.0, &dsmr.0, &ci.0]).await;
Ok(())
}
_ => {
debug!("Unimplemented DTYP: {:?}", self.dtyp);
Err(ResponseStatus::InternalError)
}
}
}
}
impl RequestHandler for AdminCommandRequestHeader {
type Ctx = Self;
async fn handle<A, C>(
&self,
ctx: &Self::Ctx,
mep: &mut crate::ManagementEndpoint,
subsys: &mut crate::Subsystem,
rest: &[u8],
resp: &mut C,
app: A,
) -> Result<(), ResponseStatus>
where
A: AsyncFnMut(CommandEffect) -> Result<(), CommandEffectError>,
C: AsyncRespChannel,
{
debug!("{self:x?}");
// ISH
if ctx.cflgs & 4 != 0 {
debug!("Support ignore shutdown state");
return Err(ResponseStatus::InternalError);
}
match &self.op {
AdminCommandRequestType::GetLogPage(req) => {
req.handle(ctx, mep, subsys, rest, resp, app).await
}
AdminCommandRequestType::Identify(req) => {
req.handle(ctx, mep, subsys, rest, resp, app).await
}
AdminCommandRequestType::NamespaceAttachement(req) => {
req.handle(ctx, mep, subsys, rest, resp, app).await
}
AdminCommandRequestType::NamespaceManagement(req) => {
req.handle(ctx, mep, subsys, rest, resp, app).await
}
AdminCommandRequestType::FormatNvm(req) => {
req.handle(ctx, mep, subsys, rest, resp, app).await
}
AdminCommandRequestType::Sanitize(req) => {
req.handle(ctx, mep, subsys, rest, resp, app).await
}
AdminCommandRequestType::DeleteIoSubmissionQueue
| AdminCommandRequestType::CreateIoSubmissionQueue
| AdminCommandRequestType::DeleteIoCompletionQueue
| AdminCommandRequestType::CreateIoCompletionQueue
| AdminCommandRequestType::Abort
| AdminCommandRequestType::AsynchronousEventRequest
| AdminCommandRequestType::KeepAlive
| AdminCommandRequestType::DirectiveSend
| AdminCommandRequestType::DirectiveReceive
| AdminCommandRequestType::NvmeMiSend
| AdminCommandRequestType::NvmeMiReceive
| AdminCommandRequestType::DiscoveryInformationManagement
| AdminCommandRequestType::FabricZoningReceive
| AdminCommandRequestType::FabricZoningLookup
| AdminCommandRequestType::FabricZoningSend
| AdminCommandRequestType::SendDiscoveryLogPage
| AdminCommandRequestType::TrackSend
| AdminCommandRequestType::TrackReceive
| AdminCommandRequestType::MigrationSend
| AdminCommandRequestType::MigrationReceive
| AdminCommandRequestType::ControllerDataQueue
| AdminCommandRequestType::DoorbellBufferConfig
| AdminCommandRequestType::FabricsCommands
| AdminCommandRequestType::LoadProgram
| AdminCommandRequestType::ProgramActivationManagement
| AdminCommandRequestType::MemoryRangeSetManagement => {
debug!("Prohibited MI admin command opcode: {:?}", self.op.id());
Err(ResponseStatus::InvalidCommandOpcode)
}
_ => {
debug!("Unimplemented OPCODE: {:?}", self.op.id());
Err(ResponseStatus::InternalError)
}
}
}
}
fn admin_constrain_body(dofst: u32, dlen: u32, body: &[u8]) -> Result<&[u8], ResponseStatus> {
// See Figure 136 in NVMe MI v2.0
// Use send_response() instead
assert!(!body.is_empty());
// TODO: propagate PEL for all errors
if dofst & 3 != 0 {
debug!("Unnatural DOFST value: {dofst:?}");
return Err(ResponseStatus::InvalidParameter);
}
// FIXME: casts
let dofst = dofst as usize;
let dlen = dlen as usize;
if dofst >= body.len() {
debug!("DOFST value exceeds unconstrained response length: {dofst:?}");
return Err(ResponseStatus::InvalidParameter);
}
if dlen & 3 != 0 {
debug!("Unnatural DLEN value: {dlen:?}");
return Err(ResponseStatus::InvalidParameter);
}
if dlen > 4096 {
debug!("DLEN too large: {dlen:?}");
return Err(ResponseStatus::InvalidParameter);
}
if dlen > body.len() || body.len() - dlen < dofst {
debug!(
"Requested response data range beginning at {:?} for {:?} bytes exceeds bounds of unconstrained response length {:?}",
dofst,
dlen,
body.len()
);
return Err(ResponseStatus::InvalidParameter);
}
if dlen == 0 {
debug!("DLEN cleared for command with data response: {dlen:?}");
return Err(ResponseStatus::InvalidParameter);
}
let end = dofst + dlen;
Ok(&body[dofst..end])
}
async fn admin_send_response_body<C>(resp: &mut C, body: &[u8]) -> Result<(), ResponseStatus>
where
C: AsyncRespChannel,
{
let mh = MessageHeader::respond(MessageType::NvmeAdminCommand).encode()?;
let acrh = AdminCommandResponseHeader {
status: ResponseStatus::Success,
cqedw0: 0,
cqedw1: 0,
cqedw3: AdminIoCqeStatus {
cid: 0,
p: true,
status: AdminIoCqeStatusType::GenericCommandStatus(
AdminIoCqeGenericCommandStatus::SuccessfulCompletion,
),
crd: crate::nvme::CommandRetryDelay::None,
m: false,
dnr: false,
}
.into(),
}
.encode()?;
send_response(resp, &[&mh.0, &acrh.0, body]).await;
Ok(())
}
async fn admin_send_status<C>(
resp: &mut C,
status: AdminIoCqeStatusType,
) -> Result<(), ResponseStatus>
where
C: AsyncRespChannel,
{
let mh = MessageHeader::respond(MessageType::NvmeAdminCommand).encode()?;
let acrh = AdminCommandResponseHeader {
status: ResponseStatus::Success,
cqedw0: 0,
cqedw1: 0,
cqedw3: AdminIoCqeStatus {
cid: 0,
p: true,
status,
crd: crate::nvme::CommandRetryDelay::None,
m: false,
dnr: true,
}
.into(),
}
.encode()?;
send_response(resp, &[&mh.0, &acrh.0]).await;
Ok(())
}
impl RequestHandler for AdminGetLogPageRequest {
type Ctx = AdminCommandRequestHeader;
async fn handle<A, C>(
&self,
ctx: &Self::Ctx,
_mep: &mut crate::ManagementEndpoint,
subsys: &mut crate::Subsystem,
rest: &[u8],
resp: &mut C,
_app: A,
) -> Result<(), ResponseStatus>
where
A: AsyncFnMut(CommandEffect) -> Result<(), CommandEffectError>,
C: AsyncRespChannel,
{
if !rest.is_empty() {
debug!("Invalid request size for Admin Get Log Page");
return Err(ResponseStatus::InvalidCommandSize);