blob: f56d6e001f23e0b2a28e208c5ea23ab3abccb49e [file] [log] [blame]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +00001// Copyright 2022, The Android Open Source Project
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// http://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//! High-level FDT functions.
16
Jiyong Parkb87f3302023-03-21 10:03:11 +090017use crate::cstr;
Jiyong Park00ceff32023-03-13 05:43:23 +000018use crate::helpers::GUEST_PAGE_SIZE;
19use crate::RebootReason;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000020use core::ffi::CStr;
Jiyong Park00ceff32023-03-13 05:43:23 +000021use core::num::NonZeroUsize;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000022use core::ops::Range;
Jiyong Park00ceff32023-03-13 05:43:23 +000023use fdtpci::PciMemoryFlags;
24use fdtpci::PciRangeType;
25use libfdt::AddressRange;
26use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000027use libfdt::Fdt;
28use libfdt::FdtError;
Jiyong Park00ceff32023-03-13 05:43:23 +000029use log::error;
30use tinyvec::ArrayVec;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000031
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000032/// Extract from /config the address range containing the pre-loaded kernel.
33pub fn kernel_range(fdt: &libfdt::Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090034 let addr = cstr!("kernel-address");
35 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000036
Jiyong Parkb87f3302023-03-21 10:03:11 +090037 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000038 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
39 let addr = addr as usize;
40 let size = size as usize;
41
42 return Ok(Some(addr..(addr + size)));
43 }
44 }
45
46 Ok(None)
47}
48
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000049/// Extract from /chosen the address range containing the pre-loaded ramdisk.
50pub fn initrd_range(fdt: &libfdt::Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090051 let start = cstr!("linux,initrd-start");
52 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000053
54 if let Some(chosen) = fdt.chosen()? {
55 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
56 return Ok(Some((start as usize)..(end as usize)));
57 }
58 }
59
60 Ok(None)
61}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +000062
Jiyong Park00ceff32023-03-13 05:43:23 +000063/// Read and validate the size and base address of memory, and returns the size
64fn parse_memory_node(fdt: &libfdt::Fdt) -> Result<NonZeroUsize, RebootReason> {
65 let memory_range = fdt
66 .memory()
67 // Actually, these checks are unnecessary because we read /memory node in entry.rs
68 // where the exactly same checks are done. We are repeating the same check just for
69 // extra safety (in case when the code structure changes in the future).
70 .map_err(|e| {
71 error!("Failed to get /memory from the DT: {e}");
72 RebootReason::InvalidFdt
73 })?
74 .ok_or_else(|| {
75 error!("Node /memory was found empty");
76 RebootReason::InvalidFdt
77 })?
78 .next()
79 .ok_or_else(|| {
80 error!("Failed to read memory range from the DT");
81 RebootReason::InvalidFdt
82 })?;
83
84 let base = memory_range.start;
85 if base as u64 != DeviceTreeInfo::RAM_BASE_ADDR {
86 error!("Memory base address {:#x} is not {:#x}", base, DeviceTreeInfo::RAM_BASE_ADDR);
87 return Err(RebootReason::InvalidFdt);
88 }
89
90 let size = memory_range.len(); // end is exclusive
91 if size % GUEST_PAGE_SIZE != 0 {
92 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
93 return Err(RebootReason::InvalidFdt);
94 }
95 // In the u-boot implementation, we checked if base + size > u64::MAX, but we don't need that
96 // because memory() function uses checked_add when constructing the Range object. If an
97 // overflow happened, we should have gotten None from the next() call above and would have
98 // bailed already.
99
100 NonZeroUsize::new(size).ok_or_else(|| {
101 error!("Memory size can't be 0");
102 RebootReason::InvalidFdt
103 })
104}
105
106/// Read the number of CPUs
107fn parse_cpu_nodes(fdt: &libfdt::Fdt) -> Result<NonZeroUsize, RebootReason> {
108 let num = fdt
Jiyong Parkb87f3302023-03-21 10:03:11 +0900109 .compatible_nodes(cstr!("arm,arm-v8"))
Jiyong Park00ceff32023-03-13 05:43:23 +0000110 .map_err(|e| {
111 error!("Failed to read compatible nodes \"arm,arm-v8\" from DT: {e}");
112 RebootReason::InvalidFdt
113 })?
114 .count();
115 NonZeroUsize::new(num).ok_or_else(|| {
116 error!("Number of CPU can't be 0");
117 RebootReason::InvalidFdt
118 })
119}
120
121#[derive(Debug)]
122#[allow(dead_code)] // TODO: remove this
123struct PciInfo {
124 ranges: [Range<u64>; 2],
125 num_irq: usize,
126}
127
128/// Read and validate PCI node
129fn parse_pci_nodes(fdt: &libfdt::Fdt) -> Result<PciInfo, RebootReason> {
130 let node = fdt
Jiyong Parkb87f3302023-03-21 10:03:11 +0900131 .compatible_nodes(cstr!("pci-host-cam-generic"))
Jiyong Park00ceff32023-03-13 05:43:23 +0000132 .map_err(|e| {
133 error!("Failed to read compatible node \"pci-host-cam-generic\" from DT: {e}");
134 RebootReason::InvalidFdt
135 })?
136 .next()
137 .ok_or_else(|| {
138 // pvmfw requires at least one pci device (virtio-blk) for the instance disk. So,
139 // let's fail early.
140 error!("Compatible node \"pci-host-cam-generic\" doesn't exist");
141 RebootReason::InvalidFdt
142 })?;
143
144 let mut iter = node
145 .ranges::<(u32, u64), u64, u64>()
146 .map_err(|e| {
147 error!("Failed to read ranges from PCI node: {e}");
148 RebootReason::InvalidFdt
149 })?
150 .ok_or_else(|| {
151 error!("PCI node missing ranges property");
152 RebootReason::InvalidFdt
153 })?;
154
155 let range0 = iter.next().ok_or_else(|| {
156 error!("First range missing in PCI node");
157 RebootReason::InvalidFdt
158 })?;
159 let range0 = get_and_validate_pci_range(&range0)?;
160
161 let range1 = iter.next().ok_or_else(|| {
162 error!("Second range missing in PCI node");
163 RebootReason::InvalidFdt
164 })?;
165 let range1 = get_and_validate_pci_range(&range1)?;
166
167 let num_irq = count_and_validate_pci_irq_masks(&node)?;
168
169 validate_pci_irq_maps(&node)?;
170
171 Ok(PciInfo { ranges: [range0, range1], num_irq })
172}
173
174fn get_and_validate_pci_range(
175 range: &AddressRange<(u32, u64), u64, u64>,
176) -> Result<Range<u64>, RebootReason> {
177 let mem_flags = PciMemoryFlags(range.addr.0);
178 let range_type = mem_flags.range_type();
179 let prefetchable = mem_flags.prefetchable();
180 let bus_addr = range.addr.1;
181 let cpu_addr = range.parent_addr;
182 let size = range.size;
183 if range_type != PciRangeType::Memory64 {
184 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
185 return Err(RebootReason::InvalidFdt);
186 }
187 if prefetchable {
188 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
189 return Err(RebootReason::InvalidFdt);
190 }
191 // Enforce ID bus-to-cpu mappings, as used by crosvm.
192 if bus_addr != cpu_addr {
193 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
194 return Err(RebootReason::InvalidFdt);
195 }
196 let bus_end = bus_addr.checked_add(size).ok_or_else(|| {
197 error!("PCI address range size {:#x} too big", size);
198 RebootReason::InvalidFdt
199 })?;
200 Ok(bus_addr..bus_end)
201}
202
203/// Iterator that takes N cells as a chunk
204struct CellChunkIterator<'a, const N: usize> {
205 cells: CellIterator<'a>,
206}
207
208impl<'a, const N: usize> CellChunkIterator<'a, N> {
209 fn new(cells: CellIterator<'a>) -> Self {
210 Self { cells }
211 }
212}
213
214impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
215 type Item = [u32; N];
216 fn next(&mut self) -> Option<Self::Item> {
217 let mut ret: Self::Item = [0; N];
218 for i in ret.iter_mut() {
219 *i = self.cells.next()?;
220 }
221 Some(ret)
222 }
223}
224
225fn count_and_validate_pci_irq_masks(pci_node: &libfdt::FdtNode) -> Result<usize, RebootReason> {
226 const IRQ_MASK_CELLS: usize = 4;
227 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
228 const IRQ_MASK_ADDR_ME: u32 = 0x0;
229 const IRQ_MASK_ADDR_LO: u32 = 0x0;
230 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
231 const EXPECTED: [u32; IRQ_MASK_CELLS] =
232 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Parkb87f3302023-03-21 10:03:11 +0900233
Jiyong Park00ceff32023-03-13 05:43:23 +0000234 let mut irq_count: usize = 0;
235 for irq_mask in CellChunkIterator::<IRQ_MASK_CELLS>::new(
236 pci_node
Jiyong Parkb87f3302023-03-21 10:03:11 +0900237 .getprop_cells(cstr!("interrupt-map-mask"))
Jiyong Park00ceff32023-03-13 05:43:23 +0000238 .map_err(|e| {
239 error!("Failed to read interrupt-map-mask property: {e}");
240 RebootReason::InvalidFdt
241 })?
242 .ok_or_else(|| {
243 error!("PCI node missing interrupt-map-mask property");
244 RebootReason::InvalidFdt
245 })?,
246 ) {
247 if irq_mask != EXPECTED {
248 error!("invalid irq mask {:?}", irq_mask);
249 return Err(RebootReason::InvalidFdt);
250 }
251 irq_count += 1;
252 }
253 Ok(irq_count)
254}
255
256fn validate_pci_irq_maps(pci_node: &libfdt::FdtNode) -> Result<(), RebootReason> {
257 const IRQ_MAP_CELLS: usize = 10;
258 const PCI_DEVICE_IDX: usize = 11;
259 const PCI_IRQ_ADDR_ME: u32 = 0;
260 const PCI_IRQ_ADDR_LO: u32 = 0;
261 const PCI_IRQ_INTC: u32 = 1;
262 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
263 const GIC_SPI: u32 = 0;
264 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
265
266 let mut phys_hi: u32 = 0;
267 let mut irq_nr = AARCH64_IRQ_BASE;
268
Jiyong Park00ceff32023-03-13 05:43:23 +0000269 for irq_map in CellChunkIterator::<IRQ_MAP_CELLS>::new(
270 pci_node
Jiyong Parkb87f3302023-03-21 10:03:11 +0900271 .getprop_cells(cstr!("interrupt-map"))
Jiyong Park00ceff32023-03-13 05:43:23 +0000272 .map_err(|e| {
273 error!("Failed to read interrupt-map property: {e}");
274 RebootReason::InvalidFdt
275 })?
276 .ok_or_else(|| {
277 error!("PCI node missing interrupt-map property");
278 RebootReason::InvalidFdt
279 })?,
280 ) {
281 phys_hi += 0x1 << PCI_DEVICE_IDX;
282
283 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
284 let pci_irq_number = irq_map[3];
285 let _controller_phandle = irq_map[4]; // skipped.
286 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
287 // interrupt-cells is <3> for GIC
288 let gic_peripheral_interrupt_type = irq_map[7];
289 let gic_irq_number = irq_map[8];
290 let gic_irq_type = irq_map[9];
291
292 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
293
294 if pci_addr != expected_pci_addr {
295 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
296 {:#x} {:#x} {:#x}",
297 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
298 return Err(RebootReason::InvalidFdt);
299 }
300 if pci_irq_number != PCI_IRQ_INTC {
301 error!(
302 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
303 pci_irq_number, PCI_IRQ_INTC
304 );
305 return Err(RebootReason::InvalidFdt);
306 }
307 if gic_addr != (0, 0) {
308 error!(
309 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
310 {:#x} {:#x}",
311 gic_addr.0, gic_addr.1, 0, 0
312 );
313 return Err(RebootReason::InvalidFdt);
314 }
315 if gic_peripheral_interrupt_type != GIC_SPI {
316 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
317 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
318 return Err(RebootReason::InvalidFdt);
319 }
320 if gic_irq_number != irq_nr {
321 error!(
322 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
323 gic_irq_number, irq_nr
324 );
325 return Err(RebootReason::InvalidFdt);
326 }
327 irq_nr += 1; // move to next irq
328 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
329 error!(
330 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
331 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
332 );
333 return Err(RebootReason::InvalidFdt);
334 }
335 }
336 Ok(())
337}
338
339#[derive(Default, Debug)]
340#[allow(dead_code)] // TODO: remove this
341pub struct SerialInfo {
342 addrs: ArrayVec<[u64; Self::SERIAL_MAX_COUNT]>,
343}
344
345impl SerialInfo {
346 const SERIAL_MAX_COUNT: usize = 4;
347}
348
349fn parse_serial_nodes(fdt: &libfdt::Fdt) -> Result<SerialInfo, RebootReason> {
350 let mut ret: SerialInfo = Default::default();
351 for (i, node) in fdt
Jiyong Parkb87f3302023-03-21 10:03:11 +0900352 .compatible_nodes(cstr!("ns16550a"))
Jiyong Park00ceff32023-03-13 05:43:23 +0000353 .map_err(|e| {
354 error!("Failed to read compatible nodes \"ns16550a\" from DT: {e}");
355 RebootReason::InvalidFdt
356 })?
357 .enumerate()
358 {
359 if i >= ret.addrs.capacity() {
360 error!("Too many serials: {i}");
361 return Err(RebootReason::InvalidFdt);
362 }
363 let reg = node
364 .reg()
365 .map_err(|e| {
366 error!("Failed to read reg property from \"ns16550a\" node: {e}");
367 RebootReason::InvalidFdt
368 })?
369 .ok_or_else(|| {
370 error!("No reg property in \"ns16550a\" node");
371 RebootReason::InvalidFdt
372 })?
373 .next()
374 .ok_or_else(|| {
375 error!("No value in reg property of \"ns16550a\" node");
376 RebootReason::InvalidFdt
377 })?;
378 ret.addrs.push(reg.addr);
379 }
380 Ok(ret)
381}
382
383#[derive(Debug)]
384#[allow(dead_code)] // TODO: remove this
385pub struct SwiotlbInfo {
386 size: u64,
387 align: u64,
388}
389
390fn parse_swiotlb_nodes(fdt: &libfdt::Fdt) -> Result<SwiotlbInfo, RebootReason> {
391 let node = fdt
Jiyong Parkb87f3302023-03-21 10:03:11 +0900392 .compatible_nodes(cstr!("restricted-dma-pool"))
Jiyong Park00ceff32023-03-13 05:43:23 +0000393 .map_err(|e| {
394 error!("Failed to read compatible nodes \"restricted-dma-pool\" from DT: {e}");
395 RebootReason::InvalidFdt
396 })?
397 .next()
398 .ok_or_else(|| {
399 error!("No compatible node \"restricted-dma-pool\" in DT");
400 RebootReason::InvalidFdt
401 })?;
402 let size = node
Jiyong Parkb87f3302023-03-21 10:03:11 +0900403 .getprop_u64(cstr!("size"))
Jiyong Park00ceff32023-03-13 05:43:23 +0000404 .map_err(|e| {
405 error!("Failed to read \"size\" property of \"restricted-dma-pool\": {e}");
406 RebootReason::InvalidFdt
407 })?
408 .ok_or_else(|| {
409 error!("No \"size\" property in \"restricted-dma-pool\"");
410 RebootReason::InvalidFdt
411 })?;
412
413 let align = node
Jiyong Parkb87f3302023-03-21 10:03:11 +0900414 .getprop_u64(cstr!("alignment"))
Jiyong Park00ceff32023-03-13 05:43:23 +0000415 .map_err(|e| {
416 error!("Failed to read \"alignment\" property of \"restricted-dma-pool\": {e}");
417 RebootReason::InvalidFdt
418 })?
419 .ok_or_else(|| {
420 error!("No \"alignment\" property in \"restricted-dma-pool\"");
421 RebootReason::InvalidFdt
422 })?;
423
424 if size == 0 || (size % GUEST_PAGE_SIZE as u64) != 0 {
425 error!("Invalid swiotlb size {:#x}", size);
426 return Err(RebootReason::InvalidFdt);
427 }
428
429 if (align % GUEST_PAGE_SIZE as u64) != 0 {
430 error!("Invalid swiotlb alignment {:#x}", align);
431 return Err(RebootReason::InvalidFdt);
432 }
433
434 Ok(SwiotlbInfo { size, align })
435}
436
437#[derive(Debug)]
438#[allow(dead_code)] // TODO: remove this
439pub struct DeviceTreeInfo {
440 memory_size: NonZeroUsize,
441 num_cpu: NonZeroUsize,
442 pci_info: PciInfo,
443 serial_info: SerialInfo,
444 swiotlb_info: SwiotlbInfo,
445}
446
447impl DeviceTreeInfo {
448 const RAM_BASE_ADDR: u64 = 0x8000_0000;
449}
450
451pub fn parse_device_tree(fdt: &libfdt::Fdt) -> Result<DeviceTreeInfo, RebootReason> {
452 Ok(DeviceTreeInfo {
453 memory_size: parse_memory_node(fdt)?,
454 num_cpu: parse_cpu_nodes(fdt)?,
455 pci_info: parse_pci_nodes(fdt)?,
456 serial_info: parse_serial_nodes(fdt)?,
457 swiotlb_info: parse_swiotlb_nodes(fdt)?,
458 })
459}
460
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000461/// Modifies the input DT according to the fields of the configuration.
462pub fn modify_for_next_stage(
463 fdt: &mut Fdt,
464 bcc: &[u8],
465 new_instance: bool,
466 strict_boot: bool,
467) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000468 fdt.unpack()?;
469
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000470 add_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
471
Jiyong Parkb87f3302023-03-21 10:03:11 +0900472 set_or_clear_chosen_flag(fdt, cstr!("avf,strict-boot"), strict_boot)?;
473 set_or_clear_chosen_flag(fdt, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000474
475 fdt.pack()?;
476
477 Ok(())
478}
479
480/// Add a "google,open-dice"-compatible reserved-memory node to the tree.
481fn add_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000482 // We reject DTs with missing reserved-memory node as validation should have checked that the
483 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parkb87f3302023-03-21 10:03:11 +0900484 let mut reserved_memory =
485 fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000486
Jiyong Parkb87f3302023-03-21 10:03:11 +0900487 let mut dice = reserved_memory.add_subnode(cstr!("dice"))?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000488
Jiyong Parkb87f3302023-03-21 10:03:11 +0900489 dice.appendprop(cstr!("compatible"), b"google,open-dice\0")?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000490
Jiyong Parkb87f3302023-03-21 10:03:11 +0900491 dice.appendprop(cstr!("no-map"), &[])?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000492
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000493 let addr = addr.try_into().unwrap();
494 let size = size.try_into().unwrap();
Jiyong Parkb87f3302023-03-21 10:03:11 +0900495 dice.appendprop_addrrange(cstr!("reg"), addr, size)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000496
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000497 Ok(())
498}
499
500fn set_or_clear_chosen_flag(fdt: &mut Fdt, flag: &CStr, value: bool) -> libfdt::Result<()> {
501 // TODO(b/249054080): Refactor to not panic if the DT doesn't contain a /chosen node.
502 let mut chosen = fdt.chosen_mut()?.unwrap();
503 if value {
504 chosen.setprop_empty(flag)?;
505 } else {
506 match chosen.delprop(flag) {
507 Ok(()) | Err(FdtError::NotFound) => (),
508 Err(e) => return Err(e),
509 }
510 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000511
512 Ok(())
513}