xref: /dragonfly/sys/platform/pc64/x86_64/efirt.c (revision e05899ce)
1 /*-
2  * Copyright (c) 2004 Marcel Moolenaar
3  * Copyright (c) 2001 Doug Rabson
4  * Copyright (c) 2016 The FreeBSD Foundation
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Konstantin Belousov
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * $FreeBSD: head/sys/amd64/amd64/efirt.c 307391 2016-10-16 06:07:43Z kib $
32  */
33 
34 #include <sys/param.h>
35 #include <sys/efi.h>
36 #include <sys/kernel.h>
37 #include <sys/linker.h>
38 #include <sys/lock.h>
39 #include <sys/module.h>
40 #include <sys/proc.h>
41 #include <sys/sched.h>
42 #include <sys/sysctl.h>
43 #include <sys/systm.h>
44 #include <sys/thread.h>
45 #include <sys/globaldata.h>
46 
47 #include <vm/vm.h>
48 #include <vm/pmap.h>
49 #include <vm/vm_map.h>
50 #include <vm/vm_object.h>
51 #include <vm/vm_param.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_pager.h>
54 #include <vm/vm_extern.h>
55 
56 #include <vm/vm_page2.h>
57 
58 #include <machine/efi.h>
59 #include <machine/metadata.h>
60 #include <machine/md_var.h>
61 #include <machine/smp.h>
62 #include <machine/vmparam.h>
63 
64 static struct efi_systbl *efi_systbl;
65 static struct efi_cfgtbl *efi_cfgtbl;
66 static struct efi_rt *efi_runtime;
67 
68 static int efi_status2err[25] = {
69 	0,		/* EFI_SUCCESS */
70 	ENOEXEC,	/* EFI_LOAD_ERROR */
71 	EINVAL,		/* EFI_INVALID_PARAMETER */
72 	ENOSYS,		/* EFI_UNSUPPORTED */
73 	EMSGSIZE, 	/* EFI_BAD_BUFFER_SIZE */
74 	EOVERFLOW,	/* EFI_BUFFER_TOO_SMALL */
75 	EBUSY,		/* EFI_NOT_READY */
76 	EIO,		/* EFI_DEVICE_ERROR */
77 	EROFS,		/* EFI_WRITE_PROTECTED */
78 	EAGAIN,		/* EFI_OUT_OF_RESOURCES */
79 	EIO,		/* EFI_VOLUME_CORRUPTED */
80 	ENOSPC,		/* EFI_VOLUME_FULL */
81 	ENXIO,		/* EFI_NO_MEDIA */
82 	ESTALE,		/* EFI_MEDIA_CHANGED */
83 	ENOENT,		/* EFI_NOT_FOUND */
84 	EACCES,		/* EFI_ACCESS_DENIED */
85 	ETIMEDOUT,	/* EFI_NO_RESPONSE */
86 	EADDRNOTAVAIL,	/* EFI_NO_MAPPING */
87 	ETIMEDOUT,	/* EFI_TIMEOUT */
88 	EDOOFUS,	/* EFI_NOT_STARTED */
89 	EALREADY,	/* EFI_ALREADY_STARTED */
90 	ECANCELED,	/* EFI_ABORTED */
91 	EPROTO,		/* EFI_ICMP_ERROR */
92 	EPROTO,		/* EFI_TFTP_ERROR */
93 	EPROTO		/* EFI_PROTOCOL_ERROR */
94 };
95 
96 MALLOC_DEFINE(M_EFI, "efi", "EFI BIOS");
97 
98 static int
99 efi_status_to_errno(efi_status status)
100 {
101 	u_long code;
102 
103 	code = status & 0x3ffffffffffffffful;
104 	return (code < nitems(efi_status2err) ? efi_status2err[code] : EDOOFUS);
105 }
106 
107 static struct lock efi_lock;
108 static struct lock resettodr_lock;
109 static mcontext_t efi_ctx;
110 static struct vmspace *efi_savevm;
111 static struct vmspace *efi_vmspace;
112 static vm_object_t efi_obj;
113 static struct efi_md *efi_map;
114 static int efi_ndesc;
115 static int efi_descsz;
116 
117 static void
118 efi_destroy_1t1_map(void)
119 {
120 	vm_object_t obj;
121 	vm_page_t m;
122 
123 	if ((obj = efi_obj) != NULL) {
124 		efi_obj = NULL;
125 		vm_object_hold(obj);
126 		vm_object_reference_locked(obj);	/* match deallocate */
127 	}
128 	if (efi_vmspace) {
129 		pmap_remove_pages(vmspace_pmap(efi_vmspace),
130 				  VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
131 		vm_map_remove(&efi_vmspace->vm_map,
132 			      VM_MIN_USER_ADDRESS,
133 			      VM_MAX_USER_ADDRESS);
134 		vmspace_rel(efi_vmspace);
135 		efi_vmspace = NULL;
136 	}
137 	if (obj) {
138 		while ((m = RB_ROOT(&obj->rb_memq)) != NULL) {
139 			vm_page_busy_wait(m, FALSE, "efipg");
140 			vm_page_unwire(m, 1);
141 			vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
142 			cdev_pager_free_page(obj, m);
143 			kfree(m, M_EFI);
144 		}
145 		vm_object_drop(obj);
146 		vm_object_deallocate(obj);
147 	}
148 }
149 
150 static int
151 efi_pg_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
152 	    vm_ooffset_t foff, struct ucred *cred, u_short *color)
153 {
154 	*color = 0;
155 	return 0;
156 }
157 
158 static void
159 efi_pg_dtor(void *handle)
160 {
161 }
162 
163 static int
164 efi_pg_fault(vm_object_t obj, vm_ooffset_t offset, int prot, vm_page_t *mres)
165 {
166 	vm_page_t m;
167 
168 	m = *mres;
169 	if ((m->flags & PG_FICTITIOUS) == 0) {
170 		*mres = NULL;
171 		vm_page_remove(m);
172 		vm_page_free(m);
173 		m = NULL;
174 	}
175 	if (m == NULL) {
176 		kprintf("efi_pg_fault: unmapped pg @%016jx\n", offset);
177 		return VM_PAGER_ERROR;
178 	}
179 
180 	/*
181 	 * Shouldn't get hit, we pre-loaded all the pages.
182 	 */
183 	kprintf("efi_pg_fault: ok %p/%p @%016jx m=%016jx,%016jx\n",
184 		obj, efi_obj, offset, m->pindex, m->phys_addr);
185 
186 	return VM_PAGER_OK;
187 }
188 
189 static struct cdev_pager_ops efi_pager_ops = {
190 	.cdev_pg_fault	= efi_pg_fault,
191 	.cdev_pg_ctor	= efi_pg_ctor,
192 	.cdev_pg_dtor	= efi_pg_dtor
193 };
194 
195 static bool
196 efi_create_1t1_map(struct efi_md *map, int ndesc, int descsz)
197 {
198 	vm_page_t m;
199 	struct efi_md *p;
200 	int i;
201 	int count;
202 	int result;
203 
204 	efi_map = map;
205 	efi_ndesc = ndesc;
206 	efi_descsz = descsz;
207 
208 	efi_vmspace = vmspace_alloc(VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
209 	pmap_pinit2(vmspace_pmap(efi_vmspace));
210 	efi_obj = cdev_pager_allocate(NULL, OBJT_MGTDEVICE, &efi_pager_ops,
211 				  VM_MAX_USER_ADDRESS,
212 				  VM_PROT_READ | VM_PROT_WRITE,
213 				  0, proc0.p_ucred);
214 	vm_object_hold(efi_obj);
215 
216 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
217 	vm_map_lock(&efi_vmspace->vm_map);
218 	result = vm_map_insert(&efi_vmspace->vm_map, &count, efi_obj, NULL,
219 			      0, 0, VM_MAX_USER_ADDRESS,
220 			      VM_MAPTYPE_NORMAL,
221 			      VM_SUBSYS_EFI,
222 			      VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE,
223 			      VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE,
224 			      0);
225 	vm_map_unlock(&efi_vmspace->vm_map);
226 	if (result != KERN_SUCCESS)
227 		goto fail;
228 
229 	for (i = 0, p = map;
230 	     i < ndesc; i++, p = efi_next_descriptor(p, descsz)) {
231 		vm_offset_t va;
232 		uint64_t idx;
233 		int mode;
234 
235 		if ((p->md_attr & EFI_MD_ATTR_RT) == 0)
236 			continue;
237 		if (p->md_virt != NULL) {
238 			if (bootverbose)
239 				kprintf("EFI Runtime entry %d is mapped\n", i);
240 			goto fail;
241 		}
242 		if ((p->md_phys & EFI_PAGE_MASK) != 0) {
243 			if (bootverbose)
244 				kprintf("EFI Runtime entry %d is not aligned\n",
245 				    i);
246 			goto fail;
247 		}
248 		if (p->md_phys + p->md_pages * EFI_PAGE_SIZE < p->md_phys ||
249 		    p->md_phys + p->md_pages * EFI_PAGE_SIZE >=
250 		    VM_MAX_USER_ADDRESS) {
251 			kprintf("EFI Runtime entry %d is not in mappable for RT:"
252 			    "base %#016jx %#jx pages\n",
253 			    i, (uintmax_t)p->md_phys,
254 			    (uintmax_t)p->md_pages);
255 			goto fail;
256 		}
257 
258 		if ((p->md_attr & EFI_MD_ATTR_WB) != 0)
259 			mode = VM_MEMATTR_WRITE_BACK;
260 		else if ((p->md_attr & EFI_MD_ATTR_WT) != 0)
261 			mode = VM_MEMATTR_WRITE_THROUGH;
262 		else if ((p->md_attr & EFI_MD_ATTR_WC) != 0)
263 			mode = VM_MEMATTR_WRITE_COMBINING;
264 		else if ((p->md_attr & EFI_MD_ATTR_WP) != 0)
265 			mode = VM_MEMATTR_WRITE_PROTECTED;
266 		else if ((p->md_attr & EFI_MD_ATTR_UC) != 0)
267 			mode = VM_MEMATTR_UNCACHEABLE;
268 		else {
269 			if (bootverbose)
270 				kprintf("EFI Runtime entry %d mapping "
271 				    "attributes unsupported\n", i);
272 			mode = VM_MEMATTR_UNCACHEABLE;
273 		}
274 
275 		if (bootverbose) {
276 			kprintf("efirt: map %016jx-%016jx\n",
277 				p->md_phys,
278 				p->md_phys + IDX_TO_OFF(p->md_pages));
279 		}
280 
281 		for (va = p->md_phys, idx = 0; idx < p->md_pages; idx++,
282 		    va += PAGE_SIZE) {
283 			m = kmalloc(sizeof(*m), M_EFI, M_WAITOK | M_ZERO);
284 			/*m->flags |= PG_WRITEABLE;*/
285 			vm_page_initfake(m, va, mode);	/* va is phys addr */
286 			m->valid = VM_PAGE_BITS_ALL;
287 			m->dirty = m->valid;
288 			vm_page_insert(m, efi_obj, OFF_TO_IDX(va));
289 			vm_page_wakeup(m);
290 		}
291 	}
292 	vm_object_drop(efi_obj);
293 	vm_map_entry_release(count);
294 
295 	return true;
296 
297 fail:
298 	vm_object_drop(efi_obj);
299 	vm_map_entry_release(count);
300 	efi_destroy_1t1_map();
301 
302 	return false;
303 }
304 
305 /*
306  * Create an environment for the EFI runtime code call.  The most
307  * important part is creating the required 1:1 physical->virtual
308  * mappings for the runtime segments.  To do that, we manually create
309  * page table which unmap userspace but gives correct kernel mapping.
310  * The 1:1 mappings for runtime segments usually occupy low 4G of the
311  * physical address map.
312  *
313  * The 1:1 mappings were chosen over the SetVirtualAddressMap() EFI RT
314  * service, because there are some BIOSes which fail to correctly
315  * relocate itself on the call, requiring both 1:1 and virtual
316  * mapping.  As result, we must provide 1:1 mapping anyway, so no
317  * reason to bother with the virtual map, and no need to add a
318  * complexity into loader.
319  *
320  * The fpu_kern_enter() call allows firmware to use FPU, as mandated
321  * by the specification.  In particular, CR0.TS bit is cleared.  Also
322  * it enters critical section, giving us neccessary protection against
323  * context switch.
324  *
325  * There is no need to disable interrupts around the change of %cr3,
326  * the kernel mappings are correct, while we only grabbed the
327  * userspace portion of VA.  Interrupts handlers must not access
328  * userspace.  Having interrupts enabled fixes the issue with
329  * firmware/SMM long operation, which would negatively affect IPIs,
330  * esp. TLB shootdown requests.
331  */
332 static int
333 efi_enter(void)
334 {
335 	thread_t td = curthread;
336 
337 	if (efi_runtime == NULL)
338 		return (ENXIO);
339 	lockmgr(&efi_lock, LK_EXCLUSIVE);
340 	efi_savevm = td->td_lwp->lwp_vmspace;
341 	pmap_setlwpvm(td->td_lwp, efi_vmspace);
342 	npxpush(&efi_ctx);
343 	cpu_invltlb();
344 
345 	return (0);
346 }
347 
348 static void
349 efi_leave(void)
350 {
351 	thread_t td = curthread;
352 
353 	pmap_setlwpvm(td->td_lwp, efi_savevm);
354 	npxpop(&efi_ctx);
355 	cpu_invltlb();
356 	efi_savevm = NULL;
357 	lockmgr(&efi_lock, LK_RELEASE);
358 }
359 
360 static int
361 efi_init(void)
362 {
363 	struct efi_map_header *efihdr;
364 	struct efi_md *map;
365 	caddr_t kmdp;
366 	size_t efisz;
367 
368 	lockinit(&efi_lock, "efi", 0, LK_CANRECURSE);
369 	lockinit(&resettodr_lock, "efitodr", 0, LK_CANRECURSE);
370 
371 	if (efi_systbl_phys == 0) {
372 		if (bootverbose)
373 			kprintf("EFI systbl not available\n");
374 		return (ENXIO);
375 	}
376 	efi_systbl = (struct efi_systbl *)PHYS_TO_DMAP(efi_systbl_phys);
377 	if (efi_systbl->st_hdr.th_sig != EFI_SYSTBL_SIG) {
378 		efi_systbl = NULL;
379 		if (bootverbose)
380 			kprintf("EFI systbl signature invalid\n");
381 		return (ENXIO);
382 	}
383 	efi_cfgtbl = (efi_systbl->st_cfgtbl == 0) ? NULL :
384 	    (struct efi_cfgtbl *)efi_systbl->st_cfgtbl;
385 	if (efi_cfgtbl == NULL) {
386 		if (bootverbose)
387 			kprintf("EFI config table is not present\n");
388 	}
389 
390 	kmdp = preload_search_by_type("elf kernel");
391 	if (kmdp == NULL)
392 		kmdp = preload_search_by_type("elf64 kernel");
393 	efihdr = (struct efi_map_header *)preload_search_info(kmdp,
394 	    MODINFO_METADATA | MODINFOMD_EFI_MAP);
395 	if (efihdr == NULL) {
396 		if (bootverbose)
397 			kprintf("EFI map is not present\n");
398 		return (ENXIO);
399 	}
400 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
401 	map = (struct efi_md *)((uint8_t *)efihdr + efisz);
402 	if (efihdr->descriptor_size == 0)
403 		return (ENOMEM);
404 
405 	if (!efi_create_1t1_map(map, efihdr->memory_size /
406 	    efihdr->descriptor_size, efihdr->descriptor_size)) {
407 		if (bootverbose)
408 			kprintf("EFI cannot create runtime map\n");
409 		return (ENOMEM);
410 	}
411 
412 	efi_runtime = (efi_systbl->st_rt == 0) ? NULL :
413 			(struct efi_rt *)efi_systbl->st_rt;
414 	if (efi_runtime == NULL) {
415 		if (bootverbose)
416 			kprintf("EFI runtime services table is not present\n");
417 		efi_destroy_1t1_map();
418 		return (ENXIO);
419 	}
420 
421 	return (0);
422 }
423 
424 static void
425 efi_uninit(void)
426 {
427 	efi_destroy_1t1_map();
428 
429 	efi_systbl = NULL;
430 	efi_cfgtbl = NULL;
431 	efi_runtime = NULL;
432 
433 	lockuninit(&efi_lock);
434 	lockuninit(&resettodr_lock);
435 }
436 
437 int
438 efi_get_table(struct uuid *uuid, void **ptr)
439 {
440 	struct efi_cfgtbl *ct;
441 	u_long count;
442 
443 	if (efi_cfgtbl == NULL)
444 		return (ENXIO);
445 	count = efi_systbl->st_entries;
446 	ct = efi_cfgtbl;
447 	while (count--) {
448 		if (!bcmp(&ct->ct_uuid, uuid, sizeof(*uuid))) {
449 			*ptr = (void *)PHYS_TO_DMAP(ct->ct_data);
450 			return (0);
451 		}
452 		ct++;
453 	}
454 	return (ENOENT);
455 }
456 
457 char SaveCode[1024];
458 
459 int
460 efi_get_time_locked(struct efi_tm *tm)
461 {
462 	efi_status status;
463 	int error;
464 
465 	KKASSERT(lockowned(&resettodr_lock) != 0);
466 	error = efi_enter();
467 	if (error != 0)
468 		return (error);
469 	status = efi_runtime->rt_gettime(tm, NULL);
470 	efi_leave();
471 	error = efi_status_to_errno(status);
472 
473 	return (error);
474 }
475 
476 int
477 efi_get_time(struct efi_tm *tm)
478 {
479 	int error;
480 
481 	if (efi_runtime == NULL)
482 		return (ENXIO);
483 	lockmgr(&resettodr_lock, LK_EXCLUSIVE);
484 	error = efi_get_time_locked(tm);
485 	lockmgr(&resettodr_lock, LK_RELEASE);
486 
487 	return (error);
488 }
489 
490 int
491 efi_reset_system(void)
492 {
493 	int error;
494 
495 	error = efi_enter();
496 	if (error != 0)
497 		return (error);
498 	efi_runtime->rt_reset(EFI_RESET_WARM, 0, 0, NULL);
499 	efi_leave();
500 	return (EIO);
501 }
502 
503 int
504 efi_set_time_locked(struct efi_tm *tm)
505 {
506 	efi_status status;
507 	int error;
508 
509 	KKASSERT(lockowned(&resettodr_lock) != 0);
510 	error = efi_enter();
511 	if (error != 0)
512 		return (error);
513 	status = efi_runtime->rt_settime(tm);
514 	efi_leave();
515 	error = efi_status_to_errno(status);
516 	return (error);
517 }
518 
519 int
520 efi_set_time(struct efi_tm *tm)
521 {
522 	int error;
523 
524 	if (efi_runtime == NULL)
525 		return (ENXIO);
526 	lockmgr(&resettodr_lock, LK_EXCLUSIVE);
527 	error = efi_set_time_locked(tm);
528 	lockmgr(&resettodr_lock, LK_RELEASE);
529 	return (error);
530 }
531 
532 int
533 efi_var_get(efi_char *name, struct uuid *vendor, uint32_t *attrib,
534     size_t *datasize, void *data)
535 {
536 	efi_status status;
537 	int error;
538 
539 	error = efi_enter();
540 	if (error != 0)
541 		return (error);
542 	status = efi_runtime->rt_getvar(name, vendor, attrib, datasize, data);
543 	efi_leave();
544 	error = efi_status_to_errno(status);
545 	return (error);
546 }
547 
548 int
549 efi_var_nextname(size_t *namesize, efi_char *name, struct uuid *vendor)
550 {
551 	efi_status status;
552 	int error;
553 
554 	error = efi_enter();
555 	if (error != 0)
556 		return (error);
557 	status = efi_runtime->rt_scanvar(namesize, name, vendor);
558 	efi_leave();
559 	error = efi_status_to_errno(status);
560 	return (error);
561 }
562 
563 int
564 efi_var_set(efi_char *name, struct uuid *vendor, uint32_t attrib,
565     size_t datasize, void *data)
566 {
567 	efi_status status;
568 	int error;
569 
570 	error = efi_enter();
571 	if (error != 0)
572 		return (error);
573 	status = efi_runtime->rt_setvar(name, vendor, attrib, datasize, data);
574 	efi_leave();
575 	error = efi_status_to_errno(status);
576 	return (error);
577 }
578 
579 static int
580 efirt_modevents(module_t m, int event, void *arg __unused)
581 {
582 
583 	switch (event) {
584 	case MOD_LOAD:
585 		return (efi_init());
586 
587 	case MOD_UNLOAD:
588 		efi_uninit();
589 		return (0);
590 
591 	case MOD_SHUTDOWN:
592 		return (0);
593 
594 	default:
595 		return (EOPNOTSUPP);
596 	}
597 }
598 
599 static moduledata_t efirt_moddata = {
600 	.name = "efirt",
601 	.evhand = efirt_modevents,
602 	.priv = NULL,
603 };
604 
605 DECLARE_MODULE(efirt, efirt_moddata, SI_SUB_DRIVERS, SI_ORDER_ANY);
606 MODULE_VERSION(efirt, 1);
607 
608 
609 /* XXX debug stuff */
610 static int
611 efi_time_sysctl_handler(SYSCTL_HANDLER_ARGS)
612 {
613 	struct efi_tm tm;
614 	int error, val;
615 
616 	val = 0;
617 	error = sysctl_handle_int(oidp, &val, 0, req);
618 	if (error != 0 || req->newptr == NULL)
619 		return (error);
620 	error = efi_get_time(&tm);
621 	if (error == 0) {
622 		uprintf("EFI reports: Year %d Month %d Day %d Hour %d Min %d "
623 		    "Sec %d\n", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour,
624 		    tm.tm_min, tm.tm_sec);
625 	}
626 	return (error);
627 }
628 
629 SYSCTL_PROC(_debug, OID_AUTO, efi_time, CTLTYPE_INT | CTLFLAG_RW, NULL, 0,
630 	    efi_time_sysctl_handler, "I", "");
631