xref: /cloud-hypervisor/virtio-devices/src/iommu.rs (revision 4ad44caa5217cf55eed512fc10fd68416a37d31c)
1 // Copyright © 2019 Intel Corporation
2 //
3 // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
4 
5 use super::Error as DeviceError;
6 use super::{
7     ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, VirtioCommon, VirtioDevice,
8     VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_VERSION_1,
9 };
10 use crate::seccomp_filters::Thread;
11 use crate::thread_helper::spawn_virtio_thread;
12 use crate::GuestMemoryMmap;
13 use crate::{DmaRemapping, VirtioInterrupt, VirtioInterruptType};
14 use anyhow::anyhow;
15 use seccompiler::SeccompAction;
16 use serde::{Deserialize, Serialize};
17 use std::collections::BTreeMap;
18 use std::io;
19 use std::mem::size_of;
20 use std::ops::Bound::Included;
21 use std::os::unix::io::AsRawFd;
22 use std::result;
23 use std::sync::atomic::{AtomicBool, Ordering};
24 use std::sync::{Arc, Barrier, Mutex, RwLock};
25 use thiserror::Error;
26 use virtio_queue::{DescriptorChain, Queue, QueueT};
27 use vm_device::dma_mapping::ExternalDmaMapping;
28 use vm_memory::{
29     Address, ByteValued, Bytes, GuestAddress, GuestAddressSpace, GuestMemoryAtomic,
30     GuestMemoryError, GuestMemoryLoadGuard,
31 };
32 use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable};
33 use vm_virtio::AccessPlatform;
34 use vmm_sys_util::eventfd::EventFd;
35 
36 /// Queues sizes
37 const QUEUE_SIZE: u16 = 256;
38 const NUM_QUEUES: usize = 2;
39 const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE; NUM_QUEUES];
40 
41 /// New descriptors are pending on the request queue.
42 /// "requestq" is meant to be used anytime an action is required to be
43 /// performed on behalf of the guest driver.
44 const REQUEST_Q_EVENT: u16 = EPOLL_HELPER_EVENT_LAST + 1;
45 /// New descriptors are pending on the event queue.
46 /// "eventq" lets the device report any fault or other asynchronous event to
47 /// the guest driver.
48 const _EVENT_Q_EVENT: u16 = EPOLL_HELPER_EVENT_LAST + 2;
49 
50 /// PROBE properties size.
51 /// This is the minimal size to provide at least one RESV_MEM property.
52 /// Because virtio-iommu expects one MSI reserved region, we must provide it,
53 /// otherwise the driver in the guest will define a predefined one between
54 /// 0x8000000 and 0x80FFFFF, which is only relevant for ARM architecture, but
55 /// will conflict with x86.
56 const PROBE_PROP_SIZE: u32 =
57     (size_of::<VirtioIommuProbeProperty>() + size_of::<VirtioIommuProbeResvMem>()) as u32;
58 
59 /// Virtio IOMMU features
60 #[allow(unused)]
61 const VIRTIO_IOMMU_F_INPUT_RANGE: u32 = 0;
62 #[allow(unused)]
63 const VIRTIO_IOMMU_F_DOMAIN_RANGE: u32 = 1;
64 #[allow(unused)]
65 const VIRTIO_IOMMU_F_MAP_UNMAP: u32 = 2;
66 #[allow(unused)]
67 const VIRTIO_IOMMU_F_BYPASS: u32 = 3;
68 const VIRTIO_IOMMU_F_PROBE: u32 = 4;
69 #[allow(unused)]
70 const VIRTIO_IOMMU_F_MMIO: u32 = 5;
71 const VIRTIO_IOMMU_F_BYPASS_CONFIG: u32 = 6;
72 
73 // Support 2MiB and 4KiB page sizes.
74 const VIRTIO_IOMMU_PAGE_SIZE_MASK: u64 = (2 << 20) | (4 << 10);
75 
76 #[derive(Copy, Clone, Debug, Default)]
77 #[repr(packed)]
78 #[allow(dead_code)]
79 struct VirtioIommuRange32 {
80     start: u32,
81     end: u32,
82 }
83 
84 #[derive(Copy, Clone, Debug, Default)]
85 #[repr(packed)]
86 #[allow(dead_code)]
87 struct VirtioIommuRange64 {
88     start: u64,
89     end: u64,
90 }
91 
92 #[derive(Copy, Clone, Debug, Default)]
93 #[repr(packed)]
94 #[allow(dead_code)]
95 struct VirtioIommuConfig {
96     page_size_mask: u64,
97     input_range: VirtioIommuRange64,
98     domain_range: VirtioIommuRange32,
99     probe_size: u32,
100     bypass: u8,
101     _reserved: [u8; 7],
102 }
103 
104 /// Virtio IOMMU request type
105 const VIRTIO_IOMMU_T_ATTACH: u8 = 1;
106 const VIRTIO_IOMMU_T_DETACH: u8 = 2;
107 const VIRTIO_IOMMU_T_MAP: u8 = 3;
108 const VIRTIO_IOMMU_T_UNMAP: u8 = 4;
109 const VIRTIO_IOMMU_T_PROBE: u8 = 5;
110 
111 #[derive(Copy, Clone, Debug, Default)]
112 #[repr(packed)]
113 struct VirtioIommuReqHead {
114     type_: u8,
115     _reserved: [u8; 3],
116 }
117 
118 /// Virtio IOMMU request status
119 const VIRTIO_IOMMU_S_OK: u8 = 0;
120 #[allow(unused)]
121 const VIRTIO_IOMMU_S_IOERR: u8 = 1;
122 #[allow(unused)]
123 const VIRTIO_IOMMU_S_UNSUPP: u8 = 2;
124 #[allow(unused)]
125 const VIRTIO_IOMMU_S_DEVERR: u8 = 3;
126 #[allow(unused)]
127 const VIRTIO_IOMMU_S_INVAL: u8 = 4;
128 #[allow(unused)]
129 const VIRTIO_IOMMU_S_RANGE: u8 = 5;
130 #[allow(unused)]
131 const VIRTIO_IOMMU_S_NOENT: u8 = 6;
132 #[allow(unused)]
133 const VIRTIO_IOMMU_S_FAULT: u8 = 7;
134 #[allow(unused)]
135 const VIRTIO_IOMMU_S_NOMEM: u8 = 8;
136 
137 #[derive(Copy, Clone, Debug, Default)]
138 #[repr(packed)]
139 #[allow(dead_code)]
140 struct VirtioIommuReqTail {
141     status: u8,
142     _reserved: [u8; 3],
143 }
144 
145 /// ATTACH request
146 #[derive(Copy, Clone, Debug, Default)]
147 #[repr(packed)]
148 struct VirtioIommuReqAttach {
149     domain: u32,
150     endpoint: u32,
151     flags: u32,
152     _reserved: [u8; 4],
153 }
154 
155 const VIRTIO_IOMMU_ATTACH_F_BYPASS: u32 = 1;
156 
157 /// DETACH request
158 #[derive(Copy, Clone, Debug, Default)]
159 #[repr(packed)]
160 struct VirtioIommuReqDetach {
161     domain: u32,
162     endpoint: u32,
163     _reserved: [u8; 8],
164 }
165 
166 /// Virtio IOMMU request MAP flags
167 #[allow(unused)]
168 const VIRTIO_IOMMU_MAP_F_READ: u32 = 1;
169 #[allow(unused)]
170 const VIRTIO_IOMMU_MAP_F_WRITE: u32 = 1 << 1;
171 #[allow(unused)]
172 const VIRTIO_IOMMU_MAP_F_MMIO: u32 = 1 << 2;
173 #[allow(unused)]
174 const VIRTIO_IOMMU_MAP_F_MASK: u32 =
175     VIRTIO_IOMMU_MAP_F_READ | VIRTIO_IOMMU_MAP_F_WRITE | VIRTIO_IOMMU_MAP_F_MMIO;
176 
177 /// MAP request
178 #[derive(Copy, Clone, Debug, Default)]
179 #[repr(packed)]
180 struct VirtioIommuReqMap {
181     domain: u32,
182     virt_start: u64,
183     virt_end: u64,
184     phys_start: u64,
185     _flags: u32,
186 }
187 
188 /// UNMAP request
189 #[derive(Copy, Clone, Debug, Default)]
190 #[repr(packed)]
191 struct VirtioIommuReqUnmap {
192     domain: u32,
193     virt_start: u64,
194     virt_end: u64,
195     _reserved: [u8; 4],
196 }
197 
198 /// Virtio IOMMU request PROBE types
199 #[allow(unused)]
200 const VIRTIO_IOMMU_PROBE_T_NONE: u16 = 0;
201 const VIRTIO_IOMMU_PROBE_T_RESV_MEM: u16 = 1;
202 #[allow(unused)]
203 const VIRTIO_IOMMU_PROBE_T_MASK: u16 = 0xfff;
204 
205 /// PROBE request
206 #[derive(Copy, Clone, Debug, Default)]
207 #[repr(packed)]
208 #[allow(dead_code)]
209 struct VirtioIommuReqProbe {
210     endpoint: u32,
211     _reserved: [u64; 8],
212 }
213 
214 #[derive(Copy, Clone, Debug, Default)]
215 #[repr(packed)]
216 #[allow(dead_code)]
217 struct VirtioIommuProbeProperty {
218     type_: u16,
219     length: u16,
220 }
221 
222 /// Virtio IOMMU request PROBE property RESV_MEM subtypes
223 #[allow(unused)]
224 const VIRTIO_IOMMU_RESV_MEM_T_RESERVED: u8 = 0;
225 const VIRTIO_IOMMU_RESV_MEM_T_MSI: u8 = 1;
226 
227 #[derive(Copy, Clone, Debug, Default)]
228 #[repr(packed)]
229 #[allow(dead_code)]
230 struct VirtioIommuProbeResvMem {
231     subtype: u8,
232     _reserved: [u8; 3],
233     start: u64,
234     end: u64,
235 }
236 
237 /// Virtio IOMMU fault flags
238 #[allow(unused)]
239 const VIRTIO_IOMMU_FAULT_F_READ: u32 = 1;
240 #[allow(unused)]
241 const VIRTIO_IOMMU_FAULT_F_WRITE: u32 = 1 << 1;
242 #[allow(unused)]
243 const VIRTIO_IOMMU_FAULT_F_EXEC: u32 = 1 << 2;
244 #[allow(unused)]
245 const VIRTIO_IOMMU_FAULT_F_ADDRESS: u32 = 1 << 8;
246 
247 /// Virtio IOMMU fault reasons
248 #[allow(unused)]
249 const VIRTIO_IOMMU_FAULT_R_UNKNOWN: u32 = 0;
250 #[allow(unused)]
251 const VIRTIO_IOMMU_FAULT_R_DOMAIN: u32 = 1;
252 #[allow(unused)]
253 const VIRTIO_IOMMU_FAULT_R_MAPPING: u32 = 2;
254 
255 /// Fault reporting through eventq
256 #[allow(unused)]
257 #[derive(Copy, Clone, Debug, Default)]
258 #[repr(packed)]
259 struct VirtioIommuFault {
260     reason: u8,
261     reserved: [u8; 3],
262     flags: u32,
263     endpoint: u32,
264     reserved2: [u8; 4],
265     address: u64,
266 }
267 
268 // SAFETY: data structure only contain integers and have no implicit padding
269 unsafe impl ByteValued for VirtioIommuRange32 {}
270 // SAFETY: data structure only contain integers and have no implicit padding
271 unsafe impl ByteValued for VirtioIommuRange64 {}
272 // SAFETY: data structure only contain integers and have no implicit padding
273 unsafe impl ByteValued for VirtioIommuConfig {}
274 // SAFETY: data structure only contain integers and have no implicit padding
275 unsafe impl ByteValued for VirtioIommuReqHead {}
276 // SAFETY: data structure only contain integers and have no implicit padding
277 unsafe impl ByteValued for VirtioIommuReqTail {}
278 // SAFETY: data structure only contain integers and have no implicit padding
279 unsafe impl ByteValued for VirtioIommuReqAttach {}
280 // SAFETY: data structure only contain integers and have no implicit padding
281 unsafe impl ByteValued for VirtioIommuReqDetach {}
282 // SAFETY: data structure only contain integers and have no implicit padding
283 unsafe impl ByteValued for VirtioIommuReqMap {}
284 // SAFETY: data structure only contain integers and have no implicit padding
285 unsafe impl ByteValued for VirtioIommuReqUnmap {}
286 // SAFETY: data structure only contain integers and have no implicit padding
287 unsafe impl ByteValued for VirtioIommuReqProbe {}
288 // SAFETY: data structure only contain integers and have no implicit padding
289 unsafe impl ByteValued for VirtioIommuProbeProperty {}
290 // SAFETY: data structure only contain integers and have no implicit padding
291 unsafe impl ByteValued for VirtioIommuProbeResvMem {}
292 // SAFETY: data structure only contain integers and have no implicit padding
293 unsafe impl ByteValued for VirtioIommuFault {}
294 
295 #[derive(Error, Debug)]
296 enum Error {
297     #[error("Guest gave us bad memory addresses: {0}")]
298     GuestMemory(GuestMemoryError),
299     #[error("Guest gave us a write only descriptor that protocol says to read from")]
300     UnexpectedWriteOnlyDescriptor,
301     #[error("Guest gave us a read only descriptor that protocol says to write to")]
302     UnexpectedReadOnlyDescriptor,
303     #[error("Guest gave us too few descriptors in a descriptor chain")]
304     DescriptorChainTooShort,
305     #[error("Guest gave us a buffer that was too short to use")]
306     BufferLengthTooSmall,
307     #[error("Guest sent us invalid request")]
308     InvalidRequest,
309     #[error("Guest sent us invalid ATTACH request")]
310     InvalidAttachRequest,
311     #[error("Guest sent us invalid DETACH request")]
312     InvalidDetachRequest,
313     #[error("Guest sent us invalid MAP request")]
314     InvalidMapRequest,
315     #[error("Invalid to map because the domain is in bypass mode")]
316     InvalidMapRequestBypassDomain,
317     #[error("Invalid to map because the domain is missing")]
318     InvalidMapRequestMissingDomain,
319     #[error("Guest sent us invalid UNMAP request")]
320     InvalidUnmapRequest,
321     #[error("Invalid to unmap because the domain is in bypass mode")]
322     InvalidUnmapRequestBypassDomain,
323     #[error("Invalid to unmap because the domain is missing")]
324     InvalidUnmapRequestMissingDomain,
325     #[error("Guest sent us invalid PROBE request")]
326     InvalidProbeRequest,
327     #[error("Failed to performing external mapping: {0}")]
328     ExternalMapping(io::Error),
329     #[error("Failed to performing external unmapping: {0}")]
330     ExternalUnmapping(io::Error),
331     #[error("Failed adding used index: {0}")]
332     QueueAddUsed(virtio_queue::Error),
333 }
334 
335 struct Request {}
336 
337 impl Request {
338     // Parse the available vring buffer. Based on the hashmap table of external
339     // mappings required from various devices such as VFIO or vhost-user ones,
340     // this function might update the hashmap table of external mappings per
341     // domain.
342     // Basically, the VMM knows about the device_id <=> mapping relationship
343     // before running the VM, but at runtime, a new domain <=> mapping hashmap
344     // is created based on the information provided from the guest driver for
345     // virtio-iommu (giving the link device_id <=> domain).
346     fn parse(
347         desc_chain: &mut DescriptorChain<GuestMemoryLoadGuard<GuestMemoryMmap>>,
348         mapping: &Arc<IommuMapping>,
349         ext_mapping: &BTreeMap<u32, Arc<dyn ExternalDmaMapping>>,
350         msi_iova_space: (u64, u64),
351     ) -> result::Result<usize, Error> {
352         let desc = desc_chain
353             .next()
354             .ok_or(Error::DescriptorChainTooShort)
355             .inspect_err(|_| {
356                 error!("Missing head descriptor");
357             })?;
358 
359         // The descriptor contains the request type which MUST be readable.
360         if desc.is_write_only() {
361             return Err(Error::UnexpectedWriteOnlyDescriptor);
362         }
363 
364         if (desc.len() as usize) < size_of::<VirtioIommuReqHead>() {
365             return Err(Error::InvalidRequest);
366         }
367 
368         let req_head: VirtioIommuReqHead = desc_chain
369             .memory()
370             .read_obj(desc.addr())
371             .map_err(Error::GuestMemory)?;
372         let req_offset = size_of::<VirtioIommuReqHead>();
373         let desc_size_left = (desc.len() as usize) - req_offset;
374         let req_addr = if let Some(addr) = desc.addr().checked_add(req_offset as u64) {
375             addr
376         } else {
377             return Err(Error::InvalidRequest);
378         };
379 
380         let (msi_iova_start, msi_iova_end) = msi_iova_space;
381 
382         // Create the reply
383         let mut reply: Vec<u8> = Vec::new();
384         let mut status = VIRTIO_IOMMU_S_OK;
385         let mut hdr_len = 0;
386 
387         let result = (|| {
388             match req_head.type_ {
389                 VIRTIO_IOMMU_T_ATTACH => {
390                     if desc_size_left != size_of::<VirtioIommuReqAttach>() {
391                         status = VIRTIO_IOMMU_S_INVAL;
392                         return Err(Error::InvalidAttachRequest);
393                     }
394 
395                     let req: VirtioIommuReqAttach = desc_chain
396                         .memory()
397                         .read_obj(req_addr as GuestAddress)
398                         .map_err(Error::GuestMemory)?;
399                     debug!("Attach request {:?}", req);
400 
401                     // Copy the value to use it as a proper reference.
402                     let domain_id = req.domain;
403                     let endpoint = req.endpoint;
404                     let bypass =
405                         (req.flags & VIRTIO_IOMMU_ATTACH_F_BYPASS) == VIRTIO_IOMMU_ATTACH_F_BYPASS;
406 
407                     let mut old_domain_id = domain_id;
408                     if let Some(&id) = mapping.endpoints.read().unwrap().get(&endpoint) {
409                         old_domain_id = id;
410                     }
411 
412                     if old_domain_id != domain_id {
413                         detach_endpoint_from_domain(endpoint, old_domain_id, mapping, ext_mapping)?;
414                     }
415 
416                     // Add endpoint associated with specific domain
417                     mapping
418                         .endpoints
419                         .write()
420                         .unwrap()
421                         .insert(endpoint, domain_id);
422 
423                     // If any other mappings exist in the domain for other containers,
424                     // make sure to issue these mappings for the new endpoint/container
425                     if let Some(domain_mappings) = &mapping.domains.read().unwrap().get(&domain_id)
426                     {
427                         if let Some(ext_map) = ext_mapping.get(&endpoint) {
428                             for (virt_start, addr_map) in &domain_mappings.mappings {
429                                 ext_map
430                                     .map(*virt_start, addr_map.gpa, addr_map.size)
431                                     .map_err(Error::ExternalUnmapping)?;
432                             }
433                         }
434                     }
435 
436                     // Add new domain with no mapping if the entry didn't exist yet
437                     let mut domains = mapping.domains.write().unwrap();
438                     let domain = Domain {
439                         mappings: BTreeMap::new(),
440                         bypass,
441                     };
442                     domains.entry(domain_id).or_insert_with(|| domain);
443                 }
444                 VIRTIO_IOMMU_T_DETACH => {
445                     if desc_size_left != size_of::<VirtioIommuReqDetach>() {
446                         status = VIRTIO_IOMMU_S_INVAL;
447                         return Err(Error::InvalidDetachRequest);
448                     }
449 
450                     let req: VirtioIommuReqDetach = desc_chain
451                         .memory()
452                         .read_obj(req_addr as GuestAddress)
453                         .map_err(Error::GuestMemory)?;
454                     debug!("Detach request {:?}", req);
455 
456                     // Copy the value to use it as a proper reference.
457                     let domain_id = req.domain;
458                     let endpoint = req.endpoint;
459 
460                     // Remove endpoint associated with specific domain
461                     detach_endpoint_from_domain(endpoint, domain_id, mapping, ext_mapping)?;
462                 }
463                 VIRTIO_IOMMU_T_MAP => {
464                     if desc_size_left != size_of::<VirtioIommuReqMap>() {
465                         status = VIRTIO_IOMMU_S_INVAL;
466                         return Err(Error::InvalidMapRequest);
467                     }
468 
469                     let req: VirtioIommuReqMap = desc_chain
470                         .memory()
471                         .read_obj(req_addr as GuestAddress)
472                         .map_err(Error::GuestMemory)?;
473                     debug!("Map request {:?}", req);
474 
475                     // Copy the value to use it as a proper reference.
476                     let domain_id = req.domain;
477 
478                     if let Some(domain) = mapping.domains.read().unwrap().get(&domain_id) {
479                         if domain.bypass {
480                             status = VIRTIO_IOMMU_S_INVAL;
481                             return Err(Error::InvalidMapRequestBypassDomain);
482                         }
483                     } else {
484                         status = VIRTIO_IOMMU_S_INVAL;
485                         return Err(Error::InvalidMapRequestMissingDomain);
486                     }
487 
488                     // Find the list of endpoints attached to the given domain.
489                     let endpoints: Vec<u32> = mapping
490                         .endpoints
491                         .write()
492                         .unwrap()
493                         .iter()
494                         .filter(|(_, &d)| d == domain_id)
495                         .map(|(&e, _)| e)
496                         .collect();
497 
498                     // For viommu all endpoints receive their own VFIO container, as a result
499                     // Each endpoint within the domain needs to be separately mapped, as the
500                     // mapping is done on a per-container level, not a per-domain level
501                     for endpoint in endpoints {
502                         if let Some(ext_map) = ext_mapping.get(&endpoint) {
503                             let size = req.virt_end - req.virt_start + 1;
504                             ext_map
505                                 .map(req.virt_start, req.phys_start, size)
506                                 .map_err(Error::ExternalMapping)?;
507                         }
508                     }
509 
510                     // Add new mapping associated with the domain
511                     mapping
512                         .domains
513                         .write()
514                         .unwrap()
515                         .get_mut(&domain_id)
516                         .unwrap()
517                         .mappings
518                         .insert(
519                             req.virt_start,
520                             Mapping {
521                                 gpa: req.phys_start,
522                                 size: req.virt_end - req.virt_start + 1,
523                             },
524                         );
525                 }
526                 VIRTIO_IOMMU_T_UNMAP => {
527                     if desc_size_left != size_of::<VirtioIommuReqUnmap>() {
528                         status = VIRTIO_IOMMU_S_INVAL;
529                         return Err(Error::InvalidUnmapRequest);
530                     }
531 
532                     let req: VirtioIommuReqUnmap = desc_chain
533                         .memory()
534                         .read_obj(req_addr as GuestAddress)
535                         .map_err(Error::GuestMemory)?;
536                     debug!("Unmap request {:?}", req);
537 
538                     // Copy the value to use it as a proper reference.
539                     let domain_id = req.domain;
540                     let virt_start = req.virt_start;
541 
542                     if let Some(domain) = mapping.domains.read().unwrap().get(&domain_id) {
543                         if domain.bypass {
544                             status = VIRTIO_IOMMU_S_INVAL;
545                             return Err(Error::InvalidUnmapRequestBypassDomain);
546                         }
547                     } else {
548                         status = VIRTIO_IOMMU_S_INVAL;
549                         return Err(Error::InvalidUnmapRequestMissingDomain);
550                     }
551 
552                     // Find the list of endpoints attached to the given domain.
553                     let endpoints: Vec<u32> = mapping
554                         .endpoints
555                         .write()
556                         .unwrap()
557                         .iter()
558                         .filter(|(_, &d)| d == domain_id)
559                         .map(|(&e, _)| e)
560                         .collect();
561 
562                     // Trigger external unmapping if necessary.
563                     for endpoint in endpoints {
564                         if let Some(ext_map) = ext_mapping.get(&endpoint) {
565                             let size = req.virt_end - virt_start + 1;
566                             ext_map
567                                 .unmap(virt_start, size)
568                                 .map_err(Error::ExternalUnmapping)?;
569                         }
570                     }
571 
572                     // Remove all mappings associated with the domain within the requested range
573                     mapping
574                         .domains
575                         .write()
576                         .unwrap()
577                         .get_mut(&domain_id)
578                         .unwrap()
579                         .mappings
580                         .retain(|&x, _| (x < req.virt_start || x > req.virt_end));
581                 }
582                 VIRTIO_IOMMU_T_PROBE => {
583                     if desc_size_left != size_of::<VirtioIommuReqProbe>() {
584                         status = VIRTIO_IOMMU_S_INVAL;
585                         return Err(Error::InvalidProbeRequest);
586                     }
587 
588                     let req: VirtioIommuReqProbe = desc_chain
589                         .memory()
590                         .read_obj(req_addr as GuestAddress)
591                         .map_err(Error::GuestMemory)?;
592                     debug!("Probe request {:?}", req);
593 
594                     let probe_prop = VirtioIommuProbeProperty {
595                         type_: VIRTIO_IOMMU_PROBE_T_RESV_MEM,
596                         length: size_of::<VirtioIommuProbeResvMem>() as u16,
597                     };
598                     reply.extend_from_slice(probe_prop.as_slice());
599 
600                     let resv_mem = VirtioIommuProbeResvMem {
601                         subtype: VIRTIO_IOMMU_RESV_MEM_T_MSI,
602                         start: msi_iova_start,
603                         end: msi_iova_end,
604                         ..Default::default()
605                     };
606                     reply.extend_from_slice(resv_mem.as_slice());
607 
608                     hdr_len = PROBE_PROP_SIZE;
609                 }
610                 _ => {
611                     status = VIRTIO_IOMMU_S_INVAL;
612                     return Err(Error::InvalidRequest);
613                 }
614             }
615             Ok(())
616         })();
617 
618         let status_desc = desc_chain.next().ok_or(Error::DescriptorChainTooShort)?;
619 
620         // The status MUST always be writable
621         if !status_desc.is_write_only() {
622             return Err(Error::UnexpectedReadOnlyDescriptor);
623         }
624 
625         if status_desc.len() < hdr_len + size_of::<VirtioIommuReqTail>() as u32 {
626             return Err(Error::BufferLengthTooSmall);
627         }
628 
629         let tail = VirtioIommuReqTail {
630             status,
631             ..Default::default()
632         };
633         reply.extend_from_slice(tail.as_slice());
634 
635         // Make sure we return the result of the request to the guest before
636         // we return a potential error internally.
637         desc_chain
638             .memory()
639             .write_slice(reply.as_slice(), status_desc.addr())
640             .map_err(Error::GuestMemory)?;
641 
642         // Return the error if the result was not Ok().
643         result?;
644 
645         Ok((hdr_len as usize) + size_of::<VirtioIommuReqTail>())
646     }
647 }
648 
649 fn detach_endpoint_from_domain(
650     endpoint: u32,
651     domain_id: u32,
652     mapping: &Arc<IommuMapping>,
653     ext_mapping: &BTreeMap<u32, Arc<dyn ExternalDmaMapping>>,
654 ) -> result::Result<(), Error> {
655     // Remove endpoint associated with specific domain
656     mapping.endpoints.write().unwrap().remove(&endpoint);
657 
658     // Trigger external unmapping for the endpoint if necessary.
659     if let Some(domain_mappings) = &mapping.domains.read().unwrap().get(&domain_id) {
660         if let Some(ext_map) = ext_mapping.get(&endpoint) {
661             for (virt_start, addr_map) in &domain_mappings.mappings {
662                 ext_map
663                     .unmap(*virt_start, addr_map.size)
664                     .map_err(Error::ExternalUnmapping)?;
665             }
666         }
667     }
668 
669     if mapping
670         .endpoints
671         .write()
672         .unwrap()
673         .iter()
674         .filter(|(_, &d)| d == domain_id)
675         .count()
676         == 0
677     {
678         mapping.domains.write().unwrap().remove(&domain_id);
679     }
680 
681     Ok(())
682 }
683 
684 struct IommuEpollHandler {
685     mem: GuestMemoryAtomic<GuestMemoryMmap>,
686     request_queue: Queue,
687     _event_queue: Queue,
688     interrupt_cb: Arc<dyn VirtioInterrupt>,
689     request_queue_evt: EventFd,
690     _event_queue_evt: EventFd,
691     kill_evt: EventFd,
692     pause_evt: EventFd,
693     mapping: Arc<IommuMapping>,
694     ext_mapping: Arc<Mutex<BTreeMap<u32, Arc<dyn ExternalDmaMapping>>>>,
695     msi_iova_space: (u64, u64),
696 }
697 
698 impl IommuEpollHandler {
699     fn request_queue(&mut self) -> Result<bool, Error> {
700         let mut used_descs = false;
701         while let Some(mut desc_chain) = self.request_queue.pop_descriptor_chain(self.mem.memory())
702         {
703             let len = Request::parse(
704                 &mut desc_chain,
705                 &self.mapping,
706                 &self.ext_mapping.lock().unwrap(),
707                 self.msi_iova_space,
708             )?;
709 
710             self.request_queue
711                 .add_used(desc_chain.memory(), desc_chain.head_index(), len as u32)
712                 .map_err(Error::QueueAddUsed)?;
713 
714             used_descs = true;
715         }
716 
717         Ok(used_descs)
718     }
719 
720     fn signal_used_queue(&self, queue_index: u16) -> result::Result<(), DeviceError> {
721         self.interrupt_cb
722             .trigger(VirtioInterruptType::Queue(queue_index))
723             .map_err(|e| {
724                 error!("Failed to signal used queue: {:?}", e);
725                 DeviceError::FailedSignalingUsedQueue(e)
726             })
727     }
728 
729     fn run(
730         &mut self,
731         paused: Arc<AtomicBool>,
732         paused_sync: Arc<Barrier>,
733     ) -> result::Result<(), EpollHelperError> {
734         let mut helper = EpollHelper::new(&self.kill_evt, &self.pause_evt)?;
735         helper.add_event(self.request_queue_evt.as_raw_fd(), REQUEST_Q_EVENT)?;
736         helper.run(paused, paused_sync, self)?;
737 
738         Ok(())
739     }
740 }
741 
742 impl EpollHelperHandler for IommuEpollHandler {
743     fn handle_event(
744         &mut self,
745         _helper: &mut EpollHelper,
746         event: &epoll::Event,
747     ) -> result::Result<(), EpollHelperError> {
748         let ev_type = event.data as u16;
749         match ev_type {
750             REQUEST_Q_EVENT => {
751                 self.request_queue_evt.read().map_err(|e| {
752                     EpollHelperError::HandleEvent(anyhow!("Failed to get queue event: {:?}", e))
753                 })?;
754 
755                 let needs_notification = self.request_queue().map_err(|e| {
756                     EpollHelperError::HandleEvent(anyhow!(
757                         "Failed to process request queue : {:?}",
758                         e
759                     ))
760                 })?;
761                 if needs_notification {
762                     self.signal_used_queue(0).map_err(|e| {
763                         EpollHelperError::HandleEvent(anyhow!(
764                             "Failed to signal used queue: {:?}",
765                             e
766                         ))
767                     })?;
768                 }
769             }
770             _ => {
771                 return Err(EpollHelperError::HandleEvent(anyhow!(
772                     "Unexpected event: {}",
773                     ev_type
774                 )));
775             }
776         }
777         Ok(())
778     }
779 }
780 
781 #[derive(Clone, Copy, Debug, Serialize, Deserialize)]
782 struct Mapping {
783     gpa: u64,
784     size: u64,
785 }
786 
787 #[derive(Clone, Debug)]
788 struct Domain {
789     mappings: BTreeMap<u64, Mapping>,
790     bypass: bool,
791 }
792 
793 #[derive(Debug)]
794 pub struct IommuMapping {
795     // Domain related to an endpoint.
796     endpoints: Arc<RwLock<BTreeMap<u32, u32>>>,
797     // Information related to each domain.
798     domains: Arc<RwLock<BTreeMap<u32, Domain>>>,
799     // Global flag indicating if endpoints that are not attached to any domain
800     // are in bypass mode.
801     bypass: AtomicBool,
802 }
803 
804 impl DmaRemapping for IommuMapping {
805     fn translate_gva(&self, id: u32, addr: u64) -> std::result::Result<u64, std::io::Error> {
806         debug!("Translate GVA addr 0x{:x}", addr);
807         if let Some(domain_id) = self.endpoints.read().unwrap().get(&id) {
808             if let Some(domain) = self.domains.read().unwrap().get(domain_id) {
809                 // Directly return identity mapping in case the domain is in
810                 // bypass mode.
811                 if domain.bypass {
812                     return Ok(addr);
813                 }
814 
815                 let range_start = if VIRTIO_IOMMU_PAGE_SIZE_MASK > addr {
816                     0
817                 } else {
818                     addr - VIRTIO_IOMMU_PAGE_SIZE_MASK
819                 };
820                 for (&key, &value) in domain
821                     .mappings
822                     .range((Included(&range_start), Included(&addr)))
823                 {
824                     if addr >= key && addr < key + value.size {
825                         let new_addr = addr - key + value.gpa;
826                         debug!("Into GPA addr 0x{:x}", new_addr);
827                         return Ok(new_addr);
828                     }
829                 }
830             }
831         } else if self.bypass.load(Ordering::Acquire) {
832             return Ok(addr);
833         }
834 
835         Err(io::Error::new(
836             io::ErrorKind::Other,
837             format!("failed to translate GVA addr 0x{addr:x}"),
838         ))
839     }
840 
841     fn translate_gpa(&self, id: u32, addr: u64) -> std::result::Result<u64, std::io::Error> {
842         debug!("Translate GPA addr 0x{:x}", addr);
843         if let Some(domain_id) = self.endpoints.read().unwrap().get(&id) {
844             if let Some(domain) = self.domains.read().unwrap().get(domain_id) {
845                 // Directly return identity mapping in case the domain is in
846                 // bypass mode.
847                 if domain.bypass {
848                     return Ok(addr);
849                 }
850 
851                 for (&key, &value) in domain.mappings.iter() {
852                     if addr >= value.gpa && addr < value.gpa + value.size {
853                         let new_addr = addr - value.gpa + key;
854                         debug!("Into GVA addr 0x{:x}", new_addr);
855                         return Ok(new_addr);
856                     }
857                 }
858             }
859         } else if self.bypass.load(Ordering::Acquire) {
860             return Ok(addr);
861         }
862 
863         Err(io::Error::new(
864             io::ErrorKind::Other,
865             format!("failed to translate GPA addr 0x{addr:x}"),
866         ))
867     }
868 }
869 
870 #[derive(Debug)]
871 pub struct AccessPlatformMapping {
872     id: u32,
873     mapping: Arc<IommuMapping>,
874 }
875 
876 impl AccessPlatformMapping {
877     pub fn new(id: u32, mapping: Arc<IommuMapping>) -> Self {
878         AccessPlatformMapping { id, mapping }
879     }
880 }
881 
882 impl AccessPlatform for AccessPlatformMapping {
883     fn translate_gva(&self, base: u64, _size: u64) -> std::result::Result<u64, std::io::Error> {
884         self.mapping.translate_gva(self.id, base)
885     }
886     fn translate_gpa(&self, base: u64, _size: u64) -> std::result::Result<u64, std::io::Error> {
887         self.mapping.translate_gpa(self.id, base)
888     }
889 }
890 
891 pub struct Iommu {
892     common: VirtioCommon,
893     id: String,
894     config: VirtioIommuConfig,
895     mapping: Arc<IommuMapping>,
896     ext_mapping: Arc<Mutex<BTreeMap<u32, Arc<dyn ExternalDmaMapping>>>>,
897     seccomp_action: SeccompAction,
898     exit_evt: EventFd,
899     msi_iova_space: (u64, u64),
900 }
901 
902 type EndpointsState = Vec<(u32, u32)>;
903 type DomainsState = Vec<(u32, (Vec<(u64, Mapping)>, bool))>;
904 
905 #[derive(Serialize, Deserialize)]
906 pub struct IommuState {
907     avail_features: u64,
908     acked_features: u64,
909     endpoints: EndpointsState,
910     domains: DomainsState,
911 }
912 
913 impl Iommu {
914     pub fn new(
915         id: String,
916         seccomp_action: SeccompAction,
917         exit_evt: EventFd,
918         msi_iova_space: (u64, u64),
919         state: Option<IommuState>,
920     ) -> io::Result<(Self, Arc<IommuMapping>)> {
921         let (avail_features, acked_features, endpoints, domains, paused) =
922             if let Some(state) = state {
923                 info!("Restoring virtio-iommu {}", id);
924                 (
925                     state.avail_features,
926                     state.acked_features,
927                     state.endpoints.into_iter().collect(),
928                     state
929                         .domains
930                         .into_iter()
931                         .map(|(k, v)| {
932                             (
933                                 k,
934                                 Domain {
935                                     mappings: v.0.into_iter().collect(),
936                                     bypass: v.1,
937                                 },
938                             )
939                         })
940                         .collect(),
941                     true,
942                 )
943             } else {
944                 let avail_features = 1u64 << VIRTIO_F_VERSION_1
945                     | 1u64 << VIRTIO_IOMMU_F_MAP_UNMAP
946                     | 1u64 << VIRTIO_IOMMU_F_PROBE
947                     | 1u64 << VIRTIO_IOMMU_F_BYPASS_CONFIG;
948 
949                 (avail_features, 0, BTreeMap::new(), BTreeMap::new(), false)
950             };
951 
952         let config = VirtioIommuConfig {
953             page_size_mask: VIRTIO_IOMMU_PAGE_SIZE_MASK,
954             probe_size: PROBE_PROP_SIZE,
955             ..Default::default()
956         };
957 
958         let mapping = Arc::new(IommuMapping {
959             endpoints: Arc::new(RwLock::new(endpoints)),
960             domains: Arc::new(RwLock::new(domains)),
961             bypass: AtomicBool::new(true),
962         });
963 
964         Ok((
965             Iommu {
966                 id,
967                 common: VirtioCommon {
968                     device_type: VirtioDeviceType::Iommu as u32,
969                     queue_sizes: QUEUE_SIZES.to_vec(),
970                     avail_features,
971                     acked_features,
972                     paused_sync: Some(Arc::new(Barrier::new(2))),
973                     min_queues: NUM_QUEUES as u16,
974                     paused: Arc::new(AtomicBool::new(paused)),
975                     ..Default::default()
976                 },
977                 config,
978                 mapping: mapping.clone(),
979                 ext_mapping: Arc::new(Mutex::new(BTreeMap::new())),
980                 seccomp_action,
981                 exit_evt,
982                 msi_iova_space,
983             },
984             mapping,
985         ))
986     }
987 
988     fn state(&self) -> IommuState {
989         IommuState {
990             avail_features: self.common.avail_features,
991             acked_features: self.common.acked_features,
992             endpoints: self
993                 .mapping
994                 .endpoints
995                 .read()
996                 .unwrap()
997                 .clone()
998                 .into_iter()
999                 .collect(),
1000             domains: self
1001                 .mapping
1002                 .domains
1003                 .read()
1004                 .unwrap()
1005                 .clone()
1006                 .into_iter()
1007                 .map(|(k, v)| (k, (v.mappings.into_iter().collect(), v.bypass)))
1008                 .collect(),
1009         }
1010     }
1011 
1012     fn update_bypass(&mut self) {
1013         // Use bypass from config if VIRTIO_IOMMU_F_BYPASS_CONFIG has been negotiated
1014         if !self
1015             .common
1016             .feature_acked(VIRTIO_IOMMU_F_BYPASS_CONFIG.into())
1017         {
1018             return;
1019         }
1020 
1021         let bypass = self.config.bypass == 1;
1022         info!("Updating bypass mode to {}", bypass);
1023         self.mapping.bypass.store(bypass, Ordering::Release);
1024     }
1025 
1026     pub fn add_external_mapping(&mut self, device_id: u32, mapping: Arc<dyn ExternalDmaMapping>) {
1027         self.ext_mapping.lock().unwrap().insert(device_id, mapping);
1028     }
1029 
1030     #[cfg(fuzzing)]
1031     pub fn wait_for_epoll_threads(&mut self) {
1032         self.common.wait_for_epoll_threads();
1033     }
1034 }
1035 
1036 impl Drop for Iommu {
1037     fn drop(&mut self) {
1038         if let Some(kill_evt) = self.common.kill_evt.take() {
1039             // Ignore the result because there is nothing we can do about it.
1040             let _ = kill_evt.write(1);
1041         }
1042         self.common.wait_for_epoll_threads();
1043     }
1044 }
1045 
1046 impl VirtioDevice for Iommu {
1047     fn device_type(&self) -> u32 {
1048         self.common.device_type
1049     }
1050 
1051     fn queue_max_sizes(&self) -> &[u16] {
1052         &self.common.queue_sizes
1053     }
1054 
1055     fn features(&self) -> u64 {
1056         self.common.avail_features
1057     }
1058 
1059     fn ack_features(&mut self, value: u64) {
1060         self.common.ack_features(value)
1061     }
1062 
1063     fn read_config(&self, offset: u64, data: &mut [u8]) {
1064         self.read_config_from_slice(self.config.as_slice(), offset, data);
1065     }
1066 
1067     fn write_config(&mut self, offset: u64, data: &[u8]) {
1068         // The "bypass" field is the only mutable field
1069         let bypass_offset =
1070             (&self.config.bypass as *const _ as u64) - (&self.config as *const _ as u64);
1071         if offset != bypass_offset || data.len() != std::mem::size_of_val(&self.config.bypass) {
1072             error!(
1073                 "Attempt to write to read-only field: offset {:x} length {}",
1074                 offset,
1075                 data.len()
1076             );
1077             return;
1078         }
1079 
1080         self.config.bypass = data[0];
1081 
1082         self.update_bypass();
1083     }
1084 
1085     fn activate(
1086         &mut self,
1087         mem: GuestMemoryAtomic<GuestMemoryMmap>,
1088         interrupt_cb: Arc<dyn VirtioInterrupt>,
1089         mut queues: Vec<(usize, Queue, EventFd)>,
1090     ) -> ActivateResult {
1091         self.common.activate(&queues, &interrupt_cb)?;
1092         let (kill_evt, pause_evt) = self.common.dup_eventfds();
1093 
1094         let (_, request_queue, request_queue_evt) = queues.remove(0);
1095         let (_, _event_queue, _event_queue_evt) = queues.remove(0);
1096 
1097         let mut handler = IommuEpollHandler {
1098             mem,
1099             request_queue,
1100             _event_queue,
1101             interrupt_cb,
1102             request_queue_evt,
1103             _event_queue_evt,
1104             kill_evt,
1105             pause_evt,
1106             mapping: self.mapping.clone(),
1107             ext_mapping: self.ext_mapping.clone(),
1108             msi_iova_space: self.msi_iova_space,
1109         };
1110 
1111         let paused = self.common.paused.clone();
1112         let paused_sync = self.common.paused_sync.clone();
1113         let mut epoll_threads = Vec::new();
1114         spawn_virtio_thread(
1115             &self.id,
1116             &self.seccomp_action,
1117             Thread::VirtioIommu,
1118             &mut epoll_threads,
1119             &self.exit_evt,
1120             move || handler.run(paused, paused_sync.unwrap()),
1121         )?;
1122 
1123         self.common.epoll_threads = Some(epoll_threads);
1124 
1125         event!("virtio-device", "activated", "id", &self.id);
1126         Ok(())
1127     }
1128 
1129     fn reset(&mut self) -> Option<Arc<dyn VirtioInterrupt>> {
1130         let result = self.common.reset();
1131         event!("virtio-device", "reset", "id", &self.id);
1132         result
1133     }
1134 }
1135 
1136 impl Pausable for Iommu {
1137     fn pause(&mut self) -> result::Result<(), MigratableError> {
1138         self.common.pause()
1139     }
1140 
1141     fn resume(&mut self) -> result::Result<(), MigratableError> {
1142         self.common.resume()
1143     }
1144 }
1145 
1146 impl Snapshottable for Iommu {
1147     fn id(&self) -> String {
1148         self.id.clone()
1149     }
1150 
1151     fn snapshot(&mut self) -> std::result::Result<Snapshot, MigratableError> {
1152         Snapshot::new_from_state(&self.state())
1153     }
1154 }
1155 impl Transportable for Iommu {}
1156 impl Migratable for Iommu {}
1157