xref: /aosp_15_r20/external/crosvm/x86_64/src/acpi.rs (revision bb4ee6a4ae7042d18b07a98463b9c8b875e44b39)
1 // Copyright 2020 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 use std::arch::x86_64::CpuidResult;
6 use std::arch::x86_64::__cpuid;
7 use std::arch::x86_64::__cpuid_count;
8 use std::collections::BTreeMap;
9 use std::sync::Arc;
10 
11 use acpi_tables::aml;
12 use acpi_tables::facs::FACS;
13 use acpi_tables::rsdp::RSDP;
14 use acpi_tables::sdt::SDT;
15 use arch::CpuSet;
16 use arch::VcpuAffinity;
17 use base::error;
18 use base::warn;
19 use devices::ACPIPMResource;
20 use devices::PciAddress;
21 use devices::PciInterruptPin;
22 use devices::PciRoot;
23 use sync::Mutex;
24 use vm_memory::GuestAddress;
25 use vm_memory::GuestMemory;
26 use zerocopy::AsBytes;
27 use zerocopy::FromBytes;
28 use zerocopy::FromZeroes;
29 
30 pub struct AcpiDevResource {
31     pub amls: Vec<u8>,
32     pub pm_iobase: u64,
33     pub pm: Arc<Mutex<ACPIPMResource>>,
34     /// Additional system descriptor tables.
35     pub sdts: Vec<SDT>,
36 }
37 
38 #[repr(C, packed)]
39 #[derive(Clone, Copy, Default, FromZeroes, FromBytes, AsBytes)]
40 struct GenericAddress {
41     _space_id: u8,
42     _bit_width: u8,
43     _bit_offset: u8,
44     _access_width: u8,
45     _address: u64,
46 }
47 
48 #[repr(C)]
49 #[derive(Clone, Copy, Default, AsBytes)]
50 struct LocalApic {
51     _type: u8,
52     _length: u8,
53     _processor_id: u8,
54     _apic_id: u8,
55     _flags: u32,
56 }
57 
58 #[repr(C)]
59 #[derive(Clone, Copy, Default, FromZeroes, FromBytes, AsBytes)]
60 struct Ioapic {
61     _type: u8,
62     _length: u8,
63     _ioapic_id: u8,
64     _reserved: u8,
65     _apic_address: u32,
66     _gsi_base: u32,
67 }
68 
69 #[repr(C, packed)]
70 #[derive(Clone, Copy, Default, FromZeroes, FromBytes, AsBytes)]
71 struct IoapicInterruptSourceOverride {
72     _type: u8,
73     _length: u8,
74     _bus: u8,
75     _source: u8,
76     _gsi: u32,
77     _flags: u16,
78 }
79 
80 #[repr(C)]
81 #[derive(Clone, Copy, Default, FromZeroes, FromBytes, AsBytes)]
82 struct Localx2Apic {
83     _type: u8,
84     _length: u8,
85     _reserved: u16,
86     _x2apic_id: u32,
87     _flags: u32,
88     _processor_id: u32,
89 }
90 
91 // Space ID for GenericAddress
92 const ADR_SPACE_SYSTEM_IO: u8 = 1;
93 
94 const OEM_REVISION: u32 = 1;
95 //DSDT
96 const DSDT_REVISION: u8 = 6;
97 // FADT
98 const FADT_LEN: u32 = 276;
99 const FADT_REVISION: u8 = 6;
100 const FADT_MINOR_REVISION: u8 = 3;
101 // FADT flags
102 const FADT_POWER_BUTTON: u32 = 1 << 4;
103 const _FADT_SLEEP_BUTTON: u32 = 1 << 5;
104 const FADT_RESET_REGISTER: u32 = 1 << 10;
105 const FADT_LOW_POWER_S2IDLE: u32 = 1 << 21;
106 // FADT fields offset
107 const FADT_FIELD_FACS_ADDR32: usize = 36;
108 const FADT_FIELD_DSDT_ADDR32: usize = 40;
109 pub const FADT_FIELD_SCI_INTERRUPT: usize = 46;
110 const FADT_FIELD_SMI_COMMAND: usize = 48;
111 const FADT_FIELD_PM1A_EVENT_BLK_ADDR: usize = 56;
112 const FADT_FIELD_PM1B_EVENT_BLK_ADDR: usize = 60;
113 const FADT_FIELD_PM1A_CONTROL_BLK_ADDR: usize = 64;
114 const FADT_FIELD_PM1B_CONTROL_BLK_ADDR: usize = 68;
115 const FADT_FIELD_PM2_CONTROL_BLK_ADDR: usize = 72;
116 const FADT_FIELD_PM_TMR_BLK_ADDR: usize = 76;
117 const FADT_FIELD_GPE0_BLK_ADDR: usize = 80;
118 const FADT_FIELD_GPE1_BLK_ADDR: usize = 84;
119 const FADT_FIELD_PM1A_EVENT_BLK_LEN: usize = 88;
120 const FADT_FIELD_PM1A_CONTROL_BLK_LEN: usize = 89;
121 const FADT_FIELD_PM2_CONTROL_BLK_LEN: usize = 90;
122 const FADT_FIELD_PM_TMR_LEN: usize = 91;
123 const FADT_FIELD_GPE0_BLK_LEN: usize = 92;
124 const FADT_FIELD_GPE1_BLK_LEN: usize = 93;
125 const FADT_FIELD_GPE1_BASE: usize = 94;
126 const FADT_FIELD_RTC_DAY_ALARM: usize = 106;
127 const FADT_FIELD_RTC_MONTH_ALARM: usize = 107;
128 const FADT_FIELD_RTC_CENTURY: usize = 108;
129 const FADT_FIELD_FLAGS: usize = 112;
130 const FADT_FIELD_RESET_REGISTER: usize = 116;
131 const FADT_FIELD_RESET_VALUE: usize = 128;
132 const FADT_FIELD_MINOR_REVISION: usize = 131;
133 const FADT_FIELD_FACS_ADDR: usize = 132;
134 const FADT_FIELD_DSDT_ADDR: usize = 140;
135 const FADT_FIELD_X_PM1A_EVENT_BLK_ADDR: usize = 148;
136 const FADT_FIELD_X_PM1B_EVENT_BLK_ADDR: usize = 160;
137 const FADT_FIELD_X_PM1A_CONTROL_BLK_ADDR: usize = 172;
138 const FADT_FIELD_X_PM1B_CONTROL_BLK_ADDR: usize = 184;
139 const FADT_FIELD_X_PM2_CONTROL_BLK_ADDR: usize = 196;
140 const FADT_FIELD_X_PM_TMR_BLK_ADDR: usize = 208;
141 const FADT_FIELD_X_GPE0_BLK_ADDR: usize = 220;
142 const FADT_FIELD_X_GPE1_BLK_ADDR: usize = 232;
143 const FADT_FIELD_HYPERVISOR_ID: usize = 268;
144 // MADT
145 const MADT_LEN: u32 = 44;
146 const MADT_REVISION: u8 = 5;
147 // MADT fields offset
148 const MADT_FIELD_LAPIC_ADDR: usize = 36;
149 const MADT_FIELD_FLAGS: usize = 40;
150 // MADT flags
151 const MADT_FLAG_PCAT_COMPAT: u32 = 1 << 0;
152 // MADT structure offsets
153 const MADT_STRUCTURE_TYPE: usize = 0;
154 const MADT_STRUCTURE_LEN: usize = 1;
155 // MADT types
156 const MADT_TYPE_LOCAL_APIC: u8 = 0;
157 const MADT_TYPE_IO_APIC: u8 = 1;
158 const MADT_TYPE_INTERRUPT_SOURCE_OVERRIDE: u8 = 2;
159 const MADT_TYPE_LOCAL_X2APIC: u8 = 9;
160 // MADT flags
161 const MADT_ENABLED: u32 = 1;
162 const MADT_INT_POLARITY_ACTIVE_LOW: u16 = 0b11;
163 const MADT_INT_TRIGGER_LEVEL: u16 = 0b11 << 2;
164 // MADT compatibility
165 const MADT_MIN_LOCAL_APIC_ID: u32 = 255;
166 // XSDT
167 const XSDT_REVISION: u8 = 1;
168 
169 const CPUID_LEAF0_EBX_CPUID_SHIFT: u32 = 24; // Offset of initial apic id.
170 
171 // MCFG
172 const MCFG_LEN: u32 = 60;
173 const MCFG_REVISION: u8 = 1;
174 const MCFG_FIELD_BASE_ADDRESS: usize = 44;
175 const MCFG_FIELD_START_BUS_NUMBER: usize = 54;
176 const MCFG_FIELD_END_BUS_NUMBER: usize = 55;
177 
178 const SSDT_REVISION: u8 = 2;
create_customize_ssdt( pci_root: Arc<Mutex<PciRoot>>, amls: BTreeMap<PciAddress, Vec<u8>>, gpe_scope_amls: BTreeMap<PciAddress, Vec<u8>>, ) -> Option<SDT>179 pub fn create_customize_ssdt(
180     pci_root: Arc<Mutex<PciRoot>>,
181     amls: BTreeMap<PciAddress, Vec<u8>>,
182     gpe_scope_amls: BTreeMap<PciAddress, Vec<u8>>,
183 ) -> Option<SDT> {
184     if amls.is_empty() {
185         return None;
186     }
187 
188     let mut ssdt = SDT::new(
189         *b"SSDT",
190         acpi_tables::HEADER_LEN,
191         SSDT_REVISION,
192         *b"CROSVM",
193         *b"CROSVMDT",
194         OEM_REVISION,
195     );
196 
197     for (address, children) in amls {
198         if let Some(path) = pci_root.lock().acpi_path(&address) {
199             ssdt.append_slice(&aml::Scope::raw((*path).into(), children));
200         }
201     }
202 
203     for children in gpe_scope_amls.values() {
204         ssdt.append_slice(children);
205     }
206 
207     Some(ssdt)
208 }
209 
create_dsdt_table(amls: &[u8]) -> SDT210 fn create_dsdt_table(amls: &[u8]) -> SDT {
211     let mut dsdt = SDT::new(
212         *b"DSDT",
213         acpi_tables::HEADER_LEN,
214         DSDT_REVISION,
215         *b"CROSVM",
216         *b"CROSVMDT",
217         OEM_REVISION,
218     );
219 
220     if !amls.is_empty() {
221         dsdt.append_slice(amls);
222     }
223 
224     dsdt
225 }
226 
create_facp_table(sci_irq: u16, force_s2idle: bool) -> SDT227 fn create_facp_table(sci_irq: u16, force_s2idle: bool) -> SDT {
228     let mut facp = SDT::new(
229         *b"FACP",
230         FADT_LEN,
231         FADT_REVISION,
232         *b"CROSVM",
233         *b"CROSVMDT",
234         OEM_REVISION,
235     );
236 
237     let mut fadt_flags: u32 = 0;
238 
239     if force_s2idle {
240         fadt_flags |= FADT_LOW_POWER_S2IDLE;
241     }
242 
243     facp.write(FADT_FIELD_FLAGS, fadt_flags);
244 
245     // SCI Interrupt
246     facp.write(FADT_FIELD_SCI_INTERRUPT, sci_irq);
247 
248     facp.write(FADT_FIELD_MINOR_REVISION, FADT_MINOR_REVISION); // FADT minor version
249     facp.write(FADT_FIELD_HYPERVISOR_ID, *b"CROSVM"); // Hypervisor Vendor Identity
250 
251     facp.write::<u8>(FADT_FIELD_RTC_CENTURY, devices::cmos::RTC_REG_CENTURY);
252     facp.write::<u8>(FADT_FIELD_RTC_DAY_ALARM, devices::cmos::RTC_REG_ALARM_DAY);
253     facp.write::<u8>(
254         FADT_FIELD_RTC_MONTH_ALARM,
255         devices::cmos::RTC_REG_ALARM_MONTH,
256     );
257 
258     facp
259 }
260 
261 // Write virtualized FADT fields
write_facp_overrides( facp: &mut SDT, facs_offset: GuestAddress, dsdt_offset: GuestAddress, pm_iobase: u32, reset_port: u32, reset_value: u8, )262 fn write_facp_overrides(
263     facp: &mut SDT,
264     facs_offset: GuestAddress,
265     dsdt_offset: GuestAddress,
266     pm_iobase: u32,
267     reset_port: u32,
268     reset_value: u8,
269 ) {
270     let fadt_flags: u32 = facp.read(FADT_FIELD_FLAGS);
271     // indicate we support FADT RESET_REG
272     facp.write(FADT_FIELD_FLAGS, fadt_flags | FADT_RESET_REGISTER);
273 
274     facp.write(FADT_FIELD_SMI_COMMAND, 0u32);
275     facp.write(FADT_FIELD_FACS_ADDR32, 0u32);
276     facp.write(FADT_FIELD_DSDT_ADDR32, 0u32);
277     facp.write(FADT_FIELD_FACS_ADDR, facs_offset.0);
278     facp.write(FADT_FIELD_DSDT_ADDR, dsdt_offset.0);
279 
280     // PM1A Event Block Address
281     facp.write(FADT_FIELD_PM1A_EVENT_BLK_ADDR, pm_iobase);
282 
283     // PM1B Event Block Address (not supported)
284     facp.write(FADT_FIELD_PM1B_EVENT_BLK_ADDR, 0u32);
285 
286     // PM1A Control Block Address
287     facp.write(
288         FADT_FIELD_PM1A_CONTROL_BLK_ADDR,
289         pm_iobase + devices::acpi::ACPIPM_RESOURCE_EVENTBLK_LEN as u32,
290     );
291 
292     // PM1B Control Block Address (not supported)
293     facp.write(FADT_FIELD_PM1B_CONTROL_BLK_ADDR, 0u32);
294 
295     // PM2 Control Block Address (not supported)
296     facp.write(FADT_FIELD_PM2_CONTROL_BLK_ADDR, 0u32);
297 
298     // PM Timer Control Block Address (not supported)
299     facp.write(FADT_FIELD_PM_TMR_BLK_ADDR, 0u32);
300 
301     // GPE0 Block Address
302     facp.write(
303         FADT_FIELD_GPE0_BLK_ADDR,
304         pm_iobase + devices::acpi::ACPIPM_RESOURCE_EVENTBLK_LEN as u32 + 4,
305     );
306 
307     // GPE1 Block Address (not supported)
308     facp.write(FADT_FIELD_GPE1_BLK_ADDR, 0u32);
309 
310     // PM1 Event Block Length
311     facp.write(
312         FADT_FIELD_PM1A_EVENT_BLK_LEN,
313         devices::acpi::ACPIPM_RESOURCE_EVENTBLK_LEN,
314     );
315 
316     // PM1 Control Block Length
317     facp.write(
318         FADT_FIELD_PM1A_CONTROL_BLK_LEN,
319         devices::acpi::ACPIPM_RESOURCE_CONTROLBLK_LEN,
320     );
321 
322     // PM2 Control Block Length (not supported)
323     facp.write(FADT_FIELD_PM2_CONTROL_BLK_LEN, 0u8);
324 
325     // PM Timer Control Block Length (not supported)
326     facp.write(FADT_FIELD_PM_TMR_LEN, 0u8);
327 
328     // GPE0 Block Length
329     facp.write(
330         FADT_FIELD_GPE0_BLK_LEN,
331         devices::acpi::ACPIPM_RESOURCE_GPE0_BLK_LEN,
332     );
333 
334     // GPE1 Block Length (not supported)
335     facp.write(FADT_FIELD_GPE1_BLK_LEN, 0u8);
336 
337     // GPE1 Base (not supported)
338     facp.write(FADT_FIELD_GPE1_BASE, 0u8);
339 
340     // PM1A Extended Event Block Address (not supported)
341     facp.write(
342         FADT_FIELD_X_PM1A_EVENT_BLK_ADDR,
343         GenericAddress {
344             ..Default::default()
345         },
346     );
347 
348     // PM1B Extended Event Block Address (not supported)
349     facp.write(
350         FADT_FIELD_X_PM1B_EVENT_BLK_ADDR,
351         GenericAddress {
352             ..Default::default()
353         },
354     );
355 
356     // PM1A Extended Control Block Address (not supported)
357     facp.write(
358         FADT_FIELD_X_PM1A_CONTROL_BLK_ADDR,
359         GenericAddress {
360             ..Default::default()
361         },
362     );
363 
364     // PM1B Extended Control Block Address (not supported)
365     facp.write(
366         FADT_FIELD_X_PM1B_CONTROL_BLK_ADDR,
367         GenericAddress {
368             ..Default::default()
369         },
370     );
371 
372     // PM2 Extended Control Block Address (not supported)
373     facp.write(
374         FADT_FIELD_X_PM2_CONTROL_BLK_ADDR,
375         GenericAddress {
376             ..Default::default()
377         },
378     );
379 
380     // PM Timer Extended Control Block Address (not supported)
381     facp.write(
382         FADT_FIELD_X_PM_TMR_BLK_ADDR,
383         GenericAddress {
384             ..Default::default()
385         },
386     );
387 
388     // GPE0 Extended Address (not supported)
389     facp.write(
390         FADT_FIELD_X_GPE0_BLK_ADDR,
391         GenericAddress {
392             ..Default::default()
393         },
394     );
395 
396     // GPE1 Extended Address (not supported)
397     facp.write(
398         FADT_FIELD_X_GPE1_BLK_ADDR,
399         GenericAddress {
400             ..Default::default()
401         },
402     );
403 
404     // Reset register
405     facp.write(
406         FADT_FIELD_RESET_REGISTER,
407         GenericAddress {
408             _space_id: ADR_SPACE_SYSTEM_IO,
409             _bit_width: 8,
410             _bit_offset: 0,
411             _access_width: 1,
412             _address: reset_port.into(),
413         },
414     );
415     facp.write(FADT_FIELD_RESET_VALUE, reset_value);
416 }
417 
next_offset(offset: GuestAddress, len: u64) -> Option<GuestAddress>418 fn next_offset(offset: GuestAddress, len: u64) -> Option<GuestAddress> {
419     // Enforce 64-byte allocation alignment.
420     match len % 64 {
421         0 => offset.checked_add(len),
422         x => offset.checked_add(len.checked_add(64 - x)?),
423     }
424 }
425 
sync_acpi_id_from_cpuid( madt: &mut SDT, cpus: BTreeMap<usize, CpuSet>, apic_ids: &mut Vec<usize>, ) -> base::Result<()>426 fn sync_acpi_id_from_cpuid(
427     madt: &mut SDT,
428     cpus: BTreeMap<usize, CpuSet>,
429     apic_ids: &mut Vec<usize>,
430 ) -> base::Result<()> {
431     let cpu_set = match base::get_cpu_affinity() {
432         Err(e) => {
433             error!("Failed to get CPU affinity: {} when create MADT", e);
434             return Err(e);
435         }
436         Ok(c) => c,
437     };
438 
439     for (vcpu, pcpu) in cpus {
440         let mut has_leafb = false;
441         let mut get_apic_id = false;
442         let mut apic_id: u8 = 0;
443 
444         if let Err(e) = base::set_cpu_affinity(pcpu) {
445             error!("Failed to set CPU affinity: {} when create MADT", e);
446             return Err(e);
447         }
448 
449         // SAFETY:
450         // Safe because we pass 0 and 0 for this call and the host supports the
451         // `cpuid` instruction
452         let mut cpuid_entry: CpuidResult = unsafe { __cpuid_count(0, 0) };
453 
454         if cpuid_entry.eax >= 0xB {
455             // SAFETY:
456             // Safe because we pass 0xB and 0 for this call and the host supports the
457             // `cpuid` instruction
458             cpuid_entry = unsafe { __cpuid_count(0xB, 0) };
459 
460             if cpuid_entry.ebx != 0 {
461                 // MADT compatibility: (ACPI Spec v6.4) On some legacy OSes,
462                 // Logical processors with APIC ID values less than 255 (whether in
463                 // XAPIC or X2APIC mode) must use the Processor Local APIC structure.
464                 if cpuid_entry.edx < MADT_MIN_LOCAL_APIC_ID {
465                     apic_id = cpuid_entry.edx as u8;
466                     get_apic_id = true;
467                 } else {
468                     // (ACPI Spec v6.4) When using the X2APIC, logical processors are
469                     // required to have a processor device object in the DSDT and must
470                     // convey the processor’s APIC information to OSPM using the Processor
471                     // Local X2APIC structure.
472                     // Now vCPUs use the DSDT passthrougt from host and the same APIC ID as
473                     // the physical CPUs. Both of them should meet ACPI specifications on
474                     // the host.
475                     has_leafb = true;
476 
477                     let x2apic = Localx2Apic {
478                         _type: MADT_TYPE_LOCAL_X2APIC,
479                         _length: std::mem::size_of::<Localx2Apic>() as u8,
480                         _x2apic_id: cpuid_entry.edx,
481                         _flags: MADT_ENABLED,
482                         _processor_id: (vcpu + 1) as u32,
483                         ..Default::default()
484                     };
485                     madt.append(x2apic);
486                     apic_ids.push(cpuid_entry.edx as usize);
487                 }
488             }
489         }
490 
491         if !has_leafb {
492             if !get_apic_id {
493                 // SAFETY:
494                 // Safe because we pass 1 for this call and the host supports the
495                 // `cpuid` instruction
496                 cpuid_entry = unsafe { __cpuid(1) };
497                 apic_id = (cpuid_entry.ebx >> CPUID_LEAF0_EBX_CPUID_SHIFT & 0xff) as u8;
498             }
499 
500             let apic = LocalApic {
501                 _type: MADT_TYPE_LOCAL_APIC,
502                 _length: std::mem::size_of::<LocalApic>() as u8,
503                 _processor_id: vcpu as u8,
504                 _apic_id: apic_id,
505                 _flags: MADT_ENABLED,
506             };
507             madt.append(apic);
508             apic_ids.push(apic_id as usize);
509         }
510     }
511 
512     if let Err(e) = base::set_cpu_affinity(cpu_set) {
513         error!("Failed to reset CPU affinity: {} when create MADT", e);
514         return Err(e);
515     }
516 
517     Ok(())
518 }
519 
520 /// Create ACPI tables and return the RSDP.
521 /// The basic tables DSDT/FACP/MADT/XSDT are constructed in this function.
522 /// # Arguments
523 ///
524 /// * `guest_mem` - The guest memory where the tables will be stored.
525 /// * `num_cpus` - Used to construct the MADT.
526 /// * `sci_irq` - Used to fill the FACP SCI_INTERRUPT field, which is going to be used by the ACPI
527 ///   drivers to register sci handler.
528 /// * `acpi_dev_resource` - resouces needed by the ACPI devices for creating tables.
529 /// * `host_cpus` - The CPU affinity per CPU used to get corresponding CPUs' apic id and set these
530 ///   apic id in MADT if `--host-cpu-topology` option is set.
531 /// * `apic_ids` - The apic id for vCPU will be sent to KVM by KVM_CREATE_VCPU ioctl.
532 /// * `pci_rqs` - PCI device to IRQ number assignments as returned by `arch::generate_pci_root()`
533 ///   (device address, IRQ number, and PCI interrupt pin assignment).
534 /// * `pcie_cfg_mmio` - Base address for the pcie enhanced configuration access mechanism
535 /// * `max_bus` - Max bus number in MCFG table
536 
create_acpi_tables( guest_mem: &GuestMemory, num_cpus: u8, sci_irq: u32, reset_port: u32, reset_value: u8, acpi_dev_resource: &AcpiDevResource, host_cpus: Option<VcpuAffinity>, apic_ids: &mut Vec<usize>, pci_irqs: &[(PciAddress, u32, PciInterruptPin)], pcie_cfg_mmio: u64, max_bus: u8, force_s2idle: bool, ) -> Option<GuestAddress>537 pub fn create_acpi_tables(
538     guest_mem: &GuestMemory,
539     num_cpus: u8,
540     sci_irq: u32,
541     reset_port: u32,
542     reset_value: u8,
543     acpi_dev_resource: &AcpiDevResource,
544     host_cpus: Option<VcpuAffinity>,
545     apic_ids: &mut Vec<usize>,
546     pci_irqs: &[(PciAddress, u32, PciInterruptPin)],
547     pcie_cfg_mmio: u64,
548     max_bus: u8,
549     force_s2idle: bool,
550 ) -> Option<GuestAddress> {
551     // RSDP is at the HI RSDP WINDOW
552     let rsdp_offset = GuestAddress(super::ACPI_HI_RSDP_WINDOW_BASE);
553     let facs_offset = next_offset(rsdp_offset, RSDP::len() as u64)?;
554     let mut offset = next_offset(facs_offset, FACS::len() as u64)?;
555     let mut dsdt_offset: Option<GuestAddress> = None;
556     let mut tables: Vec<u64> = Vec::new();
557     let mut facp: Option<SDT> = None;
558     let mut host_madt: Option<SDT> = None;
559 
560     // User supplied System Description Tables, e.g. SSDT.
561     for sdt in acpi_dev_resource.sdts.iter() {
562         if sdt.is_signature(b"FACP") {
563             facp = Some(sdt.clone());
564             continue;
565         }
566         if sdt.is_signature(b"APIC") {
567             host_madt = Some(sdt.clone());
568             continue;
569         }
570         guest_mem.write_at_addr(sdt.as_slice(), offset).ok()?;
571         if sdt.is_signature(b"DSDT") {
572             dsdt_offset = Some(offset);
573         } else {
574             tables.push(offset.0);
575         }
576         offset = next_offset(offset, sdt.len() as u64)?;
577     }
578 
579     // FACS
580     let facs = FACS::new();
581     guest_mem.write_at_addr(facs.as_bytes(), facs_offset).ok()?;
582 
583     // DSDT
584     let dsdt_offset = match dsdt_offset {
585         Some(dsdt_offset) => dsdt_offset,
586         None => {
587             let dsdt_offset = offset;
588             let dsdt = create_dsdt_table(&acpi_dev_resource.amls);
589             guest_mem.write_at_addr(dsdt.as_slice(), offset).ok()?;
590             offset = next_offset(offset, dsdt.len() as u64)?;
591             dsdt_offset
592         }
593     };
594 
595     // FACP aka FADT
596     let mut facp = facp.map_or_else(
597         || create_facp_table(sci_irq as u16, force_s2idle),
598         |facp| {
599             let fadt_flags: u32 = facp.read(FADT_FIELD_FLAGS);
600             if fadt_flags & FADT_POWER_BUTTON != 0 {
601                 warn!(
602                     "Control Method Power Button is not supported. FADT flags = 0x{:x}",
603                     fadt_flags
604                 );
605             }
606             facp
607         },
608     );
609 
610     write_facp_overrides(
611         &mut facp,
612         facs_offset,
613         dsdt_offset,
614         acpi_dev_resource.pm_iobase as u32,
615         reset_port,
616         reset_value,
617     );
618 
619     guest_mem.write_at_addr(facp.as_slice(), offset).ok()?;
620     tables.push(offset.0);
621     offset = next_offset(offset, facp.len() as u64)?;
622 
623     // MADT
624     let mut madt = SDT::new(
625         *b"APIC",
626         MADT_LEN,
627         MADT_REVISION,
628         *b"CROSVM",
629         *b"CROSVMDT",
630         OEM_REVISION,
631     );
632     madt.write(
633         MADT_FIELD_LAPIC_ADDR,
634         super::mptable::APIC_DEFAULT_PHYS_BASE,
635     );
636     // Our IrqChip implementations (the KVM in-kernel irqchip and the split irqchip) expose a pair
637     // of PC-compatible 8259 PICs.
638     madt.write(MADT_FIELD_FLAGS, MADT_FLAG_PCAT_COMPAT);
639 
640     match host_cpus {
641         Some(VcpuAffinity::PerVcpu(cpus)) => {
642             sync_acpi_id_from_cpuid(&mut madt, cpus, apic_ids).ok()?;
643         }
644         _ => {
645             for cpu in 0..num_cpus {
646                 let apic = LocalApic {
647                     _type: MADT_TYPE_LOCAL_APIC,
648                     _length: std::mem::size_of::<LocalApic>() as u8,
649                     _processor_id: cpu,
650                     _apic_id: cpu,
651                     _flags: MADT_ENABLED,
652                 };
653                 madt.append(apic);
654                 apic_ids.push(cpu as usize);
655             }
656         }
657     }
658 
659     madt.append(Ioapic {
660         _type: MADT_TYPE_IO_APIC,
661         _length: std::mem::size_of::<Ioapic>() as u8,
662         _apic_address: super::mptable::IO_APIC_DEFAULT_PHYS_BASE,
663         ..Default::default()
664     });
665 
666     // Add interrupt overrides for the PCI IRQs so that they are reported as level triggered, as
667     // required by the PCI bus. The source and system GSI are identical, so this does not actually
668     // override the mapping; we just use it to set the level-triggered flag.
669     let mut unique_pci_irqs: Vec<u32> = pci_irqs.iter().map(|(_, irq_num, _)| *irq_num).collect();
670     unique_pci_irqs.sort_unstable();
671     unique_pci_irqs.dedup();
672     for irq_num in unique_pci_irqs {
673         madt.append(IoapicInterruptSourceOverride {
674             _type: MADT_TYPE_INTERRUPT_SOURCE_OVERRIDE,
675             _length: std::mem::size_of::<IoapicInterruptSourceOverride>() as u8,
676             _bus: 0, // ISA
677             _source: irq_num as u8,
678             _gsi: irq_num,
679             _flags: MADT_INT_POLARITY_ACTIVE_LOW | MADT_INT_TRIGGER_LEVEL,
680         });
681     }
682 
683     if let Some(host_madt) = host_madt {
684         let mut idx = MADT_LEN as usize;
685         while idx + MADT_STRUCTURE_LEN < host_madt.len() {
686             let struct_type = host_madt.as_slice()[idx + MADT_STRUCTURE_TYPE];
687             let struct_len = host_madt.as_slice()[idx + MADT_STRUCTURE_LEN] as usize;
688             if struct_type == MADT_TYPE_INTERRUPT_SOURCE_OVERRIDE {
689                 if idx + struct_len <= host_madt.len() {
690                     madt.append_slice(&host_madt.as_slice()[idx..(idx + struct_len)]);
691                 } else {
692                     error!("Malformed host MADT");
693                 }
694             }
695             idx += struct_len;
696         }
697     }
698 
699     guest_mem.write_at_addr(madt.as_slice(), offset).ok()?;
700     tables.push(offset.0);
701     offset = next_offset(offset, madt.len() as u64)?;
702 
703     // MCFG
704     let mut mcfg = SDT::new(
705         *b"MCFG",
706         MCFG_LEN,
707         MCFG_REVISION,
708         *b"CROSVM",
709         *b"CROSVMDT",
710         OEM_REVISION,
711     );
712     mcfg.write(MCFG_FIELD_BASE_ADDRESS, pcie_cfg_mmio);
713     mcfg.write(MCFG_FIELD_START_BUS_NUMBER, 0_u8);
714     mcfg.write(MCFG_FIELD_END_BUS_NUMBER, max_bus);
715 
716     guest_mem.write_at_addr(mcfg.as_slice(), offset).ok()?;
717     tables.push(offset.0);
718     offset = next_offset(offset, madt.len() as u64)?;
719 
720     // XSDT
721     let mut xsdt = SDT::new(
722         *b"XSDT",
723         acpi_tables::HEADER_LEN,
724         XSDT_REVISION,
725         *b"CROSVM",
726         *b"CROSVMDT",
727         OEM_REVISION,
728     );
729     for table in tables {
730         xsdt.append(table);
731     }
732 
733     guest_mem.write_at_addr(xsdt.as_slice(), offset).ok()?;
734 
735     // RSDP
736     let rsdp = RSDP::new(*b"CROSVM", offset.0);
737     guest_mem.write_at_addr(rsdp.as_bytes(), rsdp_offset).ok()?;
738 
739     Some(rsdp_offset)
740 }
741 
742 #[cfg(test)]
743 mod tests {
744     use crate::acpi::*;
745 
746     #[test]
facp_table_creation()747     fn facp_table_creation() {
748         let sci_irq: u16 = 5;
749         let force_s2idle = true;
750         let facp = create_facp_table(sci_irq, force_s2idle);
751 
752         assert_eq!(facp.read::<u32>(FADT_FIELD_FLAGS), FADT_LOW_POWER_S2IDLE);
753         assert_eq!(facp.read::<u16>(FADT_FIELD_SCI_INTERRUPT), sci_irq);
754         assert_eq!(
755             facp.read::<u8>(FADT_FIELD_MINOR_REVISION),
756             FADT_MINOR_REVISION
757         );
758         assert_eq!(facp.read::<[u8; 6]>(FADT_FIELD_HYPERVISOR_ID), *b"CROSVM");
759         assert_eq!(
760             facp.read::<u8>(FADT_FIELD_RTC_CENTURY),
761             devices::cmos::RTC_REG_CENTURY
762         );
763         assert_eq!(
764             facp.read::<u8>(FADT_FIELD_RTC_DAY_ALARM),
765             devices::cmos::RTC_REG_ALARM_DAY
766         );
767         assert_eq!(
768             facp.read::<u8>(FADT_FIELD_RTC_MONTH_ALARM),
769             devices::cmos::RTC_REG_ALARM_MONTH
770         );
771     }
772 }
773