xref: /dragonfly/sys/platform/pc64/x86_64/efirt.c (revision 7c4f4eee)
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 	/*
209 	 * efi_obj is ref'd by cdev_pager_allocate
210 	 */
211 	efi_vmspace = vmspace_alloc(VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
212 	pmap_pinit2(vmspace_pmap(efi_vmspace));
213 	efi_obj = cdev_pager_allocate(NULL, OBJT_MGTDEVICE, &efi_pager_ops,
214 				  VM_MAX_USER_ADDRESS,
215 				  VM_PROT_READ | VM_PROT_WRITE,
216 				  0, proc0.p_ucred);
217 	vm_object_hold(efi_obj);
218 
219 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
220 	vm_map_lock(&efi_vmspace->vm_map);
221 	result = vm_map_insert(&efi_vmspace->vm_map, &count, efi_obj, NULL,
222 			      0, 0, VM_MAX_USER_ADDRESS,
223 			      VM_MAPTYPE_NORMAL,
224 			      VM_SUBSYS_EFI,
225 			      VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE,
226 			      VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE,
227 			      0);
228 	vm_map_unlock(&efi_vmspace->vm_map);
229 	if (result != KERN_SUCCESS)
230 		goto fail;
231 
232 	for (i = 0, p = map;
233 	     i < ndesc; i++, p = efi_next_descriptor(p, descsz)) {
234 		vm_offset_t va;
235 		uint64_t idx;
236 		int mode;
237 
238 		if ((p->md_attr & EFI_MD_ATTR_RT) == 0)
239 			continue;
240 		if (p->md_virt != NULL) {
241 			if (bootverbose)
242 				kprintf("EFI Runtime entry %d is mapped\n", i);
243 			goto fail;
244 		}
245 		if ((p->md_phys & EFI_PAGE_MASK) != 0) {
246 			if (bootverbose)
247 				kprintf("EFI Runtime entry %d is not aligned\n",
248 				    i);
249 			goto fail;
250 		}
251 		if (p->md_phys + p->md_pages * EFI_PAGE_SIZE < p->md_phys ||
252 		    p->md_phys + p->md_pages * EFI_PAGE_SIZE >=
253 		    VM_MAX_USER_ADDRESS) {
254 			kprintf("EFI Runtime entry %d is not in mappable for RT:"
255 			    "base %#016jx %#jx pages\n",
256 			    i, (uintmax_t)p->md_phys,
257 			    (uintmax_t)p->md_pages);
258 			goto fail;
259 		}
260 
261 		if ((p->md_attr & EFI_MD_ATTR_WB) != 0)
262 			mode = VM_MEMATTR_WRITE_BACK;
263 		else if ((p->md_attr & EFI_MD_ATTR_WT) != 0)
264 			mode = VM_MEMATTR_WRITE_THROUGH;
265 		else if ((p->md_attr & EFI_MD_ATTR_WC) != 0)
266 			mode = VM_MEMATTR_WRITE_COMBINING;
267 		else if ((p->md_attr & EFI_MD_ATTR_WP) != 0)
268 			mode = VM_MEMATTR_WRITE_PROTECTED;
269 		else if ((p->md_attr & EFI_MD_ATTR_UC) != 0)
270 			mode = VM_MEMATTR_UNCACHEABLE;
271 		else {
272 			if (bootverbose)
273 				kprintf("EFI Runtime entry %d mapping "
274 				    "attributes unsupported\n", i);
275 			mode = VM_MEMATTR_UNCACHEABLE;
276 		}
277 
278 		if (bootverbose) {
279 			kprintf("efirt: map %016jx-%016jx\n",
280 				p->md_phys,
281 				p->md_phys + IDX_TO_OFF(p->md_pages));
282 		}
283 
284 		for (va = p->md_phys, idx = 0; idx < p->md_pages; idx++,
285 		    va += PAGE_SIZE) {
286 			m = kmalloc(sizeof(*m), M_EFI, M_WAITOK | M_ZERO);
287 			/*m->flags |= PG_WRITEABLE;*/
288 			vm_page_initfake(m, va, mode);	/* va is phys addr */
289 			m->valid = VM_PAGE_BITS_ALL;
290 			m->dirty = m->valid;
291 			vm_page_insert(m, efi_obj, OFF_TO_IDX(va));
292 			vm_page_wakeup(m);
293 		}
294 	}
295 	vm_object_drop(efi_obj);
296 	vm_map_entry_release(count);
297 
298 	return true;
299 
300 fail:
301 	vm_object_drop(efi_obj);
302 	vm_map_entry_release(count);
303 	efi_destroy_1t1_map();
304 
305 	return false;
306 }
307 
308 /*
309  * Create an environment for the EFI runtime code call.  The most
310  * important part is creating the required 1:1 physical->virtual
311  * mappings for the runtime segments.  To do that, we manually create
312  * page table which unmap userspace but gives correct kernel mapping.
313  * The 1:1 mappings for runtime segments usually occupy low 4G of the
314  * physical address map.
315  *
316  * The 1:1 mappings were chosen over the SetVirtualAddressMap() EFI RT
317  * service, because there are some BIOSes which fail to correctly
318  * relocate itself on the call, requiring both 1:1 and virtual
319  * mapping.  As result, we must provide 1:1 mapping anyway, so no
320  * reason to bother with the virtual map, and no need to add a
321  * complexity into loader.
322  *
323  * The fpu_kern_enter() call allows firmware to use FPU, as mandated
324  * by the specification.  In particular, CR0.TS bit is cleared.  Also
325  * it enters critical section, giving us neccessary protection against
326  * context switch.
327  *
328  * There is no need to disable interrupts around the change of %cr3,
329  * the kernel mappings are correct, while we only grabbed the
330  * userspace portion of VA.  Interrupts handlers must not access
331  * userspace.  Having interrupts enabled fixes the issue with
332  * firmware/SMM long operation, which would negatively affect IPIs,
333  * esp. TLB shootdown requests.
334  */
335 static int
336 efi_enter(void)
337 {
338 	thread_t td = curthread;
339 
340 	if (efi_runtime == NULL)
341 		return (ENXIO);
342 	lockmgr(&efi_lock, LK_EXCLUSIVE);
343 	efi_savevm = td->td_lwp->lwp_vmspace;
344 	pmap_setlwpvm(td->td_lwp, efi_vmspace);
345 	npxpush(&efi_ctx);
346 	cpu_invltlb();
347 
348 	return (0);
349 }
350 
351 static void
352 efi_leave(void)
353 {
354 	thread_t td = curthread;
355 
356 	pmap_setlwpvm(td->td_lwp, efi_savevm);
357 	npxpop(&efi_ctx);
358 	cpu_invltlb();
359 	efi_savevm = NULL;
360 	lockmgr(&efi_lock, LK_RELEASE);
361 }
362 
363 static int
364 efi_init(void)
365 {
366 	struct efi_map_header *efihdr;
367 	struct efi_md *map;
368 	caddr_t kmdp;
369 	size_t efisz;
370 
371 	lockinit(&efi_lock, "efi", 0, LK_CANRECURSE);
372 	lockinit(&resettodr_lock, "efitodr", 0, LK_CANRECURSE);
373 
374 	if (efi_systbl_phys == 0) {
375 		if (bootverbose)
376 			kprintf("EFI systbl not available\n");
377 		return (ENXIO);
378 	}
379 	efi_systbl = (struct efi_systbl *)PHYS_TO_DMAP(efi_systbl_phys);
380 	if (efi_systbl->st_hdr.th_sig != EFI_SYSTBL_SIG) {
381 		efi_systbl = NULL;
382 		if (bootverbose)
383 			kprintf("EFI systbl signature invalid\n");
384 		return (ENXIO);
385 	}
386 	efi_cfgtbl = (efi_systbl->st_cfgtbl == 0) ? NULL :
387 	    (struct efi_cfgtbl *)efi_systbl->st_cfgtbl;
388 	if (efi_cfgtbl == NULL) {
389 		if (bootverbose)
390 			kprintf("EFI config table is not present\n");
391 	}
392 
393 	kmdp = preload_search_by_type("elf kernel");
394 	if (kmdp == NULL)
395 		kmdp = preload_search_by_type("elf64 kernel");
396 	efihdr = (struct efi_map_header *)preload_search_info(kmdp,
397 	    MODINFO_METADATA | MODINFOMD_EFI_MAP);
398 	if (efihdr == NULL) {
399 		if (bootverbose)
400 			kprintf("EFI map is not present\n");
401 		return (ENXIO);
402 	}
403 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
404 	map = (struct efi_md *)((uint8_t *)efihdr + efisz);
405 	if (efihdr->descriptor_size == 0)
406 		return (ENOMEM);
407 
408 	if (!efi_create_1t1_map(map, efihdr->memory_size /
409 	    efihdr->descriptor_size, efihdr->descriptor_size)) {
410 		if (bootverbose)
411 			kprintf("EFI cannot create runtime map\n");
412 		return (ENOMEM);
413 	}
414 
415 	efi_runtime = (efi_systbl->st_rt == 0) ? NULL :
416 			(struct efi_rt *)efi_systbl->st_rt;
417 	if (efi_runtime == NULL) {
418 		if (bootverbose)
419 			kprintf("EFI runtime services table is not present\n");
420 		efi_destroy_1t1_map();
421 		return (ENXIO);
422 	}
423 
424 	return (0);
425 }
426 
427 static void
428 efi_uninit(void)
429 {
430 	efi_destroy_1t1_map();
431 
432 	efi_systbl = NULL;
433 	efi_cfgtbl = NULL;
434 	efi_runtime = NULL;
435 
436 	lockuninit(&efi_lock);
437 	lockuninit(&resettodr_lock);
438 }
439 
440 int
441 efi_get_table(struct uuid *uuid, void **ptr)
442 {
443 	struct efi_cfgtbl *ct;
444 	u_long count;
445 
446 	if (efi_cfgtbl == NULL)
447 		return (ENXIO);
448 	count = efi_systbl->st_entries;
449 	ct = efi_cfgtbl;
450 	while (count--) {
451 		if (!bcmp(&ct->ct_uuid, uuid, sizeof(*uuid))) {
452 			*ptr = (void *)PHYS_TO_DMAP(ct->ct_data);
453 			return (0);
454 		}
455 		ct++;
456 	}
457 	return (ENOENT);
458 }
459 
460 char SaveCode[1024];
461 
462 int
463 efi_get_time_locked(struct efi_tm *tm)
464 {
465 	efi_status status;
466 	int error;
467 
468 	KKASSERT(lockowned(&resettodr_lock) != 0);
469 	error = efi_enter();
470 	if (error != 0)
471 		return (error);
472 	status = efi_runtime->rt_gettime(tm, NULL);
473 	efi_leave();
474 	error = efi_status_to_errno(status);
475 
476 	return (error);
477 }
478 
479 int
480 efi_get_time(struct efi_tm *tm)
481 {
482 	int error;
483 
484 	if (efi_runtime == NULL)
485 		return (ENXIO);
486 	lockmgr(&resettodr_lock, LK_EXCLUSIVE);
487 	error = efi_get_time_locked(tm);
488 	lockmgr(&resettodr_lock, LK_RELEASE);
489 
490 	return (error);
491 }
492 
493 int
494 efi_reset_system(void)
495 {
496 	int error;
497 
498 	error = efi_enter();
499 	if (error != 0)
500 		return (error);
501 	efi_runtime->rt_reset(EFI_RESET_WARM, 0, 0, NULL);
502 	efi_leave();
503 	return (EIO);
504 }
505 
506 int
507 efi_set_time_locked(struct efi_tm *tm)
508 {
509 	efi_status status;
510 	int error;
511 
512 	KKASSERT(lockowned(&resettodr_lock) != 0);
513 	error = efi_enter();
514 	if (error != 0)
515 		return (error);
516 	status = efi_runtime->rt_settime(tm);
517 	efi_leave();
518 	error = efi_status_to_errno(status);
519 	return (error);
520 }
521 
522 int
523 efi_set_time(struct efi_tm *tm)
524 {
525 	int error;
526 
527 	if (efi_runtime == NULL)
528 		return (ENXIO);
529 	lockmgr(&resettodr_lock, LK_EXCLUSIVE);
530 	error = efi_set_time_locked(tm);
531 	lockmgr(&resettodr_lock, LK_RELEASE);
532 	return (error);
533 }
534 
535 int
536 efi_var_get(efi_char *name, struct uuid *vendor, uint32_t *attrib,
537     size_t *datasize, void *data)
538 {
539 	efi_status status;
540 	int error;
541 
542 	error = efi_enter();
543 	if (error != 0)
544 		return (error);
545 	status = efi_runtime->rt_getvar(name, vendor, attrib, datasize, data);
546 	efi_leave();
547 	error = efi_status_to_errno(status);
548 	return (error);
549 }
550 
551 int
552 efi_var_nextname(size_t *namesize, efi_char *name, struct uuid *vendor)
553 {
554 	efi_status status;
555 	int error;
556 
557 	error = efi_enter();
558 	if (error != 0)
559 		return (error);
560 	status = efi_runtime->rt_scanvar(namesize, name, vendor);
561 	efi_leave();
562 	error = efi_status_to_errno(status);
563 	return (error);
564 }
565 
566 int
567 efi_var_set(efi_char *name, struct uuid *vendor, uint32_t attrib,
568     size_t datasize, void *data)
569 {
570 	efi_status status;
571 	int error;
572 
573 	error = efi_enter();
574 	if (error != 0)
575 		return (error);
576 	status = efi_runtime->rt_setvar(name, vendor, attrib, datasize, data);
577 	efi_leave();
578 	error = efi_status_to_errno(status);
579 	return (error);
580 }
581 
582 static int
583 efirt_modevents(module_t m, int event, void *arg __unused)
584 {
585 
586 	switch (event) {
587 	case MOD_LOAD:
588 		return (efi_init());
589 
590 	case MOD_UNLOAD:
591 		efi_uninit();
592 		return (0);
593 
594 	case MOD_SHUTDOWN:
595 		return (0);
596 
597 	default:
598 		return (EOPNOTSUPP);
599 	}
600 }
601 
602 static moduledata_t efirt_moddata = {
603 	.name = "efirt",
604 	.evhand = efirt_modevents,
605 	.priv = NULL,
606 };
607 
608 DECLARE_MODULE(efirt, efirt_moddata, SI_SUB_DRIVERS, SI_ORDER_ANY);
609 MODULE_VERSION(efirt, 1);
610 
611 
612 /* XXX debug stuff */
613 static int
614 efi_time_sysctl_handler(SYSCTL_HANDLER_ARGS)
615 {
616 	struct efi_tm tm;
617 	int error, val;
618 
619 	val = 0;
620 	error = sysctl_handle_int(oidp, &val, 0, req);
621 	if (error != 0 || req->newptr == NULL)
622 		return (error);
623 	error = efi_get_time(&tm);
624 	if (error == 0) {
625 		uprintf("EFI reports: Year %d Month %d Day %d Hour %d Min %d "
626 		    "Sec %d\n", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour,
627 		    tm.tm_min, tm.tm_sec);
628 	}
629 	return (error);
630 }
631 
632 SYSCTL_PROC(_debug, OID_AUTO, efi_time, CTLTYPE_INT | CTLFLAG_RW, NULL, 0,
633 	    efi_time_sysctl_handler, "I", "");
634