xref: /DragonStub/apps/fdt.c (revision 2604d7835e66d1fccc0973634b0121c7925e25f6)
1 #include "dragonstub/elfloader.h"
2 #include "dragonstub/printk.h"
3 #include "efidef.h"
4 #include <dragonstub/dragonstub.h>
5 #include <libfdt.h>
6 #include <libfdt_internal.h>
7 
8 struct exit_boot_struct {
9 	struct efi_boot_memmap *boot_memmap;
10 	efi_memory_desc_t *runtime_map;
11 	int runtime_entry_count;
12 	void *new_fdt_addr;
13 };
14 
15 #define EFI_DT_ADDR_CELLS_DEFAULT 2
16 #define EFI_DT_SIZE_CELLS_DEFAULT 2
17 
18 static void fdt_update_cell_size(void *fdt)
19 {
20 	int offset;
21 
22 	offset = fdt_path_offset(fdt, "/");
23 	/* Set the #address-cells and #size-cells values for an empty tree */
24 
25 	fdt_setprop_u32(fdt, offset, "#address-cells",
26 			EFI_DT_ADDR_CELLS_DEFAULT);
27 	fdt_setprop_u32(fdt, offset, "#size-cells", EFI_DT_SIZE_CELLS_DEFAULT);
28 }
29 
30 static efi_status_t update_fdt_memmap(void *fdt, struct efi_boot_memmap *map)
31 {
32 	int node = fdt_path_offset(fdt, "/chosen");
33 	u64 fdt_val64;
34 	u32 fdt_val32;
35 	int err;
36 
37 	if (node < 0)
38 		return EFI_LOAD_ERROR;
39 
40 	fdt_val64 = cpu_to_fdt64((unsigned long)map->map);
41 
42 	err = fdt_setprop_inplace_var(fdt, node, "linux,uefi-mmap-start",
43 				      fdt_val64);
44 	if (err)
45 		return EFI_LOAD_ERROR;
46 
47 	fdt_val32 = cpu_to_fdt32(map->map_size);
48 
49 	err = fdt_setprop_inplace_var(fdt, node, "linux,uefi-mmap-size",
50 				      fdt_val32);
51 	if (err)
52 		return EFI_LOAD_ERROR;
53 
54 	fdt_val32 = cpu_to_fdt32(map->desc_size);
55 
56 	err = fdt_setprop_inplace_var(fdt, node, "linux,uefi-mmap-desc-size",
57 				      fdt_val32);
58 	if (err)
59 		return EFI_LOAD_ERROR;
60 
61 	fdt_val32 = cpu_to_fdt32(map->desc_ver);
62 
63 	err = fdt_setprop_inplace_var(fdt, node, "linux,uefi-mmap-desc-ver",
64 				      fdt_val32);
65 	if (err)
66 		return EFI_LOAD_ERROR;
67 
68 	return EFI_SUCCESS;
69 }
70 
71 static efi_status_t update_fdt(void *orig_fdt, unsigned long orig_fdt_size,
72 			       void *fdt, int new_fdt_size, char *cmdline_ptr)
73 {
74 	int node, num_rsv;
75 	int status;
76 	u32 fdt_val32;
77 	u64 fdt_val64;
78 
79 	/* Do some checks on provided FDT, if it exists: */
80 	if (orig_fdt) {
81 		if (fdt_check_header(orig_fdt)) {
82 			efi_err("Device Tree header not valid!\n");
83 			return EFI_LOAD_ERROR;
84 		}
85 		/*
86 		 * We don't get the size of the FDT if we get if from a
87 		 * configuration table:
88 		 */
89 		if (orig_fdt_size && fdt_totalsize(orig_fdt) > orig_fdt_size) {
90 			efi_err("Truncated device tree! foo!\n");
91 			return EFI_LOAD_ERROR;
92 		}
93 	}
94 
95 	if (orig_fdt) {
96 		status = fdt_open_into(orig_fdt, fdt, new_fdt_size);
97 	} else {
98 		status = fdt_create_empty_tree(fdt, new_fdt_size);
99 		if (status == 0) {
100 			/*
101 			 * Any failure from the following function is
102 			 * non-critical:
103 			 */
104 			fdt_update_cell_size(fdt);
105 		}
106 	}
107 
108 	if (status != 0)
109 		goto fdt_set_fail;
110 
111 	/*
112 	 * Delete all memory reserve map entries. When booting via UEFI,
113 	 * kernel will use the UEFI memory map to find reserved regions.
114 	 */
115 	num_rsv = fdt_num_mem_rsv(fdt);
116 	while (num_rsv-- > 0)
117 		fdt_del_mem_rsv(fdt, num_rsv);
118 
119 	node = fdt_subnode_offset(fdt, 0, "chosen");
120 	if (node < 0) {
121 		node = fdt_add_subnode(fdt, 0, "chosen");
122 		if (node < 0) {
123 			/* 'node' is an error code when negative: */
124 			status = node;
125 			goto fdt_set_fail;
126 		}
127 	}
128 
129 	if (cmdline_ptr != NULL && strlen(cmdline_ptr) > 0) {
130 		status = fdt_setprop(fdt, node, "bootargs", cmdline_ptr,
131 				     strlen(cmdline_ptr) + 1);
132 		if (status)
133 			goto fdt_set_fail;
134 	}
135 
136 	/* Add FDT entries for EFI runtime services in chosen node. */
137 	node = fdt_subnode_offset(fdt, 0, "chosen");
138 	fdt_val64 = cpu_to_fdt64((u64)(unsigned long)ST);
139 
140 	status = fdt_setprop_var(fdt, node, "linux,uefi-system-table",
141 				 fdt_val64);
142 	if (status)
143 		goto fdt_set_fail;
144 
145 	fdt_val64 = UINT64_MAX; /* placeholder */
146 
147 	status = fdt_setprop_var(fdt, node, "linux,uefi-mmap-start", fdt_val64);
148 	if (status)
149 		goto fdt_set_fail;
150 
151 	fdt_val32 = UINT32_MAX; /* placeholder */
152 
153 	status = fdt_setprop_var(fdt, node, "linux,uefi-mmap-size", fdt_val32);
154 	if (status)
155 		goto fdt_set_fail;
156 
157 	status = fdt_setprop_var(fdt, node, "linux,uefi-mmap-desc-size",
158 				 fdt_val32);
159 	if (status)
160 		goto fdt_set_fail;
161 
162 	status = fdt_setprop_var(fdt, node, "linux,uefi-mmap-desc-ver",
163 				 fdt_val32);
164 	if (status)
165 		goto fdt_set_fail;
166 
167 	bool enalbed_ramdomize_base = false;
168 #ifdef CONFIG_RANDOMIZE_BASE
169 	enalbed_ramdomize_base = true;
170 #endif
171 	if (enalbed_ramdomize_base && !efi_nokaslr) {
172 		efi_status_t efi_status;
173 
174 		efi_status = efi_get_random_bytes(sizeof(fdt_val64),
175 						  (u8 *)&fdt_val64);
176 		if (efi_status == EFI_SUCCESS) {
177 			status = fdt_setprop_var(fdt, node, "kaslr-seed",
178 						 fdt_val64);
179 			if (status)
180 				goto fdt_set_fail;
181 		}
182 	}
183 
184 	/* Shrink the FDT back to its minimum size: */
185 	fdt_pack(fdt);
186 
187 	return EFI_SUCCESS;
188 
189 fdt_set_fail:
190 	if (status == -FDT_ERR_NOSPACE)
191 		return EFI_BUFFER_TOO_SMALL;
192 
193 	return EFI_LOAD_ERROR;
194 }
195 
196 static efi_status_t exit_boot_func(struct efi_boot_memmap *map, void *priv)
197 {
198 	struct exit_boot_struct *p = priv;
199 
200 	p->boot_memmap = map;
201 
202 	/*
203 	 * Update the memory map with virtual addresses. The function will also
204 	 * populate @runtime_map with copies of just the EFI_MEMORY_RUNTIME
205 	 * entries so that we can pass it straight to SetVirtualAddressMap()
206 	 */
207 	efi_get_virtmap(map->map, map->map_size, map->desc_size, p->runtime_map,
208 			&p->runtime_entry_count);
209 
210 	return update_fdt_memmap(p->new_fdt_addr, map);
211 }
212 
213 /*
214  * Allocate memory for a new FDT, then add EFI and commandline related fields
215  * to the FDT.  This routine increases the FDT allocation size until the
216  * allocated memory is large enough.  EFI allocations are in EFI_PAGE_SIZE
217  * granules, which are fixed at 4K bytes, so in most cases the first allocation
218  * should succeed.  EFI boot services are exited at the end of this function.
219  * There must be no allocations between the get_memory_map() call and the
220  * exit_boot_services() call, so the exiting of boot services is very tightly
221  * tied to the creation of the FDT with the final memory map in it.
222  */
223 static efi_status_t allocate_new_fdt_and_exit_boot(void *handle,
224 						   efi_loaded_image_t *image,
225 						   unsigned long *new_fdt_addr,
226 						   char *cmdline_ptr)
227 {
228 	unsigned long desc_size;
229 	u32 desc_ver;
230 	efi_status_t status;
231 	struct exit_boot_struct priv = { 0 };
232 	unsigned long fdt_addr = 0;
233 	unsigned long fdt_size = 0;
234 	if (!efi_novamap) {
235 		status = efi_alloc_virtmap(&priv.runtime_map, &desc_size,
236 					   &desc_ver);
237 		if (status != EFI_SUCCESS) {
238 			efi_err("Unable to retrieve UEFI memory map.\n");
239 			return status;
240 		}
241 	}
242 	/*
243 	 * Unauthenticated device tree data is a security hazard, so ignore
244 	 * 'dtb=' unless UEFI Secure Boot is disabled.  We assume that secure
245 	 * boot is enabled if we can't determine its state.
246 	 */
247 	bool config_efi_armstub_dtb_loader = false;
248 #ifdef CONFIG_EFI_ARMSTUB_DTB_LOADER
249 	config_efi_armstub_dtb_loader = true;
250 #endif
251 	print_efi_secureboot_mode(efi_get_secureboot());
252 
253 	if (!config_efi_armstub_dtb_loader ||
254 	    efi_get_secureboot() != efi_secureboot_mode_disabled) {
255 		if (strstr(cmdline_ptr, "dtb="))
256 			efi_err("Ignoring DTB from command line.\n");
257 	} else {
258 		efi_todo("Load DTB from command line\n");
259 		// status = efi_load_dtb(image, &fdt_addr, &fdt_size);
260 
261 		// if (status != EFI_SUCCESS && status != EFI_NOT_READY) {
262 		// 	efi_err("Failed to load device tree!\n");
263 		// 	goto fail;
264 		// }
265 	}
266 
267 	if (fdt_addr) {
268 		efi_info("Using DTB from command line\n");
269 	} else {
270 		/* Look for a device tree configuration table entry. */
271 		fdt_addr = (uintptr_t)get_fdt(&fdt_size);
272 		if (fdt_addr)
273 			efi_info("Using DTB from configuration table\n");
274 	}
275 
276 	if (!fdt_addr)
277 		efi_info("Generating empty DTB\n");
278 
279 	status = efi_allocate_pages(MAX_FDT_SIZE, new_fdt_addr, ULONG_MAX);
280 	if (status != EFI_SUCCESS) {
281 		efi_err("Unable to allocate memory for new device tree.\n");
282 		goto fail;
283 	}
284 	efi_debug("New FDT address: 0x%lx\n", *new_fdt_addr);
285 	efi_info("Generating new FDT...\n");
286 	status = update_fdt((void *)fdt_addr, fdt_size, (void *)*new_fdt_addr,
287 			    MAX_FDT_SIZE, cmdline_ptr);
288 
289 	if (status != EFI_SUCCESS) {
290 		efi_err("Unable to construct new device tree.\n");
291 		goto fail_free_new_fdt;
292 	}
293 
294 	priv.new_fdt_addr = (void *)*new_fdt_addr;
295 
296 	efi_info("Exiting boot services...\n");
297 	status = efi_exit_boot_services(handle, &priv, exit_boot_func);
298 
299 	if (status == EFI_SUCCESS) {
300 		efi_set_virtual_address_map_t *svam;
301 
302 		if (efi_novamap)
303 			return EFI_SUCCESS;
304 
305 		/* Install the new virtual address map */
306 		svam = ST->RuntimeServices->SetVirtualAddressMap;
307 		status = svam(priv.runtime_entry_count * desc_size, desc_size,
308 			      desc_ver, priv.runtime_map);
309 
310 		/*
311 			 * We are beyond the point of no return here, so if the call to
312 			 * SetVirtualAddressMap() failed, we need to signal that to the
313 			 * incoming kernel but proceed normally otherwise.
314 			 */
315 		if (status != EFI_SUCCESS) {
316 			efi_memory_desc_t *p;
317 			int l;
318 
319 			/*
320 				 * Set the virtual address field of all
321 				 * EFI_MEMORY_RUNTIME entries to U64_MAX. This will
322 				 * signal the incoming kernel that no virtual
323 				 * translation has been installed.
324 				 */
325 			for (l = 0; l < priv.boot_memmap->map_size;
326 			     l += priv.boot_memmap->desc_size) {
327 				p = (void *)priv.boot_memmap->map + l;
328 
329 				if (p->Attribute & EFI_MEMORY_RUNTIME)
330 					p->VirtualStart = UINT64_MAX;
331 			}
332 		}
333 		return EFI_SUCCESS;
334 	}
335 
336 	efi_err("Exit boot services failed.\n");
337 
338 fail_free_new_fdt:
339 	efi_free(MAX_FDT_SIZE, *new_fdt_addr);
340 
341 fail:
342 	efi_free(fdt_size, fdt_addr);
343 
344 	efi_bs_call(FreePool, priv.runtime_map);
345 
346 	return EFI_LOAD_ERROR;
347 }
348 
349 efi_status_t efi_boot_kernel(efi_handle_t handle,
350 			     efi_loaded_image_t *loaded_image,
351 			     struct payload_info *payload_info,
352 			     char *cmdline_ptr)
353 {
354 	unsigned long fdt_addr;
355 	efi_status_t status;
356 
357 	efi_info("Loading ELF payload...\n");
358 	// 加载ELF
359 	status = load_elf(payload_info);
360 
361 	if (status != EFI_SUCCESS) {
362 		efi_err("Failed to load ELF payload, efi error code: %d\n",
363 			status);
364 		return status;
365 	}
366 
367 	status = allocate_new_fdt_and_exit_boot(handle, loaded_image, &fdt_addr,
368 						cmdline_ptr);
369 	if (status != EFI_SUCCESS) {
370 		efi_err("Failed to update FDT and exit boot services\n");
371 		return status;
372 	}
373 #ifdef CONFIG_ARM
374 	efi_handle_post_ebs_state();
375 #endif
376 
377 	efi_enter_kernel(payload_info, fdt_addr,
378 			 fdt_totalsize((void *)fdt_addr));
379 	/* not reached */
380 }
381 
382 void *get_fdt(unsigned long *fdt_size)
383 {
384 	void *fdt;
385 
386 	fdt = get_efi_config_table(DEVICE_TREE_GUID);
387 
388 	if (!fdt)
389 		return NULL;
390 
391 	if (fdt_check_header(fdt) != 0) {
392 		efi_err("Invalid header detected on UEFI supplied FDT, ignoring ...\n");
393 		return NULL;
394 	}
395 	*fdt_size = fdt_totalsize(fdt);
396 	return fdt;
397 }
398