1use alloc::{collections::BTreeMap, sync::Arc, vec::Vec};
42use core::{
43 fmt,
44 ops::{BitAnd, BitOr},
45 sync::atomic::{AtomicBool, AtomicU64, Ordering},
46};
47
48use crate::sync::{FixedQueue, SpinLock};
49
50pub const IOVA_BASE: u64 = 0x1_0000_0000;
55
56pub const IOMMU_PAGE_SIZE: u64 = 4096;
58
59pub const IOMMU_SUPERPAGE_2M: u64 = 2 * 1024 * 1024;
61pub const IOMMU_SUPERPAGE_1G: u64 = 1024 * 1024 * 1024;
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum MappingKind {
67 Page4K,
69 Page2M,
71 Page1G,
73}
74
75impl MappingKind {
76 pub const fn size(self) -> u64 {
78 match self {
79 MappingKind::Page4K => IOMMU_PAGE_SIZE,
80 MappingKind::Page2M => IOMMU_SUPERPAGE_2M,
81 MappingKind::Page1G => IOMMU_SUPERPAGE_1G,
82 }
83 }
84
85 pub fn best_for(iova: u64, len: u64) -> Option<Self> {
89 if len == 0 || len & (IOMMU_PAGE_SIZE - 1) != 0 {
90 return None;
91 }
92 if len >= IOMMU_SUPERPAGE_1G
93 && iova & (IOMMU_SUPERPAGE_1G - 1) == 0
94 && len & (IOMMU_SUPERPAGE_1G - 1) == 0
95 {
96 Some(MappingKind::Page1G)
97 } else if len >= IOMMU_SUPERPAGE_2M
98 && iova & (IOMMU_SUPERPAGE_2M - 1) == 0
99 && len & (IOMMU_SUPERPAGE_2M - 1) == 0
100 {
101 Some(MappingKind::Page2M)
102 } else {
103 Some(MappingKind::Page4K)
104 }
105 }
106}
107
108pub const MAX_DOMAIN_ID: u16 = u16::MAX;
110
111const BITMAP_WORDS: usize = (MAX_DOMAIN_ID as usize + 1) / 64;
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
119pub struct Sbdf {
120 pub segment: u16,
121 pub bus: u8,
122 pub device: u8,
123 pub function: u8,
124}
125
126impl Sbdf {
127 pub const fn new(segment: u16, bus: u8, device: u8, function: u8) -> Self {
129 Self {
130 segment,
131 bus,
132 device,
133 function,
134 }
135 }
136
137 pub const fn from_pci(bus: u8, device: u8, function: u8) -> Self {
139 Self::new(0, bus, device, function)
140 }
141
142 pub const fn to_u32(self) -> u32 {
144 ((self.segment as u32) << 16)
145 | ((self.bus as u32) << 8)
146 | ((self.device as u32 & 0x1f) << 3)
147 | (self.function as u32 & 0x7)
148 }
149
150 pub const fn from_u32(raw: u32) -> Self {
152 Self {
153 segment: (raw >> 16) as u16,
154 bus: (raw >> 8) as u8,
155 device: ((raw >> 3) & 0x1f) as u8,
156 function: (raw & 0x7) as u8,
157 }
158 }
159}
160
161impl fmt::Display for Sbdf {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 write!(
164 f,
165 "{:04x}:{:02x}:{:02x}.{:x}",
166 self.segment, self.bus, self.device, self.function
167 )
168 }
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
182pub struct DmaProt(u8);
183
184impl DmaProt {
185 pub const NONE: Self = Self(0);
187 pub const READ: Self = Self(0b01);
189 pub const WRITE: Self = Self(0b10);
191 pub const READ_WRITE: Self = Self(0b11);
193
194 pub const fn bits(self) -> u8 {
196 self.0
197 }
198
199 pub const fn from_bits(bits: u8) -> Option<Self> {
201 if bits & !0b11 != 0 {
202 None
203 } else {
204 Some(Self(bits))
205 }
206 }
207
208 pub const fn contains(self, other: Self) -> bool {
210 self.0 & other.0 == other.0
211 }
212
213 pub const fn is_empty(self) -> bool {
215 self.0 == 0
216 }
217
218 pub const fn readable(self) -> bool {
220 self.0 & Self::READ.0 != 0
221 }
222
223 pub const fn writable(self) -> bool {
225 self.0 & Self::WRITE.0 != 0
226 }
227}
228
229impl BitOr for DmaProt {
230 type Output = Self;
231
232 fn bitor(self, rhs: Self) -> Self {
233 Self(self.0 | rhs.0)
234 }
235}
236
237impl BitAnd for DmaProt {
238 type Output = Self;
239
240 fn bitand(self, rhs: Self) -> Self {
241 Self(self.0 & rhs.0)
242 }
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251pub enum IommuError {
252 NotPresent,
254 BackendNotReady,
256 NoDomainSpace,
258 UnknownDomain,
260 InvalidRange,
262 Overlap,
264 NotMapped,
266 AlreadyMapped,
268 Reserved,
270 Quiesced,
272 Unsupported,
274 Hardware,
276}
277
278impl IommuError {
279 pub const fn as_str(self) -> &'static str {
281 match self {
282 IommuError::NotPresent => "no IOMMU firmware present",
283 IommuError::BackendNotReady => "IOMMU backend not ready",
284 IommuError::NoDomainSpace => "no free IOMMU domain id",
285 IommuError::UnknownDomain => "unknown IOMMU domain",
286 IommuError::InvalidRange => "invalid IOVA range",
287 IommuError::Overlap => "overlapping IOVA range",
288 IommuError::NotMapped => "IOVA range not mapped",
289 IommuError::AlreadyMapped => "buffer already mapped to a domain",
290 IommuError::Reserved => "physical range is firmware-reserved",
291 IommuError::Quiesced => "IOMMU domain is quiesced",
292 IommuError::Unsupported => "operation not supported by the IOMMU backend",
293 IommuError::Hardware => "IOMMU hardware refused the operation",
294 }
295 }
296}
297
298#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
300pub struct DomainId(pub u16);
301
302impl DomainId {
303 pub const fn raw(self) -> u16 {
305 self.0
306 }
307
308 pub const fn from_raw(raw: u16) -> Self {
310 Self(raw)
311 }
312}
313
314#[derive(Debug, Clone, Copy, PartialEq, Eq)]
320pub struct Mapping {
321 pub iova: u64,
322 pub phys: u64,
323 pub len: u64,
324 pub prot: DmaProt,
325 pub kind: MappingKind,
326}
327
328impl Mapping {
329 pub const fn end(&self) -> u64 {
331 self.iova.saturating_add(self.len)
332 }
333
334 pub const fn contains(&self, iova: u64) -> bool {
336 iova >= self.iova && iova < self.end()
337 }
338}
339
340#[derive(Debug, Clone, Copy, PartialEq, Eq)]
342pub struct Translation {
343 pub phys: u64,
344 pub prot: DmaProt,
345 pub remaining: u64,
347}
348
349#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355pub enum FaultPolicy {
356 Log,
358 Notify,
360 KillOwner,
362 Panic,
364}
365
366impl FaultPolicy {
367 pub const fn from_raw(raw: u8) -> Self {
369 match raw {
370 1 => FaultPolicy::Notify,
371 2 => FaultPolicy::KillOwner,
372 3 => FaultPolicy::Panic,
373 _ => FaultPolicy::Log,
374 }
375 }
376
377 pub const fn as_raw(self) -> u8 {
379 match self {
380 FaultPolicy::Log => 0,
381 FaultPolicy::Notify => 1,
382 FaultPolicy::KillOwner => 2,
383 FaultPolicy::Panic => 3,
384 }
385 }
386
387 pub const fn action(self) -> FaultAction {
389 match self {
390 FaultPolicy::Log => FaultAction::Logged,
391 FaultPolicy::Notify => FaultAction::Notified,
392 FaultPolicy::KillOwner => FaultAction::OwnerRevoked,
393 FaultPolicy::Panic => FaultAction::Panicked,
394 }
395 }
396}
397
398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
400pub enum FaultAction {
401 Logged,
402 Notified,
403 OwnerRevoked,
404 Panicked,
405}
406
407impl FaultAction {
408 pub const fn as_raw(self) -> u8 {
410 match self {
411 FaultAction::Logged => 0,
412 FaultAction::Notified => 1,
413 FaultAction::OwnerRevoked => 2,
414 FaultAction::Panicked => 3,
415 }
416 }
417}
418
419#[derive(Debug, Clone, Copy, PartialEq, Eq)]
421pub enum FaultReason {
422 Read,
424 Write,
426 Permission,
428 OutOfRange,
430}
431
432impl FaultReason {
433 pub const fn as_raw(self) -> u8 {
435 match self {
436 FaultReason::Read => 0,
437 FaultReason::Write => 1,
438 FaultReason::Permission => 2,
439 FaultReason::OutOfRange => 3,
440 }
441 }
442}
443
444#[derive(Debug, Clone, Copy, PartialEq, Eq)]
446pub struct FaultRecord {
447 pub seq: u64,
448 pub timestamp_ns: u64,
449 pub domain: DomainId,
450 pub sbdf: Sbdf,
451 pub iova: u64,
452 pub reason: FaultReason,
453 pub access: DmaProt,
454 pub owner: Option<u32>,
455 pub action: FaultAction,
456}
457
458pub const FAULT_QUEUE_CAPACITY: usize = 256;
460pub const FAULT_BURST: u32 = 32;
462
463static FAULTS: SpinLock<FixedQueue<FaultRecord, FAULT_QUEUE_CAPACITY>> =
464 SpinLock::new(FixedQueue::new());
465static FAULT_SEQ: AtomicU64 = AtomicU64::new(1);
466static FAULT_DROPPED: AtomicU64 = AtomicU64::new(0);
467
468#[derive(Debug, Clone, PartialEq, Eq)]
477pub struct ReservedRegion {
478 pub segment: u16,
479 pub base: u64,
481 pub limit: u64,
483 pub devices: Vec<Sbdf>,
485 pub all_bus_from: Option<u8>,
487 pub identity_mapped: bool,
489}
490
491impl ReservedRegion {
492 pub const fn contains(&self, phys: u64) -> bool {
494 phys >= self.base && phys <= self.limit
495 }
496
497 pub const fn overlaps(&self, start: u64, len: u64) -> bool {
499 match start.checked_add(len) {
500 Some(end) => start <= self.limit && end > self.base,
501 None => true,
502 }
503 }
504
505 pub fn covers(&self, sbdf: Sbdf) -> bool {
507 if self.segment != sbdf.segment {
508 return false;
509 }
510 if self.devices.iter().any(|d| *d == sbdf) {
511 return true;
512 }
513 self.all_bus_from
514 .map(|bus| sbdf.bus >= bus)
515 .unwrap_or(false)
516 }
517}
518
519static RESERVED: SpinLock<Vec<ReservedRegion>> = SpinLock::new(Vec::new());
520static PANIC_ON_INVALID_RMRR: AtomicBool = AtomicBool::new(false);
521
522pub fn set_reserved_regions(regions: Vec<ReservedRegion>, panic_on_invalid: bool) {
524 PANIC_ON_INVALID_RMRR.store(panic_on_invalid, Ordering::Release);
525 for region in ®ions {
526 if region.base > region.limit {
527 if panic_on_invalid {
528 panic!(
529 "IOMMU: invalid RMRR {}..{} for segment {}",
530 region.base, region.limit, region.segment
531 );
532 }
533 log::warn!(
534 "[IOMMU] ignoring inverted RMRR {:#x}..{:#x} seg={}",
535 region.base,
536 region.limit,
537 region.segment
538 );
539 }
540 }
541 *RESERVED.lock() = regions;
542}
543
544pub fn reserved_regions() -> Vec<ReservedRegion> {
546 RESERVED.lock().clone()
547}
548
549pub fn reserved_conflict(sbdf: Sbdf, start: u64, len: u64) -> Option<ReservedRegion> {
551 RESERVED
552 .lock()
553 .iter()
554 .find(|r| r.covers(sbdf) && r.overlaps(start, len))
555 .cloned()
556}
557
558#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
564pub struct DomainStats {
565 pub maps: u64,
566 pub unmaps: u64,
567 pub bytes_mapped: u64,
568 pub faults: u64,
569 pub dropped_faults: u64,
570}
571
572#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
574pub struct IommuStats {
575 pub domains_created: u64,
576 pub domains_destroyed: u64,
577 pub maps: u64,
578 pub unmaps: u64,
579 pub faults: u64,
580 pub dropped_faults: u64,
581 pub activations: u64,
582}
583
584static STATS: SpinLock<IommuStats> = SpinLock::new(IommuStats {
585 domains_created: 0,
586 domains_destroyed: 0,
587 maps: 0,
588 unmaps: 0,
589 faults: 0,
590 dropped_faults: 0,
591 activations: 0,
592});
593
594pub fn stats() -> IommuStats {
596 *STATS.lock()
597}
598
599#[derive(Debug)]
600struct DomainState {
601 refs: usize,
602 generation: u64,
603 quiesced: bool,
604 owner: Option<u32>,
605 policy: FaultPolicy,
606 fault_budget: u32,
607 stats: DomainStats,
608 mappings: BTreeMap<u64, Mapping>,
609}
610
611impl DomainState {
612 fn new(owner: Option<u32>, policy: FaultPolicy) -> Self {
613 Self {
614 refs: 1,
615 generation: 0,
616 quiesced: false,
617 owner,
618 policy,
619 fault_budget: FAULT_BURST,
620 stats: DomainStats::default(),
621 mappings: BTreeMap::new(),
622 }
623 }
624
625 fn alloc_iova(&self, len: u64) -> Result<u64, IommuError> {
627 let mut candidate = IOVA_BASE;
628 for mapping in self.mappings.values() {
629 if mapping.end() <= candidate {
630 continue;
631 }
632 let fits = candidate
633 .checked_add(len)
634 .map(|end| end <= mapping.iova)
635 .unwrap_or(false);
636 if fits {
637 return Ok(candidate);
638 }
639 candidate = candidate.max(mapping.end());
640 }
641 candidate.checked_add(len).ok_or(IommuError::InvalidRange)?;
642 Ok(candidate)
643 }
644}
645
646pub struct Domain {
652 id: DomainId,
653 sbdf: Sbdf,
654 state: SpinLock<DomainState>,
655}
656
657impl fmt::Debug for Domain {
658 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659 let state = self.state.lock();
660 f.debug_struct("Domain")
661 .field("id", &self.id)
662 .field("sbdf", &self.sbdf)
663 .field("refs", &state.refs)
664 .field("generation", &state.generation)
665 .field("mappings", &state.mappings.len())
666 .finish()
667 }
668}
669
670impl Domain {
671 #[allow(dead_code)]
673 fn new(id: DomainId, sbdf: Sbdf) -> Self {
674 Self::new_owned(id, sbdf, None, FaultPolicy::Log)
675 }
676
677 fn new_owned(id: DomainId, sbdf: Sbdf, owner: Option<u32>, policy: FaultPolicy) -> Self {
678 Self {
679 id,
680 sbdf,
681 state: SpinLock::new(DomainState::new(owner, policy)),
682 }
683 }
684
685 pub const fn id(&self) -> DomainId {
687 self.id
688 }
689
690 pub const fn sbdf(&self) -> Sbdf {
692 self.sbdf
693 }
694
695 pub fn owner(&self) -> Option<u32> {
697 self.state.lock().owner
698 }
699
700 pub fn fault_policy(&self) -> FaultPolicy {
702 self.state.lock().policy
703 }
704
705 pub fn set_fault_policy(&self, policy: FaultPolicy) {
707 self.state.lock().policy = policy;
708 }
709
710 pub fn is_quiesced(&self) -> bool {
712 self.state.lock().quiesced
713 }
714
715 pub fn quiesce(&self) {
717 let mut state = self.state.lock();
718 state.quiesced = true;
719 state.generation = state.generation.wrapping_add(1);
720 }
721
722 pub fn resume(&self) {
724 let mut state = self.state.lock();
725 state.quiesced = false;
726 state.generation = state.generation.wrapping_add(1);
727 }
728
729 pub fn stats(&self) -> DomainStats {
731 self.state.lock().stats
732 }
733
734 pub fn mapped_bytes(&self) -> u64 {
736 self.state
737 .lock()
738 .mappings
739 .values()
740 .map(|mapping| mapping.len)
741 .sum()
742 }
743
744 pub fn refs(&self) -> usize {
746 self.state.lock().refs
747 }
748
749 pub fn acquire(&self) -> usize {
751 let mut state = self.state.lock();
752 state.refs = state.refs.saturating_add(1);
753 state.refs
754 }
755
756 pub fn release(&self) -> usize {
758 let mut state = self.state.lock();
759 state.refs = state.refs.saturating_sub(1);
760 state.refs
761 }
762
763 pub fn generation(&self) -> u64 {
765 self.state.lock().generation
766 }
767
768 pub fn mapping_count(&self) -> usize {
770 self.state.lock().mappings.len()
771 }
772
773 pub fn mappings(&self) -> Vec<Mapping> {
775 self.state.lock().mappings.values().copied().collect()
776 }
777
778 pub fn is_active(&self) -> bool {
780 !self.state.lock().mappings.is_empty()
781 }
782
783 pub fn map(&self, iova: u64, phys: u64, len: u64, prot: DmaProt) -> Result<(), IommuError> {
788 let kind = MappingKind::best_for(iova, len)
789 .filter(|kind| phys & (kind.size() - 1) == 0)
790 .unwrap_or(MappingKind::Page4K);
791 self.map_kind(iova, phys, len, prot, kind)
792 }
793
794 pub fn map_kind(
796 &self,
797 iova: u64,
798 phys: u64,
799 len: u64,
800 prot: DmaProt,
801 kind: MappingKind,
802 ) -> Result<(), IommuError> {
803 self.map_impl(iova, phys, len, prot, kind, false)
804 }
805
806 pub fn map_reserved(
811 &self,
812 iova: u64,
813 phys: u64,
814 len: u64,
815 prot: DmaProt,
816 ) -> Result<(), IommuError> {
817 let kind = MappingKind::best_for(iova, len)
818 .filter(|kind| phys & (kind.size() - 1) == 0)
819 .unwrap_or(MappingKind::Page4K);
820 self.map_impl(iova, phys, len, prot, kind, true)
821 }
822
823 fn map_impl(
824 &self,
825 iova: u64,
826 phys: u64,
827 len: u64,
828 prot: DmaProt,
829 kind: MappingKind,
830 allow_reserved: bool,
831 ) -> Result<(), IommuError> {
832 validate_range(iova, len)?;
833 let leaf = kind.size();
834 if iova & (leaf - 1) != 0 || len & (leaf - 1) != 0 {
835 return Err(IommuError::InvalidRange);
836 }
837 if phys & (IOMMU_PAGE_SIZE - 1) != 0 {
838 return Err(IommuError::InvalidRange);
839 }
840 phys.checked_add(len).ok_or(IommuError::InvalidRange)?;
841
842 if !allow_reserved && reserved_conflict(self.sbdf, phys, len).is_some() {
845 return Err(IommuError::Reserved);
846 }
847
848 let mut state = self.state.lock();
849 if state.quiesced {
850 return Err(IommuError::Quiesced);
851 }
852
853 if let Some((_, prev)) = state.mappings.range(..=iova).next_back() {
855 if prev.end() > iova {
856 return Err(IommuError::Overlap);
857 }
858 }
859 if let Some((&next_start, _)) = state.mappings.range(iova..iova + len).next() {
861 debug_assert!(next_start >= iova);
862 return Err(IommuError::Overlap);
863 }
864
865 crate::arch::iommu::map_domain(self.id, self.sbdf, iova, phys, len, prot, kind)
868 .map_err(backend_error)?;
869
870 state.mappings.insert(
871 iova,
872 Mapping {
873 iova,
874 phys,
875 len,
876 prot,
877 kind,
878 },
879 );
880 state.generation = state.generation.wrapping_add(1);
881 state.stats.maps = state.stats.maps.wrapping_add(1);
882 state.stats.bytes_mapped = state.stats.bytes_mapped.wrapping_add(len);
883 drop(state);
884 let mut global = STATS.lock();
885 global.maps = global.maps.wrapping_add(1);
886 Ok(())
887 }
888
889 pub fn map_auto(&self, phys: u64, len: u64, prot: DmaProt) -> Result<u64, IommuError> {
891 validate_range(0, len)?;
892 let iova = {
893 let state = self.state.lock();
894 state.alloc_iova(len)?
895 };
896 self.map(iova, phys, len, prot)?;
897 Ok(iova)
898 }
899
900 pub fn unmap(&self, iova: u64, len: u64) -> Result<usize, IommuError> {
905 validate_range(iova, len)?;
906 let end = iova + len;
907 let mut state = self.state.lock();
908
909 let mut keys: Vec<u64> = Vec::new();
910 if let Some((&start, prev)) = state.mappings.range(..end).next_back() {
911 if prev.end() > iova {
912 keys.push(start);
913 }
914 }
915 for &start in state.mappings.range(iova..end).map(|(k, _)| k) {
916 if !keys.contains(&start) {
917 keys.push(start);
918 }
919 }
920 if keys.is_empty() {
921 return Err(IommuError::NotMapped);
922 }
923 for key in &keys {
924 let Some(mapping) = state.mappings.get(key) else {
925 continue;
926 };
927 if mapping.iova < iova || mapping.end() > end {
928 return Err(IommuError::InvalidRange);
929 }
930 }
931
932 for key in &keys {
934 if let Some(mapping) = state.mappings.get(key).copied() {
935 crate::arch::iommu::unmap_domain(
936 self.id,
937 self.sbdf,
938 mapping.iova,
939 mapping.len,
940 mapping.kind,
941 )
942 .map_err(backend_error)?;
943 }
944 }
945
946 let mut removed_bytes = 0u64;
947 for key in &keys {
948 if let Some(mapping) = state.mappings.remove(key) {
949 removed_bytes = removed_bytes.wrapping_add(mapping.len);
950 }
951 }
952 state.generation = state.generation.wrapping_add(1);
953 state.stats.unmaps = state.stats.unmaps.wrapping_add(keys.len() as u64);
954 state.stats.bytes_mapped = state.stats.bytes_mapped.saturating_sub(removed_bytes);
955 let removed = keys.len();
956 drop(state);
957 let mut global = STATS.lock();
958 global.unmaps = global.unmaps.wrapping_add(removed as u64);
959 Ok(removed)
960 }
961
962 pub fn unmap_exact(&self, iova: u64) -> Result<Mapping, IommuError> {
964 let mut state = self.state.lock();
965 let mapping = *state.mappings.get(&iova).ok_or(IommuError::NotMapped)?;
966 crate::arch::iommu::unmap_domain(
967 self.id,
968 self.sbdf,
969 mapping.iova,
970 mapping.len,
971 mapping.kind,
972 )
973 .map_err(backend_error)?;
974 state.mappings.remove(&iova);
975 state.generation = state.generation.wrapping_add(1);
976 state.stats.unmaps = state.stats.unmaps.wrapping_add(1);
977 state.stats.bytes_mapped = state.stats.bytes_mapped.saturating_sub(mapping.len);
978 Ok(mapping)
979 }
980
981 pub fn translate(&self, iova: u64) -> Option<Translation> {
986 let state = self.state.lock();
987 let (_, mapping) = state.mappings.range(..=iova).next_back()?;
988 if !mapping.contains(iova) {
989 return None;
990 }
991 Some(Translation {
992 phys: mapping.phys + (iova - mapping.iova),
993 prot: mapping.prot,
994 remaining: mapping.end() - iova,
995 })
996 }
997
998 pub fn reset(&self) {
1000 let mappings: Vec<Mapping> = self.state.lock().mappings.values().copied().collect();
1001 for mapping in mappings {
1002 let _ = crate::arch::iommu::unmap_domain(
1003 self.id,
1004 self.sbdf,
1005 mapping.iova,
1006 mapping.len,
1007 mapping.kind,
1008 );
1009 }
1010 let mut state = self.state.lock();
1011 if !state.mappings.is_empty() {
1012 state.mappings.clear();
1013 state.stats.bytes_mapped = 0;
1014 state.generation = state.generation.wrapping_add(1);
1015 }
1016 }
1017
1018 pub fn report_fault(
1024 &self,
1025 iova: u64,
1026 reason: FaultReason,
1027 access: DmaProt,
1028 ) -> Option<FaultRecord> {
1029 let (owner, action, seq) = {
1030 let mut state = self.state.lock();
1031 state.stats.faults = state.stats.faults.wrapping_add(1);
1032 let policy = state.policy;
1033 let action = policy.action();
1034 let seq = FAULT_SEQ.fetch_add(1, Ordering::Relaxed);
1035 if state.fault_budget == 0 {
1036 state.stats.dropped_faults = state.stats.dropped_faults.wrapping_add(1);
1037 drop(state);
1038 FAULT_DROPPED.fetch_add(1, Ordering::Relaxed);
1039 let mut global = STATS.lock();
1040 global.dropped_faults = global.dropped_faults.wrapping_add(1);
1041 drop(global);
1042 if policy == FaultPolicy::Panic {
1043 panic!("IOMMU fault (rate-limited) domain={:?}", self.id);
1044 }
1045 return None;
1046 }
1047 state.fault_budget -= 1;
1048 (state.owner, action, seq)
1049 };
1050
1051 let record = FaultRecord {
1052 seq,
1053 timestamp_ns: crate::syscall::time::current_time_ns(),
1054 domain: self.id,
1055 sbdf: self.sbdf,
1056 iova,
1057 reason,
1058 access,
1059 owner,
1060 action,
1061 };
1062
1063 {
1064 let mut global = STATS.lock();
1065 global.faults = global.faults.wrapping_add(1);
1066 }
1067 if FAULTS.lock().push_back(record).is_err() {
1068 FAULT_DROPPED.fetch_add(1, Ordering::Relaxed);
1069 let mut global = STATS.lock();
1070 global.dropped_faults = global.dropped_faults.wrapping_add(1);
1071 }
1072
1073 match action {
1074 FaultAction::OwnerRevoked => {
1075 if let Some(sid) = owner {
1076 revoke_owner(sid);
1077 }
1078 }
1079 FaultAction::Panicked => {
1080 panic!(
1081 "IOMMU fault: sbdf={} iova={:#x} domain={:?}",
1082 self.sbdf, iova, self.id
1083 );
1084 }
1085 _ => {}
1086 }
1087 Some(record)
1088 }
1089}
1090
1091fn validate_range(iova: u64, len: u64) -> Result<(), IommuError> {
1092 if len == 0 || iova & (IOMMU_PAGE_SIZE - 1) != 0 || len & (IOMMU_PAGE_SIZE - 1) != 0 {
1093 return Err(IommuError::InvalidRange);
1094 }
1095 iova.checked_add(len).ok_or(IommuError::InvalidRange)?;
1096 Ok(())
1097}
1098
1099fn backend_error(error: crate::arch::iommu::IommuError) -> IommuError {
1100 use crate::arch::iommu::IommuError as Backend;
1101 match error {
1102 Backend::NotPresent => IommuError::NotPresent,
1103 Backend::NotReady => IommuError::BackendNotReady,
1104 Backend::Unsupported => IommuError::Unsupported,
1105 Backend::Hardware => IommuError::Hardware,
1106 Backend::InvalidDomain => IommuError::UnknownDomain,
1107 }
1108}
1109
1110static DOMAINS: SpinLock<BTreeMap<DomainId, Arc<Domain>>> = SpinLock::new(BTreeMap::new());
1115static DOMAIN_BITMAP: SpinLock<[u64; BITMAP_WORDS]> = SpinLock::new([0u64; BITMAP_WORDS]);
1116static HARDWARE_ENABLED: AtomicBool = AtomicBool::new(false);
1117
1118fn allocate_domain_id() -> Result<DomainId, IommuError> {
1119 let mut bitmap = DOMAIN_BITMAP.lock();
1120 for word in 0..BITMAP_WORDS {
1122 let mut free = !bitmap[word];
1123 if word == 0 {
1124 free &= !1u64; }
1126 if free == 0 {
1127 continue;
1128 }
1129 let bit = free.trailing_zeros() as usize;
1130 bitmap[word] |= 1u64 << bit;
1131 return Ok(DomainId((word * 64 + bit) as u16));
1132 }
1133 Err(IommuError::NoDomainSpace)
1134}
1135
1136fn free_domain_id(id: DomainId) {
1137 let index = id.0 as usize;
1138 if index == 0 || index > MAX_DOMAIN_ID as usize {
1139 return;
1140 }
1141 let mut bitmap = DOMAIN_BITMAP.lock();
1142 bitmap[index / 64] &= !(1u64 << (index % 64));
1143}
1144
1145pub fn firmware_present() -> bool {
1147 crate::acpi::get_dmar().is_some() || crate::acpi::get_ivrs().is_some()
1148}
1149
1150pub fn enabled() -> bool {
1152 HARDWARE_ENABLED.load(Ordering::Acquire)
1153}
1154
1155pub fn domain_for(sbdf: Sbdf) -> Result<Arc<Domain>, IommuError> {
1160 domain_for_owned(sbdf, None, FaultPolicy::Log)
1161}
1162
1163pub fn domain_for_owned(
1169 sbdf: Sbdf,
1170 owner: Option<u32>,
1171 policy: FaultPolicy,
1172) -> Result<Arc<Domain>, IommuError> {
1173 let mut domains = DOMAINS.lock();
1174 if let Some(existing) = domains.values().find(|domain| domain.sbdf() == sbdf) {
1175 existing.acquire();
1176 return Ok(existing.clone());
1177 }
1178 let id = allocate_domain_id()?;
1179 let domain = Arc::new(Domain::new_owned(id, sbdf, owner, policy));
1180 domains.insert(id, domain.clone());
1181 {
1182 let mut global = STATS.lock();
1183 global.domains_created = global.domains_created.wrapping_add(1);
1184 }
1185
1186 for region in RESERVED.lock().iter().filter(|r| r.covers(sbdf)) {
1188 let start = region.base & !(IOMMU_PAGE_SIZE - 1);
1189 let Some(end) = region
1190 .limit
1191 .checked_add(IOMMU_PAGE_SIZE)
1192 .map(|limit| limit & !(IOMMU_PAGE_SIZE - 1))
1193 else {
1194 continue;
1195 };
1196 if end <= start {
1197 continue;
1198 }
1199 if let Err(err) = domain.map_reserved(start, start, end - start, DmaProt::READ_WRITE) {
1200 log::warn!(
1201 "[IOMMU] cannot identity-map RMRR {:#x}..{:#x} for {}: {:?}",
1202 start,
1203 end - 1,
1204 sbdf,
1205 err
1206 );
1207 }
1208 }
1209
1210 Ok(domain)
1211}
1212
1213pub fn create_domain(bus: u8, device: u8, function: u8) -> Result<Arc<Domain>, IommuError> {
1215 domain_for(Sbdf::from_pci(bus, device, function))
1216}
1217
1218pub fn get_domain(id: DomainId) -> Option<Arc<Domain>> {
1223 DOMAINS.lock().get(&id).cloned()
1224}
1225
1226pub fn find_domain(sbdf: Sbdf) -> Option<Arc<Domain>> {
1228 DOMAINS
1229 .lock()
1230 .values()
1231 .find(|domain| domain.sbdf() == sbdf)
1232 .cloned()
1233}
1234
1235pub fn release_domain(domain: &Arc<Domain>) -> bool {
1237 if domain.release() > 0 {
1238 return false;
1239 }
1240 let id = domain.id();
1241 domain.reset();
1242 let mut domains = DOMAINS.lock();
1243 let same = domains
1245 .get(&id)
1246 .map(|entry| Arc::ptr_eq(entry, domain))
1247 .unwrap_or(false);
1248 if same {
1249 domains.remove(&id);
1250 free_domain_id(id);
1251 let mut global = STATS.lock();
1252 global.domains_destroyed = global.domains_destroyed.wrapping_add(1);
1253 true
1254 } else {
1255 false
1256 }
1257}
1258
1259pub fn teardown(id: DomainId) -> bool {
1261 let mut domains = DOMAINS.lock();
1262 let Some(domain) = domains.remove(&id) else {
1263 return false;
1264 };
1265 domain.reset();
1266 free_domain_id(id);
1267 let mut global = STATS.lock();
1268 global.domains_destroyed = global.domains_destroyed.wrapping_add(1);
1269 true
1270}
1271
1272pub fn map(
1274 domain: DomainId,
1275 iova: u64,
1276 phys: u64,
1277 len: u64,
1278 prot: DmaProt,
1279) -> Result<(), IommuError> {
1280 let domain = lookup(domain)?;
1281 domain.map(iova, phys, len, prot)
1282}
1283
1284pub fn unmap(domain: DomainId, iova: u64, len: u64) -> Result<usize, IommuError> {
1286 let domain = lookup(domain)?;
1287 domain.unmap(iova, len)
1288}
1289
1290pub fn translate(domain: DomainId, iova: u64) -> Option<Translation> {
1292 lookup(domain).ok()?.translate(iova)
1293}
1294
1295fn lookup(id: DomainId) -> Result<Arc<Domain>, IommuError> {
1296 DOMAINS
1297 .lock()
1298 .get(&id)
1299 .cloned()
1300 .ok_or(IommuError::UnknownDomain)
1301}
1302
1303pub fn domain_count() -> usize {
1305 DOMAINS.lock().len()
1306}
1307
1308pub fn owner_usage(sid: u32) -> (usize, u64) {
1310 let domains = DOMAINS.lock();
1311 let owned: Vec<Arc<Domain>> = domains
1312 .values()
1313 .filter(|domain| domain.owner() == Some(sid))
1314 .cloned()
1315 .collect();
1316 drop(domains);
1317 let mut bytes = 0u64;
1318 for domain in &owned {
1319 bytes = bytes.saturating_add(domain.mapped_bytes());
1320 }
1321 (owned.len(), bytes)
1322}
1323
1324pub fn revoke_owner(sid: u32) -> usize {
1326 let ids: Vec<DomainId> = {
1327 let domains = DOMAINS.lock();
1328 domains
1329 .values()
1330 .filter(|domain| domain.owner() == Some(sid))
1331 .map(|domain| domain.id())
1332 .collect()
1333 };
1334 let mut revoked = 0;
1335 for id in ids {
1336 if teardown(id) {
1337 revoked += 1;
1338 }
1339 }
1340 if revoked > 0 {
1341 log::warn!("[IOMMU] revoked {} domain(s) for silo {}", revoked, sid);
1342 }
1343 revoked
1344}
1345
1346pub fn quiesce(id: DomainId) -> Result<(), IommuError> {
1348 lookup(id)?.quiesce();
1349 Ok(())
1350}
1351
1352pub fn resume(id: DomainId) -> Result<(), IommuError> {
1354 lookup(id)?.resume();
1355 Ok(())
1356}
1357
1358pub fn detach(id: DomainId) -> bool {
1360 if let Ok(domain) = lookup(id) {
1361 domain.quiesce();
1362 }
1363 teardown(id)
1364}
1365
1366pub fn detach_device(sbdf: Sbdf) -> usize {
1368 let ids: Vec<DomainId> = DOMAINS
1369 .lock()
1370 .values()
1371 .filter(|domain| domain.sbdf() == sbdf)
1372 .map(|domain| domain.id())
1373 .collect();
1374 let mut detached = 0;
1375 for id in ids {
1376 if detach(id) {
1377 detached += 1;
1378 }
1379 }
1380 if detached > 0 {
1381 log::info!("[IOMMU] detached {} domain(s) from {}", detached, sbdf);
1382 }
1383 detached
1384}
1385
1386pub fn map_super(
1388 domain: DomainId,
1389 iova: u64,
1390 phys: u64,
1391 len: u64,
1392 prot: DmaProt,
1393) -> Result<MappingKind, IommuError> {
1394 let domain = lookup(domain)?;
1395 let kind = MappingKind::best_for(iova, len)
1396 .filter(|kind| phys & (kind.size() - 1) == 0)
1397 .ok_or(IommuError::InvalidRange)?;
1398 domain.map_kind(iova, phys, len, prot, kind)?;
1399 Ok(kind)
1400}
1401
1402pub fn next_fault() -> Option<FaultRecord> {
1408 FAULTS.lock().pop_front()
1409}
1410
1411pub fn faults_dropped() -> u64 {
1413 FAULT_DROPPED.load(Ordering::Relaxed)
1414}
1415
1416pub fn refill_fault_budget(domain: DomainId, burst: u32) {
1418 if let Ok(domain) = lookup(domain) {
1419 domain.state.lock().fault_budget = burst;
1420 }
1421}
1422
1423pub fn inject_fault(
1425 domain: DomainId,
1426 iova: u64,
1427 reason: FaultReason,
1428 access: DmaProt,
1429) -> Option<FaultRecord> {
1430 lookup(domain).ok()?.report_fault(iova, reason, access)
1431}
1432
1433#[derive(Debug, Clone, PartialEq, Eq)]
1439pub struct IommuGroup {
1440 pub id: u32,
1441 pub segment: u16,
1442 pub bus: u8,
1443 pub devices: Vec<Sbdf>,
1444}
1445
1446pub fn groups() -> Vec<IommuGroup> {
1448 let Some(dmar) = crate::acpi::get_dmar() else {
1449 return Vec::new();
1450 };
1451 let Ok(units) = dmar.drhds() else {
1452 return Vec::new();
1453 };
1454 let mut groups: Vec<IommuGroup> = Vec::new();
1455 for unit in units {
1456 for scope in unit.scopes {
1457 let e = match scope.endpoint() {
1458 Some(endpoint) => endpoint,
1459 None => continue,
1460 };
1461 let sbdf = Sbdf::new(unit.segment, e.0, e.1, e.2);
1462 if let Some(group) = groups
1463 .iter_mut()
1464 .find(|g| g.segment == sbdf.segment && g.bus == sbdf.bus)
1465 {
1466 if !group.devices.contains(&sbdf) {
1467 group.devices.push(sbdf);
1468 }
1469 } else {
1470 groups.push(IommuGroup {
1471 id: groups.len() as u32,
1472 segment: sbdf.segment,
1473 bus: sbdf.bus,
1474 devices: alloc::vec![sbdf],
1475 });
1476 }
1477 }
1478 }
1479 groups
1480}
1481
1482pub fn init() {
1486 crate::serial_println!("[IOMMU] init: probing firmware tables");
1489 let discovery = crate::arch::iommu::init();
1490 load_reserved_regions();
1491 if discovery.present {
1492 crate::serial_println!(
1493 "[IOMMU] {} backend, {} DRHD unit(s), {} RMRR, {} ATSR, {} bit host width, \
1494 intr-remap={}, x2apic-opt-out={}, ready={}",
1495 discovery.backend,
1496 discovery.units,
1497 discovery.rmrrs,
1498 discovery.atsrs,
1499 discovery.host_address_width,
1500 discovery.intr_remap,
1501 discovery.x2apic_opt_out,
1502 discovery.ready
1503 );
1504 log::info!(
1505 "[IOMMU] {} backend, {} unit(s), ready={}",
1506 discovery.backend,
1507 discovery.units,
1508 discovery.ready
1509 );
1510 } else {
1511 crate::serial_println!("[IOMMU] no IOMMU firmware table found (DMA is untranslated)");
1512 }
1513}
1514
1515pub fn activate() -> bool {
1521 if HARDWARE_ENABLED.load(Ordering::Acquire) {
1522 return true;
1523 }
1524 let backend = crate::arch::iommu::backend();
1525 if !backend.is_ready() {
1526 return false;
1527 }
1528 if backend.activate().is_err() {
1529 return false;
1530 }
1531 HARDWARE_ENABLED.store(true, Ordering::Release);
1532 let mut global = STATS.lock();
1533 global.activations = global.activations.wrapping_add(1);
1534 true
1535}
1536
1537fn load_reserved_regions() {
1539 use crate::acpi::dmar::ScopeKind;
1540
1541 let Some(dmar) = crate::acpi::get_dmar() else {
1542 return;
1543 };
1544 let Ok(rmrrs) = dmar.rmrrs() else {
1545 return;
1546 };
1547
1548 let mut regions = Vec::new();
1549 for rmrr in rmrrs {
1550 let mut devices = Vec::new();
1551 let mut all_bus_from: Option<u8> = None;
1552 for scope in &rmrr.scopes {
1553 match scope.kind {
1554 ScopeKind::PciEndpoint => {
1555 if let Some((bus, device, function)) = scope.endpoint() {
1556 devices.push(Sbdf::new(rmrr.segment, bus, device, function));
1557 }
1558 }
1559 ScopeKind::PciSubHierarchy => {
1560 if scope.path.is_empty() {
1561 all_bus_from = Some(
1562 all_bus_from
1563 .map(|bus| bus.min(scope.start_bus))
1564 .unwrap_or(scope.start_bus),
1565 );
1566 } else if let Some(path) = scope.path.last() {
1567 devices.push(Sbdf::new(
1568 rmrr.segment,
1569 scope.start_bus,
1570 path.device,
1571 path.function,
1572 ));
1573 }
1574 }
1575 _ => {}
1576 }
1577 }
1578 if devices.is_empty() && all_bus_from.is_none() {
1579 let panic_on_invalid = PANIC_ON_INVALID_RMRR.load(Ordering::Acquire);
1580 if panic_on_invalid {
1581 panic!(
1582 "IOMMU: RMRR {:#x}..{:#x} has no device scope",
1583 rmrr.base, rmrr.limit
1584 );
1585 }
1586 log::warn!(
1587 "[IOMMU] ignoring RMRR {:#x}..{:#x} without a usable device scope",
1588 rmrr.base,
1589 rmrr.limit
1590 );
1591 continue;
1592 }
1593 regions.push(ReservedRegion {
1594 segment: rmrr.segment,
1595 base: rmrr.base,
1596 limit: rmrr.limit,
1597 devices,
1598 all_bus_from,
1599 identity_mapped: false,
1600 });
1601 }
1602
1603 if !regions.is_empty() {
1604 log::info!("[IOMMU] {} reserved region(s) from RMRR", regions.len());
1605 }
1606
1607 if let Some(ivrs) = crate::acpi::get_ivrs() {
1609 for md in ivrs.ivmd_blocks() {
1610 if md.typ != 0x20 && md.typ != 0x22 {
1611 continue;
1612 }
1613 let Some(end) = md.start_addr.checked_add(md.length_bytes) else {
1614 continue;
1615 };
1616 if end <= md.start_addr {
1617 continue;
1618 }
1619 let mut devices = Vec::new();
1620 let mut all_bus_from = None;
1621 if md.device_id == 0xffff {
1622 all_bus_from = Some(0);
1623 } else {
1624 let devfn = md.device_id;
1625 devices.push(Sbdf::new(
1626 md.pci_segment,
1627 (devfn >> 8) as u8,
1628 ((devfn >> 3) & 0x1f) as u8,
1629 (devfn & 0x7) as u8,
1630 ));
1631 }
1632 regions.push(ReservedRegion {
1633 segment: md.pci_segment,
1634 base: md.start_addr,
1635 limit: end - 1,
1636 devices,
1637 all_bus_from,
1638 identity_mapped: false,
1639 });
1640 }
1641 }
1642
1643 set_reserved_regions(regions, false);
1644}
1645
1646#[cfg(test)]
1647mod tests {
1648 use super::*;
1649
1650 #[test]
1651 fn sbdf_roundtrip() {
1652 let sbdf = Sbdf::new(2, 0x1f, 3, 5);
1653 assert_eq!(Sbdf::from_u32(sbdf.to_u32()), sbdf);
1654 }
1655
1656 #[test]
1657 fn map_translate_unmap() {
1658 let domain = Domain::new(DomainId(7), Sbdf::from_pci(0, 2, 0));
1659 domain
1660 .map(IOVA_BASE, 0x1000, 0x2000, DmaProt::READ_WRITE)
1661 .unwrap();
1662 let t = domain.translate(IOVA_BASE + 0x1800).unwrap();
1663 assert_eq!(t.phys, 0x2800);
1664 assert_eq!(t.remaining, 0x800);
1665 assert_eq!(domain.generation(), 1);
1666
1667 assert!(domain
1668 .map(IOVA_BASE, 0x9000, 0x1000, DmaProt::READ)
1669 .is_err());
1670 assert!(domain
1671 .map(IOVA_BASE - 0x1000, 0x9000, 0x3000, DmaProt::READ)
1672 .is_err());
1673
1674 assert_eq!(domain.unmap(IOVA_BASE, 0x2000).unwrap(), 1);
1675 assert!(domain.translate(IOVA_BASE).is_none());
1676 assert_eq!(domain.unmap(IOVA_BASE, 0x2000), Err(IommuError::NotMapped));
1677 }
1678
1679 #[test]
1680 fn auto_iova_skips_holes() {
1681 let domain = Domain::new(DomainId(9), Sbdf::from_pci(0, 3, 0));
1682 let a = domain.map_auto(0x10_0000, 0x1000, DmaProt::READ).unwrap();
1683 let b = domain.map_auto(0x20_0000, 0x1000, DmaProt::READ).unwrap();
1684 assert_eq!(a, IOVA_BASE);
1685 assert_eq!(b, IOVA_BASE + 0x1000);
1686 domain.unmap_exact(a).unwrap();
1687 let c = domain.map_auto(0x30_0000, 0x1000, DmaProt::READ).unwrap();
1688 assert_eq!(c, IOVA_BASE);
1689 }
1690
1691 #[test]
1692 fn dma_prot_bits() {
1693 assert!(DmaProt::READ_WRITE.contains(DmaProt::READ));
1694 assert!(DmaProt::READ_WRITE.contains(DmaProt::WRITE));
1695 assert!(!DmaProt::READ.contains(DmaProt::WRITE));
1696 assert!(DmaProt::READ.readable() && !DmaProt::READ.writable());
1697 assert_eq!(DmaProt::from_bits(0b100), None);
1698 assert_eq!(DmaProt::from_bits(0b11), Some(DmaProt::READ_WRITE));
1699 }
1700
1701 #[test]
1702 fn superpage_selection() {
1703 assert_eq!(
1704 MappingKind::best_for(IOVA_BASE, IOMMU_SUPERPAGE_2M),
1705 Some(MappingKind::Page2M)
1706 );
1707 assert_eq!(
1708 MappingKind::best_for(IOVA_BASE, IOMMU_SUPERPAGE_1G),
1709 Some(MappingKind::Page1G)
1710 );
1711 assert_eq!(
1713 MappingKind::best_for(IOVA_BASE + IOMMU_PAGE_SIZE, IOMMU_SUPERPAGE_2M),
1714 Some(MappingKind::Page4K)
1715 );
1716 assert_eq!(MappingKind::best_for(IOVA_BASE, 0), None);
1717 }
1718
1719 #[test]
1720 fn quiesce_refuses_new_mappings() {
1721 let domain = Domain::new(DomainId(21), Sbdf::from_pci(0, 5, 0));
1722 domain.quiesce();
1723 assert_eq!(
1724 domain.map(IOVA_BASE, 0x1000, 0x1000, DmaProt::READ),
1725 Err(IommuError::Quiesced)
1726 );
1727 domain.resume();
1728 assert!(domain.map(IOVA_BASE, 0x1000, 0x1000, DmaProt::READ).is_ok());
1729 }
1730
1731 #[test]
1732 fn reserved_regions_are_rejected() {
1733 let sbdf = Sbdf::from_pci(0, 6, 0);
1734 set_reserved_regions(
1735 alloc::vec![ReservedRegion {
1736 segment: 0,
1737 base: 0x8000,
1738 limit: 0x8fff,
1739 devices: alloc::vec![sbdf],
1740 all_bus_from: None,
1741 identity_mapped: false,
1742 }],
1743 false,
1744 );
1745 let domain = Domain::new(DomainId(22), sbdf);
1746 assert_eq!(
1747 domain.map(IOVA_BASE, 0x8000, 0x1000, DmaProt::READ),
1748 Err(IommuError::Reserved)
1749 );
1750 assert!(domain
1752 .map_reserved(0x8000, 0x8000, 0x1000, DmaProt::READ_WRITE)
1753 .is_ok());
1754 set_reserved_regions(alloc::vec![], false);
1755 }
1756
1757 #[test]
1758 fn fault_policy_kill_owner_records_the_action() {
1759 let domain = Domain::new_owned(
1760 DomainId(23),
1761 Sbdf::from_pci(0, 7, 0),
1762 Some(42),
1763 FaultPolicy::KillOwner,
1764 );
1765 let record = domain
1766 .report_fault(IOVA_BASE, FaultReason::Write, DmaProt::WRITE)
1767 .expect("fault queued");
1768 assert_eq!(record.owner, Some(42));
1769 assert_eq!(record.action, FaultAction::OwnerRevoked);
1770 assert_eq!(domain.stats().faults, 1);
1771 }
1772
1773 #[test]
1774 fn rejects_unaligned_and_empty() {
1775 let domain = Domain::new(DomainId(11), Sbdf::from_pci(0, 4, 0));
1776 assert_eq!(
1777 domain.map(IOVA_BASE + 1, 0x1000, 0x1000, DmaProt::READ),
1778 Err(IommuError::InvalidRange)
1779 );
1780 assert_eq!(
1781 domain.map(IOVA_BASE, 0x1000, 0, DmaProt::READ),
1782 Err(IommuError::InvalidRange)
1783 );
1784 }
1785}