Alioth Code Coverage

fw_cfg.rs21.21%

1// Copyright 2024 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[cfg(target_arch = "x86_64")]
16pub mod acpi;
17
18use std::ffi::CString;
19use std::fmt;
20use std::fs::File;
21use std::io::{ErrorKind, Read, Result, Seek, SeekFrom};
22#[cfg(target_arch = "x86_64")]
23use std::mem::size_of;
24use std::mem::size_of_val;
25use std::os::unix::fs::FileExt;
26#[cfg(target_arch = "x86_64")]
27use std::path::Path;
28use std::sync::Arc;
29
30use alioth_macros::Layout;
31use bitfield::bitfield;
32use parking_lot::Mutex;
33use serde::de::{self, MapAccess, Visitor};
34use serde::{Deserialize, Deserializer};
35use serde_aco::Help;
36use zerocopy::{FromBytes, Immutable, IntoBytes};
37
38#[cfg(target_arch = "x86_64")]
39use crate::arch::layout::{
40 PORT_FW_CFG_DATA, PORT_FW_CFG_DMA_HI, PORT_FW_CFG_DMA_LO, PORT_FW_CFG_SELECTOR,
41};
42use crate::device::{self, MmioDev, Pause};
43#[cfg(target_arch = "x86_64")]
44use crate::firmware::acpi::AcpiTable;
45#[cfg(target_arch = "x86_64")]
46use crate::loader::linux::bootparams::{
47 BootE820Entry, BootParams, E820_ACPI, E820_PMEM, E820_RAM, E820_RESERVED,
48};
49use crate::mem;
50use crate::mem::emulated::{Action, Mmio};
51use crate::mem::mapped::RamBus;
52#[cfg(target_arch = "x86_64")]
53use crate::mem::{MemRegionEntry, MemRegionType};
54use crate::utils::endian::{Bu16, Bu32, Bu64, Lu32};
55
56#[cfg(target_arch = "x86_64")]
57use self::acpi::create_acpi_loader;
58
59pub const SELECTOR_WR: u16 = 1 << 14;
60
61pub const FW_CFG_SIGNATURE: u16 = 0x00;
62pub const FW_CFG_ID: u16 = 0x01;
63pub const FW_CFG_UUID: u16 = 0x02;
64pub const FW_CFG_RAM_SIZE: u16 = 0x03;
65pub const FW_CFG_NOGRAPHIC: u16 = 0x04;
66pub const FW_CFG_NB_CPUS: u16 = 0x05;
67pub const FW_CFG_MACHINE_ID: u16 = 0x06;
68pub const FW_CFG_KERNEL_ADDR: u16 = 0x07;
69pub const FW_CFG_KERNEL_SIZE: u16 = 0x08;
70pub const FW_CFG_KERNEL_CMDLINE: u16 = 0x09;
71pub const FW_CFG_INITRD_ADDR: u16 = 0x0a;
72pub const FW_CFG_INITRD_SIZE: u16 = 0x0b;
73pub const FW_CFG_BOOT_DEVICE: u16 = 0x0c;
74pub const FW_CFG_NUMA: u16 = 0x0d;
75pub const FW_CFG_BOOT_MENU: u16 = 0x0e;
76pub const FW_CFG_MAX_CPUS: u16 = 0x0f;
77pub const FW_CFG_KERNEL_ENTRY: u16 = 0x10;
78pub const FW_CFG_KERNEL_DATA: u16 = 0x11;
79pub const FW_CFG_INITRD_DATA: u16 = 0x12;
80pub const FW_CFG_CMDLINE_ADDR: u16 = 0x13;
81pub const FW_CFG_CMDLINE_SIZE: u16 = 0x14;
82pub const FW_CFG_CMDLINE_DATA: u16 = 0x15;
83pub const FW_CFG_SETUP_ADDR: u16 = 0x16;
84pub const FW_CFG_SETUP_SIZE: u16 = 0x17;
85pub const FW_CFG_SETUP_DATA: u16 = 0x18;
86pub const FW_CFG_FILE_DIR: u16 = 0x19;
87pub const FW_CFG_KNOWN_ITEMS: usize = 0x20;
88
89pub const FW_CFG_FILE_FIRST: u16 = 0x20;
90pub const FW_CFG_DMA_SIGNATURE: [u8; 8] = *b"QEMU CFG";
91pub const FW_CFG_FEATURE: [u8; 4] = [0b11, 0, 0, 0];
92
93pub const FILE_NAME_SIZE: usize = 56;
94
95fn create_file_name(name: &str) -> [u8; FILE_NAME_SIZE] {
96 let mut c_name = [0u8; FILE_NAME_SIZE];
97 let c_len = std::cmp::min(FILE_NAME_SIZE - 1, name.len());
98 c_name[0..c_len].copy_from_slice(&name.as_bytes()[0..c_len]);
99 c_name
100}
101
102#[derive(Debug)]
103pub enum FwCfgContent {
104 Bytes(Vec<u8>),
105 Slice(&'static [u8]),
106 File(u64, File),
107 Lu32(Lu32),
108}
109
110struct FwCfgContentAccess<'a> {
111 content: &'a FwCfgContent,
112 offset: u32,
113}
114
115impl Read for FwCfgContentAccess<'_> {
116 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {8x
117 match self.content {8x
118 FwCfgContent::File(offset, f) => {2x
119 Seek::seek(&mut (&*f), SeekFrom::Start(offset + self.offset as u64))?;2x
120 Read::read(&mut (&*f), buf)2x
121 }
122 FwCfgContent::Bytes(b) => match b.get(self.offset as usize..) {2x
123 Some(mut s) => s.read(buf),1x
124 None => Err(ErrorKind::UnexpectedEof)?,1x
125 },
126 FwCfgContent::Slice(b) => match b.get(self.offset as usize..) {2x
127 Some(mut s) => s.read(buf),1x
128 None => Err(ErrorKind::UnexpectedEof)?,1x
129 },
130 FwCfgContent::Lu32(n) => match n.as_bytes().get(self.offset as usize..) {2x
131 Some(mut s) => s.read(buf),1x
132 None => Err(ErrorKind::UnexpectedEof)?,1x
133 },
134 }
135 }8x
136}
137
138impl Default for FwCfgContent {
139 fn default() -> Self {3x
140 FwCfgContent::Slice(&[])3x
141 }3x
142}
143
144impl FwCfgContent {
145 fn size(&self) -> Result<u32> {5x
146 let ret = match self {5x
147 FwCfgContent::Bytes(v) => v.len(),1x
148 FwCfgContent::File(offset, f) => (f.metadata()?.len() - offset) as usize,1x
149 FwCfgContent::Slice(s) => s.len(),2x
150 FwCfgContent::Lu32(n) => size_of_val(n),1x
151 };
152 u32::try_from(ret).map_err(|_| std::io::ErrorKind::InvalidInput.into())5x
153 }5x
154
155 fn access(&self, offset: u32) -> FwCfgContentAccess<'_> {8x
156 FwCfgContentAccess {8x
157 content: self,8x
158 offset,8x
159 }8x
160 }8x
161
162 fn read(&self, offset: u32) -> Option<u8> {6x
163 match self {6x
164 FwCfgContent::Bytes(b) => b.get(offset as usize).copied(),1x
165 FwCfgContent::Slice(s) => s.get(offset as usize).copied(),2x
166 FwCfgContent::File(o, f) => {2x
167 let mut buf = [0u8];2x
168 match f.read_exact_at(&mut buf, o + offset as u64) {2x
169 Ok(_) => Some(buf[0]),1x
170 Err(e) => {1x
171 log::error!("fw_cfg: reading {f:?}: {e:?}");1x
172 None1x
173 }
174 }
175 }
176 FwCfgContent::Lu32(n) => n.as_bytes().get(offset as usize).copied(),1x
177 }
178 }6x
179}
180
181#[derive(Debug, Default)]
182pub struct FwCfgItem {
183 pub name: String,
184 pub content: FwCfgContent,
185}
186
187/// https://www.qemu.org/docs/master/specs/fw_cfg.html
188#[derive(Debug)]
189pub struct FwCfg {
190 selector: u16,
191 data_offset: u32,
192 dma_address: u64,
193 items: Vec<FwCfgItem>, // 0x20 and above
194 known_items: [FwCfgContent; FW_CFG_KNOWN_ITEMS], // 0x0 to 0x19
195 memory: Arc<RamBus>,
196}
197
198#[repr(C)]
199#[derive(Debug, IntoBytes, FromBytes, Immutable, Layout)]
200struct FwCfgDmaAccess {
201 control: Bu32,
202 length: Bu32,
203 address: Bu64,
204}
205
206bitfield! {
207 struct AccessControl(u32);
208 impl Debug;
209 error, set_error: 0;
210 read, _: 1;
211 skip, _: 2;
212 select, _ : 3;
213 write, _ :4;
214 selector, _: 31, 16;
215}
216
217#[repr(C)]
218#[derive(Debug, IntoBytes, Immutable)]
219struct FwCfgFilesHeader {
220 count: Bu32,
221}
222
223#[repr(C)]
224#[derive(Debug, IntoBytes, Immutable)]
225struct FwCfgFile {
226 size: Bu32,
227 select: Bu16,
228 _reserved: u16,
229 name: [u8; FILE_NAME_SIZE],
230}
231
232impl FwCfg {
233 pub fn new(memory: Arc<RamBus>, items: Vec<FwCfgItem>) -> Result<Self> {
234 const DEFAULT_ITEM: FwCfgContent = FwCfgContent::Slice(&[]);
235 let mut known_items = [DEFAULT_ITEM; FW_CFG_KNOWN_ITEMS];
236 known_items[FW_CFG_SIGNATURE as usize] = FwCfgContent::Slice(&FW_CFG_DMA_SIGNATURE);
237 known_items[FW_CFG_ID as usize] = FwCfgContent::Slice(&FW_CFG_FEATURE);
238 let file_buf = Vec::from(FwCfgFilesHeader { count: 0.into() }.as_bytes());
239 known_items[FW_CFG_FILE_DIR as usize] = FwCfgContent::Bytes(file_buf);
240
241 let mut dev = Self {
242 selector: 0,
243 data_offset: 0,
244 dma_address: 0,
245 memory,
246 items: vec![],
247 known_items,
248 };
249 for item in items {
250 dev.add_item(item)?;
251 }
252 Ok(dev)
253 }
254
255 fn get_file_dir_mut(&mut self) -> &mut Vec<u8> {
256 let FwCfgContent::Bytes(file_buf) = &mut self.known_items[FW_CFG_FILE_DIR as usize] else {
257 unreachable!("fw_cfg: selector {FW_CFG_FILE_DIR:#x} should be FwCfgContent::Byte!")
258 };
259 file_buf
260 }
261
262 fn update_count(&mut self) {
263 let header = FwCfgFilesHeader {
264 count: (self.items.len() as u32).into(),
265 };
266 self.get_file_dir_mut()[0..4].copy_from_slice(header.as_bytes());
267 }
268
269 #[cfg(target_arch = "x86_64")]
270 pub(crate) fn add_e820(&mut self, mem_regions: &[(u64, MemRegionEntry)]) -> Result<()> {
271 let mut bytes = vec![];
272 for (addr, region) in mem_regions.iter() {
273 let type_ = match region.type_ {
274 MemRegionType::Ram => E820_RAM,
275 MemRegionType::Reserved => E820_RESERVED,
276 MemRegionType::Acpi => E820_ACPI,
277 MemRegionType::Pmem => E820_PMEM,
278 MemRegionType::Hidden => continue,
279 };
280 let entry = BootE820Entry {
281 addr: *addr,
282 size: region.size,
283 type_,
284 };
285 bytes.extend_from_slice(entry.as_bytes());
286 }
287 let item = FwCfgItem {
288 name: "etc/e820".to_owned(),
289 content: FwCfgContent::Bytes(bytes),
290 };
291 self.add_item(item)
292 }
293
294 #[cfg(target_arch = "x86_64")]
295 pub(crate) fn add_acpi(&mut self, acpi_table: AcpiTable) -> Result<()> {
296 let [table_loader, acpi_rsdp, apci_tables] = create_acpi_loader(acpi_table);
297 self.add_item(table_loader)?;
298 self.add_item(acpi_rsdp)?;
299 self.add_item(apci_tables)
300 }
301
302 #[cfg(target_arch = "x86_64")]
303 pub fn add_kernel_data(&mut self, p: &Path) -> Result<()> {
304 let file = File::open(p)?;
305 let mut buffer = vec![0u8; size_of::<BootParams>()];
306 file.read_exact_at(&mut buffer, 0)?;
307 let bp = BootParams::mut_from_bytes(&mut buffer).unwrap();
308 if bp.hdr.setup_sects == 0 {
309 bp.hdr.setup_sects = 4;
310 }
311 bp.hdr.type_of_loader = 0xff;
312 let kernel_start = (bp.hdr.setup_sects as usize + 1) * 512;
313 self.known_items[FW_CFG_SETUP_SIZE as usize] =
314 FwCfgContent::Lu32((buffer.len() as u32).into());
315 self.known_items[FW_CFG_SETUP_DATA as usize] = FwCfgContent::Bytes(buffer);
316 self.known_items[FW_CFG_KERNEL_SIZE as usize] =
317 FwCfgContent::Lu32((file.metadata()?.len() as u32 - kernel_start as u32).into());
318 self.known_items[FW_CFG_KERNEL_DATA as usize] =
319 FwCfgContent::File(kernel_start as u64, file);
320 Ok(())
321 }
322
323 pub fn add_initramfs_data(&mut self, p: &Path) -> Result<()> {
324 let file = File::open(p)?;
325 let initramfs_size = file.metadata()?.len() as u32;
326 self.known_items[FW_CFG_INITRD_SIZE as usize] = FwCfgContent::Lu32(initramfs_size.into());
327 self.known_items[FW_CFG_INITRD_DATA as usize] = FwCfgContent::File(0, file);
328 Ok(())
329 }
330
331 pub fn add_kernel_cmdline(&mut self, s: CString) {
332 let bytes = s.into_bytes_with_nul();
333 self.known_items[FW_CFG_CMDLINE_SIZE as usize] =
334 FwCfgContent::Lu32((bytes.len() as u32).into());
335 self.known_items[FW_CFG_CMDLINE_DATA as usize] = FwCfgContent::Bytes(bytes);
336 }
337
338 pub fn add_item(&mut self, item: FwCfgItem) -> Result<()> {
339 let index = self.items.len();
340 let c_name = create_file_name(&item.name);
341 let size = item.content.size()?;
342 let cfg_file = FwCfgFile {
343 size: size.into(),
344 select: (FW_CFG_FILE_FIRST + index as u16).into(),
345 _reserved: 0,
346 name: c_name,
347 };
348 self.get_file_dir_mut()
349 .extend_from_slice(cfg_file.as_bytes());
350 self.items.push(item);
351 self.update_count();
352 Ok(())
353 }
354
355 fn dma_read_content(
356 &self,
357 content: &FwCfgContent,
358 offset: u32,
359 len: u32,
360 address: u64,
361 ) -> Result<u32> {
362 let content_size = content.size()?.saturating_sub(offset);
363 let op_size = std::cmp::min(content_size, len);
364 let r = self
365 .memory
366 .write_range(address, op_size as u64, content.access(offset));
367 match r {
368 Err(e) => {
369 log::error!("fw_cfg: dam read error: {e:x?}");
370 Err(ErrorKind::InvalidInput.into())
371 }
372 Ok(()) => Ok(op_size),
373 }
374 }
375
376 fn dma_read(&mut self, selector: u16, len: u32, address: u64) -> Result<()> {
377 let op_size = if let Some(content) = self.known_items.get(selector as usize) {
378 self.dma_read_content(content, self.data_offset, len, address)
379 } else if let Some(item) = self.items.get((selector - FW_CFG_FILE_FIRST) as usize) {
380 self.dma_read_content(&item.content, self.data_offset, len, address)
381 } else {
382 log::error!("fw_cfg: selector {selector:#x} does not exist.");
383 Err(ErrorKind::NotFound.into())
384 }?;
385 self.data_offset += op_size;
386 Ok(())
387 }
388
389 fn dma_write(&self, _selector: u16, _len: u32, _address: u64) -> Result<()> {
390 unimplemented!()
391 }
392
393 fn do_dma(&mut self) {
394 let dma_address = self.dma_address;
395 let dma_access: FwCfgDmaAccess = match self.memory.read_t(dma_address) {
396 Ok(access) => access,
397 Err(e) => {
398 log::error!("fw_cfg: invalid address of dma access {dma_address:#x}: {e:?}");
399 return;
400 }
401 };
402 let control = AccessControl(dma_access.control.into());
403 if control.select() {
404 self.selector = control.select() as u16;
405 }
406 let len = dma_access.length.to_ne();
407 let addr = dma_access.address.to_ne();
408 let ret = if control.read() {
409 self.dma_read(self.selector, len, addr)
410 } else if control.write() {
411 self.dma_write(self.selector, len, addr)
412 } else if control.skip() {
413 self.data_offset += len;
414 Ok(())
415 } else {
416 Err(ErrorKind::InvalidData.into())
417 };
418 let mut access_resp = AccessControl(0);
419 if let Err(e) = ret {
420 log::error!("fw_cfg: dma operation {dma_access:x?}: {e:x?}");
421 access_resp.set_error(true);
422 }
423 if let Err(e) = self.memory.write_t(
424 dma_address + FwCfgDmaAccess::OFFSET_CONTROL as u64,
425 &Bu32::from(access_resp.0),
426 ) {
427 log::error!("fw_cfg: finishing dma: {e:?}")
428 }
429 }
430
431 fn read_data(&mut self) -> u8 {
432 let ret = if let Some(content) = self.known_items.get(self.selector as usize) {
433 content.read(self.data_offset)
434 } else if let Some(item) = self.items.get((self.selector - FW_CFG_FILE_FIRST) as usize) {
435 item.content.read(self.data_offset)
436 } else {
437 log::error!("fw_cfg: selector {:#x} does not exist.", self.selector);
438 None
439 };
440 if let Some(val) = ret {
441 self.data_offset += 1;
442 val
443 } else {
444 0
445 }
446 }
447
448 fn write_data(&self, _val: u8) {
449 if self.selector & SELECTOR_WR != SELECTOR_WR {
450 log::error!("fw_cfg: data is read only");
451 return;
452 }
453 log::warn!("fw_cfg: write data no op.")
454 }
455}
456
457impl Mmio for Mutex<FwCfg> {
458 fn size(&self) -> u64 {
459 16
460 }
461
462 fn read(&self, offset: u64, size: u8) -> mem::Result<u64> {
463 let mut fw_cfg = self.lock();
464 let port = offset as u16 + PORT_FW_CFG_SELECTOR;
465 let ret = match (port, size) {
466 (PORT_FW_CFG_SELECTOR, _) => {
467 log::error!("fw_cfg: selector registeris write-only.");
468 0
469 }
470 (PORT_FW_CFG_DATA, 1) => fw_cfg.read_data() as u64,
471 (PORT_FW_CFG_DMA_HI, 4) => {
472 let addr = fw_cfg.dma_address;
473 let addr_hi = (addr >> 32) as u32;
474 addr_hi.to_be() as u64
475 }
476 (PORT_FW_CFG_DMA_LO, 4) => {
477 let addr = fw_cfg.dma_address;
478 let addr_lo = (addr & 0xffff_ffff) as u32;
479 addr_lo.to_be() as u64
480 }
481 _ => {
482 log::error!("fw_cfg: read unknown port {port:#x} with size {size}.");
483 0
484 }
485 };
486 Ok(ret)
487 }
488
489 fn write(&self, offset: u64, size: u8, val: u64) -> mem::Result<Action> {
490 let mut fw_cfg = self.lock();
491 let port = offset as u16 + PORT_FW_CFG_SELECTOR;
492 match (port, size) {
493 (PORT_FW_CFG_SELECTOR, 2) => {
494 fw_cfg.selector = val as u16;
495 fw_cfg.data_offset = 0;
496 }
497 (PORT_FW_CFG_DATA, 1) => fw_cfg.write_data(val as u8),
498 (PORT_FW_CFG_DMA_HI, 4) => {
499 fw_cfg.dma_address &= 0xffff_ffff;
500 fw_cfg.dma_address |= (u32::from_be(val as u32) as u64) << 32;
501 }
502 (PORT_FW_CFG_DMA_LO, 4) => {
503 fw_cfg.dma_address &= !0xffff_ffff;
504 fw_cfg.dma_address |= u32::from_be(val as u32) as u64;
505 fw_cfg.do_dma();
506 }
507 _ => log::error!(
508 "fw_cfg: write 0x{val:0width$x} to unknown port {port:#x}.",
509 width = 2 * size as usize,
510 ),
511 };
512 Ok(Action::None)
513 }
514}
515
516impl Pause for Mutex<FwCfg> {
517 fn pause(&self) -> device::Result<()> {
518 Ok(())
519 }
520
521 fn resume(&self) -> device::Result<()> {
522 Ok(())
523 }
524}
525
526impl MmioDev for Mutex<FwCfg> {}
527
528#[derive(Debug, PartialEq, Eq, Deserialize, Help)]
529pub enum FwCfgContentParam {
530 /// Path to a file with binary contents.
531 #[serde(alias = "file")]
532 File(Box<Path>),
533 /// A UTF-8 encoded string.
534 #[serde(alias = "string")]
535 String(String),
536}
537
538#[derive(Debug, PartialEq, Eq, Help)]
539pub struct FwCfgItemParam {
540 /// Selector key of an item.
541 pub name: String,
542 /// Item content.
543 #[serde_aco(flatten)]
544 pub content: FwCfgContentParam,
545}
546
547impl<'de> Deserialize<'de> for FwCfgItemParam {
548 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>2x
549 where2x
550 D: Deserializer<'de>,2x
551 {
552 #[derive(Deserialize)]
553 #[serde(field_identifier, rename_all = "lowercase")]
554 enum Field {
555 Name,
556 File,
557 String,
558 }
559
560 struct ParamVisitor;
561
562 impl<'de> Visitor<'de> for ParamVisitor {
563 type Value = FwCfgItemParam;
564
565 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
566 formatter.write_str("struct FwCfgItemParam")
567 }
568
569 fn visit_map<V>(self, mut map: V) -> std::result::Result<Self::Value, V::Error>2x
570 where2x
571 V: MapAccess<'de>,2x
572 {
573 let mut name = None;2x
574 let mut content = None;2x
575 while let Some(key) = map.next_key()? {6x
576 match key {4x
577 Field::Name => {
578 if name.is_some() {2x
579 return Err(de::Error::duplicate_field("file"));
580 }2x
581 name = Some(map.next_value()?);2x
582 }
583 Field::String => {
584 if content.is_some() {1x
585 return Err(de::Error::duplicate_field("string,file"));
586 }1x
587 content = Some(FwCfgContentParam::String(map.next_value()?));1x
588 }
589 Field::File => {
590 if content.is_some() {1x
591 return Err(de::Error::duplicate_field("string,file"));
592 }1x
593 content = Some(FwCfgContentParam::File(map.next_value()?));1x
594 }
595 }
596 }
597 let name = name.ok_or_else(|| de::Error::missing_field("name"))?;2x
598 let content = content.ok_or_else(|| de::Error::missing_field("file,string"))?;2x
599 Ok(FwCfgItemParam { name, content })2x
600 }2x
601 }
602
603 const FIELDS: &[&str] = &["name", "file", "string"];
604 deserializer.deserialize_struct("FwCfgItemParam", FIELDS, ParamVisitor)2x
605 }2x
606}
607
608impl FwCfgItemParam {
609 pub fn build(self) -> Result<FwCfgItem> {
610 match self.content {
611 FwCfgContentParam::File(file) => {
612 let f = File::open(file)?;
613 Ok(FwCfgItem {
614 name: self.name,
615 content: FwCfgContent::File(0, f),
616 })
617 }
618 FwCfgContentParam::String(string) => Ok(FwCfgItem {
619 name: self.name,
620 content: FwCfgContent::Bytes(string.into()),
621 }),
622 }
623 }
624}
625
626#[cfg(test)]
627#[path = "fw_cfg_test.rs"]
628mod tests;
629