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