]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/efirt.c
Merge llvm, clang, lld and lldb trunk r291476.
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / efirt.c
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
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include <sys/param.h>
36 #include <sys/efi.h>
37 #include <sys/kernel.h>
38 #include <sys/linker.h>
39 #include <sys/lock.h>
40 #include <sys/module.h>
41 #include <sys/mutex.h>
42 #include <sys/clock.h>
43 #include <sys/proc.h>
44 #include <sys/rwlock.h>
45 #include <sys/sched.h>
46 #include <sys/sysctl.h>
47 #include <sys/systm.h>
48 #include <machine/fpu.h>
49 #include <machine/efi.h>
50 #include <machine/metadata.h>
51 #include <machine/md_var.h>
52 #include <machine/smp.h>
53 #include <machine/vmparam.h>
54 #include <vm/vm.h>
55 #include <vm/pmap.h>
56 #include <vm/vm_map.h>
57 #include <vm/vm_object.h>
58 #include <vm/vm_page.h>
59 #include <vm/vm_pager.h>
60
61 static struct efi_systbl *efi_systbl;
62 static struct efi_cfgtbl *efi_cfgtbl;
63 static struct efi_rt *efi_runtime;
64
65 static int efi_status2err[25] = {
66         0,              /* EFI_SUCCESS */
67         ENOEXEC,        /* EFI_LOAD_ERROR */
68         EINVAL,         /* EFI_INVALID_PARAMETER */
69         ENOSYS,         /* EFI_UNSUPPORTED */
70         EMSGSIZE,       /* EFI_BAD_BUFFER_SIZE */
71         EOVERFLOW,      /* EFI_BUFFER_TOO_SMALL */
72         EBUSY,          /* EFI_NOT_READY */
73         EIO,            /* EFI_DEVICE_ERROR */
74         EROFS,          /* EFI_WRITE_PROTECTED */
75         EAGAIN,         /* EFI_OUT_OF_RESOURCES */
76         EIO,            /* EFI_VOLUME_CORRUPTED */
77         ENOSPC,         /* EFI_VOLUME_FULL */
78         ENXIO,          /* EFI_NO_MEDIA */
79         ESTALE,         /* EFI_MEDIA_CHANGED */
80         ENOENT,         /* EFI_NOT_FOUND */
81         EACCES,         /* EFI_ACCESS_DENIED */
82         ETIMEDOUT,      /* EFI_NO_RESPONSE */
83         EADDRNOTAVAIL,  /* EFI_NO_MAPPING */
84         ETIMEDOUT,      /* EFI_TIMEOUT */
85         EDOOFUS,        /* EFI_NOT_STARTED */
86         EALREADY,       /* EFI_ALREADY_STARTED */
87         ECANCELED,      /* EFI_ABORTED */
88         EPROTO,         /* EFI_ICMP_ERROR */
89         EPROTO,         /* EFI_TFTP_ERROR */
90         EPROTO          /* EFI_PROTOCOL_ERROR */
91 };
92
93 static int
94 efi_status_to_errno(efi_status status)
95 {
96         u_long code;
97
98         code = status & 0x3ffffffffffffffful;
99         return (code < nitems(efi_status2err) ? efi_status2err[code] : EDOOFUS);
100 }
101
102 static struct mtx efi_lock;
103 static pml4_entry_t *efi_pml4;
104 static vm_object_t obj_1t1_pt;
105 static vm_page_t efi_pml4_page;
106
107 static void
108 efi_destroy_1t1_map(void)
109 {
110         vm_page_t m;
111
112         if (obj_1t1_pt != NULL) {
113                 VM_OBJECT_RLOCK(obj_1t1_pt);
114                 TAILQ_FOREACH(m, &obj_1t1_pt->memq, listq)
115                         m->wire_count = 0;
116                 atomic_subtract_int(&vm_cnt.v_wire_count,
117                     obj_1t1_pt->resident_page_count);
118                 VM_OBJECT_RUNLOCK(obj_1t1_pt);
119                 vm_object_deallocate(obj_1t1_pt);
120         }
121
122         obj_1t1_pt = NULL;
123         efi_pml4 = NULL;
124         efi_pml4_page = NULL;
125 }
126
127 static vm_page_t
128 efi_1t1_page(vm_pindex_t idx)
129 {
130
131         return (vm_page_grab(obj_1t1_pt, idx, VM_ALLOC_NOBUSY |
132             VM_ALLOC_WIRED | VM_ALLOC_ZERO));
133 }
134
135 static pt_entry_t *
136 efi_1t1_pte(vm_offset_t va)
137 {
138         pml4_entry_t *pml4e;
139         pdp_entry_t *pdpe;
140         pd_entry_t *pde;
141         pt_entry_t *pte;
142         vm_page_t m;
143         vm_pindex_t pml4_idx, pdp_idx, pd_idx;
144         vm_paddr_t mphys;
145
146         pml4_idx = pmap_pml4e_index(va);
147         pml4e = &efi_pml4[pml4_idx];
148         if (*pml4e == 0) {
149                 m = efi_1t1_page(1 + pml4_idx);
150                 mphys =  VM_PAGE_TO_PHYS(m);
151                 *pml4e = mphys | X86_PG_RW | X86_PG_V;
152         } else {
153                 mphys = *pml4e & ~PAGE_MASK;
154         }
155
156         pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys);
157         pdp_idx = pmap_pdpe_index(va);
158         pdpe += pdp_idx;
159         if (*pdpe == 0) {
160                 m = efi_1t1_page(1 + NPML4EPG + (pml4_idx + 1) * (pdp_idx + 1));
161                 mphys =  VM_PAGE_TO_PHYS(m);
162                 *pdpe = mphys | X86_PG_RW | X86_PG_V;
163         } else {
164                 mphys = *pdpe & ~PAGE_MASK;
165         }
166
167         pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
168         pd_idx = pmap_pde_index(va);
169         pde += pd_idx;
170         if (*pde == 0) {
171                 m = efi_1t1_page(1 + NPML4EPG + NPML4EPG * NPDPEPG +
172                     (pml4_idx + 1) * (pdp_idx + 1) * (pd_idx + 1));
173                 mphys = VM_PAGE_TO_PHYS(m);
174                 *pde = mphys | X86_PG_RW | X86_PG_V;
175         } else {
176                 mphys = *pde & ~PAGE_MASK;
177         }
178
179         pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
180         pte += pmap_pte_index(va);
181         KASSERT(*pte == 0, ("va %#jx *pt %#jx", va, *pte));
182
183         return (pte);
184 }
185
186 static bool
187 efi_create_1t1_map(struct efi_md *map, int ndesc, int descsz)
188 {
189         struct efi_md *p;
190         pt_entry_t *pte;
191         vm_offset_t va;
192         uint64_t idx;
193         int bits, i, mode;
194
195         obj_1t1_pt = vm_pager_allocate(OBJT_PHYS, NULL, 1 + NPML4EPG +
196             NPML4EPG * NPDPEPG + NPML4EPG * NPDPEPG * NPDEPG,
197             VM_PROT_ALL, 0, NULL);
198         VM_OBJECT_WLOCK(obj_1t1_pt);
199         efi_pml4_page = efi_1t1_page(0);
200         VM_OBJECT_WUNLOCK(obj_1t1_pt);
201         efi_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(efi_pml4_page));
202         pmap_pinit_pml4(efi_pml4_page);
203
204         for (i = 0, p = map; i < ndesc; i++, p = efi_next_descriptor(p,
205             descsz)) {
206                 if ((p->md_attr & EFI_MD_ATTR_RT) == 0)
207                         continue;
208                 if (p->md_virt != NULL) {
209                         if (bootverbose)
210                                 printf("EFI Runtime entry %d is mapped\n", i);
211                         goto fail;
212                 }
213                 if ((p->md_phys & EFI_PAGE_MASK) != 0) {
214                         if (bootverbose)
215                                 printf("EFI Runtime entry %d is not aligned\n",
216                                     i);
217                         goto fail;
218                 }
219                 if (p->md_phys + p->md_pages * EFI_PAGE_SIZE < p->md_phys ||
220                     p->md_phys + p->md_pages * EFI_PAGE_SIZE >=
221                     VM_MAXUSER_ADDRESS) {
222                         printf("EFI Runtime entry %d is not in mappable for RT:"
223                             "base %#016jx %#jx pages\n",
224                             i, (uintmax_t)p->md_phys,
225                             (uintmax_t)p->md_pages);
226                         goto fail;
227                 }
228                 if ((p->md_attr & EFI_MD_ATTR_WB) != 0)
229                         mode = VM_MEMATTR_WRITE_BACK;
230                 else if ((p->md_attr & EFI_MD_ATTR_WT) != 0)
231                         mode = VM_MEMATTR_WRITE_THROUGH;
232                 else if ((p->md_attr & EFI_MD_ATTR_WC) != 0)
233                         mode = VM_MEMATTR_WRITE_COMBINING;
234                 else if ((p->md_attr & EFI_MD_ATTR_WP) != 0)
235                         mode = VM_MEMATTR_WRITE_PROTECTED;
236                 else if ((p->md_attr & EFI_MD_ATTR_UC) != 0)
237                         mode = VM_MEMATTR_UNCACHEABLE;
238                 else {
239                         if (bootverbose)
240                                 printf("EFI Runtime entry %d mapping "
241                                     "attributes unsupported\n", i);
242                         mode = VM_MEMATTR_UNCACHEABLE;
243                 }
244                 bits = pmap_cache_bits(kernel_pmap, mode, FALSE) | X86_PG_RW |
245                     X86_PG_V;
246                 VM_OBJECT_WLOCK(obj_1t1_pt);
247                 for (va = p->md_phys, idx = 0; idx < p->md_pages; idx++,
248                     va += PAGE_SIZE) {
249                         pte = efi_1t1_pte(va);
250                         pte_store(pte, va | bits);
251                 }
252                 VM_OBJECT_WUNLOCK(obj_1t1_pt);
253         }
254
255         return (true);
256
257 fail:
258         efi_destroy_1t1_map();
259         return (false);
260 }
261
262 /*
263  * Create an environment for the EFI runtime code call.  The most
264  * important part is creating the required 1:1 physical->virtual
265  * mappings for the runtime segments.  To do that, we manually create
266  * page table which unmap userspace but gives correct kernel mapping.
267  * The 1:1 mappings for runtime segments usually occupy low 4G of the
268  * physical address map.
269  *
270  * The 1:1 mappings were chosen over the SetVirtualAddressMap() EFI RT
271  * service, because there are some BIOSes which fail to correctly
272  * relocate itself on the call, requiring both 1:1 and virtual
273  * mapping.  As result, we must provide 1:1 mapping anyway, so no
274  * reason to bother with the virtual map, and no need to add a
275  * complexity into loader.
276  *
277  * The fpu_kern_enter() call allows firmware to use FPU, as mandated
278  * by the specification.  In particular, CR0.TS bit is cleared.  Also
279  * it enters critical section, giving us neccessary protection against
280  * context switch.
281  *
282  * There is no need to disable interrupts around the change of %cr3,
283  * the kernel mappings are correct, while we only grabbed the
284  * userspace portion of VA.  Interrupts handlers must not access
285  * userspace.  Having interrupts enabled fixes the issue with
286  * firmware/SMM long operation, which would negatively affect IPIs,
287  * esp. TLB shootdown requests.
288  */
289 static int
290 efi_enter(void)
291 {
292         pmap_t curpmap;
293         int error;
294
295         if (efi_runtime == NULL)
296                 return (ENXIO);
297         curpmap = PCPU_GET(curpmap);
298         PMAP_LOCK(curpmap);
299         mtx_lock(&efi_lock);
300         error = fpu_kern_enter(curthread, NULL, FPU_KERN_NOCTX);
301         if (error != 0) {
302                 PMAP_UNLOCK(curpmap);
303                 return (error);
304         }
305
306         /*
307          * IPI TLB shootdown handler invltlb_pcid_handler() reloads
308          * %cr3 from the curpmap->pm_cr3, which would disable runtime
309          * segments mappings.  Block the handler's action by setting
310          * curpmap to impossible value.  See also comment in
311          * pmap.c:pmap_activate_sw().
312          */
313         if (pmap_pcid_enabled && !invpcid_works)
314                 PCPU_SET(curpmap, NULL);
315
316         load_cr3(VM_PAGE_TO_PHYS(efi_pml4_page) | (pmap_pcid_enabled ?
317             curpmap->pm_pcids[PCPU_GET(cpuid)].pm_pcid : 0));
318         /*
319          * If PCID is enabled, the clear CR3_PCID_SAVE bit in the loaded %cr3
320          * causes TLB invalidation.
321          */
322         if (!pmap_pcid_enabled)
323                 invltlb();
324         return (0);
325 }
326
327 static void
328 efi_leave(void)
329 {
330         pmap_t curpmap;
331
332         curpmap = &curproc->p_vmspace->vm_pmap;
333         if (pmap_pcid_enabled && !invpcid_works)
334                 PCPU_SET(curpmap, curpmap);
335         load_cr3(curpmap->pm_cr3 | (pmap_pcid_enabled ?
336             curpmap->pm_pcids[PCPU_GET(cpuid)].pm_pcid : 0));
337         if (!pmap_pcid_enabled)
338                 invltlb();
339
340         fpu_kern_leave(curthread, NULL);
341         mtx_unlock(&efi_lock);
342         PMAP_UNLOCK(curpmap);
343 }
344
345 static int
346 efi_init(void)
347 {
348         struct efi_map_header *efihdr;
349         struct efi_md *map;
350         caddr_t kmdp;
351         size_t efisz;
352
353         mtx_init(&efi_lock, "efi", NULL, MTX_DEF);
354
355         if (efi_systbl_phys == 0) {
356                 if (bootverbose)
357                         printf("EFI systbl not available\n");
358                 return (0);
359         }
360         efi_systbl = (struct efi_systbl *)PHYS_TO_DMAP(efi_systbl_phys);
361         if (efi_systbl->st_hdr.th_sig != EFI_SYSTBL_SIG) {
362                 efi_systbl = NULL;
363                 if (bootverbose)
364                         printf("EFI systbl signature invalid\n");
365                 return (0);
366         }
367         efi_cfgtbl = (efi_systbl->st_cfgtbl == 0) ? NULL :
368             (struct efi_cfgtbl *)efi_systbl->st_cfgtbl;
369         if (efi_cfgtbl == NULL) {
370                 if (bootverbose)
371                         printf("EFI config table is not present\n");
372         }
373
374         kmdp = preload_search_by_type("elf kernel");
375         if (kmdp == NULL)
376                 kmdp = preload_search_by_type("elf64 kernel");
377         efihdr = (struct efi_map_header *)preload_search_info(kmdp,
378             MODINFO_METADATA | MODINFOMD_EFI_MAP);
379         if (efihdr == NULL) {
380                 if (bootverbose)
381                         printf("EFI map is not present\n");
382                 return (0);
383         }
384         efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
385         map = (struct efi_md *)((uint8_t *)efihdr + efisz);
386         if (efihdr->descriptor_size == 0)
387                 return (ENOMEM);
388
389         if (!efi_create_1t1_map(map, efihdr->memory_size /
390             efihdr->descriptor_size, efihdr->descriptor_size)) {
391                 if (bootverbose)
392                         printf("EFI cannot create runtime map\n");
393                 return (ENOMEM);
394         }
395
396         efi_runtime = (efi_systbl->st_rt == 0) ? NULL :
397             (struct efi_rt *)efi_systbl->st_rt;
398         if (efi_runtime == NULL) {
399                 if (bootverbose)
400                         printf("EFI runtime services table is not present\n");
401                 efi_destroy_1t1_map();
402                 return (ENXIO);
403         }
404
405         return (0);
406 }
407
408 static void
409 efi_uninit(void)
410 {
411
412         efi_destroy_1t1_map();
413
414         efi_systbl = NULL;
415         efi_cfgtbl = NULL;
416         efi_runtime = NULL;
417
418         mtx_destroy(&efi_lock);
419 }
420
421 int
422 efi_get_table(struct uuid *uuid, void **ptr)
423 {
424         struct efi_cfgtbl *ct;
425         u_long count;
426
427         if (efi_cfgtbl == NULL)
428                 return (ENXIO);
429         count = efi_systbl->st_entries;
430         ct = efi_cfgtbl;
431         while (count--) {
432                 if (!bcmp(&ct->ct_uuid, uuid, sizeof(*uuid))) {
433                         *ptr = (void *)PHYS_TO_DMAP(ct->ct_data);
434                         return (0);
435                 }
436                 ct++;
437         }
438         return (ENOENT);
439 }
440
441 int
442 efi_get_time_locked(struct efi_tm *tm)
443 {
444         efi_status status;
445         int error;
446
447         mtx_assert(&resettodr_lock, MA_OWNED);
448         error = efi_enter();
449         if (error != 0)
450                 return (error);
451         status = efi_runtime->rt_gettime(tm, NULL);
452         efi_leave();
453         error = efi_status_to_errno(status);
454         return (error);
455 }
456
457 int
458 efi_get_time(struct efi_tm *tm)
459 {
460         int error;
461
462         if (efi_runtime == NULL)
463                 return (ENXIO);
464         mtx_lock(&resettodr_lock);
465         error = efi_get_time_locked(tm);
466         mtx_unlock(&resettodr_lock);
467         return (error);
468 }
469
470 int
471 efi_reset_system(void)
472 {
473         int error;
474
475         error = efi_enter();
476         if (error != 0)
477                 return (error);
478         efi_runtime->rt_reset(EFI_RESET_WARM, 0, 0, NULL);
479         efi_leave();
480         return (EIO);
481 }
482
483 int
484 efi_set_time_locked(struct efi_tm *tm)
485 {
486         efi_status status;
487         int error;
488
489         mtx_assert(&resettodr_lock, MA_OWNED);
490         error = efi_enter();
491         if (error != 0)
492                 return (error);
493         status = efi_runtime->rt_settime(tm);
494         efi_leave();
495         error = efi_status_to_errno(status);
496         return (error);
497 }
498
499 int
500 efi_set_time(struct efi_tm *tm)
501 {
502         int error;
503
504         if (efi_runtime == NULL)
505                 return (ENXIO);
506         mtx_lock(&resettodr_lock);
507         error = efi_set_time_locked(tm);
508         mtx_unlock(&resettodr_lock);
509         return (error);
510 }
511
512 int
513 efi_var_get(efi_char *name, struct uuid *vendor, uint32_t *attrib,
514     size_t *datasize, void *data)
515 {
516         efi_status status;
517         int error;
518
519         error = efi_enter();
520         if (error != 0)
521                 return (error);
522         status = efi_runtime->rt_getvar(name, vendor, attrib, datasize, data);
523         efi_leave();
524         error = efi_status_to_errno(status);
525         return (error);
526 }
527
528 int
529 efi_var_nextname(size_t *namesize, efi_char *name, struct uuid *vendor)
530 {
531         efi_status status;
532         int error;
533
534         error = efi_enter();
535         if (error != 0)
536                 return (error);
537         status = efi_runtime->rt_scanvar(namesize, name, vendor);
538         efi_leave();
539         error = efi_status_to_errno(status);
540         return (error);
541 }
542
543 int
544 efi_var_set(efi_char *name, struct uuid *vendor, uint32_t attrib,
545     size_t datasize, void *data)
546 {
547         efi_status status;
548         int error;
549
550         error = efi_enter();
551         if (error != 0)
552                 return (error);
553         status = efi_runtime->rt_setvar(name, vendor, attrib, datasize, data);
554         efi_leave();
555         error = efi_status_to_errno(status);
556         return (error);
557 }
558
559 static int
560 efirt_modevents(module_t m, int event, void *arg __unused)
561 {
562
563         switch (event) {
564         case MOD_LOAD:
565                 return (efi_init());
566
567         case MOD_UNLOAD:
568                 efi_uninit();
569                 return (0);
570
571         case MOD_SHUTDOWN:
572                 return (0);
573
574         default:
575                 return (EOPNOTSUPP);
576         }
577 }
578
579 static moduledata_t efirt_moddata = {
580         .name = "efirt",
581         .evhand = efirt_modevents,
582         .priv = NULL,
583 };
584 DECLARE_MODULE(efirt, efirt_moddata, SI_SUB_VM_CONF, SI_ORDER_ANY);
585 MODULE_VERSION(efirt, 1);
586
587 /* XXX debug stuff */
588 static int
589 efi_time_sysctl_handler(SYSCTL_HANDLER_ARGS)
590 {
591         struct efi_tm tm;
592         int error, val;
593
594         val = 0;
595         error = sysctl_handle_int(oidp, &val, 0, req);
596         if (error != 0 || req->newptr == NULL)
597                 return (error);
598         error = efi_get_time(&tm);
599         if (error == 0) {
600                 uprintf("EFI reports: Year %d Month %d Day %d Hour %d Min %d "
601                     "Sec %d\n", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour,
602                     tm.tm_min, tm.tm_sec);
603         }
604         return (error);
605 }
606
607 SYSCTL_PROC(_debug, OID_AUTO, efi_time, CTLTYPE_INT | CTLFLAG_RW, NULL, 0,
608     efi_time_sysctl_handler, "I", "");