blob: 0068f95ccfdb999da321ea6eacadbb2f3b2a29bb [file] [log] [blame]
Lorenz Brun54a5a052023-10-02 16:40:11 +02001#![no_main]
2#![no_std]
3
4extern crate alloc;
5
6use alloc::vec::Vec;
7use core::result::Result;
8use core::fmt;
9use prost::Message;
10use uefi::fs::FileSystem;
11use uefi::proto::device_path::build::media::FilePath;
12use uefi::proto::device_path::build::DevicePathBuilder;
13use uefi::proto::device_path::{DeviceSubType, DeviceType, LoadedImageDevicePath};
14use uefi::table::boot;
15use uefi::{prelude::*, CStr16};
16use uefi_services::println;
17
18use abloader_proto::monogon::metropolis::node::core::abloader;
19
20const A_LOADER_PATH: &CStr16 = cstr16!("\\EFI\\metropolis\\boot-a.efi");
21const B_LOADER_PATH: &CStr16 = cstr16!("\\EFI\\metropolis\\boot-b.efi");
22
23const LOADER_STATE_PATH: &CStr16 = cstr16!("\\EFI\\metropolis\\loader_state.pb");
24
25enum ValidSlot {
26 A,
27 B,
28}
29
30impl ValidSlot {
31 // other returns B if the value is A and A if the value is B.
32 fn other(&self) -> Self {
33 match self {
34 ValidSlot::A => ValidSlot::B,
35 ValidSlot::B => ValidSlot::A,
36 }
37 }
38 // path returns the path to the slot's EFI payload.
39 fn path(&self) -> &'static CStr16 {
40 match self {
41 ValidSlot::A => A_LOADER_PATH,
42 ValidSlot::B => B_LOADER_PATH,
43 }
44 }
45}
46
47enum ReadLoaderStateError {
48 FSReadError(uefi::fs::Error),
49 DecodeError(prost::DecodeError),
50}
51
52impl fmt::Display for ReadLoaderStateError {
53 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54 match self {
55 ReadLoaderStateError::FSReadError(e) => write!(f, "while reading state file: {}", e),
56 ReadLoaderStateError::DecodeError(e) => write!(f, "while decoding state file contents: {}", e),
57 }
58 }
59}
60
61fn read_loader_state(fs: &mut FileSystem) -> Result<abloader::AbLoaderData, ReadLoaderStateError> {
62 let state_raw = fs.read(&LOADER_STATE_PATH).map_err(|e| ReadLoaderStateError::FSReadError(e))?;
63 abloader::AbLoaderData::decode(state_raw.as_slice()).map_err(|e| ReadLoaderStateError::DecodeError(e))
64}
65
66fn load_slot_image(slot: &ValidSlot, boot_services: &BootServices) -> uefi::Result<Handle> {
67 let mut storage = Vec::new();
68
69 // Build the path to the slot payload. This takes the path to the loader
70 // itself, strips off the file path and following element(s) and appends
71 // the path to the correct slot payload.
72 let new_image_path = {
73 let loaded_image_device_path = boot_services
74 .open_protocol_exclusive::<LoadedImageDevicePath>(boot_services.image_handle())?;
75
76 let mut builder = DevicePathBuilder::with_vec(&mut storage);
77
78 for node in loaded_image_device_path.node_iter() {
79 if node.full_type() == (DeviceType::MEDIA, DeviceSubType::MEDIA_FILE_PATH) {
80 break;
81 }
82
83 builder = builder.push(&node).unwrap();
84 }
85
86 builder = builder
87 .push(&FilePath {
88 path_name: slot.path(),
89 })
90 .unwrap();
91
92 builder.finalize().unwrap()
93 };
94
95 boot_services
96 .load_image(
97 boot_services.image_handle(),
98 boot::LoadImageSource::FromDevicePath {
99 device_path: new_image_path,
100 from_boot_manager: false,
101 },
102 )
103}
104
105#[entry]
106fn main(_handle: Handle, mut system_table: SystemTable<Boot>) -> Status {
107 uefi_services::init(&mut system_table).unwrap();
108
109 let boot_services = system_table.boot_services();
110
111 let boot_slot_raw = {
112 let mut esp_fs = boot_services
113 .get_image_file_system(boot_services.image_handle())
114 .expect("image filesystem not available");
115
116 let mut loader_data = match read_loader_state(&mut esp_fs) {
117 Ok(d) => d,
118 Err(e) => {
119 println!("Unable to load A/B loader state, using default slot A: {}", e);
120 abloader::AbLoaderData {
121 active_slot: abloader::Slot::A.into(),
122 next_slot: abloader::Slot::None.into(),
123 }
124 }
125 };
126
127 // If next_slot is set, use it as slot to boot but clear it in the
128 // state file as the next boot should not use it again. If it should
129 // be permanently activated, it is the OS's job to put it into
130 if loader_data.next_slot != abloader::Slot::None.into() {
131 let next_slot = loader_data.next_slot;
132 loader_data.next_slot = abloader::Slot::None.into();
133 let new_loader_data = loader_data.encode_to_vec();
134 esp_fs
135 .write(&LOADER_STATE_PATH, new_loader_data)
136 .expect("failed to write back abdata");
137 next_slot
138 } else {
139 loader_data.active_slot
140 }
141 };
142
143 let boot_slot = match abloader::Slot::try_from(boot_slot_raw) {
144 Ok(abloader::Slot::A) => ValidSlot::A,
145 Ok(abloader::Slot::B) => ValidSlot::B,
146 _ => {
147 println!("Invalid slot ({}) active, falling back to A", boot_slot_raw);
148 ValidSlot::A
149 }
150 };
151
152 let payload_image = match load_slot_image(&boot_slot, boot_services) {
153 Ok(img) => img,
154 Err(e) => {
155 println!("Error loading intended slot, falling back to other slot: {}", e);
156 match load_slot_image(&boot_slot.other(), boot_services) {
157 Ok(img) => img,
158 Err(e) => {
159 panic!("Loading from both slots failed, second slot error: {}", e);
160 },
161 }
162 }
163 };
164
165 // Boot the payload.
166 boot_services
167 .start_image(payload_image)
168 .expect("failed to start payload");
169 Status::SUCCESS
170}