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