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