fw_cfg.rs21.21%
1
// Copyright 2024 Google LLC2
//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 at6
//7
// https://www.apache.org/licenses/LICENSE-2.08
//9
// Unless required by applicable law or agreed to in writing, software10
// 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 and13
// limitations under the License.14
15
#[cfg(target_arch = "x86_64")]16
pub mod acpi;17
18
use std::ffi::CString;19
use std::fmt;20
use std::fs::File;21
use std::io::{ErrorKind, Read, Result, Seek, SeekFrom};22
#[cfg(target_arch = "x86_64")]23
use std::mem::size_of;24
use std::mem::size_of_val;25
use std::os::unix::fs::FileExt;26
#[cfg(target_arch = "x86_64")]27
use std::path::Path;28
use std::sync::Arc;29
30
use alioth_macros::Layout;31
use bitfield::bitfield;32
use parking_lot::Mutex;33
use serde::de::{self, MapAccess, Visitor};34
use serde::{Deserialize, Deserializer};35
use serde_aco::Help;36
use zerocopy::{FromBytes, Immutable, IntoBytes};37
38
#[cfg(target_arch = "x86_64")]39
use crate::arch::layout::{40
PORT_FW_CFG_DATA, PORT_FW_CFG_DMA_HI, PORT_FW_CFG_DMA_LO, PORT_FW_CFG_SELECTOR,41
};42
use crate::device::{self, MmioDev, Pause};43
#[cfg(target_arch = "x86_64")]44
use crate::firmware::acpi::AcpiTable;45
#[cfg(target_arch = "x86_64")]46
use crate::loader::linux::bootparams::{47
BootE820Entry, BootParams, E820_ACPI, E820_PMEM, E820_RAM, E820_RESERVED,48
};49
use crate::mem;50
use crate::mem::emulated::{Action, Mmio};51
use crate::mem::mapped::RamBus;52
#[cfg(target_arch = "x86_64")]53
use crate::mem::{MemRegionEntry, MemRegionType};54
use crate::utils::endian::{Bu16, Bu32, Bu64, Lu32};55
56
#[cfg(target_arch = "x86_64")]57
use self::acpi::create_acpi_loader;58
59
pub const SELECTOR_WR: u16 = 1 << 14;60
61
pub const FW_CFG_SIGNATURE: u16 = 0x00;62
pub const FW_CFG_ID: u16 = 0x01;63
pub const FW_CFG_UUID: u16 = 0x02;64
pub const FW_CFG_RAM_SIZE: u16 = 0x03;65
pub const FW_CFG_NOGRAPHIC: u16 = 0x04;66
pub const FW_CFG_NB_CPUS: u16 = 0x05;67
pub const FW_CFG_MACHINE_ID: u16 = 0x06;68
pub const FW_CFG_KERNEL_ADDR: u16 = 0x07;69
pub const FW_CFG_KERNEL_SIZE: u16 = 0x08;70
pub const FW_CFG_KERNEL_CMDLINE: u16 = 0x09;71
pub const FW_CFG_INITRD_ADDR: u16 = 0x0a;72
pub const FW_CFG_INITRD_SIZE: u16 = 0x0b;73
pub const FW_CFG_BOOT_DEVICE: u16 = 0x0c;74
pub const FW_CFG_NUMA: u16 = 0x0d;75
pub const FW_CFG_BOOT_MENU: u16 = 0x0e;76
pub const FW_CFG_MAX_CPUS: u16 = 0x0f;77
pub const FW_CFG_KERNEL_ENTRY: u16 = 0x10;78
pub const FW_CFG_KERNEL_DATA: u16 = 0x11;79
pub const FW_CFG_INITRD_DATA: u16 = 0x12;80
pub const FW_CFG_CMDLINE_ADDR: u16 = 0x13;81
pub const FW_CFG_CMDLINE_SIZE: u16 = 0x14;82
pub const FW_CFG_CMDLINE_DATA: u16 = 0x15;83
pub const FW_CFG_SETUP_ADDR: u16 = 0x16;84
pub const FW_CFG_SETUP_SIZE: u16 = 0x17;85
pub const FW_CFG_SETUP_DATA: u16 = 0x18;86
pub const FW_CFG_FILE_DIR: u16 = 0x19;87
pub const FW_CFG_KNOWN_ITEMS: usize = 0x20;88
89
pub const FW_CFG_FILE_FIRST: u16 = 0x20;90
pub const FW_CFG_DMA_SIGNATURE: [u8; 8] = *b"QEMU CFG";91
pub const FW_CFG_FEATURE: [u8; 4] = [0b11, 0, 0, 0];92
93
pub const FILE_NAME_SIZE: usize = 56;94
95
fn 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_name100
}101
102
#[derive(Debug)]103
pub enum FwCfgContent {104
Bytes(Vec<u8>),105
Slice(&'static [u8]),106
File(u64, File),107
Lu32(Lu32),108
}109
110
struct FwCfgContentAccess<'a> {111
content: &'a FwCfgContent,112
offset: u32,113
}114
115
impl Read for FwCfgContentAccess<'_> {116
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {8x117
match self.content {8x118
FwCfgContent::File(offset, f) => {2x119
Seek::seek(&mut (&*f), SeekFrom::Start(offset + self.offset as u64))?;2x120
Read::read(&mut (&*f), buf)2x121
}122
FwCfgContent::Bytes(b) => match b.get(self.offset as usize..) {2x123
Some(mut s) => s.read(buf),1x124
None => Err(ErrorKind::UnexpectedEof)?,1x125
},126
FwCfgContent::Slice(b) => match b.get(self.offset as usize..) {2x127
Some(mut s) => s.read(buf),1x128
None => Err(ErrorKind::UnexpectedEof)?,1x129
},130
FwCfgContent::Lu32(n) => match n.as_bytes().get(self.offset as usize..) {2x131
Some(mut s) => s.read(buf),1x132
None => Err(ErrorKind::UnexpectedEof)?,1x133
},134
}135
}8x136
}137
138
impl Default for FwCfgContent {139
fn default() -> Self {3x140
FwCfgContent::Slice(&[])3x141
}3x142
}143
144
impl FwCfgContent {145
fn size(&self) -> Result<u32> {5x146
let ret = match self {5x147
FwCfgContent::Bytes(v) => v.len(),1x148
FwCfgContent::File(offset, f) => (f.metadata()?.len() - offset) as usize,1x149
FwCfgContent::Slice(s) => s.len(),2x150
FwCfgContent::Lu32(n) => size_of_val(n),1x151
};152
u32::try_from(ret).map_err(|_| std::io::ErrorKind::InvalidInput.into())5x153
}5x154
155
fn access(&self, offset: u32) -> FwCfgContentAccess<'_> {8x156
FwCfgContentAccess {8x157
content: self,8x158
offset,8x159
}8x160
}8x161
162
fn read(&self, offset: u32) -> Option<u8> {6x163
match self {6x164
FwCfgContent::Bytes(b) => b.get(offset as usize).copied(),1x165
FwCfgContent::Slice(s) => s.get(offset as usize).copied(),2x166
FwCfgContent::File(o, f) => {2x167
let mut buf = [0u8];2x168
match f.read_exact_at(&mut buf, o + offset as u64) {2x169
Ok(_) => Some(buf[0]),1x170
Err(e) => {1x171
log::error!("fw_cfg: reading {f:?}: {e:?}");1x172
None1x173
}174
}175
}176
FwCfgContent::Lu32(n) => n.as_bytes().get(offset as usize).copied(),1x177
}178
}6x179
}180
181
#[derive(Debug, Default)]182
pub struct FwCfgItem {183
pub name: String,184
pub content: FwCfgContent,185
}186
187
/// https://www.qemu.org/docs/master/specs/fw_cfg.html188
#[derive(Debug)]189
pub struct FwCfg {190
selector: u16,191
data_offset: u32,192
dma_address: u64,193
items: Vec<FwCfgItem>, // 0x20 and above194
known_items: [FwCfgContent; FW_CFG_KNOWN_ITEMS], // 0x0 to 0x19195
memory: Arc<RamBus>,196
}197
198
#[repr(C)]199
#[derive(Debug, IntoBytes, FromBytes, Immutable, Layout)]200
struct FwCfgDmaAccess {201
control: Bu32,202
length: Bu32,203
address: Bu64,204
}205
206
bitfield! {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)]219
struct FwCfgFilesHeader {220
count: Bu32,221
}222
223
#[repr(C)]224
#[derive(Debug, IntoBytes, Immutable)]225
struct FwCfgFile {226
size: Bu32,227
select: Bu16,228
_reserved: u16,229
name: [u8; FILE_NAME_SIZE],230
}231
232
impl 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_buf260
}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 = self365
.memory366
.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
None439
};440
if let Some(val) = ret {441
self.data_offset += 1;442
val443
} else {444
0445
}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
457
impl Mmio for Mutex<FwCfg> {458
fn size(&self) -> u64 {459
16460
}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
0469
}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 u64475
}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 u64480
}481
_ => {482
log::error!("fw_cfg: read unknown port {port:#x} with size {size}.");483
0484
}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
516
impl 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
526
impl MmioDev for Mutex<FwCfg> {}527
528
#[derive(Debug, PartialEq, Eq, Deserialize, Help)]529
pub 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)]539
pub 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
547
impl<'de> Deserialize<'de> for FwCfgItemParam {548
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>2x549
where2x550
D: Deserializer<'de>,2x551
{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>2x570
where2x571
V: MapAccess<'de>,2x572
{573
let mut name = None;2x574
let mut content = None;2x575
while let Some(key) = map.next_key()? {6x576
match key {4x577
Field::Name => {578
if name.is_some() {2x579
return Err(de::Error::duplicate_field("file"));580
}2x581
name = Some(map.next_value()?);2x582
}583
Field::String => {584
if content.is_some() {1x585
return Err(de::Error::duplicate_field("string,file"));586
}1x587
content = Some(FwCfgContentParam::String(map.next_value()?));1x588
}589
Field::File => {590
if content.is_some() {1x591
return Err(de::Error::duplicate_field("string,file"));592
}1x593
content = Some(FwCfgContentParam::File(map.next_value()?));1x594
}595
}596
}597
let name = name.ok_or_else(|| de::Error::missing_field("name"))?;2x598
let content = content.ok_or_else(|| de::Error::missing_field("file,string"))?;2x599
Ok(FwCfgItemParam { name, content })2x600
}2x601
}602
603
const FIELDS: &[&str] = &["name", "file", "string"];604
deserializer.deserialize_struct("FwCfgItemParam", FIELDS, ParamVisitor)2x605
}2x606
}607
608
impl 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"]628
mod tests;629