1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  EFI boot manager
4  *
5  *  Copyright (c) 2017 Rob Clark
6  */
7 
8 #define LOG_CATEGORY LOGC_EFI
9 
10 #include <common.h>
11 #include <charset.h>
12 #include <log.h>
13 #include <malloc.h>
14 #include <efi_default_filename.h>
15 #include <efi_loader.h>
16 #include <efi_variable.h>
17 #include <asm/unaligned.h>
18 
19 static const struct efi_boot_services *bs;
20 static const struct efi_runtime_services *rs;
21 
22 const efi_guid_t efi_guid_bootmenu_auto_generated =
23 		EFICONFIG_AUTO_GENERATED_ENTRY_GUID;
24 
25 /*
26  * bootmgr implements the logic of trying to find a payload to boot
27  * based on the BootOrder + BootXXXX variables, and then loading it.
28  *
29  * TODO detecting a special key held (f9?) and displaying a boot menu
30  * like you would get on a PC would be clever.
31  *
32  * TODO if we had a way to write and persist variables after the OS
33  * has started, we'd also want to check OsIndications to see if we
34  * should do normal or recovery boot.
35  */
36 
37 /**
38  * expand_media_path() - expand a device path for default file name
39  * @device_path:	device path to check against
40  *
41  * If @device_path is a media or disk partition which houses a file
42  * system, this function returns a full device path which contains
43  * an architecture-specific default file name for removable media.
44  *
45  * Return:	a newly allocated device path
46  */
47 static
expand_media_path(struct efi_device_path * device_path)48 struct efi_device_path *expand_media_path(struct efi_device_path *device_path)
49 {
50 	struct efi_device_path *rem, *full_path;
51 	efi_handle_t handle;
52 
53 	if (!device_path)
54 		return NULL;
55 
56 	/*
57 	 * If device_path is a (removable) media or partition which provides
58 	 * simple file system protocol, append a default file name to support
59 	 * booting from removable media.
60 	 */
61 	handle = efi_dp_find_obj(device_path,
62 				 &efi_simple_file_system_protocol_guid, &rem);
63 	if (handle) {
64 		if (rem->type == DEVICE_PATH_TYPE_END) {
65 			full_path = efi_dp_from_file(device_path,
66 						     "/EFI/BOOT/" BOOTEFI_NAME);
67 		} else {
68 			full_path = efi_dp_dup(device_path);
69 		}
70 	} else {
71 		full_path = efi_dp_dup(device_path);
72 	}
73 
74 	return full_path;
75 }
76 
77 /**
78  * try_load_from_file_path() - try to load a file
79  *
80  * Given a file media path iterate through a list of handles and try to
81  * to load the file from each of them until the first success.
82  *
83  * @fs_handles: array of handles with the simple file protocol
84  * @num:	number of handles in fs_handles
85  * @fp:		file path to open
86  * @handle:	on return pointer to handle for loaded image
87  * @removable:	if true only consider removable media, else only non-removable
88  */
try_load_from_file_path(efi_handle_t * fs_handles,efi_uintn_t num,struct efi_device_path * fp,efi_handle_t * handle,bool removable)89 static efi_status_t try_load_from_file_path(efi_handle_t *fs_handles,
90 					    efi_uintn_t num,
91 					    struct efi_device_path *fp,
92 					    efi_handle_t *handle,
93 					    bool removable)
94 {
95 	struct efi_handler *handler;
96 	struct efi_device_path *dp;
97 	int i;
98 	efi_status_t ret;
99 
100 	for (i = 0; i < num; i++) {
101 		if (removable != efi_disk_is_removable(fs_handles[i]))
102 			continue;
103 
104 		ret = efi_search_protocol(fs_handles[i], &efi_guid_device_path,
105 					  &handler);
106 		if (ret != EFI_SUCCESS)
107 			continue;
108 
109 		dp = handler->protocol_interface;
110 		if (!dp)
111 			continue;
112 
113 		dp = efi_dp_append(dp, fp);
114 		if (!dp)
115 			continue;
116 
117 		ret = EFI_CALL(efi_load_image(true, efi_root, dp, NULL, 0,
118 					      handle));
119 		efi_free_pool(dp);
120 		if (ret == EFI_SUCCESS)
121 			return ret;
122 	}
123 
124 	return EFI_NOT_FOUND;
125 }
126 
127 /**
128  * try_load_from_short_path
129  * @fp:		file path
130  * @handle:	pointer to handle for newly installed image
131  *
132  * Enumerate all the devices which support file system operations,
133  * prepend its media device path to the file path, @fp, and
134  * try to load the file.
135  * This function should be called when handling a short-form path
136  * which is starting with a file device path.
137  *
138  * Return:	status code
139  */
try_load_from_short_path(struct efi_device_path * fp,efi_handle_t * handle)140 static efi_status_t try_load_from_short_path(struct efi_device_path *fp,
141 					     efi_handle_t *handle)
142 {
143 	efi_handle_t *fs_handles;
144 	efi_uintn_t num;
145 	efi_status_t ret;
146 
147 	ret = EFI_CALL(efi_locate_handle_buffer(
148 					BY_PROTOCOL,
149 					&efi_simple_file_system_protocol_guid,
150 					NULL,
151 					&num, &fs_handles));
152 	if (ret != EFI_SUCCESS)
153 		return ret;
154 	if (!num)
155 		return EFI_NOT_FOUND;
156 
157 	/* removable media first */
158 	ret = try_load_from_file_path(fs_handles, num, fp, handle, true);
159 	if (ret == EFI_SUCCESS)
160 		goto out;
161 
162 	/* fixed media */
163 	ret = try_load_from_file_path(fs_handles, num, fp, handle, false);
164 	if (ret == EFI_SUCCESS)
165 		goto out;
166 
167 out:
168 	return ret;
169 }
170 
171 /**
172  * try_load_entry() - try to load image for boot option
173  *
174  * Attempt to load load-option number 'n', returning device_path and file_path
175  * if successful. This checks that the EFI_LOAD_OPTION is active (enabled)
176  * and that the specified file to boot exists.
177  *
178  * @n:			number of the boot option, e.g. 0x0a13 for Boot0A13
179  * @handle:		on return handle for the newly installed image
180  * @load_options:	load options set on the loaded image protocol
181  * Return:		status code
182  */
try_load_entry(u16 n,efi_handle_t * handle,void ** load_options)183 static efi_status_t try_load_entry(u16 n, efi_handle_t *handle,
184 				   void **load_options)
185 {
186 	struct efi_load_option lo;
187 	u16 varname[9];
188 	void *load_option;
189 	efi_uintn_t size;
190 	efi_status_t ret;
191 
192 	efi_create_indexed_name(varname, sizeof(varname), "Boot", n);
193 
194 	load_option = efi_get_var(varname, &efi_global_variable_guid, &size);
195 	if (!load_option)
196 		return EFI_LOAD_ERROR;
197 
198 	ret = efi_deserialize_load_option(&lo, load_option, &size);
199 	if (ret != EFI_SUCCESS) {
200 		log_warning("Invalid load option for %ls\n", varname);
201 		goto error;
202 	}
203 
204 	if (lo.attributes & LOAD_OPTION_ACTIVE) {
205 		struct efi_device_path *file_path;
206 		u32 attributes;
207 
208 		log_debug("trying to load \"%ls\" from %pD\n", lo.label,
209 			  lo.file_path);
210 
211 		if (EFI_DP_TYPE(lo.file_path, MEDIA_DEVICE, FILE_PATH)) {
212 			/* file_path doesn't contain a device path */
213 			ret = try_load_from_short_path(lo.file_path, handle);
214 		} else {
215 			file_path = expand_media_path(lo.file_path);
216 			ret = EFI_CALL(efi_load_image(true, efi_root, file_path,
217 						      NULL, 0, handle));
218 			efi_free_pool(file_path);
219 		}
220 		if (ret != EFI_SUCCESS) {
221 			log_warning("Loading %ls '%ls' failed\n",
222 				    varname, lo.label);
223 			goto error;
224 		}
225 
226 		attributes = EFI_VARIABLE_BOOTSERVICE_ACCESS |
227 			     EFI_VARIABLE_RUNTIME_ACCESS;
228 		ret = efi_set_variable_int(u"BootCurrent",
229 					   &efi_global_variable_guid,
230 					   attributes, sizeof(n), &n, false);
231 		if (ret != EFI_SUCCESS)
232 			goto unload;
233 		/* try to register load file2 for initrd's */
234 		if (IS_ENABLED(CONFIG_EFI_LOAD_FILE2_INITRD)) {
235 			ret = efi_initrd_register();
236 			if (ret != EFI_SUCCESS)
237 				goto unload;
238 		}
239 
240 		log_info("Booting: %ls\n", lo.label);
241 	} else {
242 		ret = EFI_LOAD_ERROR;
243 	}
244 
245 	/* Set load options */
246 	if (size >= sizeof(efi_guid_t) &&
247 	    !guidcmp(lo.optional_data, &efi_guid_bootmenu_auto_generated))
248 		size = 0;
249 
250 	if (size) {
251 		*load_options = malloc(size);
252 		if (!*load_options) {
253 			ret = EFI_OUT_OF_RESOURCES;
254 			goto error;
255 		}
256 		memcpy(*load_options, lo.optional_data, size);
257 		ret = efi_set_load_options(*handle, size, *load_options);
258 	} else {
259 		*load_options = NULL;
260 	}
261 
262 error:
263 	free(load_option);
264 
265 	return ret;
266 
267 unload:
268 	if (EFI_CALL(efi_unload_image(*handle)) != EFI_SUCCESS)
269 		log_err("Unloading image failed\n");
270 	free(load_option);
271 
272 	return ret;
273 }
274 
275 /**
276  * efi_bootmgr_load() - try to load from BootNext or BootOrder
277  *
278  * Attempt to load from BootNext or in the order specified by BootOrder
279  * EFI variable, the available load-options, finding and returning
280  * the first one that can be loaded successfully.
281  *
282  * @handle:		on return handle for the newly installed image
283  * @load_options:	load options set on the loaded image protocol
284  * Return:		status code
285  */
efi_bootmgr_load(efi_handle_t * handle,void ** load_options)286 efi_status_t efi_bootmgr_load(efi_handle_t *handle, void **load_options)
287 {
288 	u16 bootnext, *bootorder;
289 	efi_uintn_t size;
290 	int i, num;
291 	efi_status_t ret;
292 
293 	bs = systab.boottime;
294 	rs = systab.runtime;
295 
296 	/* BootNext */
297 	size = sizeof(bootnext);
298 	ret = efi_get_variable_int(u"BootNext",
299 				   &efi_global_variable_guid,
300 				   NULL, &size, &bootnext, NULL);
301 	if (ret == EFI_SUCCESS || ret == EFI_BUFFER_TOO_SMALL) {
302 		/* BootNext does exist here */
303 		if (ret == EFI_BUFFER_TOO_SMALL || size != sizeof(u16))
304 			log_err("BootNext must be 16-bit integer\n");
305 
306 		/* delete BootNext */
307 		ret = efi_set_variable_int(u"BootNext",
308 					   &efi_global_variable_guid,
309 					   0, 0, NULL, false);
310 
311 		/* load BootNext */
312 		if (ret == EFI_SUCCESS) {
313 			if (size == sizeof(u16)) {
314 				ret = try_load_entry(bootnext, handle,
315 						     load_options);
316 				if (ret == EFI_SUCCESS)
317 					return ret;
318 				log_warning(
319 					"Loading from BootNext failed, falling back to BootOrder\n");
320 			}
321 		} else {
322 			log_err("Deleting BootNext failed\n");
323 		}
324 	}
325 
326 	/* BootOrder */
327 	bootorder = efi_get_var(u"BootOrder", &efi_global_variable_guid, &size);
328 	if (!bootorder) {
329 		log_info("BootOrder not defined\n");
330 		ret = EFI_NOT_FOUND;
331 		goto error;
332 	}
333 
334 	num = size / sizeof(uint16_t);
335 	for (i = 0; i < num; i++) {
336 		log_debug("trying to load Boot%04X\n", bootorder[i]);
337 		ret = try_load_entry(bootorder[i], handle, load_options);
338 		if (ret == EFI_SUCCESS)
339 			break;
340 	}
341 
342 	free(bootorder);
343 
344 error:
345 	return ret;
346 }
347