-
Notifications
You must be signed in to change notification settings - Fork 86
/
pci.rs
1397 lines (1242 loc) · 43.3 KB
/
pci.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
// Copyright (c) 2020 Thomas Lambertz, RWTH Aachen University
// 2020 Frederik Schulz, RWTH Aachen Univerity
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! A module containing all virtio specific pci functionality
//!
//! The module contains ...
#![allow(dead_code)]
use crate::arch::kernel::pci as kernel_pci;
use crate::arch::kernel::pci::error::PciError;
use crate::arch::kernel::pci::{PciAdapter, PciDriver};
use crate::arch::mm::PhysAddr;
use crate::synch::spinlock::SpinlockIrqSave;
use alloc::vec::Vec;
use core::convert::TryInto;
use core::mem;
use core::result::Result;
use crate::drivers::error::DriverError;
use crate::drivers::net::virtio_net::VirtioNetDriver;
use crate::drivers::virtio::device;
use crate::drivers::virtio::env;
use crate::drivers::virtio::env::memory::{MemLen, MemOff, VirtMemAddr};
use crate::drivers::virtio::error::VirtioError;
use crate::arch::x86_64::kernel::irq::*;
use crate::drivers::net::network_irqhandler;
use crate::drivers::virtio::depr::virtio_fs;
/// Virtio device ID's
/// See Virtio specification v1.1. - 5
/// and v1.1. - 4.1.2.1
///
// WARN: Upon changes in the set of the enum variants
// one MUST adjust the associated From<u16>
// implementation, in order catch all cases correctly,
// as this function uses the catch-all "_" case!
#[allow(dead_code, non_camel_case_types)]
#[repr(u16)]
pub enum DevId {
INVALID = 0x0,
VIRTIO_TRANS_DEV_ID_NET = 0x1000,
VIRTIO_TRANS_DEV_ID_BLK = 0x1001,
VIRTIO_TRANS_DEV_ID_MEM_BALL = 0x1002,
VIRTIO_TRANS_DEV_ID_CONS = 0x1003,
VIRTIO_TRANS_DEV_ID_SCSI = 0x1004,
VIRTIO_TRANS_DEV_ID_ENTROPY = 0x1005,
VIRTIO_TRANS_DEV_ID_9P = 0x1009,
VIRTIO_DEV_ID_NET = 0x1041,
VIRTIO_DEV_ID_FS = 0x105A,
}
impl From<DevId> for u16 {
fn from(val: DevId) -> u16 {
match val {
DevId::VIRTIO_TRANS_DEV_ID_NET => 0x1000,
DevId::VIRTIO_TRANS_DEV_ID_BLK => 0x1001,
DevId::VIRTIO_TRANS_DEV_ID_MEM_BALL => 0x1002,
DevId::VIRTIO_TRANS_DEV_ID_CONS => 0x1003,
DevId::VIRTIO_TRANS_DEV_ID_SCSI => 0x1004,
DevId::VIRTIO_TRANS_DEV_ID_ENTROPY => 0x1005,
DevId::VIRTIO_TRANS_DEV_ID_9P => 0x1009,
DevId::VIRTIO_DEV_ID_NET => 0x1041,
DevId::VIRTIO_DEV_ID_FS => 0x105A,
DevId::INVALID => 0x0,
}
}
}
impl From<u16> for DevId {
fn from(val: u16) -> Self {
match val {
0x1000 => DevId::VIRTIO_TRANS_DEV_ID_NET,
0x1001 => DevId::VIRTIO_TRANS_DEV_ID_BLK,
0x1002 => DevId::VIRTIO_TRANS_DEV_ID_MEM_BALL,
0x1003 => DevId::VIRTIO_TRANS_DEV_ID_CONS,
0x1004 => DevId::VIRTIO_TRANS_DEV_ID_SCSI,
0x1005 => DevId::VIRTIO_TRANS_DEV_ID_ENTROPY,
0x1009 => DevId::VIRTIO_TRANS_DEV_ID_9P,
0x1041 => DevId::VIRTIO_DEV_ID_NET,
0x105A => DevId::VIRTIO_DEV_ID_FS,
_ => DevId::INVALID,
}
}
}
/// Virtio's cfg_type constants; indicating type of structure in capabilities list
/// See Virtio specification v1.1 - 4.1.4
//
// WARN: Upon changes in the set of the enum variants
// one MUST adjust the associated From<u8>
// implementation, in order catch all cases correctly,
// as this function uses the catch-all "_" case!
#[allow(dead_code, non_camel_case_types)]
#[derive(Copy, Clone, PartialEq)]
#[repr(u8)]
pub enum CfgType {
INVALID = 0,
VIRTIO_PCI_CAP_COMMON_CFG = 1,
VIRTIO_PCI_CAP_NOTIFY_CFG = 2,
VIRTIO_PCI_CAP_ISR_CFG = 3,
VIRTIO_PCI_CAP_DEVICE_CFG = 4,
VIRTIO_PCI_CAP_PCI_CFG = 5,
VIRTIO_PCI_CAP_SHARED_MEMORY_CFG = 8,
}
impl From<CfgType> for u8 {
fn from(val: CfgType) -> u8 {
match val {
CfgType::INVALID => 0,
CfgType::VIRTIO_PCI_CAP_COMMON_CFG => 1,
CfgType::VIRTIO_PCI_CAP_NOTIFY_CFG => 2,
CfgType::VIRTIO_PCI_CAP_ISR_CFG => 3,
CfgType::VIRTIO_PCI_CAP_DEVICE_CFG => 4,
CfgType::VIRTIO_PCI_CAP_PCI_CFG => 5,
CfgType::VIRTIO_PCI_CAP_SHARED_MEMORY_CFG => 8,
}
}
}
impl From<u8> for CfgType {
fn from(val: u8) -> Self {
match val {
1 => CfgType::VIRTIO_PCI_CAP_COMMON_CFG,
2 => CfgType::VIRTIO_PCI_CAP_NOTIFY_CFG,
3 => CfgType::VIRTIO_PCI_CAP_ISR_CFG,
4 => CfgType::VIRTIO_PCI_CAP_DEVICE_CFG,
5 => CfgType::VIRTIO_PCI_CAP_PCI_CFG,
8 => CfgType::VIRTIO_PCI_CAP_SHARED_MEMORY_CFG,
_ => CfgType::INVALID,
}
}
}
/// Public structure to allow drivers to read the configuration space
/// savely
#[derive(Clone)]
pub struct Origin {
cfg_ptr: u32, // Register to be read to reach configuration structure of type cfg_type
dev: u8, // PCI device this configuration comes from
bus: u8, // Bus of the PCI device
dev_id: u16,
cap_struct: PciCapRaw,
}
/// Maps a given device specific pci configuration structure and
/// returns a static reference to it.
pub fn map_dev_cfg<T>(cap: &PciCap) -> Option<&'static mut T> {
if cap.cfg_type != CfgType::VIRTIO_PCI_CAP_DEVICE_CFG {
error!("Capability of device config has wrong id. Mapping not possible...");
return None;
};
if cap.bar_len() < u64::from(cap.len() + cap.offset()) {
error!(
"Device config of device {:x}, does not fit into memeory specified by bar!",
cap.dev_id(),
);
return None;
}
// Drivers MAY do this check. See Virtio specification v1.1. - 4.1.4.1
if cap.len() < MemLen::from(mem::size_of::<T>()) {
error!("Device specific config from device {:x}, does not represent actual structure specified by the standard!", cap.dev_id());
return None;
}
let virt_addr_raw: VirtMemAddr = cap.bar_addr() + cap.offset();
// Create mutable reference to the PCI structure in PCI memory
let dev_cfg: &'static mut T = unsafe { &mut *(usize::from(virt_addr_raw) as *mut T) };
Some(dev_cfg)
}
/// Virtio's PCI capabilites structure.
/// See Virtio specification v.1.1 - 4.1.4
///
/// Indicating: Where the capability field is mapped in memory and
/// Which id (sometimes also indicates priority for multiple
/// capabilites of same type) it holds.
///
/// This structure does NOT represent the structure in the standard,
/// as it is not directly mapped into address space from PCI device
/// configuration space.
/// Therefore the struct only contains necessary information to map
/// corresponding [CfgType](enums.CfgType.html) into address space.
#[derive(Clone)]
pub struct PciCap {
cfg_type: CfgType,
bar: PciBar,
id: u8,
offset: MemOff,
length: MemLen,
// Following field can be used to retrieve original structure
// from the config space. Needed by some structures and f
// device specific configs.
origin: Origin,
}
impl PciCap {
pub fn offset(&self) -> MemOff {
self.offset
}
pub fn len(&self) -> MemLen {
self.length
}
pub fn bar_len(&self) -> u64 {
self.bar.length
}
pub fn bar_addr(&self) -> VirtMemAddr {
self.bar.mem_addr
}
pub fn dev_id(&self) -> u16 {
self.origin.dev_id
}
}
/// Virtio's PCI capabilites structure.
/// See Virtio specification v.1.1 - 4.1.4
///
/// WARN: endianness of this structure should be seen as little endian.
/// As this structure is not meant to be used outside of this module and for
/// ease of conversion from reading data into struct from PCI configuration
/// space, no conversion is made for struct fields.
#[derive(Clone)]
#[repr(C)]
struct PciCapRaw {
cap_vndr: u8,
cap_next: u8,
cap_len: u8,
cfg_type: u8,
bar_index: u8,
id: u8,
padding: [u8; 2],
offset: u32,
length: u32,
}
// This only shows compiler, that structs are identical
// with themselves.
impl Eq for PciCapRaw {}
// In order to compare two PciCapRaw structs PartialEq is needed
impl PartialEq for PciCapRaw {
fn eq(&self, other: &Self) -> bool {
if self.cap_vndr == other.cap_vndr
&& self.cap_next == other.cap_next
&& self.cap_len == other.cap_len
&& self.cfg_type == other.cfg_type
&& self.bar_index == other.bar_index
&& self.id == other.id
&& self.offset == other.offset
&& self.length == other.length
{
true
} else {
false
}
}
}
/// Universal Caplist Collections holds all universal capability structures for
/// a given Virtio PCI device.
///
/// As Virtio's PCI devices are allowed to present multiple capability
/// structures of the same [CfgType](enums.cfgtype.html), the structure
/// provides a driver with all capabilites, sorted in descending priority,
/// allowing the driver to choose.
/// The structure contains a special dev_cfg_list field, a vector holding
/// [PciCap](structs.pcicap.html) objects, to allow the driver to map its
/// device specific configurations independently.
pub struct UniCapsColl {
com_cfg_list: Vec<ComCfg>,
notif_cfg_list: Vec<NotifCfg>,
isr_stat_list: Vec<IsrStatus>,
pci_cfg_acc_list: Vec<PciCfgAlt>,
sh_mem_cfg_list: Vec<ShMemCfg>,
dev_cfg_list: Vec<PciCap>,
}
impl UniCapsColl {
/// Returns an Caps with empty lists.
fn new() -> Self {
UniCapsColl {
com_cfg_list: Vec::new(),
notif_cfg_list: Vec::new(),
isr_stat_list: Vec::new(),
pci_cfg_acc_list: Vec::new(),
sh_mem_cfg_list: Vec::new(),
dev_cfg_list: Vec::new(),
}
}
fn add_cfg_common(&mut self, com: ComCfg) {
self.com_cfg_list.push(com);
// Resort array
//
// This should not be to expensive, as "rational" devices will hold an
// acceptibal amount of configuration structures.
self.com_cfg_list.sort_by(|a, b| b.rank.cmp(&a.rank));
}
fn add_cfg_notif(&mut self, notif: NotifCfg) {
self.notif_cfg_list.push(notif);
// Resort array
//
// This should not be to expensive, as "rational" devices will hold an
// acceptable amount of configuration structures.
self.notif_cfg_list.sort_by(|a, b| b.rank.cmp(&a.rank));
}
fn add_cfg_isr(&mut self, isr_stat: IsrStatus) {
self.isr_stat_list.push(isr_stat);
// Resort array
//
// This should not be to expensive, as "rational" devices will hold an
// acceptable amount of configuration structures.
self.isr_stat_list.sort_by(|a, b| b.rank.cmp(&a.rank));
}
fn add_cfg_alt(&mut self, pci_alt: PciCfgAlt) {
self.pci_cfg_acc_list.push(pci_alt);
// Resort array
//
// This should not be to expensive, as "rational" devices will hold an
// acceptable amount of configuration structures.
self.pci_cfg_acc_list
.sort_by(|a, b| b.pci_cap.id.cmp(&a.pci_cap.id));
}
fn add_cfg_sh_mem(&mut self, sh_mem: ShMemCfg) {
self.sh_mem_cfg_list.push(sh_mem);
// Resort array
//
// This should not be to expensive, as "rational" devices will hold an
// acceptable amount of configuration structures.
self.sh_mem_cfg_list.sort_by(|a, b| b.id.cmp(&a.id));
}
fn add_cfg_dev(&mut self, pci_cap: PciCap) {
self.dev_cfg_list.push(pci_cap);
// Resort array
//
// This should not be to expensive, as "rational" devices will hold an
// acceptable amount of configuration structures.
self.dev_cfg_list.sort_by(|a, b| b.id.cmp(&a.id));
}
}
// Public interface of UniCapsCollection
impl UniCapsColl {
/// Returns the highest prioritized PciCap that indiactes a
/// Virito device configuration.
///
/// INFO: This function removes the capability and returns ownership.
pub fn get_dev_cfg(&mut self) -> Option<PciCap> {
self.dev_cfg_list.pop()
}
/// Returns the highest prioritized common configuration structure.
///
/// INFO: This function removes the capability and returns ownership.
pub fn get_com_cfg(&mut self) -> Option<ComCfg> {
self.com_cfg_list.pop()
}
/// Returns the highest prioritized ISR status configuraiton structure.
///
/// INFO: This function removes the Capability and returns ownership.
pub fn get_isr_cfg(&mut self) -> Option<IsrStatus> {
self.isr_stat_list.pop()
}
/// Returns the highest prioritized notification structure.
///
/// INFO: This function removes the Capability and returns ownership.
pub fn get_notif_cfg(&mut self) -> Option<NotifCfg> {
self.notif_cfg_list.pop()
}
}
/// Wraps a [ComCfgRaw](structs.comcfgraw.html) in order to preserve
/// the original structure.
///
/// Provides a safe API for Raw structure and allows interaction with the device via
/// the structure.
pub struct ComCfg {
/// References the raw structure in PCI memory space. Is static as
/// long as the device is present, which is mandatory in order to let this code work.
com_cfg: &'static mut ComCfgRaw,
/// Preferences of the device for this config. From 1 (highest) to 2^7-1 (lowest)
rank: u8,
}
// Private interface of ComCfg
impl ComCfg {
fn new(raw: &'static mut ComCfgRaw, rank: u8) -> Self {
ComCfg { com_cfg: raw, rank }
}
}
pub struct VqCfgHandler<'a> {
vq_index: u16,
raw: &'a mut ComCfgRaw,
}
impl<'a> VqCfgHandler<'a> {
/// Sets the size of a given virtqueue. In case the provided size exceeds the maximum allowed
/// size, the size is set to this maximum instead. Else size is set to the provided value.
///
/// Returns the set size in form of a `u16`.
pub fn set_vq_size(&mut self, size: u16) -> u16 {
self.raw.queue_select = self.vq_index;
if self.raw.queue_size < size {
self.raw.queue_size
} else {
self.raw.queue_size = size;
self.raw.queue_size
}
}
pub fn set_ring_addr(&mut self, addr: PhysAddr) {
self.raw.queue_select = self.vq_index;
self.raw.queue_desc = addr.as_u64();
}
pub fn set_drv_ctrl_addr(&mut self, addr: PhysAddr) {
self.raw.queue_select = self.vq_index;
self.raw.queue_driver = addr.as_u64();
}
pub fn set_dev_ctrl_addr(&mut self, addr: PhysAddr) {
self.raw.queue_select = self.vq_index;
self.raw.queue_device = addr.as_u64();
}
pub fn notif_off(&mut self) -> u16 {
self.raw.queue_select = self.vq_index;
self.raw.queue_notify_off
}
pub fn enable_queue(&mut self) {
self.raw.queue_select = self.vq_index;
self.raw.queue_enable = 1;
}
}
// Public Interface of ComCfg
impl ComCfg {
/// Select a queue via an index. If queue does NOT exist returns `None`, else
/// returns `Some(VqCfgHandler)`.
///
/// INFO: The queue size is automatically bounded by constant `src::config:VIRTIO_MAX_QUEUE_SIZE`.
pub fn select_vq(&mut self, index: u16) -> Option<VqCfgHandler> {
self.com_cfg.queue_select = index;
if self.com_cfg.queue_size == 0 {
None
} else {
Some(VqCfgHandler {
vq_index: index,
raw: self.com_cfg,
})
}
}
/// Returns the device status field.
pub fn dev_status(&self) -> u8 {
self.com_cfg.device_status
}
/// Resets the device status field to zero.
pub fn reset_dev(&mut self) {
self.com_cfg.device_status = 0;
}
/// Sets the device status field to FAILED.
/// A driver MUST NOT initialize and use the device any further after this.
/// A driver MAY use the device again after a proper reset of the device.
pub fn set_failed(&mut self) {
self.com_cfg.device_status = u8::from(device::Status::FAILED);
}
/// Sets the ACKNOWLEDGE bit in the device status field. This indicates, the
/// OS has notived the device
pub fn ack_dev(&mut self) {
self.com_cfg.device_status |= u8::from(device::Status::ACKNOWLEDGE);
}
/// Sets the DRIVER bit in the device status field. This indicates, the OS
/// know how to run this device.
pub fn set_drv(&mut self) {
self.com_cfg.device_status |= u8::from(device::Status::DRIVER);
}
/// Sets the FEATURES_OK bit in the device status field.
///
/// Drivers MUST NOT accept new features after this step.
pub fn features_ok(&mut self) {
self.com_cfg.device_status |= u8::from(device::Status::FEATURES_OK);
}
/// In order to correctly check feature negotiaten, this function
/// MUST be called after [self.features_ok()](ComCfg::features_ok()) in order to check
/// if features have been accepted by the device after negotiation.
///
/// Re-reads device status to ensure the FEATURES_OK bit is still set:
/// otherwise, the device does not support our subset of features and the device is unusable.
pub fn check_features(&self) -> bool {
self.com_cfg.device_status & u8::from(device::Status::FEATURES_OK)
== u8::from(device::Status::FEATURES_OK)
}
/// Sets the DRIVER_OK bit in the device status field.
///
/// After this call, the device is "live"!
pub fn drv_ok(&mut self) {
self.com_cfg.device_status |= u8::from(device::Status::DRIVER_OK)
}
/// Returns the features offered by the device. Coded in a 64bit value.
pub fn dev_features(&mut self) -> u64 {
// Indicate device to show high 32 bits in device_feature field.
// See Virtio specification v1.1. - 4.1.4.3
self.com_cfg.device_feature_select = 1;
// read high 32 bits of device features
let mut dev_feat = u64::from(self.com_cfg.device_feature) << 32;
// Indicate device to show low 32 bits in device_feature field.
// See Virtio specification v1.1. - 4.1.4.3
self.com_cfg.device_feature_select = 0;
// read low 32 bits of device features
dev_feat |= u64::from(self.com_cfg.device_feature);
dev_feat
}
/// Write selected features into driver_select field.
pub fn set_drv_features(&mut self, feats: u64) {
let high: u32 = (feats >> 32) as u32;
let low: u32 = feats as u32;
// Indicate to device that driver_features field shows low 32 bits.
// See Virtio specification v1.1. - 4.1.4.3
self.com_cfg.driver_feature_select = 0;
// write low 32 bits of device features
self.com_cfg.driver_feature = low;
// Indicate to device that driver_features field shows high 32 bits.
// See Virtio specification v1.1. - 4.1.4.3
self.com_cfg.driver_feature_select = 1;
// write high 32 bits of device features
self.com_cfg.driver_feature = high;
}
}
/// Common configuration structure of Virtio PCI devices.
/// See Virtio specification v1.1 - 4.1.43
///
/// Fields read-write-rules in source code refer to driver rights.
#[repr(C)]
struct ComCfgRaw {
// About whole device
device_feature_select: u32, // read-write
device_feature: u32, // read-only for driver
driver_feature_select: u32, // read-write
driver_feature: u32, // read-write
config_msix_vector: u16, // read-write
num_queues: u16, // read-only for driver
device_status: u8, // read-write
config_generation: u8, // read-only for driver
// About a specific virtqueue
queue_select: u16, // read-write
queue_size: u16, // read-write
queue_msix_vector: u16, // read-write
queue_enable: u16, // read-write
queue_notify_off: u16, // read-only for driver. Offset of the notification area.
queue_desc: u64, // read-write
queue_driver: u64, // read-write
queue_device: u64, // read-write
}
// Common configuration raw does NOT provide a PUBLIC
// interface.
impl ComCfgRaw {
/// Returns a boxed [ComCfgRaw](ComCfgRaw) structure. The box points to the actual structure inside the
/// PCI devices memory space.
fn map(cap: &PciCap) -> Option<&'static mut ComCfgRaw> {
if cap.bar.length < u64::from(cap.length + cap.offset) {
error!("Common config of with id {} of device {:x}, does not fit into memeory specified by bar {:x}!",
cap.id,
cap.origin.dev_id,
cap.bar.index
);
return None;
}
// Using "as u32" is safe here as ComCfgRaw has a defined size smaller 2^31-1
// Drivers MAY do this check. See Virtio specification v1.1. - 4.1.4.1
if cap.length < MemLen::from(mem::size_of::<ComCfgRaw>() * 8) {
error!("Common config of with id {}, does not represent actual structure specified by the standard!", cap.id);
return None;
}
let virt_addr_raw = cap.bar.mem_addr + cap.offset;
// Create mutable reference to the PCI structure in PCI memory
let com_cfg_raw: &mut ComCfgRaw =
unsafe { &mut *(usize::from(virt_addr_raw) as *mut ComCfgRaw) };
Some(com_cfg_raw)
}
}
/// Notification Structure to handle virtqueue notification settings.
/// See Virtio specification v1.1 - 4.1.4.4
//
pub struct NotifCfg {
/// Start addr, from where the notification addresses for the virtqueues are computed
base_addr: VirtMemAddr,
notify_off_multiplier: u32,
/// Preferences of the device for this config. From 1 (highest) to 2^7-1 (lowest)
rank: u8,
/// defines the maximum size of the notification space, starting from base_addr.
length: MemLen,
}
impl NotifCfg {
fn new(cap: &PciCap) -> Option<Self> {
if cap.bar.length < u64::from(u32::from(cap.length + cap.offset)) {
error!("Notification config with id {} of device {:x}, does not fit into memeory specified by bar {:x}!",
cap.id,
cap.origin.dev_id,
cap.bar.index
);
return None;
}
// Assumes the cap_len is a multiple of 8
// This read MIGHT be slow, as it does NOT ensure 32 bit alignment.
let notify_off_multiplier = env::pci::read_cfg_no_adapter(
cap.origin.bus,
cap.origin.dev,
cap.origin.cfg_ptr + u32::from(cap.origin.cap_struct.cap_len),
);
// define base memory address from which the actuall Queue Notify address can be derived via
// base_addr + queue_notify_off * notify_off_multiplier.
//
// Where queue_notify_off is taken from the respective common configuration struct.
// See Virtio specification v1.1. - 4.1.4.4
//
// Base address here already includes offset!
let base_addr = VirtMemAddr::from(cap.bar.mem_addr + cap.offset);
Some(NotifCfg {
base_addr: base_addr,
notify_off_multiplier,
rank: cap.id,
length: cap.length,
})
}
/// Returns base address of notification area as an usize
pub fn base(&self) -> usize {
usize::from(self.base_addr)
}
/// Returns the multiplier, needed in order to calculate the
/// notification address for a specific queue.
pub fn multiplier(&self) -> u32 {
self.notify_off_multiplier
}
}
/// Control structure, allowing to notify a device via PCI bus.
/// Typcially hold by a virtqueue.
pub struct NotifCtrl {
/// Indicates if VIRTIO_F_NOTIFICATION_DATA has been negotiated
f_notif_data: bool,
/// Where to write notification
notif_addr: *mut usize,
}
impl NotifCtrl {
/// Retunrs a new controller. By default MSI-X capabilities and VIRTIO_F_NOTIFICATION_DATA
/// are disabled.
pub fn new(notif_addr: *mut usize) -> Self {
NotifCtrl {
f_notif_data: false,
notif_addr,
}
}
/// Enables VIRTIO_F_NOTIFICATION_DATA. This changes which data is provided to the device. ONLY a good idea if Feature has been negotiated.
pub fn enable_notif_data(&mut self) {
self.f_notif_data = true;
}
pub fn notify_dev(&self, notif_data: &[u8]) {
// See Virtio specification v.1.1. - 4.1.5.2
// Depending in the feature negotiation, we write eitehr only the
// virtqueue index or the index and the next position inside the queue.
if self.f_notif_data {
unsafe {
let notif_area = core::slice::from_raw_parts_mut(self.notif_addr as *mut u8, 4);
let mut notif_data = notif_data.into_iter();
for byte in notif_area {
*byte = *notif_data.next().unwrap();
}
}
} else {
unsafe {
let notif_area = core::slice::from_raw_parts_mut(self.notif_addr as *mut u8, 2);
let mut notif_data = notif_data.into_iter();
for byte in notif_area {
*byte = *notif_data.next().unwrap();
}
}
}
}
}
/// Wraps a [IsrStatusRaw](structs.isrstatusraw.html) in order to preserve
/// the original structure and allow interaction with the device via
/// the structure.
///
/// Provides a safe API for Raw structure and allows interaction with the device via
/// the structure.
pub struct IsrStatus {
/// References the raw structure in PCI memory space. Is static as
/// long as the device is present, which is mandatory in order to let this code work.
isr_stat: &'static mut IsrStatusRaw,
/// Preferences of the device for this config. From 1 (highest) to 2^7-1 (lowest)
rank: u8,
}
impl IsrStatus {
fn new(raw: &'static mut IsrStatusRaw, rank: u8) -> Self {
IsrStatus {
isr_stat: raw,
rank,
}
}
pub fn is_interrupt(&self) -> bool {
self.isr_stat.flags & 1 << 0 == 1
}
pub fn is_cfg_change(&self) -> bool {
self.isr_stat.flags & 1 << 1 == 1 << 1
}
}
/// ISR status structure of Virtio PCI devices.
/// See Virtio specification v1.1. - 4.1.4.5
///
/// Contains a single byte, containing the interrupt numnbers used
/// for handling interrupts.
/// The 8-bit field is read as an bitmap and allows to distinguish between
/// interrupts triggered by changes in the configuration and interrupts
/// triggered by events of a virtqueue.
///
/// Bitmap layout (from least to most significant bit in the byte):
///
/// 0 : Queue interrupt
///
/// 1 : Device configuration interrupt
///
/// 2 - 31 : Reserved
#[repr(C)]
struct IsrStatusRaw {
flags: u8,
}
impl IsrStatusRaw {
/// Returns a mutable reference to the ISR status capability structure indicated by the
/// [PciCap](PciCap) struct. Reference has a static lifetime as the structure is controlled by the
/// device and will not be moved.
fn map(cap: &PciCap) -> Option<&'static mut IsrStatusRaw> {
if cap.bar.length < u64::from(cap.length + cap.offset) {
error!("ISR status config with id {} of device {:x}, does not fit into memeory specified by bar {:x}!",
cap.id,
cap.origin.dev_id,
cap.bar.index
);
return None;
}
let virt_addr_raw: VirtMemAddr = cap.bar.mem_addr + cap.offset;
// Create mutable reference to the PCI structure in the devices memory area
let isr_stat_raw: &mut IsrStatusRaw =
unsafe { &mut *(usize::from(virt_addr_raw) as *mut IsrStatusRaw) };
Some(isr_stat_raw)
}
// returns true if second bit, from left is 1.
// read DOES reset flag
fn cfg_event() -> bool {
unimplemented!();
}
// returns true if first bit, from left is 1.
// read DOES reset flag
fn vqueue_event() -> bool {
unimplemented!();
}
}
/// PCI configuration access structure of Virtio PCI devices.
/// See Virtio specification v1.1. - 4.1.4.8
///
/// ONLY an alternative access method to the common configuration, notification,
/// ISR and device-specific configuration regions/structures.
//
// Currently has no functionality. All funcitonalty must be done via the read_config methods
// as this struct writes/reads to/from the configuration space which can NOT be mapped!
pub struct PciCfgAlt {
pci_cap: PciCap,
pci_cfg_data: [u8; 4], // Data for BAR access
// TODO:
// The fields cap.bar, cap.length, cap.offset and pci_cfg_data are read-write (RW) for the driver.
// To access a device region, the driver writes into the capability structure (ie. within the PCI configuration
// space) as follows:
// • The driver sets the BAR to access by writing to cap.bar.
// • The driver sets the size of the access by writing 1, 2 or 4 to cap.length.
// • The driver sets the offset within the BAR by writing to cap.offset.
// At that point, pci_cfg_data will provide a window of size cap.length into the given cap.bar at offset cap.offset.
}
impl PciCfgAlt {
fn new(cap: &PciCap) -> Self {
PciCfgAlt {
pci_cap: cap.clone(),
pci_cfg_data: [0; 4],
}
}
}
/// Shared memory configuration structure of Virtio PCI devices.
/// See Virtio specification v1.1. - 4.1.4.7
///
/// Each shared memory region is defined via a single shared
/// memory structure. Each region is identified by an id indicated
/// via the capability.id field of PciCapRaw.
///
/// The shared memory region is defined via a PciCap64 structure.
/// See Virtio specification v.1.1 - 4.1.4 for structure.
///
// Only used for capabilites that require offsets or lengths
// larger than 4GB.
// #[repr(C)]
// struct PciCap64 {
// pci_cap: PciCap,
// offset_high: u32,
// length_high: u32
pub struct ShMemCfg {
mem_addr: VirtMemAddr,
length: MemLen,
sh_mem: ShMem,
/// Shared memory regions are identified via an ID
/// See Virtio specification v1.1. - 4.1.4.7
id: u8,
}
impl ShMemCfg {
fn new(cap: &PciCap) -> Option<Self> {
if cap.bar.length < u64::from(cap.length + cap.offset) {
error!("Shared memory config of with id {} of device {:x}, does not fit into memeory specified by bar {:x}!",
cap.id,
cap.origin.dev_id,
cap.bar.index
);
return None;
}
// Read the PciCap64 fields after the PciCap structure to get the right offset and length
// Assumes the cap_len is a multiple of 8
// This read MIGHT be slow, as it does NOT ensure 32 bit alignment.
let offset_high = env::pci::read_cfg_no_adapter(
cap.origin.bus,
cap.origin.bus,
cap.origin.cfg_ptr + u32::from(cap.origin.cap_struct.cap_len),
);
// Create 64 bit offset from high and low 32 bit values
let offset =
MemOff::from((u64::from(offset_high) << 32) ^ u64::from(cap.origin.cap_struct.offset));
// Assumes the cap_len is a multiple of 8
// This read MIGHT be slow, as it does NOT ensure 32 bit alignment.
let length_high = env::pci::read_cfg_no_adapter(
cap.origin.bus,
cap.origin.bus,
cap.origin.cfg_ptr + u32::from(cap.origin.cap_struct.cap_len + 4),
);
// Create 64 bit length from high and low 32 bit values
let length =
MemLen::from((u64::from(length_high) << 32) ^ u64::from(cap.origin.cap_struct.length));
let virt_addr_raw = cap.bar.mem_addr + offset;
let raw_ptr = usize::from(virt_addr_raw) as *mut u8;
// Zero initialize shared memory area
unsafe {
for i in 0..usize::from(length) {
*(raw_ptr.add(i)) = 0;
}
};
// Currently in place in order to ensure a safe cast below
// "len: cap.bar.length as usize"
// In order to remove this assert a safe conversion from
// kernel PciBar struct into usize must be made
assert!(mem::size_of::<usize>() == 8);
Some(ShMemCfg {
mem_addr: virt_addr_raw,
length: cap.length,
sh_mem: ShMem {
ptr: raw_ptr,
len: cap.bar.length as usize,
},
id: cap.id,
})
}
}
/// Defines a shared memory locate at location ptr with a length of len.
/// The shared memories Drop implementation does not dealloc the memory
/// behind the pointer but sets it to zero, to prevent leakage of data.
struct ShMem {
ptr: *mut u8,
len: usize,
}
impl core::ops::Deref for ShMem {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
}
}
impl core::ops::DerefMut for ShMem {
fn deref_mut(&mut self) -> &mut [u8] {
unsafe { core::slice::from_raw_parts_mut(self.ptr, self.len) }
}
}
// Upon drop the shared memory region is "deleted" with zeros.
impl Drop for ShMem {
fn drop(&mut self) {
for i in 0..self.len {
unsafe {
*(self.ptr.add(i)) = 0;
}
}
}
}
/// PciBar stores the virtual memory address and associated length of memory space
/// a PCI device's physical memory indicated by the device's BAR has been mapped to.
//
// Currently all fields are public as the struct is instanciated in the drivers::virtio::env module
#[derive(Copy, Clone, Debug)]
pub struct PciBar {
index: u8,
mem_addr: VirtMemAddr,
length: u64,
}
impl PciBar {
pub fn new(index: u8, mem_addr: VirtMemAddr, length: u64) -> Self {
PciBar {
index,
mem_addr,
length,