xref: /cloud-hypervisor/pci/src/msix.rs (revision 9af2968a7dc47b89bf07ea9dc5e735084efcfa3a)
1 // Copyright © 2019 Intel Corporation
2 //
3 // SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
4 //
5 
6 use crate::{PciCapability, PciCapabilityId};
7 use anyhow::anyhow;
8 use byteorder::{ByteOrder, LittleEndian};
9 use std::io;
10 use std::result;
11 use std::sync::Arc;
12 use versionize::{VersionMap, Versionize, VersionizeResult};
13 use versionize_derive::Versionize;
14 use vm_device::interrupt::{
15     InterruptIndex, InterruptSourceConfig, InterruptSourceGroup, MsiIrqSourceConfig,
16 };
17 use vm_memory::ByteValued;
18 use vm_migration::{MigratableError, Pausable, Snapshot, Snapshottable, VersionMapped};
19 
20 const MAX_MSIX_VECTORS_PER_DEVICE: u16 = 2048;
21 const MSIX_TABLE_ENTRIES_MODULO: u64 = 16;
22 const MSIX_PBA_ENTRIES_MODULO: u64 = 8;
23 const BITS_PER_PBA_ENTRY: usize = 64;
24 const FUNCTION_MASK_BIT: u8 = 14;
25 const MSIX_ENABLE_BIT: u8 = 15;
26 const FUNCTION_MASK_MASK: u16 = (1 << FUNCTION_MASK_BIT) as u16;
27 const MSIX_ENABLE_MASK: u16 = (1 << MSIX_ENABLE_BIT) as u16;
28 pub const MSIX_TABLE_ENTRY_SIZE: usize = 16;
29 
30 #[derive(Debug)]
31 enum Error {
32     /// Failed enabling the interrupt route.
33     EnableInterruptRoute(io::Error),
34     /// Failed updating the interrupt route.
35     UpdateInterruptRoute(io::Error),
36 }
37 
38 #[derive(Debug, Clone, Versionize)]
39 pub struct MsixTableEntry {
40     pub msg_addr_lo: u32,
41     pub msg_addr_hi: u32,
42     pub msg_data: u32,
43     pub vector_ctl: u32,
44 }
45 
46 impl MsixTableEntry {
47     pub fn masked(&self) -> bool {
48         self.vector_ctl & 0x1 == 0x1
49     }
50 }
51 
52 impl Default for MsixTableEntry {
53     fn default() -> Self {
54         MsixTableEntry {
55             msg_addr_lo: 0,
56             msg_addr_hi: 0,
57             msg_data: 0,
58             vector_ctl: 0x1,
59         }
60     }
61 }
62 
63 #[derive(Versionize)]
64 struct MsixConfigState {
65     table_entries: Vec<MsixTableEntry>,
66     pba_entries: Vec<u64>,
67     masked: bool,
68     enabled: bool,
69 }
70 
71 impl VersionMapped for MsixConfigState {}
72 
73 pub struct MsixConfig {
74     pub table_entries: Vec<MsixTableEntry>,
75     pub pba_entries: Vec<u64>,
76     pub devid: u32,
77     interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>,
78     masked: bool,
79     enabled: bool,
80 }
81 
82 impl MsixConfig {
83     pub fn new(
84         msix_vectors: u16,
85         interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>,
86         devid: u32,
87     ) -> Self {
88         assert!(msix_vectors <= MAX_MSIX_VECTORS_PER_DEVICE);
89 
90         let mut table_entries: Vec<MsixTableEntry> = Vec::new();
91         table_entries.resize_with(msix_vectors as usize, Default::default);
92         let mut pba_entries: Vec<u64> = Vec::new();
93         let num_pba_entries: usize = ((msix_vectors as usize) / BITS_PER_PBA_ENTRY) + 1;
94         pba_entries.resize_with(num_pba_entries, Default::default);
95 
96         MsixConfig {
97             table_entries,
98             pba_entries,
99             devid,
100             interrupt_source_group,
101             masked: true,
102             enabled: false,
103         }
104     }
105 
106     fn state(&self) -> MsixConfigState {
107         MsixConfigState {
108             table_entries: self.table_entries.clone(),
109             pba_entries: self.pba_entries.clone(),
110             masked: self.masked,
111             enabled: self.enabled,
112         }
113     }
114 
115     fn set_state(&mut self, state: &MsixConfigState) -> result::Result<(), Error> {
116         self.table_entries = state.table_entries.clone();
117         self.pba_entries = state.pba_entries.clone();
118         self.masked = state.masked;
119         self.enabled = state.enabled;
120 
121         if self.enabled && !self.masked {
122             for (idx, table_entry) in self.table_entries.iter().enumerate() {
123                 if table_entry.masked() {
124                     continue;
125                 }
126 
127                 let config = MsiIrqSourceConfig {
128                     high_addr: table_entry.msg_addr_hi,
129                     low_addr: table_entry.msg_addr_lo,
130                     data: table_entry.msg_data,
131                     devid: self.devid,
132                 };
133 
134                 self.interrupt_source_group
135                     .update(idx as InterruptIndex, InterruptSourceConfig::MsiIrq(config))
136                     .map_err(Error::UpdateInterruptRoute)?;
137 
138                 self.interrupt_source_group
139                     .enable()
140                     .map_err(Error::EnableInterruptRoute)?;
141             }
142         }
143 
144         Ok(())
145     }
146 
147     pub fn masked(&self) -> bool {
148         self.masked
149     }
150 
151     pub fn enabled(&self) -> bool {
152         self.enabled
153     }
154 
155     pub fn set_msg_ctl(&mut self, reg: u16) {
156         let old_masked = self.masked;
157         let old_enabled = self.enabled;
158 
159         self.masked = ((reg >> FUNCTION_MASK_BIT) & 1u16) == 1u16;
160         self.enabled = ((reg >> MSIX_ENABLE_BIT) & 1u16) == 1u16;
161 
162         // Update interrupt routing
163         if old_masked != self.masked || old_enabled != self.enabled {
164             if self.enabled && !self.masked {
165                 for (idx, table_entry) in self.table_entries.iter().enumerate() {
166                     let config = MsiIrqSourceConfig {
167                         high_addr: table_entry.msg_addr_hi,
168                         low_addr: table_entry.msg_addr_lo,
169                         data: table_entry.msg_data,
170                         devid: self.devid,
171                     };
172 
173                     if let Err(e) = self
174                         .interrupt_source_group
175                         .update(idx as InterruptIndex, InterruptSourceConfig::MsiIrq(config))
176                     {
177                         error!("Failed updating vector: {:?}", e);
178                     }
179 
180                     if table_entry.masked() {
181                         if let Err(e) = self.interrupt_source_group.mask(idx as InterruptIndex) {
182                             error!("Failed masking vector: {:?}", e);
183                         }
184                     } else if let Err(e) = self.interrupt_source_group.unmask(idx as InterruptIndex)
185                     {
186                         error!("Failed unmasking vector: {:?}", e);
187                     }
188                 }
189             } else if old_enabled || !old_masked {
190                 if let Err(e) = self.interrupt_source_group.disable() {
191                     error!("Failed disabling irq_fd: {:?}", e);
192                 }
193             }
194         }
195 
196         // If the Function Mask bit was set, and has just been cleared, it's
197         // important to go through the entire PBA to check if there was any
198         // pending MSI-X message to inject, given that the vector is not
199         // masked.
200         if old_masked && !self.masked {
201             for (index, entry) in self.table_entries.clone().iter().enumerate() {
202                 if !entry.masked() && self.get_pba_bit(index as u16) == 1 {
203                     self.inject_msix_and_clear_pba(index);
204                 }
205             }
206         }
207     }
208 
209     pub fn read_table(&self, offset: u64, data: &mut [u8]) {
210         assert!((data.len() == 4 || data.len() == 8));
211 
212         let index: usize = (offset / MSIX_TABLE_ENTRIES_MODULO) as usize;
213         let modulo_offset = offset % MSIX_TABLE_ENTRIES_MODULO;
214 
215         match data.len() {
216             4 => {
217                 let value = match modulo_offset {
218                     0x0 => self.table_entries[index].msg_addr_lo,
219                     0x4 => self.table_entries[index].msg_addr_hi,
220                     0x8 => self.table_entries[index].msg_data,
221                     0xc => self.table_entries[index].vector_ctl,
222                     _ => {
223                         error!("invalid offset");
224                         0
225                     }
226                 };
227 
228                 debug!("MSI_R TABLE offset 0x{:x} data 0x{:x}", offset, value);
229                 LittleEndian::write_u32(data, value);
230             }
231             8 => {
232                 let value = match modulo_offset {
233                     0x0 => {
234                         (u64::from(self.table_entries[index].msg_addr_hi) << 32)
235                             | u64::from(self.table_entries[index].msg_addr_lo)
236                     }
237                     0x8 => {
238                         (u64::from(self.table_entries[index].vector_ctl) << 32)
239                             | u64::from(self.table_entries[index].msg_data)
240                     }
241                     _ => {
242                         error!("invalid offset");
243                         0
244                     }
245                 };
246 
247                 debug!("MSI_R TABLE offset 0x{:x} data 0x{:x}", offset, value);
248                 LittleEndian::write_u64(data, value);
249             }
250             _ => {
251                 error!("invalid data length");
252             }
253         }
254     }
255 
256     pub fn write_table(&mut self, offset: u64, data: &[u8]) {
257         assert!((data.len() == 4 || data.len() == 8));
258 
259         let index: usize = (offset / MSIX_TABLE_ENTRIES_MODULO) as usize;
260         let modulo_offset = offset % MSIX_TABLE_ENTRIES_MODULO;
261 
262         // Store the value of the entry before modification
263         let mut old_entry: Option<MsixTableEntry> = None;
264 
265         match data.len() {
266             4 => {
267                 let value = LittleEndian::read_u32(data);
268                 match modulo_offset {
269                     0x0 => self.table_entries[index].msg_addr_lo = value,
270                     0x4 => self.table_entries[index].msg_addr_hi = value,
271                     0x8 => self.table_entries[index].msg_data = value,
272                     0xc => {
273                         old_entry = Some(self.table_entries[index].clone());
274                         self.table_entries[index].vector_ctl = value;
275                     }
276                     _ => error!("invalid offset"),
277                 };
278 
279                 debug!("MSI_W TABLE offset 0x{:x} data 0x{:x}", offset, value);
280             }
281             8 => {
282                 let value = LittleEndian::read_u64(data);
283                 match modulo_offset {
284                     0x0 => {
285                         self.table_entries[index].msg_addr_lo = (value & 0xffff_ffffu64) as u32;
286                         self.table_entries[index].msg_addr_hi = (value >> 32) as u32;
287                     }
288                     0x8 => {
289                         old_entry = Some(self.table_entries[index].clone());
290                         self.table_entries[index].msg_data = (value & 0xffff_ffffu64) as u32;
291                         self.table_entries[index].vector_ctl = (value >> 32) as u32;
292                     }
293                     _ => error!("invalid offset"),
294                 };
295 
296                 debug!("MSI_W TABLE offset 0x{:x} data 0x{:x}", offset, value);
297             }
298             _ => error!("invalid data length"),
299         };
300 
301         // Update interrupt routes
302         if self.enabled && !self.masked {
303             let table_entry = &self.table_entries[index];
304 
305             let config = MsiIrqSourceConfig {
306                 high_addr: table_entry.msg_addr_hi,
307                 low_addr: table_entry.msg_addr_lo,
308                 data: table_entry.msg_data,
309                 devid: self.devid,
310             };
311 
312             if let Err(e) = self.interrupt_source_group.update(
313                 index as InterruptIndex,
314                 InterruptSourceConfig::MsiIrq(config),
315             ) {
316                 error!("Failed updating vector: {:?}", e);
317             }
318 
319             if table_entry.masked() {
320                 if let Err(e) = self.interrupt_source_group.mask(index as InterruptIndex) {
321                     error!("Failed masking vector: {:?}", e);
322                 }
323             } else if let Err(e) = self.interrupt_source_group.unmask(index as InterruptIndex) {
324                 error!("Failed unmasking vector: {:?}", e);
325             }
326         }
327 
328         // After the MSI-X table entry has been updated, it is necessary to
329         // check if the vector control masking bit has changed. In case the
330         // bit has been flipped from 1 to 0, we need to inject a MSI message
331         // if the corresponding pending bit from the PBA is set. Once the MSI
332         // has been injected, the pending bit in the PBA needs to be cleared.
333         // All of this is valid only if MSI-X has not been masked for the whole
334         // device.
335         if let Some(old_entry) = old_entry {
336             // Check if bit has been flipped
337             if !self.masked()
338                 && old_entry.masked()
339                 && !self.table_entries[index].masked()
340                 && self.get_pba_bit(index as u16) == 1
341             {
342                 self.inject_msix_and_clear_pba(index);
343             }
344         }
345     }
346 
347     pub fn read_pba(&mut self, offset: u64, data: &mut [u8]) {
348         assert!((data.len() == 4 || data.len() == 8));
349 
350         let index: usize = (offset / MSIX_PBA_ENTRIES_MODULO) as usize;
351         let modulo_offset = offset % MSIX_PBA_ENTRIES_MODULO;
352 
353         match data.len() {
354             4 => {
355                 let value: u32 = match modulo_offset {
356                     0x0 => (self.pba_entries[index] & 0xffff_ffffu64) as u32,
357                     0x4 => (self.pba_entries[index] >> 32) as u32,
358                     _ => {
359                         error!("invalid offset");
360                         0
361                     }
362                 };
363 
364                 debug!("MSI_R PBA offset 0x{:x} data 0x{:x}", offset, value);
365                 LittleEndian::write_u32(data, value);
366             }
367             8 => {
368                 let value: u64 = match modulo_offset {
369                     0x0 => self.pba_entries[index],
370                     _ => {
371                         error!("invalid offset");
372                         0
373                     }
374                 };
375 
376                 debug!("MSI_R PBA offset 0x{:x} data 0x{:x}", offset, value);
377                 LittleEndian::write_u64(data, value);
378             }
379             _ => {
380                 error!("invalid data length");
381             }
382         }
383     }
384 
385     pub fn write_pba(&mut self, _offset: u64, _data: &[u8]) {
386         error!("Pending Bit Array is read only");
387     }
388 
389     pub fn set_pba_bit(&mut self, vector: u16, reset: bool) {
390         assert!(vector < MAX_MSIX_VECTORS_PER_DEVICE);
391 
392         let index: usize = (vector as usize) / BITS_PER_PBA_ENTRY;
393         let shift: usize = (vector as usize) % BITS_PER_PBA_ENTRY;
394         let mut mask: u64 = (1 << shift) as u64;
395 
396         if reset {
397             mask = !mask;
398             self.pba_entries[index] &= mask;
399         } else {
400             self.pba_entries[index] |= mask;
401         }
402     }
403 
404     fn get_pba_bit(&self, vector: u16) -> u8 {
405         assert!(vector < MAX_MSIX_VECTORS_PER_DEVICE);
406 
407         let index: usize = (vector as usize) / BITS_PER_PBA_ENTRY;
408         let shift: usize = (vector as usize) % BITS_PER_PBA_ENTRY;
409 
410         ((self.pba_entries[index] >> shift) & 0x0000_0001u64) as u8
411     }
412 
413     fn inject_msix_and_clear_pba(&mut self, vector: usize) {
414         // Inject the MSI message
415         match self
416             .interrupt_source_group
417             .trigger(vector as InterruptIndex)
418         {
419             Ok(_) => debug!("MSI-X injected on vector control flip"),
420             Err(e) => error!("failed to inject MSI-X: {}", e),
421         }
422 
423         // Clear the bit from PBA
424         self.set_pba_bit(vector as u16, true);
425     }
426 }
427 
428 impl Pausable for MsixConfig {}
429 
430 impl Snapshottable for MsixConfig {
431     fn id(&self) -> String {
432         String::from("msix_config")
433     }
434 
435     fn snapshot(&mut self) -> std::result::Result<Snapshot, MigratableError> {
436         Snapshot::new_from_versioned_state(&self.id(), &self.state())
437     }
438 
439     fn restore(&mut self, snapshot: Snapshot) -> std::result::Result<(), MigratableError> {
440         self.set_state(&snapshot.to_versioned_state(&self.id())?)
441             .map_err(|e| {
442                 MigratableError::Restore(anyhow!(
443                     "Could not restore state for {}: {:?}",
444                     self.id(),
445                     e
446                 ))
447             })
448     }
449 }
450 
451 #[allow(dead_code)]
452 #[repr(packed)]
453 #[derive(Clone, Copy, Default)]
454 pub struct MsixCap {
455     // Message Control Register
456     //   10-0:  MSI-X Table size
457     //   13-11: Reserved
458     //   14:    Mask. Mask all MSI-X when set.
459     //   15:    Enable. Enable all MSI-X when set.
460     pub msg_ctl: u16,
461     // Table. Contains the offset and the BAR indicator (BIR)
462     //   2-0:  Table BAR indicator (BIR). Can be 0 to 5.
463     //   31-3: Table offset in the BAR pointed by the BIR.
464     pub table: u32,
465     // Pending Bit Array. Contains the offset and the BAR indicator (BIR)
466     //   2-0:  PBA BAR indicator (BIR). Can be 0 to 5.
467     //   31-3: PBA offset in the BAR pointed by the BIR.
468     pub pba: u32,
469 }
470 
471 // It is safe to implement ByteValued. All members are simple numbers and any value is valid.
472 unsafe impl ByteValued for MsixCap {}
473 
474 impl PciCapability for MsixCap {
475     fn bytes(&self) -> &[u8] {
476         self.as_slice()
477     }
478 
479     fn id(&self) -> PciCapabilityId {
480         PciCapabilityId::MsiX
481     }
482 }
483 
484 impl MsixCap {
485     pub fn new(
486         table_pci_bar: u8,
487         table_size: u16,
488         table_off: u32,
489         pba_pci_bar: u8,
490         pba_off: u32,
491     ) -> Self {
492         assert!(table_size < MAX_MSIX_VECTORS_PER_DEVICE);
493 
494         // Set the table size and enable MSI-X.
495         let msg_ctl: u16 = 0x8000u16 + table_size - 1;
496 
497         MsixCap {
498             msg_ctl,
499             table: (table_off & 0xffff_fff8u32) | u32::from(table_pci_bar & 0x7u8),
500             pba: (pba_off & 0xffff_fff8u32) | u32::from(pba_pci_bar & 0x7u8),
501         }
502     }
503 
504     pub fn set_msg_ctl(&mut self, data: u16) {
505         self.msg_ctl = (self.msg_ctl & !(FUNCTION_MASK_MASK | MSIX_ENABLE_MASK))
506             | (data & (FUNCTION_MASK_MASK | MSIX_ENABLE_MASK));
507     }
508 
509     pub fn masked(&self) -> bool {
510         (self.msg_ctl >> FUNCTION_MASK_BIT) & 0x1 == 0x1
511     }
512 
513     pub fn enabled(&self) -> bool {
514         (self.msg_ctl >> MSIX_ENABLE_BIT) & 0x1 == 0x1
515     }
516 
517     pub fn table_offset(&self) -> u32 {
518         self.table & 0xffff_fff8
519     }
520 
521     pub fn pba_offset(&self) -> u32 {
522         self.pba & 0xffff_fff8
523     }
524 
525     pub fn table_bir(&self) -> u32 {
526         self.table & 0x7
527     }
528 
529     pub fn pba_bir(&self) -> u32 {
530         self.pba & 0x7
531     }
532 
533     pub fn table_size(&self) -> u16 {
534         (self.msg_ctl & 0x7ff) + 1
535     }
536 }
537