1 /*-
2 * Copyright (c) 2003 Peter Wemm.
3 * Copyright (c) 1992 Terrence R. Lambert.
4 * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * William Jolitz.
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 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 *
38 * from: @(#)machdep.c 7.4 (Berkeley) 6/3/91
39 */
40
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD: releng/10.3/sys/amd64/amd64/machdep.c 294683 2016-01-24 21:04:06Z ian $");
43
44 #include "opt_atalk.h"
45 #include "opt_atpic.h"
46 #include "opt_compat.h"
47 #include "opt_cpu.h"
48 #include "opt_ddb.h"
49 #include "opt_inet.h"
50 #include "opt_ipx.h"
51 #include "opt_isa.h"
52 #include "opt_kstack_pages.h"
53 #include "opt_maxmem.h"
54 #include "opt_mp_watchdog.h"
55 #include "opt_perfmon.h"
56 #include "opt_platform.h"
57 #include "opt_sched.h"
58 #include "opt_kdtrace.h"
59
60 #include <sys/param.h>
61 #include <sys/proc.h>
62 #include <sys/systm.h>
63 #include <sys/bio.h>
64 #include <sys/buf.h>
65 #include <sys/bus.h>
66 #include <sys/callout.h>
67 #include <sys/cons.h>
68 #include <sys/cpu.h>
69 #include <sys/efi.h>
70 #include <sys/eventhandler.h>
71 #include <sys/exec.h>
72 #include <sys/imgact.h>
73 #include <sys/kdb.h>
74 #include <sys/kernel.h>
75 #include <sys/ktr.h>
76 #include <sys/linker.h>
77 #include <sys/lock.h>
78 #include <sys/malloc.h>
79 #include <sys/memrange.h>
80 #include <sys/msgbuf.h>
81 #include <sys/mutex.h>
82 #include <sys/pcpu.h>
83 #include <sys/ptrace.h>
84 #include <sys/reboot.h>
85 #include <sys/rwlock.h>
86 #include <sys/sched.h>
87 #include <sys/signalvar.h>
88 #ifdef SMP
89 #include <sys/smp.h>
90 #endif
91 #include <sys/syscallsubr.h>
92 #include <sys/sysctl.h>
93 #include <sys/sysent.h>
94 #include <sys/sysproto.h>
95 #include <sys/ucontext.h>
96 #include <sys/vmmeter.h>
97
98 #include <vm/vm.h>
99 #include <vm/vm_extern.h>
100 #include <vm/vm_kern.h>
101 #include <vm/vm_page.h>
102 #include <vm/vm_map.h>
103 #include <vm/vm_object.h>
104 #include <vm/vm_pager.h>
105 #include <vm/vm_param.h>
106
107 #ifdef DDB
108 #ifndef KDB
109 #error KDB must be enabled in order for DDB to work!
110 #endif
111 #include <ddb/ddb.h>
112 #include <ddb/db_sym.h>
113 #endif
114
115 #include <net/netisr.h>
116
117 #include <machine/clock.h>
118 #include <machine/cpu.h>
119 #include <machine/cputypes.h>
120 #include <machine/intr_machdep.h>
121 #include <x86/mca.h>
122 #include <machine/md_var.h>
123 #include <machine/metadata.h>
124 #include <machine/mp_watchdog.h>
125 #include <machine/pc/bios.h>
126 #include <machine/pcb.h>
127 #include <machine/proc.h>
128 #include <machine/reg.h>
129 #include <machine/sigframe.h>
130 #include <machine/specialreg.h>
131 #ifdef PERFMON
132 #include <machine/perfmon.h>
133 #endif
134 #include <machine/tss.h>
135 #ifdef SMP
136 #include <machine/smp.h>
137 #endif
138 #ifdef FDT
139 #include <x86/fdt.h>
140 #endif
141
142 #ifdef DEV_ATPIC
143 #include <x86/isa/icu.h>
144 #else
145 #include <machine/apicvar.h>
146 #endif
147
148 #include <isa/isareg.h>
149 #include <isa/rtc.h>
150
151 /* Sanity check for __curthread() */
152 CTASSERT(offsetof(struct pcpu, pc_curthread) == 0);
153
154 extern u_int64_t hammer_time(u_int64_t, u_int64_t);
155
156 #define CS_SECURE(cs) (ISPL(cs) == SEL_UPL)
157 #define EFL_SECURE(ef, oef) ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
158
159 static void cpu_startup(void *);
160 static void get_fpcontext(struct thread *td, mcontext_t *mcp,
161 char *xfpusave, size_t xfpusave_len);
162 static int set_fpcontext(struct thread *td, mcontext_t *mcp,
163 char *xfpustate, size_t xfpustate_len);
164 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
165
166 /*
167 * The file "conf/ldscript.amd64" defines the symbol "kernphys". Its value is
168 * the physical address at which the kernel is loaded.
169 */
170 extern char kernphys[];
171 #ifdef DDB
172 extern vm_offset_t ksym_start, ksym_end;
173 #endif
174
175 struct msgbuf *msgbufp;
176
177 /* Intel ICH registers */
178 #define ICH_PMBASE 0x400
179 #define ICH_SMI_EN ICH_PMBASE + 0x30
180
181 int _udatasel, _ucodesel, _ucode32sel, _ufssel, _ugssel;
182
183 int cold = 1;
184
185 long Maxmem = 0;
186 long realmem = 0;
187
188 /*
189 * The number of PHYSMAP entries must be one less than the number of
190 * PHYSSEG entries because the PHYSMAP entry that spans the largest
191 * physical address that is accessible by ISA DMA is split into two
192 * PHYSSEG entries.
193 */
194 #define PHYSMAP_SIZE (2 * (VM_PHYSSEG_MAX - 1))
195
196 vm_paddr_t phys_avail[PHYSMAP_SIZE + 2];
197 vm_paddr_t dump_avail[PHYSMAP_SIZE + 2];
198
199 /* must be 2 less so 0 0 can signal end of chunks */
200 #define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(phys_avail[0])) - 2)
201 #define DUMP_AVAIL_ARRAY_END ((sizeof(dump_avail) / sizeof(dump_avail[0])) - 2)
202
203 struct kva_md_info kmi;
204
205 static struct trapframe proc0_tf;
206 struct region_descriptor r_gdt, r_idt;
207
208 struct pcpu __pcpu[MAXCPU];
209
210 struct mtx icu_lock;
211
212 struct mem_range_softc mem_range_softc;
213
214 struct mtx dt_lock; /* lock for GDT and LDT */
215
216 void (*vmm_resume_p)(void);
217
218 static void
219 cpu_startup(dummy)
220 void *dummy;
221 {
222 uintmax_t memsize;
223 char *sysenv;
224
225 /*
226 * On MacBooks, we need to disallow the legacy USB circuit to
227 * generate an SMI# because this can cause several problems,
228 * namely: incorrect CPU frequency detection and failure to
229 * start the APs.
230 * We do this by disabling a bit in the SMI_EN (SMI Control and
231 * Enable register) of the Intel ICH LPC Interface Bridge.
232 */
233 sysenv = getenv("smbios.system.product");
234 if (sysenv != NULL) {
235 if (strncmp(sysenv, "MacBook1,1", 10) == 0 ||
236 strncmp(sysenv, "MacBook3,1", 10) == 0 ||
237 strncmp(sysenv, "MacBook4,1", 10) == 0 ||
238 strncmp(sysenv, "MacBookPro1,1", 13) == 0 ||
239 strncmp(sysenv, "MacBookPro1,2", 13) == 0 ||
240 strncmp(sysenv, "MacBookPro3,1", 13) == 0 ||
241 strncmp(sysenv, "MacBookPro4,1", 13) == 0 ||
242 strncmp(sysenv, "Macmini1,1", 10) == 0) {
243 if (bootverbose)
244 printf("Disabling LEGACY_USB_EN bit on "
245 "Intel ICH.\n");
246 outl(ICH_SMI_EN, inl(ICH_SMI_EN) & ~0x8);
247 }
248 freeenv(sysenv);
249 }
250
251 /*
252 * Good {morning,afternoon,evening,night}.
253 */
254 startrtclock();
255 printcpuinfo();
256 panicifcpuunsupported();
257 #ifdef PERFMON
258 perfmon_init();
259 #endif
260
261 /*
262 * Display physical memory if SMBIOS reports reasonable amount.
263 */
264 memsize = 0;
265 sysenv = getenv("smbios.memory.enabled");
266 if (sysenv != NULL) {
267 memsize = (uintmax_t)strtoul(sysenv, (char **)NULL, 10) << 10;
268 freeenv(sysenv);
269 }
270 if (memsize < ptoa((uintmax_t)cnt.v_free_count))
271 memsize = ptoa((uintmax_t)Maxmem);
272 printf("real memory = %ju (%ju MB)\n", memsize, memsize >> 20);
273 realmem = atop(memsize);
274
275 /*
276 * Display any holes after the first chunk of extended memory.
277 */
278 if (bootverbose) {
279 int indx;
280
281 printf("Physical memory chunk(s):\n");
282 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
283 vm_paddr_t size;
284
285 size = phys_avail[indx + 1] - phys_avail[indx];
286 printf(
287 "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
288 (uintmax_t)phys_avail[indx],
289 (uintmax_t)phys_avail[indx + 1] - 1,
290 (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
291 }
292 }
293
294 vm_ksubmap_init(&kmi);
295
296 printf("avail memory = %ju (%ju MB)\n",
297 ptoa((uintmax_t)cnt.v_free_count),
298 ptoa((uintmax_t)cnt.v_free_count) / 1048576);
299
300 /*
301 * Set up buffers, so they can be used to read disk labels.
302 */
303 bufinit();
304 vm_pager_bufferinit();
305
306 cpu_setregs();
307 }
308
309 /*
310 * Send an interrupt to process.
311 *
312 * Stack is set up to allow sigcode stored
313 * at top to call routine, followed by call
314 * to sigreturn routine below. After sigreturn
315 * resets the signal mask, the stack, and the
316 * frame pointer, it returns to the user
317 * specified pc, psl.
318 */
319 void
320 sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
321 {
322 struct sigframe sf, *sfp;
323 struct pcb *pcb;
324 struct proc *p;
325 struct thread *td;
326 struct sigacts *psp;
327 char *sp;
328 struct trapframe *regs;
329 char *xfpusave;
330 size_t xfpusave_len;
331 int sig;
332 int oonstack;
333
334 td = curthread;
335 pcb = td->td_pcb;
336 p = td->td_proc;
337 PROC_LOCK_ASSERT(p, MA_OWNED);
338 sig = ksi->ksi_signo;
339 psp = p->p_sigacts;
340 mtx_assert(&psp->ps_mtx, MA_OWNED);
341 regs = td->td_frame;
342 oonstack = sigonstack(regs->tf_rsp);
343
344 if (cpu_max_ext_state_size > sizeof(struct savefpu) && use_xsave) {
345 xfpusave_len = cpu_max_ext_state_size - sizeof(struct savefpu);
346 xfpusave = __builtin_alloca(xfpusave_len);
347 } else {
348 xfpusave_len = 0;
349 xfpusave = NULL;
350 }
351
352 /* Save user context. */
353 bzero(&sf, sizeof(sf));
354 sf.sf_uc.uc_sigmask = *mask;
355 sf.sf_uc.uc_stack = td->td_sigstk;
356 sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
357 ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
358 sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
359 bcopy(regs, &sf.sf_uc.uc_mcontext.mc_rdi, sizeof(*regs));
360 sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext); /* magic */
361 get_fpcontext(td, &sf.sf_uc.uc_mcontext, xfpusave, xfpusave_len);
362 fpstate_drop(td);
363 sf.sf_uc.uc_mcontext.mc_fsbase = pcb->pcb_fsbase;
364 sf.sf_uc.uc_mcontext.mc_gsbase = pcb->pcb_gsbase;
365 bzero(sf.sf_uc.uc_mcontext.mc_spare,
366 sizeof(sf.sf_uc.uc_mcontext.mc_spare));
367 bzero(sf.sf_uc.__spare__, sizeof(sf.sf_uc.__spare__));
368
369 /* Allocate space for the signal handler context. */
370 if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
371 SIGISMEMBER(psp->ps_sigonstack, sig)) {
372 sp = td->td_sigstk.ss_sp + td->td_sigstk.ss_size;
373 #if defined(COMPAT_43)
374 td->td_sigstk.ss_flags |= SS_ONSTACK;
375 #endif
376 } else
377 sp = (char *)regs->tf_rsp - 128;
378 if (xfpusave != NULL) {
379 sp -= xfpusave_len;
380 sp = (char *)((unsigned long)sp & ~0x3Ful);
381 sf.sf_uc.uc_mcontext.mc_xfpustate = (register_t)sp;
382 }
383 sp -= sizeof(struct sigframe);
384 /* Align to 16 bytes. */
385 sfp = (struct sigframe *)((unsigned long)sp & ~0xFul);
386
387 /* Build the argument list for the signal handler. */
388 regs->tf_rdi = sig; /* arg 1 in %rdi */
389 regs->tf_rdx = (register_t)&sfp->sf_uc; /* arg 3 in %rdx */
390 bzero(&sf.sf_si, sizeof(sf.sf_si));
391 if (SIGISMEMBER(psp->ps_siginfo, sig)) {
392 /* Signal handler installed with SA_SIGINFO. */
393 regs->tf_rsi = (register_t)&sfp->sf_si; /* arg 2 in %rsi */
394 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
395
396 /* Fill in POSIX parts */
397 sf.sf_si = ksi->ksi_info;
398 sf.sf_si.si_signo = sig; /* maybe a translated signal */
399 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
400 } else {
401 /* Old FreeBSD-style arguments. */
402 regs->tf_rsi = ksi->ksi_code; /* arg 2 in %rsi */
403 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
404 sf.sf_ahu.sf_handler = catcher;
405 }
406 mtx_unlock(&psp->ps_mtx);
407 PROC_UNLOCK(p);
408
409 /*
410 * Copy the sigframe out to the user's stack.
411 */
412 if (copyout(&sf, sfp, sizeof(*sfp)) != 0 ||
413 (xfpusave != NULL && copyout(xfpusave,
414 (void *)sf.sf_uc.uc_mcontext.mc_xfpustate, xfpusave_len)
415 != 0)) {
416 #ifdef DEBUG
417 printf("process %ld has trashed its stack\n", (long)p->p_pid);
418 #endif
419 PROC_LOCK(p);
420 sigexit(td, SIGILL);
421 }
422
423 regs->tf_rsp = (long)sfp;
424 regs->tf_rip = p->p_sysent->sv_sigcode_base;
425 regs->tf_rflags &= ~(PSL_T | PSL_D);
426 regs->tf_cs = _ucodesel;
427 regs->tf_ds = _udatasel;
428 regs->tf_ss = _udatasel;
429 regs->tf_es = _udatasel;
430 regs->tf_fs = _ufssel;
431 regs->tf_gs = _ugssel;
432 regs->tf_flags = TF_HASSEGS;
433 set_pcb_flags(pcb, PCB_FULL_IRET);
434 PROC_LOCK(p);
435 mtx_lock(&psp->ps_mtx);
436 }
437
438 /*
439 * System call to cleanup state after a signal
440 * has been taken. Reset signal mask and
441 * stack state from context left by sendsig (above).
442 * Return to previous pc and psl as specified by
443 * context left by sendsig. Check carefully to
444 * make sure that the user has not modified the
445 * state to gain improper privileges.
446 *
447 * MPSAFE
448 */
449 int
450 sys_sigreturn(td, uap)
451 struct thread *td;
452 struct sigreturn_args /* {
453 const struct __ucontext *sigcntxp;
454 } */ *uap;
455 {
456 ucontext_t uc;
457 struct pcb *pcb;
458 struct proc *p;
459 struct trapframe *regs;
460 ucontext_t *ucp;
461 char *xfpustate;
462 size_t xfpustate_len;
463 long rflags;
464 int cs, error, ret;
465 ksiginfo_t ksi;
466
467 pcb = td->td_pcb;
468 p = td->td_proc;
469
470 error = copyin(uap->sigcntxp, &uc, sizeof(uc));
471 if (error != 0) {
472 uprintf("pid %d (%s): sigreturn copyin failed\n",
473 p->p_pid, td->td_name);
474 return (error);
475 }
476 ucp = &uc;
477 if ((ucp->uc_mcontext.mc_flags & ~_MC_FLAG_MASK) != 0) {
478 uprintf("pid %d (%s): sigreturn mc_flags %x\n", p->p_pid,
479 td->td_name, ucp->uc_mcontext.mc_flags);
480 return (EINVAL);
481 }
482 regs = td->td_frame;
483 rflags = ucp->uc_mcontext.mc_rflags;
484 /*
485 * Don't allow users to change privileged or reserved flags.
486 */
487 if (!EFL_SECURE(rflags, regs->tf_rflags)) {
488 uprintf("pid %d (%s): sigreturn rflags = 0x%lx\n", p->p_pid,
489 td->td_name, rflags);
490 return (EINVAL);
491 }
492
493 /*
494 * Don't allow users to load a valid privileged %cs. Let the
495 * hardware check for invalid selectors, excess privilege in
496 * other selectors, invalid %eip's and invalid %esp's.
497 */
498 cs = ucp->uc_mcontext.mc_cs;
499 if (!CS_SECURE(cs)) {
500 uprintf("pid %d (%s): sigreturn cs = 0x%x\n", p->p_pid,
501 td->td_name, cs);
502 ksiginfo_init_trap(&ksi);
503 ksi.ksi_signo = SIGBUS;
504 ksi.ksi_code = BUS_OBJERR;
505 ksi.ksi_trapno = T_PROTFLT;
506 ksi.ksi_addr = (void *)regs->tf_rip;
507 trapsignal(td, &ksi);
508 return (EINVAL);
509 }
510
511 if ((uc.uc_mcontext.mc_flags & _MC_HASFPXSTATE) != 0) {
512 xfpustate_len = uc.uc_mcontext.mc_xfpustate_len;
513 if (xfpustate_len > cpu_max_ext_state_size -
514 sizeof(struct savefpu)) {
515 uprintf("pid %d (%s): sigreturn xfpusave_len = 0x%zx\n",
516 p->p_pid, td->td_name, xfpustate_len);
517 return (EINVAL);
518 }
519 xfpustate = __builtin_alloca(xfpustate_len);
520 error = copyin((const void *)uc.uc_mcontext.mc_xfpustate,
521 xfpustate, xfpustate_len);
522 if (error != 0) {
523 uprintf(
524 "pid %d (%s): sigreturn copying xfpustate failed\n",
525 p->p_pid, td->td_name);
526 return (error);
527 }
528 } else {
529 xfpustate = NULL;
530 xfpustate_len = 0;
531 }
532 ret = set_fpcontext(td, &ucp->uc_mcontext, xfpustate, xfpustate_len);
533 if (ret != 0) {
534 uprintf("pid %d (%s): sigreturn set_fpcontext err %d\n",
535 p->p_pid, td->td_name, ret);
536 return (ret);
537 }
538 bcopy(&ucp->uc_mcontext.mc_rdi, regs, sizeof(*regs));
539 pcb->pcb_fsbase = ucp->uc_mcontext.mc_fsbase;
540 pcb->pcb_gsbase = ucp->uc_mcontext.mc_gsbase;
541
542 #if defined(COMPAT_43)
543 if (ucp->uc_mcontext.mc_onstack & 1)
544 td->td_sigstk.ss_flags |= SS_ONSTACK;
545 else
546 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
547 #endif
548
549 kern_sigprocmask(td, SIG_SETMASK, &ucp->uc_sigmask, NULL, 0);
550 set_pcb_flags(pcb, PCB_FULL_IRET);
551 return (EJUSTRETURN);
552 }
553
554 #ifdef COMPAT_FREEBSD4
555 int
556 freebsd4_sigreturn(struct thread *td, struct freebsd4_sigreturn_args *uap)
557 {
558
559 return sys_sigreturn(td, (struct sigreturn_args *)uap);
560 }
561 #endif
562
563
564 /*
565 * Machine dependent boot() routine
566 *
567 * I haven't seen anything to put here yet
568 * Possibly some stuff might be grafted back here from boot()
569 */
570 void
571 cpu_boot(int howto)
572 {
573 }
574
575 /*
576 * Flush the D-cache for non-DMA I/O so that the I-cache can
577 * be made coherent later.
578 */
579 void
580 cpu_flush_dcache(void *ptr, size_t len)
581 {
582 /* Not applicable */
583 }
584
585 /* Get current clock frequency for the given cpu id. */
586 int
587 cpu_est_clockrate(int cpu_id, uint64_t *rate)
588 {
589 uint64_t tsc1, tsc2;
590 uint64_t acnt, mcnt, perf;
591 register_t reg;
592
593 if (pcpu_find(cpu_id) == NULL || rate == NULL)
594 return (EINVAL);
595
596 /*
597 * If TSC is P-state invariant and APERF/MPERF MSRs do not exist,
598 * DELAY(9) based logic fails.
599 */
600 if (tsc_is_invariant && !tsc_perf_stat)
601 return (EOPNOTSUPP);
602
603 #ifdef SMP
604 if (smp_cpus > 1) {
605 /* Schedule ourselves on the indicated cpu. */
606 thread_lock(curthread);
607 sched_bind(curthread, cpu_id);
608 thread_unlock(curthread);
609 }
610 #endif
611
612 /* Calibrate by measuring a short delay. */
613 reg = intr_disable();
614 if (tsc_is_invariant) {
615 wrmsr(MSR_MPERF, 0);
616 wrmsr(MSR_APERF, 0);
617 tsc1 = rdtsc();
618 DELAY(1000);
619 mcnt = rdmsr(MSR_MPERF);
620 acnt = rdmsr(MSR_APERF);
621 tsc2 = rdtsc();
622 intr_restore(reg);
623 perf = 1000 * acnt / mcnt;
624 *rate = (tsc2 - tsc1) * perf;
625 } else {
626 tsc1 = rdtsc();
627 DELAY(1000);
628 tsc2 = rdtsc();
629 intr_restore(reg);
630 *rate = (tsc2 - tsc1) * 1000;
631 }
632
633 #ifdef SMP
634 if (smp_cpus > 1) {
635 thread_lock(curthread);
636 sched_unbind(curthread);
637 thread_unlock(curthread);
638 }
639 #endif
640
641 return (0);
642 }
643
644 /*
645 * Shutdown the CPU as much as possible
646 */
647 void
648 cpu_halt(void)
649 {
650 for (;;)
651 halt();
652 }
653
654 void (*cpu_idle_hook)(sbintime_t) = NULL; /* ACPI idle hook. */
655 static int cpu_ident_amdc1e = 0; /* AMD C1E supported. */
656 static int idle_mwait = 1; /* Use MONITOR/MWAIT for short idle. */
657 TUNABLE_INT("machdep.idle_mwait", &idle_mwait);
658 SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RW, &idle_mwait,
659 0, "Use MONITOR/MWAIT for short idle");
660
661 #define STATE_RUNNING 0x0
662 #define STATE_MWAIT 0x1
663 #define STATE_SLEEPING 0x2
664
665 static void
666 cpu_idle_acpi(sbintime_t sbt)
667 {
668 int *state;
669
670 state = (int *)PCPU_PTR(monitorbuf);
671 *state = STATE_SLEEPING;
672
673 /* See comments in cpu_idle_hlt(). */
674 disable_intr();
675 if (sched_runnable())
676 enable_intr();
677 else if (cpu_idle_hook)
678 cpu_idle_hook(sbt);
679 else
680 __asm __volatile("sti; hlt");
681 *state = STATE_RUNNING;
682 }
683
684 static void
685 cpu_idle_hlt(sbintime_t sbt)
686 {
687 int *state;
688
689 state = (int *)PCPU_PTR(monitorbuf);
690 *state = STATE_SLEEPING;
691
692 /*
693 * Since we may be in a critical section from cpu_idle(), if
694 * an interrupt fires during that critical section we may have
695 * a pending preemption. If the CPU halts, then that thread
696 * may not execute until a later interrupt awakens the CPU.
697 * To handle this race, check for a runnable thread after
698 * disabling interrupts and immediately return if one is
699 * found. Also, we must absolutely guarentee that hlt is
700 * the next instruction after sti. This ensures that any
701 * interrupt that fires after the call to disable_intr() will
702 * immediately awaken the CPU from hlt. Finally, please note
703 * that on x86 this works fine because of interrupts enabled only
704 * after the instruction following sti takes place, while IF is set
705 * to 1 immediately, allowing hlt instruction to acknowledge the
706 * interrupt.
707 */
708 disable_intr();
709 if (sched_runnable())
710 enable_intr();
711 else
712 __asm __volatile("sti; hlt");
713 *state = STATE_RUNNING;
714 }
715
716 static void
717 cpu_idle_mwait(sbintime_t sbt)
718 {
719 int *state;
720
721 state = (int *)PCPU_PTR(monitorbuf);
722 *state = STATE_MWAIT;
723
724 /* See comments in cpu_idle_hlt(). */
725 disable_intr();
726 if (sched_runnable()) {
727 enable_intr();
728 *state = STATE_RUNNING;
729 return;
730 }
731 cpu_monitor(state, 0, 0);
732 if (*state == STATE_MWAIT)
733 __asm __volatile("sti; mwait" : : "a" (MWAIT_C1), "c" (0));
734 else
735 enable_intr();
736 *state = STATE_RUNNING;
737 }
738
739 static void
740 cpu_idle_spin(sbintime_t sbt)
741 {
742 int *state;
743 int i;
744
745 state = (int *)PCPU_PTR(monitorbuf);
746 *state = STATE_RUNNING;
747
748 /*
749 * The sched_runnable() call is racy but as long as there is
750 * a loop missing it one time will have just a little impact if any
751 * (and it is much better than missing the check at all).
752 */
753 for (i = 0; i < 1000; i++) {
754 if (sched_runnable())
755 return;
756 cpu_spinwait();
757 }
758 }
759
760 /*
761 * C1E renders the local APIC timer dead, so we disable it by
762 * reading the Interrupt Pending Message register and clearing
763 * both C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
764 *
765 * Reference:
766 * "BIOS and Kernel Developer's Guide for AMD NPT Family 0Fh Processors"
767 * #32559 revision 3.00+
768 */
769 #define MSR_AMDK8_IPM 0xc0010055
770 #define AMDK8_SMIONCMPHALT (1ULL << 27)
771 #define AMDK8_C1EONCMPHALT (1ULL << 28)
772 #define AMDK8_CMPHALT (AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
773
774 static void
775 cpu_probe_amdc1e(void)
776 {
777
778 /*
779 * Detect the presence of C1E capability mostly on latest
780 * dual-cores (or future) k8 family.
781 */
782 if (cpu_vendor_id == CPU_VENDOR_AMD &&
783 (cpu_id & 0x00000f00) == 0x00000f00 &&
784 (cpu_id & 0x0fff0000) >= 0x00040000) {
785 cpu_ident_amdc1e = 1;
786 }
787 }
788
789 void (*cpu_idle_fn)(sbintime_t) = cpu_idle_acpi;
790
791 void
792 cpu_idle(int busy)
793 {
794 uint64_t msr;
795 sbintime_t sbt = -1;
796
797 CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
798 busy, curcpu);
799 #ifdef MP_WATCHDOG
800 ap_watchdog(PCPU_GET(cpuid));
801 #endif
802 /* If we are busy - try to use fast methods. */
803 if (busy) {
804 if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
805 cpu_idle_mwait(busy);
806 goto out;
807 }
808 }
809
810 /* If we have time - switch timers into idle mode. */
811 if (!busy) {
812 critical_enter();
813 sbt = cpu_idleclock();
814 }
815
816 /* Apply AMD APIC timer C1E workaround. */
817 if (cpu_ident_amdc1e && cpu_disable_c3_sleep) {
818 msr = rdmsr(MSR_AMDK8_IPM);
819 if (msr & AMDK8_CMPHALT)
820 wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
821 }
822
823 /* Call main idle method. */
824 cpu_idle_fn(sbt);
825
826 /* Switch timers mack into active mode. */
827 if (!busy) {
828 cpu_activeclock();
829 critical_exit();
830 }
831 out:
832 CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
833 busy, curcpu);
834 }
835
836 int
837 cpu_idle_wakeup(int cpu)
838 {
839 struct pcpu *pcpu;
840 int *state;
841
842 pcpu = pcpu_find(cpu);
843 state = (int *)pcpu->pc_monitorbuf;
844 /*
845 * This doesn't need to be atomic since missing the race will
846 * simply result in unnecessary IPIs.
847 */
848 if (*state == STATE_SLEEPING)
849 return (0);
850 if (*state == STATE_MWAIT)
851 *state = STATE_RUNNING;
852 return (1);
853 }
854
855 /*
856 * Ordered by speed/power consumption.
857 */
858 struct {
859 void *id_fn;
860 char *id_name;
861 } idle_tbl[] = {
862 { cpu_idle_spin, "spin" },
863 { cpu_idle_mwait, "mwait" },
864 { cpu_idle_hlt, "hlt" },
865 { cpu_idle_acpi, "acpi" },
866 { NULL, NULL }
867 };
868
869 static int
870 idle_sysctl_available(SYSCTL_HANDLER_ARGS)
871 {
872 char *avail, *p;
873 int error;
874 int i;
875
876 avail = malloc(256, M_TEMP, M_WAITOK);
877 p = avail;
878 for (i = 0; idle_tbl[i].id_name != NULL; i++) {
879 if (strstr(idle_tbl[i].id_name, "mwait") &&
880 (cpu_feature2 & CPUID2_MON) == 0)
881 continue;
882 if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
883 cpu_idle_hook == NULL)
884 continue;
885 p += sprintf(p, "%s%s", p != avail ? ", " : "",
886 idle_tbl[i].id_name);
887 }
888 error = sysctl_handle_string(oidp, avail, 0, req);
889 free(avail, M_TEMP);
890 return (error);
891 }
892
893 SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
894 0, 0, idle_sysctl_available, "A", "list of available idle functions");
895
896 static int
897 idle_sysctl(SYSCTL_HANDLER_ARGS)
898 {
899 char buf[16];
900 int error;
901 char *p;
902 int i;
903
904 p = "unknown";
905 for (i = 0; idle_tbl[i].id_name != NULL; i++) {
906 if (idle_tbl[i].id_fn == cpu_idle_fn) {
907 p = idle_tbl[i].id_name;
908 break;
909 }
910 }
911 strncpy(buf, p, sizeof(buf));
912 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
913 if (error != 0 || req->newptr == NULL)
914 return (error);
915 for (i = 0; idle_tbl[i].id_name != NULL; i++) {
916 if (strstr(idle_tbl[i].id_name, "mwait") &&
917 (cpu_feature2 & CPUID2_MON) == 0)
918 continue;
919 if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
920 cpu_idle_hook == NULL)
921 continue;
922 if (strcmp(idle_tbl[i].id_name, buf))
923 continue;
924 cpu_idle_fn = idle_tbl[i].id_fn;
925 return (0);
926 }
927 return (EINVAL);
928 }
929
930 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
931 idle_sysctl, "A", "currently selected idle function");
932
933 /*
934 * Reset registers to default values on exec.
935 */
936 void
937 exec_setregs(struct thread *td, struct image_params *imgp, u_long stack)
938 {
939 struct trapframe *regs = td->td_frame;
940 struct pcb *pcb = td->td_pcb;
941
942 mtx_lock(&dt_lock);
943 if (td->td_proc->p_md.md_ldt != NULL)
944 user_ldt_free(td);
945 else
946 mtx_unlock(&dt_lock);
947
948 pcb->pcb_fsbase = 0;
949 pcb->pcb_gsbase = 0;
950 clear_pcb_flags(pcb, PCB_32BIT);
951 pcb->pcb_initial_fpucw = __INITIAL_FPUCW__;
952 set_pcb_flags(pcb, PCB_FULL_IRET);
953
954 bzero((char *)regs, sizeof(struct trapframe));
955 regs->tf_rip = imgp->entry_addr;
956 regs->tf_rsp = ((stack - 8) & ~0xFul) + 8;
957 regs->tf_rdi = stack; /* argv */
958 regs->tf_rflags = PSL_USER | (regs->tf_rflags & PSL_T);
959 regs->tf_ss = _udatasel;
960 regs->tf_cs = _ucodesel;
961 regs->tf_ds = _udatasel;
962 regs->tf_es = _udatasel;
963 regs->tf_fs = _ufssel;
964 regs->tf_gs = _ugssel;
965 regs->tf_flags = TF_HASSEGS;
966 td->td_retval[1] = 0;
967
968 /*
969 * Reset the hardware debug registers if they were in use.
970 * They won't have any meaning for the newly exec'd process.
971 */
972 if (pcb->pcb_flags & PCB_DBREGS) {
973 pcb->pcb_dr0 = 0;
974 pcb->pcb_dr1 = 0;
975 pcb->pcb_dr2 = 0;
976 pcb->pcb_dr3 = 0;
977 pcb->pcb_dr6 = 0;
978 pcb->pcb_dr7 = 0;
979 if (pcb == curpcb) {
980 /*
981 * Clear the debug registers on the running
982 * CPU, otherwise they will end up affecting
983 * the next process we switch to.
984 */
985 reset_dbregs();
986 }
987 clear_pcb_flags(pcb, PCB_DBREGS);
988 }
989
990 /*
991 * Drop the FP state if we hold it, so that the process gets a
992 * clean FP state if it uses the FPU again.
993 */
994 fpstate_drop(td);
995 }
996
997 void
998 cpu_setregs(void)
999 {
1000 register_t cr0;
1001
1002 cr0 = rcr0();
1003 /*
1004 * CR0_MP, CR0_NE and CR0_TS are also set by npx_probe() for the
1005 * BSP. See the comments there about why we set them.
1006 */
1007 cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
1008 load_cr0(cr0);
1009 }
1010
1011 /*
1012 * Initialize amd64 and configure to run kernel
1013 */
1014
1015 /*
1016 * Initialize segments & interrupt table
1017 */
1018
1019 struct user_segment_descriptor gdt[NGDT * MAXCPU];/* global descriptor tables */
1020 static struct gate_descriptor idt0[NIDT];
1021 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
1022
1023 static char dblfault_stack[PAGE_SIZE] __aligned(16);
1024
1025 static char nmi0_stack[PAGE_SIZE] __aligned(16);
1026 CTASSERT(sizeof(struct nmi_pcpu) == 16);
1027
1028 struct amd64tss common_tss[MAXCPU];
1029
1030 /*
1031 * Software prototypes -- in more palatable form.
1032 *
1033 * Keep GUFS32, GUGS32, GUCODE32 and GUDATA at the same
1034 * slots as corresponding segments for i386 kernel.
1035 */
1036 struct soft_segment_descriptor gdt_segs[] = {
1037 /* GNULL_SEL 0 Null Descriptor */
1038 { .ssd_base = 0x0,
1039 .ssd_limit = 0x0,
1040 .ssd_type = 0,
1041 .ssd_dpl = 0,
1042 .ssd_p = 0,
1043 .ssd_long = 0,
1044 .ssd_def32 = 0,
1045 .ssd_gran = 0 },
1046 /* GNULL2_SEL 1 Null Descriptor */
1047 { .ssd_base = 0x0,
1048 .ssd_limit = 0x0,
1049 .ssd_type = 0,
1050 .ssd_dpl = 0,
1051 .ssd_p = 0,
1052 .ssd_long = 0,
1053 .ssd_def32 = 0,
1054 .ssd_gran = 0 },
1055 /* GUFS32_SEL 2 32 bit %gs Descriptor for user */
1056 { .ssd_base = 0x0,
1057 .ssd_limit = 0xfffff,
1058 .ssd_type = SDT_MEMRWA,
1059 .ssd_dpl = SEL_UPL,
1060 .ssd_p = 1,
1061 .ssd_long = 0,
1062 .ssd_def32 = 1,
1063 .ssd_gran = 1 },
1064 /* GUGS32_SEL 3 32 bit %fs Descriptor for user */
1065 { .ssd_base = 0x0,
1066 .ssd_limit = 0xfffff,
1067 .ssd_type = SDT_MEMRWA,
1068 .ssd_dpl = SEL_UPL,
1069 .ssd_p = 1,
1070 .ssd_long = 0,
1071 .ssd_def32 = 1,
1072 .ssd_gran = 1 },
1073 /* GCODE_SEL 4 Code Descriptor for kernel */
1074 { .ssd_base = 0x0,
1075 .ssd_limit = 0xfffff,
1076 .ssd_type = SDT_MEMERA,
1077 .ssd_dpl = SEL_KPL,
1078 .ssd_p = 1,
1079 .ssd_long = 1,
1080 .ssd_def32 = 0,
1081 .ssd_gran = 1 },
1082 /* GDATA_SEL 5 Data Descriptor for kernel */
1083 { .ssd_base = 0x0,
1084 .ssd_limit = 0xfffff,
1085 .ssd_type = SDT_MEMRWA,
1086 .ssd_dpl = SEL_KPL,
1087 .ssd_p = 1,
1088 .ssd_long = 1,
1089 .ssd_def32 = 0,
1090 .ssd_gran = 1 },
1091 /* GUCODE32_SEL 6 32 bit Code Descriptor for user */
1092 { .ssd_base = 0x0,
1093 .ssd_limit = 0xfffff,
1094 .ssd_type = SDT_MEMERA,
1095 .ssd_dpl = SEL_UPL,
1096 .ssd_p = 1,
1097 .ssd_long = 0,
1098 .ssd_def32 = 1,
1099 .ssd_gran = 1 },
1100 /* GUDATA_SEL 7 32/64 bit Data Descriptor for user */
1101 { .ssd_base = 0x0,
1102 .ssd_limit = 0xfffff,
1103 .ssd_type = SDT_MEMRWA,
1104 .ssd_dpl = SEL_UPL,
1105 .ssd_p = 1,
1106 .ssd_long = 0,
1107 .ssd_def32 = 1,
1108 .ssd_gran = 1 },
1109 /* GUCODE_SEL 8 64 bit Code Descriptor for user */
1110 { .ssd_base = 0x0,
1111 .ssd_limit = 0xfffff,
1112 .ssd_type = SDT_MEMERA,
1113 .ssd_dpl = SEL_UPL,
1114 .ssd_p = 1,
1115 .ssd_long = 1,
1116 .ssd_def32 = 0,
1117 .ssd_gran = 1 },
1118 /* GPROC0_SEL 9 Proc 0 Tss Descriptor */
1119 { .ssd_base = 0x0,
1120 .ssd_limit = sizeof(struct amd64tss) + IOPAGES * PAGE_SIZE - 1,
1121 .ssd_type = SDT_SYSTSS,
1122 .ssd_dpl = SEL_KPL,
1123 .ssd_p = 1,
1124 .ssd_long = 0,
1125 .ssd_def32 = 0,
1126 .ssd_gran = 0 },
1127 /* Actually, the TSS is a system descriptor which is double size */
1128 { .ssd_base = 0x0,
1129 .ssd_limit = 0x0,
1130 .ssd_type = 0,
1131 .ssd_dpl = 0,
1132 .ssd_p = 0,
1133 .ssd_long = 0,
1134 .ssd_def32 = 0,
1135 .ssd_gran = 0 },
1136 /* GUSERLDT_SEL 11 LDT Descriptor */
1137 { .ssd_base = 0x0,
1138 .ssd_limit = 0x0,
1139 .ssd_type = 0,
1140 .ssd_dpl = 0,
1141 .ssd_p = 0,
1142 .ssd_long = 0,
1143 .ssd_def32 = 0,
1144 .ssd_gran = 0 },
1145 /* GUSERLDT_SEL 12 LDT Descriptor, double size */
1146 { .ssd_base = 0x0,
1147 .ssd_limit = 0x0,
1148 .ssd_type = 0,
1149 .ssd_dpl = 0,
1150 .ssd_p = 0,
1151 .ssd_long = 0,
1152 .ssd_def32 = 0,
1153 .ssd_gran = 0 },
1154 };
1155
1156 void
1157 setidt(int idx, inthand_t *func, int typ, int dpl, int ist)
1158 {
1159 struct gate_descriptor *ip;
1160
1161 ip = idt + idx;
1162 ip->gd_looffset = (uintptr_t)func;
1163 ip->gd_selector = GSEL(GCODE_SEL, SEL_KPL);
1164 ip->gd_ist = ist;
1165 ip->gd_xx = 0;
1166 ip->gd_type = typ;
1167 ip->gd_dpl = dpl;
1168 ip->gd_p = 1;
1169 ip->gd_hioffset = ((uintptr_t)func)>>16 ;
1170 }
1171
1172 extern inthand_t
1173 IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1174 IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1175 IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1176 IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1177 IDTVEC(xmm), IDTVEC(dblfault),
1178 #ifdef KDTRACE_HOOKS
1179 IDTVEC(dtrace_ret),
1180 #endif
1181 #ifdef XENHVM
1182 IDTVEC(xen_intr_upcall),
1183 #endif
1184 IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
1185
1186 #ifdef DDB
1187 /*
1188 * Display the index and function name of any IDT entries that don't use
1189 * the default 'rsvd' entry point.
1190 */
1191 DB_SHOW_COMMAND(idt, db_show_idt)
1192 {
1193 struct gate_descriptor *ip;
1194 int idx;
1195 uintptr_t func;
1196
1197 ip = idt;
1198 for (idx = 0; idx < NIDT && !db_pager_quit; idx++) {
1199 func = ((long)ip->gd_hioffset << 16 | ip->gd_looffset);
1200 if (func != (uintptr_t)&IDTVEC(rsvd)) {
1201 db_printf("%3d\t", idx);
1202 db_printsym(func, DB_STGY_PROC);
1203 db_printf("\n");
1204 }
1205 ip++;
1206 }
1207 }
1208
1209 /* Show privileged registers. */
1210 DB_SHOW_COMMAND(sysregs, db_show_sysregs)
1211 {
1212 struct {
1213 uint16_t limit;
1214 uint64_t base;
1215 } __packed idtr, gdtr;
1216 uint16_t ldt, tr;
1217
1218 __asm __volatile("sidt %0" : "=m" (idtr));
1219 db_printf("idtr\t0x%016lx/%04x\n",
1220 (u_long)idtr.base, (u_int)idtr.limit);
1221 __asm __volatile("sgdt %0" : "=m" (gdtr));
1222 db_printf("gdtr\t0x%016lx/%04x\n",
1223 (u_long)gdtr.base, (u_int)gdtr.limit);
1224 __asm __volatile("sldt %0" : "=r" (ldt));
1225 db_printf("ldtr\t0x%04x\n", ldt);
1226 __asm __volatile("str %0" : "=r" (tr));
1227 db_printf("tr\t0x%04x\n", tr);
1228 db_printf("cr0\t0x%016lx\n", rcr0());
1229 db_printf("cr2\t0x%016lx\n", rcr2());
1230 db_printf("cr3\t0x%016lx\n", rcr3());
1231 db_printf("cr4\t0x%016lx\n", rcr4());
1232 if (rcr4() & CR4_XSAVE)
1233 db_printf("xcr0\t0x%016lx\n", rxcr(0));
1234 db_printf("EFER\t0x%016lx\n", rdmsr(MSR_EFER));
1235 if (cpu_feature2 & (CPUID2_VMX | CPUID2_SMX))
1236 db_printf("FEATURES_CTL\t%016lx\n",
1237 rdmsr(MSR_IA32_FEATURE_CONTROL));
1238 db_printf("DEBUG_CTL\t0x%016lx\n", rdmsr(MSR_DEBUGCTLMSR));
1239 db_printf("PAT\t0x%016lx\n", rdmsr(MSR_PAT));
1240 db_printf("GSBASE\t0x%016lx\n", rdmsr(MSR_GSBASE));
1241 }
1242
1243 DB_SHOW_COMMAND(dbregs, db_show_dbregs)
1244 {
1245
1246 db_printf("dr0\t0x%016lx\n", rdr0());
1247 db_printf("dr1\t0x%016lx\n", rdr1());
1248 db_printf("dr2\t0x%016lx\n", rdr2());
1249 db_printf("dr3\t0x%016lx\n", rdr3());
1250 db_printf("dr6\t0x%016lx\n", rdr6());
1251 db_printf("dr7\t0x%016lx\n", rdr7());
1252 }
1253 #endif
1254
1255 void
1256 sdtossd(sd, ssd)
1257 struct user_segment_descriptor *sd;
1258 struct soft_segment_descriptor *ssd;
1259 {
1260
1261 ssd->ssd_base = (sd->sd_hibase << 24) | sd->sd_lobase;
1262 ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1263 ssd->ssd_type = sd->sd_type;
1264 ssd->ssd_dpl = sd->sd_dpl;
1265 ssd->ssd_p = sd->sd_p;
1266 ssd->ssd_long = sd->sd_long;
1267 ssd->ssd_def32 = sd->sd_def32;
1268 ssd->ssd_gran = sd->sd_gran;
1269 }
1270
1271 void
1272 ssdtosd(ssd, sd)
1273 struct soft_segment_descriptor *ssd;
1274 struct user_segment_descriptor *sd;
1275 {
1276
1277 sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
1278 sd->sd_hibase = (ssd->ssd_base >> 24) & 0xff;
1279 sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
1280 sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
1281 sd->sd_type = ssd->ssd_type;
1282 sd->sd_dpl = ssd->ssd_dpl;
1283 sd->sd_p = ssd->ssd_p;
1284 sd->sd_long = ssd->ssd_long;
1285 sd->sd_def32 = ssd->ssd_def32;
1286 sd->sd_gran = ssd->ssd_gran;
1287 }
1288
1289 void
1290 ssdtosyssd(ssd, sd)
1291 struct soft_segment_descriptor *ssd;
1292 struct system_segment_descriptor *sd;
1293 {
1294
1295 sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
1296 sd->sd_hibase = (ssd->ssd_base >> 24) & 0xfffffffffful;
1297 sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
1298 sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
1299 sd->sd_type = ssd->ssd_type;
1300 sd->sd_dpl = ssd->ssd_dpl;
1301 sd->sd_p = ssd->ssd_p;
1302 sd->sd_gran = ssd->ssd_gran;
1303 }
1304
1305 #if !defined(DEV_ATPIC) && defined(DEV_ISA)
1306 #include <isa/isavar.h>
1307 #include <isa/isareg.h>
1308 /*
1309 * Return a bitmap of the current interrupt requests. This is 8259-specific
1310 * and is only suitable for use at probe time.
1311 * This is only here to pacify sio. It is NOT FATAL if this doesn't work.
1312 * It shouldn't be here. There should probably be an APIC centric
1313 * implementation in the apic driver code, if at all.
1314 */
1315 intrmask_t
1316 isa_irq_pending(void)
1317 {
1318 u_char irr1;
1319 u_char irr2;
1320
1321 irr1 = inb(IO_ICU1);
1322 irr2 = inb(IO_ICU2);
1323 return ((irr2 << 8) | irr1);
1324 }
1325 #endif
1326
1327 u_int basemem;
1328
1329 static int
1330 add_physmap_entry(uint64_t base, uint64_t length, vm_paddr_t *physmap,
1331 int *physmap_idxp)
1332 {
1333 int i, insert_idx, physmap_idx;
1334
1335 physmap_idx = *physmap_idxp;
1336
1337 if (length == 0)
1338 return (1);
1339
1340 /*
1341 * Find insertion point while checking for overlap. Start off by
1342 * assuming the new entry will be added to the end.
1343 *
1344 * NB: physmap_idx points to the next free slot.
1345 */
1346 insert_idx = physmap_idx;
1347 for (i = 0; i <= physmap_idx; i += 2) {
1348 if (base < physmap[i + 1]) {
1349 if (base + length <= physmap[i]) {
1350 insert_idx = i;
1351 break;
1352 }
1353 if (boothowto & RB_VERBOSE)
1354 printf(
1355 "Overlapping memory regions, ignoring second region\n");
1356 return (1);
1357 }
1358 }
1359
1360 /* See if we can prepend to the next entry. */
1361 if (insert_idx <= physmap_idx && base + length == physmap[insert_idx]) {
1362 physmap[insert_idx] = base;
1363 return (1);
1364 }
1365
1366 /* See if we can append to the previous entry. */
1367 if (insert_idx > 0 && base == physmap[insert_idx - 1]) {
1368 physmap[insert_idx - 1] += length;
1369 return (1);
1370 }
1371
1372 physmap_idx += 2;
1373 *physmap_idxp = physmap_idx;
1374 if (physmap_idx == PHYSMAP_SIZE) {
1375 printf(
1376 "Too many segments in the physical address map, giving up\n");
1377 return (0);
1378 }
1379
1380 /*
1381 * Move the last 'N' entries down to make room for the new
1382 * entry if needed.
1383 */
1384 for (i = (physmap_idx - 2); i > insert_idx; i -= 2) {
1385 physmap[i] = physmap[i - 2];
1386 physmap[i + 1] = physmap[i - 1];
1387 }
1388
1389 /* Insert the new entry. */
1390 physmap[insert_idx] = base;
1391 physmap[insert_idx + 1] = base + length;
1392 return (1);
1393 }
1394
1395 static void
1396 add_smap_entries(struct bios_smap *smapbase, vm_paddr_t *physmap,
1397 int *physmap_idx)
1398 {
1399 struct bios_smap *smap, *smapend;
1400 u_int32_t smapsize;
1401
1402 /*
1403 * Memory map from INT 15:E820.
1404 *
1405 * subr_module.c says:
1406 * "Consumer may safely assume that size value precedes data."
1407 * ie: an int32_t immediately precedes smap.
1408 */
1409 smapsize = *((u_int32_t *)smapbase - 1);
1410 smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
1411
1412 for (smap = smapbase; smap < smapend; smap++) {
1413 if (boothowto & RB_VERBOSE)
1414 printf("SMAP type=%02x base=%016lx len=%016lx\n",
1415 smap->type, smap->base, smap->length);
1416
1417 if (smap->type != SMAP_TYPE_MEMORY)
1418 continue;
1419
1420 if (!add_physmap_entry(smap->base, smap->length, physmap,
1421 physmap_idx))
1422 break;
1423 }
1424 }
1425
1426 #define efi_next_descriptor(ptr, size) \
1427 ((struct efi_md *)(((uint8_t *) ptr) + size))
1428
1429 static void
1430 add_efi_map_entries(struct efi_map_header *efihdr, vm_paddr_t *physmap,
1431 int *physmap_idx)
1432 {
1433 struct efi_md *map, *p;
1434 const char *type;
1435 size_t efisz;
1436 int ndesc, i;
1437
1438 static const char *types[] = {
1439 "Reserved",
1440 "LoaderCode",
1441 "LoaderData",
1442 "BootServicesCode",
1443 "BootServicesData",
1444 "RuntimeServicesCode",
1445 "RuntimeServicesData",
1446 "ConventionalMemory",
1447 "UnusableMemory",
1448 "ACPIReclaimMemory",
1449 "ACPIMemoryNVS",
1450 "MemoryMappedIO",
1451 "MemoryMappedIOPortSpace",
1452 "PalCode"
1453 };
1454
1455 /*
1456 * Memory map data provided by UEFI via the GetMemoryMap
1457 * Boot Services API.
1458 */
1459 efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
1460 map = (struct efi_md *)((uint8_t *)efihdr + efisz);
1461
1462 if (efihdr->descriptor_size == 0)
1463 return;
1464 ndesc = efihdr->memory_size / efihdr->descriptor_size;
1465
1466 if (boothowto & RB_VERBOSE)
1467 printf("%23s %12s %12s %8s %4s\n",
1468 "Type", "Physical", "Virtual", "#Pages", "Attr");
1469
1470 for (i = 0, p = map; i < ndesc; i++,
1471 p = efi_next_descriptor(p, efihdr->descriptor_size)) {
1472 if (boothowto & RB_VERBOSE) {
1473 if (p->md_type <= EFI_MD_TYPE_PALCODE)
1474 type = types[p->md_type];
1475 else
1476 type = "<INVALID>";
1477 printf("%23s %012lx %12p %08lx ", type, p->md_phys,
1478 p->md_virt, p->md_pages);
1479 if (p->md_attr & EFI_MD_ATTR_UC)
1480 printf("UC ");
1481 if (p->md_attr & EFI_MD_ATTR_WC)
1482 printf("WC ");
1483 if (p->md_attr & EFI_MD_ATTR_WT)
1484 printf("WT ");
1485 if (p->md_attr & EFI_MD_ATTR_WB)
1486 printf("WB ");
1487 if (p->md_attr & EFI_MD_ATTR_UCE)
1488 printf("UCE ");
1489 if (p->md_attr & EFI_MD_ATTR_WP)
1490 printf("WP ");
1491 if (p->md_attr & EFI_MD_ATTR_RP)
1492 printf("RP ");
1493 if (p->md_attr & EFI_MD_ATTR_XP)
1494 printf("XP ");
1495 if (p->md_attr & EFI_MD_ATTR_RT)
1496 printf("RUNTIME");
1497 printf("\n");
1498 }
1499
1500 switch (p->md_type) {
1501 case EFI_MD_TYPE_CODE:
1502 case EFI_MD_TYPE_DATA:
1503 case EFI_MD_TYPE_BS_CODE:
1504 case EFI_MD_TYPE_BS_DATA:
1505 case EFI_MD_TYPE_FREE:
1506 /*
1507 * We're allowed to use any entry with these types.
1508 */
1509 break;
1510 default:
1511 continue;
1512 }
1513
1514 if (!add_physmap_entry(p->md_phys, (p->md_pages * PAGE_SIZE),
1515 physmap, physmap_idx))
1516 break;
1517 }
1518 }
1519
1520 static char bootmethod[16] = "";
1521 SYSCTL_STRING(_machdep, OID_AUTO, bootmethod, CTLFLAG_RD, bootmethod, 0,
1522 "System firmware boot method");
1523
1524 #define PAGES_PER_GB (1024 * 1024 * 1024 / PAGE_SIZE)
1525
1526 /*
1527 * Populate the (physmap) array with base/bound pairs describing the
1528 * available physical memory in the system, then test this memory and
1529 * build the phys_avail array describing the actually-available memory.
1530 *
1531 * Total memory size may be set by the kernel environment variable
1532 * hw.physmem or the compile-time define MAXMEM.
1533 *
1534 * XXX first should be vm_paddr_t.
1535 */
1536 static void
1537 getmemsize(caddr_t kmdp, u_int64_t first)
1538 {
1539 int i, physmap_idx, pa_indx, da_indx;
1540 vm_paddr_t pa, physmap[PHYSMAP_SIZE];
1541 u_long physmem_start, physmem_tunable, memtest;
1542 pt_entry_t *pte;
1543 struct bios_smap *smapbase;
1544 struct efi_map_header *efihdr;
1545 quad_t dcons_addr, dcons_size;
1546 int page_counter;
1547
1548 bzero(physmap, sizeof(physmap));
1549 physmap_idx = 0;
1550
1551 efihdr = (struct efi_map_header *)preload_search_info(kmdp,
1552 MODINFO_METADATA | MODINFOMD_EFI_MAP);
1553 smapbase = (struct bios_smap *)preload_search_info(kmdp,
1554 MODINFO_METADATA | MODINFOMD_SMAP);
1555
1556 if (efihdr != NULL) {
1557 add_efi_map_entries(efihdr, physmap, &physmap_idx);
1558 strlcpy(bootmethod, "UEFI", sizeof(bootmethod));
1559 } else if (smapbase != NULL) {
1560 add_smap_entries(smapbase, physmap, &physmap_idx);
1561 strlcpy(bootmethod, "BIOS", sizeof(bootmethod));
1562 } else {
1563 panic("No BIOS smap or EFI map info from loader!");
1564 }
1565
1566 physmap_idx -= 2;
1567
1568 /*
1569 * Find the 'base memory' segment for SMP
1570 */
1571 basemem = 0;
1572 for (i = 0; i <= physmap_idx; i += 2) {
1573 if (physmap[i] <= 0xA0000) {
1574 basemem = physmap[i + 1] / 1024;
1575 break;
1576 }
1577 }
1578 if (basemem == 0 || basemem > 640) {
1579 if (bootverbose)
1580 printf(
1581 "Memory map doesn't contain a basemem segment, faking it");
1582 basemem = 640;
1583 }
1584
1585 #ifdef SMP
1586 /* make hole for AP bootstrap code */
1587 if (physmap[1] >= 0x100000000)
1588 panic("Basemem segment is not suitable for AP bootstrap code!");
1589 physmap[1] = mp_bootaddress(physmap[1] / 1024);
1590 #endif
1591
1592 /*
1593 * Maxmem isn't the "maximum memory", it's one larger than the
1594 * highest page of the physical address space. It should be
1595 * called something like "Maxphyspage". We may adjust this
1596 * based on ``hw.physmem'' and the results of the memory test.
1597 */
1598 Maxmem = atop(physmap[physmap_idx + 1]);
1599
1600 #ifdef MAXMEM
1601 Maxmem = MAXMEM / 4;
1602 #endif
1603
1604 if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
1605 Maxmem = atop(physmem_tunable);
1606
1607 /*
1608 * The boot memory test is disabled by default, as it takes a
1609 * significant amount of time on large-memory systems, and is
1610 * unfriendly to virtual machines as it unnecessarily touches all
1611 * pages.
1612 *
1613 * A general name is used as the code may be extended to support
1614 * additional tests beyond the current "page present" test.
1615 */
1616 memtest = 0;
1617 TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
1618
1619 /*
1620 * Don't allow MAXMEM or hw.physmem to extend the amount of memory
1621 * in the system.
1622 */
1623 if (Maxmem > atop(physmap[physmap_idx + 1]))
1624 Maxmem = atop(physmap[physmap_idx + 1]);
1625
1626 if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1627 (boothowto & RB_VERBOSE))
1628 printf("Physical memory use set to %ldK\n", Maxmem * 4);
1629
1630 /* call pmap initialization to make new kernel address space */
1631 pmap_bootstrap(&first);
1632
1633 /*
1634 * Size up each available chunk of physical memory.
1635 *
1636 * XXX Some BIOSes corrupt low 64KB between suspend and resume.
1637 * By default, mask off the first 16 pages unless we appear to be
1638 * running in a VM.
1639 */
1640 physmem_start = (vm_guest > VM_GUEST_NO ? 1 : 16) << PAGE_SHIFT;
1641 TUNABLE_ULONG_FETCH("hw.physmem.start", &physmem_start);
1642 if (physmap[0] < physmem_start) {
1643 if (physmem_start < PAGE_SIZE)
1644 physmap[0] = PAGE_SIZE;
1645 else if (physmem_start >= physmap[1])
1646 physmap[0] = round_page(physmap[1] - PAGE_SIZE);
1647 else
1648 physmap[0] = round_page(physmem_start);
1649 }
1650 pa_indx = 0;
1651 da_indx = 1;
1652 phys_avail[pa_indx++] = physmap[0];
1653 phys_avail[pa_indx] = physmap[0];
1654 dump_avail[da_indx] = physmap[0];
1655 pte = CMAP1;
1656
1657 /*
1658 * Get dcons buffer address
1659 */
1660 if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
1661 getenv_quad("dcons.size", &dcons_size) == 0)
1662 dcons_addr = 0;
1663
1664 /*
1665 * physmap is in bytes, so when converting to page boundaries,
1666 * round up the start address and round down the end address.
1667 */
1668 page_counter = 0;
1669 if (memtest != 0)
1670 printf("Testing system memory");
1671 for (i = 0; i <= physmap_idx; i += 2) {
1672 vm_paddr_t end;
1673
1674 end = ptoa((vm_paddr_t)Maxmem);
1675 if (physmap[i + 1] < end)
1676 end = trunc_page(physmap[i + 1]);
1677 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1678 int tmp, page_bad, full;
1679 int *ptr = (int *)CADDR1;
1680
1681 full = FALSE;
1682 /*
1683 * block out kernel memory as not available.
1684 */
1685 if (pa >= (vm_paddr_t)kernphys && pa < first)
1686 goto do_dump_avail;
1687
1688 /*
1689 * block out dcons buffer
1690 */
1691 if (dcons_addr > 0
1692 && pa >= trunc_page(dcons_addr)
1693 && pa < dcons_addr + dcons_size)
1694 goto do_dump_avail;
1695
1696 page_bad = FALSE;
1697 if (memtest == 0)
1698 goto skip_memtest;
1699
1700 /*
1701 * Print a "." every GB to show we're making
1702 * progress.
1703 */
1704 page_counter++;
1705 if ((page_counter % PAGES_PER_GB) == 0)
1706 printf(".");
1707
1708 /*
1709 * map page into kernel: valid, read/write,non-cacheable
1710 */
1711 *pte = pa | PG_V | PG_RW | PG_NC_PWT | PG_NC_PCD;
1712 invltlb();
1713
1714 tmp = *(int *)ptr;
1715 /*
1716 * Test for alternating 1's and 0's
1717 */
1718 *(volatile int *)ptr = 0xaaaaaaaa;
1719 if (*(volatile int *)ptr != 0xaaaaaaaa)
1720 page_bad = TRUE;
1721 /*
1722 * Test for alternating 0's and 1's
1723 */
1724 *(volatile int *)ptr = 0x55555555;
1725 if (*(volatile int *)ptr != 0x55555555)
1726 page_bad = TRUE;
1727 /*
1728 * Test for all 1's
1729 */
1730 *(volatile int *)ptr = 0xffffffff;
1731 if (*(volatile int *)ptr != 0xffffffff)
1732 page_bad = TRUE;
1733 /*
1734 * Test for all 0's
1735 */
1736 *(volatile int *)ptr = 0x0;
1737 if (*(volatile int *)ptr != 0x0)
1738 page_bad = TRUE;
1739 /*
1740 * Restore original value.
1741 */
1742 *(int *)ptr = tmp;
1743
1744 skip_memtest:
1745 /*
1746 * Adjust array of valid/good pages.
1747 */
1748 if (page_bad == TRUE)
1749 continue;
1750 /*
1751 * If this good page is a continuation of the
1752 * previous set of good pages, then just increase
1753 * the end pointer. Otherwise start a new chunk.
1754 * Note that "end" points one higher than end,
1755 * making the range >= start and < end.
1756 * If we're also doing a speculative memory
1757 * test and we at or past the end, bump up Maxmem
1758 * so that we keep going. The first bad page
1759 * will terminate the loop.
1760 */
1761 if (phys_avail[pa_indx] == pa) {
1762 phys_avail[pa_indx] += PAGE_SIZE;
1763 } else {
1764 pa_indx++;
1765 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1766 printf(
1767 "Too many holes in the physical address space, giving up\n");
1768 pa_indx--;
1769 full = TRUE;
1770 goto do_dump_avail;
1771 }
1772 phys_avail[pa_indx++] = pa; /* start */
1773 phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
1774 }
1775 physmem++;
1776 do_dump_avail:
1777 if (dump_avail[da_indx] == pa) {
1778 dump_avail[da_indx] += PAGE_SIZE;
1779 } else {
1780 da_indx++;
1781 if (da_indx == DUMP_AVAIL_ARRAY_END) {
1782 da_indx--;
1783 goto do_next;
1784 }
1785 dump_avail[da_indx++] = pa; /* start */
1786 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
1787 }
1788 do_next:
1789 if (full)
1790 break;
1791 }
1792 }
1793 *pte = 0;
1794 invltlb();
1795 if (memtest != 0)
1796 printf("\n");
1797
1798 /*
1799 * XXX
1800 * The last chunk must contain at least one page plus the message
1801 * buffer to avoid complicating other code (message buffer address
1802 * calculation, etc.).
1803 */
1804 while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1805 round_page(msgbufsize) >= phys_avail[pa_indx]) {
1806 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1807 phys_avail[pa_indx--] = 0;
1808 phys_avail[pa_indx--] = 0;
1809 }
1810
1811 Maxmem = atop(phys_avail[pa_indx]);
1812
1813 /* Trim off space for the message buffer. */
1814 phys_avail[pa_indx] -= round_page(msgbufsize);
1815
1816 /* Map the message buffer. */
1817 msgbufp = (struct msgbuf *)PHYS_TO_DMAP(phys_avail[pa_indx]);
1818 }
1819
1820 u_int64_t
1821 hammer_time(u_int64_t modulep, u_int64_t physfree)
1822 {
1823 caddr_t kmdp;
1824 int gsel_tss, x;
1825 struct pcpu *pc;
1826 struct nmi_pcpu *np;
1827 struct xstate_hdr *xhdr;
1828 u_int64_t msr;
1829 char *env;
1830 size_t kstack0_sz;
1831
1832 thread0.td_kstack = physfree + KERNBASE;
1833 thread0.td_kstack_pages = KSTACK_PAGES;
1834 kstack0_sz = thread0.td_kstack_pages * PAGE_SIZE;
1835 bzero((void *)thread0.td_kstack, kstack0_sz);
1836 physfree += kstack0_sz;
1837
1838 /*
1839 * This may be done better later if it gets more high level
1840 * components in it. If so just link td->td_proc here.
1841 */
1842 proc_linkup0(&proc0, &thread0);
1843
1844 preload_metadata = (caddr_t)(uintptr_t)(modulep + KERNBASE);
1845 preload_bootstrap_relocate(KERNBASE);
1846 kmdp = preload_search_by_type("elf kernel");
1847 if (kmdp == NULL)
1848 kmdp = preload_search_by_type("elf64 kernel");
1849 boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
1850 init_static_kenv(MD_FETCH(kmdp, MODINFOMD_ENVP, char *) + KERNBASE, 0);
1851 #ifdef DDB
1852 ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
1853 ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
1854 #endif
1855
1856 /* Init basic tunables, hz etc */
1857 init_param1();
1858
1859 /*
1860 * make gdt memory segments
1861 */
1862 for (x = 0; x < NGDT; x++) {
1863 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1) &&
1864 x != GUSERLDT_SEL && x != (GUSERLDT_SEL) + 1)
1865 ssdtosd(&gdt_segs[x], &gdt[x]);
1866 }
1867 gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&common_tss[0];
1868 ssdtosyssd(&gdt_segs[GPROC0_SEL],
1869 (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1870
1871 r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1872 r_gdt.rd_base = (long) gdt;
1873 lgdt(&r_gdt);
1874 pc = &__pcpu[0];
1875
1876 wrmsr(MSR_FSBASE, 0); /* User value */
1877 wrmsr(MSR_GSBASE, (u_int64_t)pc);
1878 wrmsr(MSR_KGSBASE, 0); /* User value while in the kernel */
1879
1880 pcpu_init(pc, 0, sizeof(struct pcpu));
1881 dpcpu_init((void *)(physfree + KERNBASE), 0);
1882 physfree += DPCPU_SIZE;
1883 PCPU_SET(prvspace, pc);
1884 PCPU_SET(curthread, &thread0);
1885 PCPU_SET(tssp, &common_tss[0]);
1886 PCPU_SET(commontssp, &common_tss[0]);
1887 PCPU_SET(tss, (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1888 PCPU_SET(ldt, (struct system_segment_descriptor *)&gdt[GUSERLDT_SEL]);
1889 PCPU_SET(fs32p, &gdt[GUFS32_SEL]);
1890 PCPU_SET(gs32p, &gdt[GUGS32_SEL]);
1891
1892 /*
1893 * Initialize mutexes.
1894 *
1895 * icu_lock: in order to allow an interrupt to occur in a critical
1896 * section, to set pcpu->ipending (etc...) properly, we
1897 * must be able to get the icu lock, so it can't be
1898 * under witness.
1899 */
1900 mutex_init();
1901 mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS);
1902 mtx_init(&dt_lock, "descriptor tables", NULL, MTX_DEF);
1903
1904 /* exceptions */
1905 for (x = 0; x < NIDT; x++)
1906 setidt(x, &IDTVEC(rsvd), SDT_SYSIGT, SEL_KPL, 0);
1907 setidt(IDT_DE, &IDTVEC(div), SDT_SYSIGT, SEL_KPL, 0);
1908 setidt(IDT_DB, &IDTVEC(dbg), SDT_SYSIGT, SEL_KPL, 0);
1909 setidt(IDT_NMI, &IDTVEC(nmi), SDT_SYSIGT, SEL_KPL, 2);
1910 setidt(IDT_BP, &IDTVEC(bpt), SDT_SYSIGT, SEL_UPL, 0);
1911 setidt(IDT_OF, &IDTVEC(ofl), SDT_SYSIGT, SEL_KPL, 0);
1912 setidt(IDT_BR, &IDTVEC(bnd), SDT_SYSIGT, SEL_KPL, 0);
1913 setidt(IDT_UD, &IDTVEC(ill), SDT_SYSIGT, SEL_KPL, 0);
1914 setidt(IDT_NM, &IDTVEC(dna), SDT_SYSIGT, SEL_KPL, 0);
1915 setidt(IDT_DF, &IDTVEC(dblfault), SDT_SYSIGT, SEL_KPL, 1);
1916 setidt(IDT_FPUGP, &IDTVEC(fpusegm), SDT_SYSIGT, SEL_KPL, 0);
1917 setidt(IDT_TS, &IDTVEC(tss), SDT_SYSIGT, SEL_KPL, 0);
1918 setidt(IDT_NP, &IDTVEC(missing), SDT_SYSIGT, SEL_KPL, 0);
1919 setidt(IDT_SS, &IDTVEC(stk), SDT_SYSIGT, SEL_KPL, 0);
1920 setidt(IDT_GP, &IDTVEC(prot), SDT_SYSIGT, SEL_KPL, 0);
1921 setidt(IDT_PF, &IDTVEC(page), SDT_SYSIGT, SEL_KPL, 0);
1922 setidt(IDT_MF, &IDTVEC(fpu), SDT_SYSIGT, SEL_KPL, 0);
1923 setidt(IDT_AC, &IDTVEC(align), SDT_SYSIGT, SEL_KPL, 0);
1924 setidt(IDT_MC, &IDTVEC(mchk), SDT_SYSIGT, SEL_KPL, 0);
1925 setidt(IDT_XF, &IDTVEC(xmm), SDT_SYSIGT, SEL_KPL, 0);
1926 #ifdef KDTRACE_HOOKS
1927 setidt(IDT_DTRACE_RET, &IDTVEC(dtrace_ret), SDT_SYSIGT, SEL_UPL, 0);
1928 #endif
1929 #ifdef XENHVM
1930 setidt(IDT_EVTCHN, &IDTVEC(xen_intr_upcall), SDT_SYSIGT, SEL_UPL, 0);
1931 #endif
1932
1933 r_idt.rd_limit = sizeof(idt0) - 1;
1934 r_idt.rd_base = (long) idt;
1935 lidt(&r_idt);
1936
1937 /*
1938 * Initialize the i8254 before the console so that console
1939 * initialization can use DELAY().
1940 */
1941 i8254_init();
1942
1943 /*
1944 * Use vt(4) by default for UEFI boot (during the sc(4)/vt(4)
1945 * transition).
1946 */
1947 if (kmdp != NULL && preload_search_info(kmdp,
1948 MODINFO_METADATA | MODINFOMD_EFI_MAP) != NULL)
1949 vty_set_preferred(VTY_VT);
1950
1951 identify_cpu(); /* Final stage of CPU initialization */
1952 initializecpu(); /* Initialize CPU registers */
1953 initializecpucache();
1954
1955 /* doublefault stack space, runs on ist1 */
1956 common_tss[0].tss_ist1 = (long)&dblfault_stack[sizeof(dblfault_stack)];
1957
1958 /*
1959 * NMI stack, runs on ist2. The pcpu pointer is stored just
1960 * above the start of the ist2 stack.
1961 */
1962 np = ((struct nmi_pcpu *) &nmi0_stack[sizeof(nmi0_stack)]) - 1;
1963 np->np_pcpu = (register_t) pc;
1964 common_tss[0].tss_ist2 = (long) np;
1965
1966 /* Set the IO permission bitmap (empty due to tss seg limit) */
1967 common_tss[0].tss_iobase = sizeof(struct amd64tss) +
1968 IOPAGES * PAGE_SIZE;
1969
1970 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1971 ltr(gsel_tss);
1972
1973 /* Set up the fast syscall stuff */
1974 msr = rdmsr(MSR_EFER) | EFER_SCE;
1975 wrmsr(MSR_EFER, msr);
1976 wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
1977 wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
1978 msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
1979 ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
1980 wrmsr(MSR_STAR, msr);
1981 wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
1982
1983 getmemsize(kmdp, physfree);
1984 init_param2(physmem);
1985
1986 /* now running on new page tables, configured,and u/iom is accessible */
1987
1988 cninit();
1989
1990 #ifdef DEV_ISA
1991 #ifdef DEV_ATPIC
1992 elcr_probe();
1993 atpic_startup();
1994 #else
1995 /* Reset and mask the atpics and leave them shut down. */
1996 atpic_reset();
1997
1998 /*
1999 * Point the ICU spurious interrupt vectors at the APIC spurious
2000 * interrupt handler.
2001 */
2002 setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
2003 setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
2004 #endif
2005 #else
2006 #error "have you forgotten the isa device?";
2007 #endif
2008
2009 kdb_init();
2010
2011 #ifdef KDB
2012 if (boothowto & RB_KDB)
2013 kdb_enter(KDB_WHY_BOOTFLAGS,
2014 "Boot flags requested debugger");
2015 #endif
2016
2017 msgbufinit(msgbufp, msgbufsize);
2018 fpuinit();
2019
2020 /*
2021 * Set up thread0 pcb after fpuinit calculated pcb + fpu save
2022 * area size. Zero out the extended state header in fpu save
2023 * area.
2024 */
2025 thread0.td_pcb = get_pcb_td(&thread0);
2026 bzero(get_pcb_user_save_td(&thread0), cpu_max_ext_state_size);
2027 if (use_xsave) {
2028 xhdr = (struct xstate_hdr *)(get_pcb_user_save_td(&thread0) +
2029 1);
2030 xhdr->xstate_bv = xsave_mask;
2031 }
2032 /* make an initial tss so cpu can get interrupt stack on syscall! */
2033 common_tss[0].tss_rsp0 = (vm_offset_t)thread0.td_pcb;
2034 /* Ensure the stack is aligned to 16 bytes */
2035 common_tss[0].tss_rsp0 &= ~0xFul;
2036 PCPU_SET(rsp0, common_tss[0].tss_rsp0);
2037 PCPU_SET(curpcb, thread0.td_pcb);
2038
2039 /* transfer to user mode */
2040
2041 _ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
2042 _udatasel = GSEL(GUDATA_SEL, SEL_UPL);
2043 _ucode32sel = GSEL(GUCODE32_SEL, SEL_UPL);
2044 _ufssel = GSEL(GUFS32_SEL, SEL_UPL);
2045 _ugssel = GSEL(GUGS32_SEL, SEL_UPL);
2046
2047 load_ds(_udatasel);
2048 load_es(_udatasel);
2049 load_fs(_ufssel);
2050
2051 /* setup proc 0's pcb */
2052 thread0.td_pcb->pcb_flags = 0;
2053 thread0.td_pcb->pcb_cr3 = KPML4phys; /* PCID 0 is reserved for kernel */
2054 thread0.td_frame = &proc0_tf;
2055
2056 env = getenv("kernelname");
2057 if (env != NULL)
2058 strlcpy(kernelname, env, sizeof(kernelname));
2059
2060 cpu_probe_amdc1e();
2061
2062 #ifdef FDT
2063 x86_init_fdt();
2064 #endif
2065
2066 /* Location of kernel stack for locore */
2067 return ((u_int64_t)thread0.td_pcb);
2068 }
2069
2070 void
2071 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
2072 {
2073
2074 pcpu->pc_acpi_id = 0xffffffff;
2075 }
2076
2077 static int
2078 smap_sysctl_handler(SYSCTL_HANDLER_ARGS)
2079 {
2080 struct bios_smap *smapbase;
2081 struct bios_smap_xattr smap;
2082 caddr_t kmdp;
2083 uint32_t *smapattr;
2084 int count, error, i;
2085
2086 /* Retrieve the system memory map from the loader. */
2087 kmdp = preload_search_by_type("elf kernel");
2088 if (kmdp == NULL)
2089 kmdp = preload_search_by_type("elf64 kernel");
2090 smapbase = (struct bios_smap *)preload_search_info(kmdp,
2091 MODINFO_METADATA | MODINFOMD_SMAP);
2092 if (smapbase == NULL)
2093 return (0);
2094 smapattr = (uint32_t *)preload_search_info(kmdp,
2095 MODINFO_METADATA | MODINFOMD_SMAP_XATTR);
2096 count = *((uint32_t *)smapbase - 1) / sizeof(*smapbase);
2097 error = 0;
2098 for (i = 0; i < count; i++) {
2099 smap.base = smapbase[i].base;
2100 smap.length = smapbase[i].length;
2101 smap.type = smapbase[i].type;
2102 if (smapattr != NULL)
2103 smap.xattr = smapattr[i];
2104 else
2105 smap.xattr = 0;
2106 error = SYSCTL_OUT(req, &smap, sizeof(smap));
2107 }
2108 return (error);
2109 }
2110 SYSCTL_PROC(_machdep, OID_AUTO, smap, CTLTYPE_OPAQUE|CTLFLAG_RD, NULL, 0,
2111 smap_sysctl_handler, "S,bios_smap_xattr", "Raw BIOS SMAP data");
2112
2113 static int
2114 efi_map_sysctl_handler(SYSCTL_HANDLER_ARGS)
2115 {
2116 struct efi_map_header *efihdr;
2117 caddr_t kmdp;
2118 uint32_t efisize;
2119
2120 kmdp = preload_search_by_type("elf kernel");
2121 if (kmdp == NULL)
2122 kmdp = preload_search_by_type("elf64 kernel");
2123 efihdr = (struct efi_map_header *)preload_search_info(kmdp,
2124 MODINFO_METADATA | MODINFOMD_EFI_MAP);
2125 if (efihdr == NULL)
2126 return (0);
2127 efisize = *((uint32_t *)efihdr - 1);
2128 return (SYSCTL_OUT(req, efihdr, efisize));
2129 }
2130 SYSCTL_PROC(_machdep, OID_AUTO, efi_map, CTLTYPE_OPAQUE|CTLFLAG_RD, NULL, 0,
2131 efi_map_sysctl_handler, "S,efi_map_header", "Raw EFI Memory Map");
2132
2133 void
2134 spinlock_enter(void)
2135 {
2136 struct thread *td;
2137 register_t flags;
2138
2139 td = curthread;
2140 if (td->td_md.md_spinlock_count == 0) {
2141 flags = intr_disable();
2142 td->td_md.md_spinlock_count = 1;
2143 td->td_md.md_saved_flags = flags;
2144 } else
2145 td->td_md.md_spinlock_count++;
2146 critical_enter();
2147 }
2148
2149 void
2150 spinlock_exit(void)
2151 {
2152 struct thread *td;
2153 register_t flags;
2154
2155 td = curthread;
2156 critical_exit();
2157 flags = td->td_md.md_saved_flags;
2158 td->td_md.md_spinlock_count--;
2159 if (td->td_md.md_spinlock_count == 0)
2160 intr_restore(flags);
2161 }
2162
2163 /*
2164 * Construct a PCB from a trapframe. This is called from kdb_trap() where
2165 * we want to start a backtrace from the function that caused us to enter
2166 * the debugger. We have the context in the trapframe, but base the trace
2167 * on the PCB. The PCB doesn't have to be perfect, as long as it contains
2168 * enough for a backtrace.
2169 */
2170 void
2171 makectx(struct trapframe *tf, struct pcb *pcb)
2172 {
2173
2174 pcb->pcb_r12 = tf->tf_r12;
2175 pcb->pcb_r13 = tf->tf_r13;
2176 pcb->pcb_r14 = tf->tf_r14;
2177 pcb->pcb_r15 = tf->tf_r15;
2178 pcb->pcb_rbp = tf->tf_rbp;
2179 pcb->pcb_rbx = tf->tf_rbx;
2180 pcb->pcb_rip = tf->tf_rip;
2181 pcb->pcb_rsp = tf->tf_rsp;
2182 }
2183
2184 int
2185 ptrace_set_pc(struct thread *td, unsigned long addr)
2186 {
2187
2188 td->td_frame->tf_rip = addr;
2189 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
2190 return (0);
2191 }
2192
2193 int
2194 ptrace_single_step(struct thread *td)
2195 {
2196 td->td_frame->tf_rflags |= PSL_T;
2197 return (0);
2198 }
2199
2200 int
2201 ptrace_clear_single_step(struct thread *td)
2202 {
2203 td->td_frame->tf_rflags &= ~PSL_T;
2204 return (0);
2205 }
2206
2207 int
2208 fill_regs(struct thread *td, struct reg *regs)
2209 {
2210 struct trapframe *tp;
2211
2212 tp = td->td_frame;
2213 return (fill_frame_regs(tp, regs));
2214 }
2215
2216 int
2217 fill_frame_regs(struct trapframe *tp, struct reg *regs)
2218 {
2219 regs->r_r15 = tp->tf_r15;
2220 regs->r_r14 = tp->tf_r14;
2221 regs->r_r13 = tp->tf_r13;
2222 regs->r_r12 = tp->tf_r12;
2223 regs->r_r11 = tp->tf_r11;
2224 regs->r_r10 = tp->tf_r10;
2225 regs->r_r9 = tp->tf_r9;
2226 regs->r_r8 = tp->tf_r8;
2227 regs->r_rdi = tp->tf_rdi;
2228 regs->r_rsi = tp->tf_rsi;
2229 regs->r_rbp = tp->tf_rbp;
2230 regs->r_rbx = tp->tf_rbx;
2231 regs->r_rdx = tp->tf_rdx;
2232 regs->r_rcx = tp->tf_rcx;
2233 regs->r_rax = tp->tf_rax;
2234 regs->r_rip = tp->tf_rip;
2235 regs->r_cs = tp->tf_cs;
2236 regs->r_rflags = tp->tf_rflags;
2237 regs->r_rsp = tp->tf_rsp;
2238 regs->r_ss = tp->tf_ss;
2239 if (tp->tf_flags & TF_HASSEGS) {
2240 regs->r_ds = tp->tf_ds;
2241 regs->r_es = tp->tf_es;
2242 regs->r_fs = tp->tf_fs;
2243 regs->r_gs = tp->tf_gs;
2244 } else {
2245 regs->r_ds = 0;
2246 regs->r_es = 0;
2247 regs->r_fs = 0;
2248 regs->r_gs = 0;
2249 }
2250 return (0);
2251 }
2252
2253 int
2254 set_regs(struct thread *td, struct reg *regs)
2255 {
2256 struct trapframe *tp;
2257 register_t rflags;
2258
2259 tp = td->td_frame;
2260 rflags = regs->r_rflags & 0xffffffff;
2261 if (!EFL_SECURE(rflags, tp->tf_rflags) || !CS_SECURE(regs->r_cs))
2262 return (EINVAL);
2263 tp->tf_r15 = regs->r_r15;
2264 tp->tf_r14 = regs->r_r14;
2265 tp->tf_r13 = regs->r_r13;
2266 tp->tf_r12 = regs->r_r12;
2267 tp->tf_r11 = regs->r_r11;
2268 tp->tf_r10 = regs->r_r10;
2269 tp->tf_r9 = regs->r_r9;
2270 tp->tf_r8 = regs->r_r8;
2271 tp->tf_rdi = regs->r_rdi;
2272 tp->tf_rsi = regs->r_rsi;
2273 tp->tf_rbp = regs->r_rbp;
2274 tp->tf_rbx = regs->r_rbx;
2275 tp->tf_rdx = regs->r_rdx;
2276 tp->tf_rcx = regs->r_rcx;
2277 tp->tf_rax = regs->r_rax;
2278 tp->tf_rip = regs->r_rip;
2279 tp->tf_cs = regs->r_cs;
2280 tp->tf_rflags = rflags;
2281 tp->tf_rsp = regs->r_rsp;
2282 tp->tf_ss = regs->r_ss;
2283 if (0) { /* XXXKIB */
2284 tp->tf_ds = regs->r_ds;
2285 tp->tf_es = regs->r_es;
2286 tp->tf_fs = regs->r_fs;
2287 tp->tf_gs = regs->r_gs;
2288 tp->tf_flags = TF_HASSEGS;
2289 }
2290 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
2291 return (0);
2292 }
2293
2294 /* XXX check all this stuff! */
2295 /* externalize from sv_xmm */
2296 static void
2297 fill_fpregs_xmm(struct savefpu *sv_xmm, struct fpreg *fpregs)
2298 {
2299 struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
2300 struct envxmm *penv_xmm = &sv_xmm->sv_env;
2301 int i;
2302
2303 /* pcb -> fpregs */
2304 bzero(fpregs, sizeof(*fpregs));
2305
2306 /* FPU control/status */
2307 penv_fpreg->en_cw = penv_xmm->en_cw;
2308 penv_fpreg->en_sw = penv_xmm->en_sw;
2309 penv_fpreg->en_tw = penv_xmm->en_tw;
2310 penv_fpreg->en_opcode = penv_xmm->en_opcode;
2311 penv_fpreg->en_rip = penv_xmm->en_rip;
2312 penv_fpreg->en_rdp = penv_xmm->en_rdp;
2313 penv_fpreg->en_mxcsr = penv_xmm->en_mxcsr;
2314 penv_fpreg->en_mxcsr_mask = penv_xmm->en_mxcsr_mask;
2315
2316 /* FPU registers */
2317 for (i = 0; i < 8; ++i)
2318 bcopy(sv_xmm->sv_fp[i].fp_acc.fp_bytes, fpregs->fpr_acc[i], 10);
2319
2320 /* SSE registers */
2321 for (i = 0; i < 16; ++i)
2322 bcopy(sv_xmm->sv_xmm[i].xmm_bytes, fpregs->fpr_xacc[i], 16);
2323 }
2324
2325 /* internalize from fpregs into sv_xmm */
2326 static void
2327 set_fpregs_xmm(struct fpreg *fpregs, struct savefpu *sv_xmm)
2328 {
2329 struct envxmm *penv_xmm = &sv_xmm->sv_env;
2330 struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
2331 int i;
2332
2333 /* fpregs -> pcb */
2334 /* FPU control/status */
2335 penv_xmm->en_cw = penv_fpreg->en_cw;
2336 penv_xmm->en_sw = penv_fpreg->en_sw;
2337 penv_xmm->en_tw = penv_fpreg->en_tw;
2338 penv_xmm->en_opcode = penv_fpreg->en_opcode;
2339 penv_xmm->en_rip = penv_fpreg->en_rip;
2340 penv_xmm->en_rdp = penv_fpreg->en_rdp;
2341 penv_xmm->en_mxcsr = penv_fpreg->en_mxcsr;
2342 penv_xmm->en_mxcsr_mask = penv_fpreg->en_mxcsr_mask & cpu_mxcsr_mask;
2343
2344 /* FPU registers */
2345 for (i = 0; i < 8; ++i)
2346 bcopy(fpregs->fpr_acc[i], sv_xmm->sv_fp[i].fp_acc.fp_bytes, 10);
2347
2348 /* SSE registers */
2349 for (i = 0; i < 16; ++i)
2350 bcopy(fpregs->fpr_xacc[i], sv_xmm->sv_xmm[i].xmm_bytes, 16);
2351 }
2352
2353 /* externalize from td->pcb */
2354 int
2355 fill_fpregs(struct thread *td, struct fpreg *fpregs)
2356 {
2357
2358 KASSERT(td == curthread || TD_IS_SUSPENDED(td) ||
2359 P_SHOULDSTOP(td->td_proc),
2360 ("not suspended thread %p", td));
2361 fpugetregs(td);
2362 fill_fpregs_xmm(get_pcb_user_save_td(td), fpregs);
2363 return (0);
2364 }
2365
2366 /* internalize to td->pcb */
2367 int
2368 set_fpregs(struct thread *td, struct fpreg *fpregs)
2369 {
2370
2371 set_fpregs_xmm(fpregs, get_pcb_user_save_td(td));
2372 fpuuserinited(td);
2373 return (0);
2374 }
2375
2376 /*
2377 * Get machine context.
2378 */
2379 int
2380 get_mcontext(struct thread *td, mcontext_t *mcp, int flags)
2381 {
2382 struct pcb *pcb;
2383 struct trapframe *tp;
2384
2385 pcb = td->td_pcb;
2386 tp = td->td_frame;
2387 PROC_LOCK(curthread->td_proc);
2388 mcp->mc_onstack = sigonstack(tp->tf_rsp);
2389 PROC_UNLOCK(curthread->td_proc);
2390 mcp->mc_r15 = tp->tf_r15;
2391 mcp->mc_r14 = tp->tf_r14;
2392 mcp->mc_r13 = tp->tf_r13;
2393 mcp->mc_r12 = tp->tf_r12;
2394 mcp->mc_r11 = tp->tf_r11;
2395 mcp->mc_r10 = tp->tf_r10;
2396 mcp->mc_r9 = tp->tf_r9;
2397 mcp->mc_r8 = tp->tf_r8;
2398 mcp->mc_rdi = tp->tf_rdi;
2399 mcp->mc_rsi = tp->tf_rsi;
2400 mcp->mc_rbp = tp->tf_rbp;
2401 mcp->mc_rbx = tp->tf_rbx;
2402 mcp->mc_rcx = tp->tf_rcx;
2403 mcp->mc_rflags = tp->tf_rflags;
2404 if (flags & GET_MC_CLEAR_RET) {
2405 mcp->mc_rax = 0;
2406 mcp->mc_rdx = 0;
2407 mcp->mc_rflags &= ~PSL_C;
2408 } else {
2409 mcp->mc_rax = tp->tf_rax;
2410 mcp->mc_rdx = tp->tf_rdx;
2411 }
2412 mcp->mc_rip = tp->tf_rip;
2413 mcp->mc_cs = tp->tf_cs;
2414 mcp->mc_rsp = tp->tf_rsp;
2415 mcp->mc_ss = tp->tf_ss;
2416 mcp->mc_ds = tp->tf_ds;
2417 mcp->mc_es = tp->tf_es;
2418 mcp->mc_fs = tp->tf_fs;
2419 mcp->mc_gs = tp->tf_gs;
2420 mcp->mc_flags = tp->tf_flags;
2421 mcp->mc_len = sizeof(*mcp);
2422 get_fpcontext(td, mcp, NULL, 0);
2423 mcp->mc_fsbase = pcb->pcb_fsbase;
2424 mcp->mc_gsbase = pcb->pcb_gsbase;
2425 mcp->mc_xfpustate = 0;
2426 mcp->mc_xfpustate_len = 0;
2427 bzero(mcp->mc_spare, sizeof(mcp->mc_spare));
2428 return (0);
2429 }
2430
2431 /*
2432 * Set machine context.
2433 *
2434 * However, we don't set any but the user modifiable flags, and we won't
2435 * touch the cs selector.
2436 */
2437 int
2438 set_mcontext(struct thread *td, mcontext_t *mcp)
2439 {
2440 struct pcb *pcb;
2441 struct trapframe *tp;
2442 char *xfpustate;
2443 long rflags;
2444 int ret;
2445
2446 pcb = td->td_pcb;
2447 tp = td->td_frame;
2448 if (mcp->mc_len != sizeof(*mcp) ||
2449 (mcp->mc_flags & ~_MC_FLAG_MASK) != 0)
2450 return (EINVAL);
2451 rflags = (mcp->mc_rflags & PSL_USERCHANGE) |
2452 (tp->tf_rflags & ~PSL_USERCHANGE);
2453 if (mcp->mc_flags & _MC_HASFPXSTATE) {
2454 if (mcp->mc_xfpustate_len > cpu_max_ext_state_size -
2455 sizeof(struct savefpu))
2456 return (EINVAL);
2457 xfpustate = __builtin_alloca(mcp->mc_xfpustate_len);
2458 ret = copyin((void *)mcp->mc_xfpustate, xfpustate,
2459 mcp->mc_xfpustate_len);
2460 if (ret != 0)
2461 return (ret);
2462 } else
2463 xfpustate = NULL;
2464 ret = set_fpcontext(td, mcp, xfpustate, mcp->mc_xfpustate_len);
2465 if (ret != 0)
2466 return (ret);
2467 tp->tf_r15 = mcp->mc_r15;
2468 tp->tf_r14 = mcp->mc_r14;
2469 tp->tf_r13 = mcp->mc_r13;
2470 tp->tf_r12 = mcp->mc_r12;
2471 tp->tf_r11 = mcp->mc_r11;
2472 tp->tf_r10 = mcp->mc_r10;
2473 tp->tf_r9 = mcp->mc_r9;
2474 tp->tf_r8 = mcp->mc_r8;
2475 tp->tf_rdi = mcp->mc_rdi;
2476 tp->tf_rsi = mcp->mc_rsi;
2477 tp->tf_rbp = mcp->mc_rbp;
2478 tp->tf_rbx = mcp->mc_rbx;
2479 tp->tf_rdx = mcp->mc_rdx;
2480 tp->tf_rcx = mcp->mc_rcx;
2481 tp->tf_rax = mcp->mc_rax;
2482 tp->tf_rip = mcp->mc_rip;
2483 tp->tf_rflags = rflags;
2484 tp->tf_rsp = mcp->mc_rsp;
2485 tp->tf_ss = mcp->mc_ss;
2486 tp->tf_flags = mcp->mc_flags;
2487 if (tp->tf_flags & TF_HASSEGS) {
2488 tp->tf_ds = mcp->mc_ds;
2489 tp->tf_es = mcp->mc_es;
2490 tp->tf_fs = mcp->mc_fs;
2491 tp->tf_gs = mcp->mc_gs;
2492 }
2493 if (mcp->mc_flags & _MC_HASBASES) {
2494 pcb->pcb_fsbase = mcp->mc_fsbase;
2495 pcb->pcb_gsbase = mcp->mc_gsbase;
2496 }
2497 set_pcb_flags(pcb, PCB_FULL_IRET);
2498 return (0);
2499 }
2500
2501 static void
2502 get_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpusave,
2503 size_t xfpusave_len)
2504 {
2505 size_t max_len, len;
2506
2507 mcp->mc_ownedfp = fpugetregs(td);
2508 bcopy(get_pcb_user_save_td(td), &mcp->mc_fpstate[0],
2509 sizeof(mcp->mc_fpstate));
2510 mcp->mc_fpformat = fpuformat();
2511 if (!use_xsave || xfpusave_len == 0)
2512 return;
2513 max_len = cpu_max_ext_state_size - sizeof(struct savefpu);
2514 len = xfpusave_len;
2515 if (len > max_len) {
2516 len = max_len;
2517 bzero(xfpusave + max_len, len - max_len);
2518 }
2519 mcp->mc_flags |= _MC_HASFPXSTATE;
2520 mcp->mc_xfpustate_len = len;
2521 bcopy(get_pcb_user_save_td(td) + 1, xfpusave, len);
2522 }
2523
2524 static int
2525 set_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpustate,
2526 size_t xfpustate_len)
2527 {
2528 struct savefpu *fpstate;
2529 int error;
2530
2531 if (mcp->mc_fpformat == _MC_FPFMT_NODEV)
2532 return (0);
2533 else if (mcp->mc_fpformat != _MC_FPFMT_XMM)
2534 return (EINVAL);
2535 else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE) {
2536 /* We don't care what state is left in the FPU or PCB. */
2537 fpstate_drop(td);
2538 error = 0;
2539 } else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU ||
2540 mcp->mc_ownedfp == _MC_FPOWNED_PCB) {
2541 fpstate = (struct savefpu *)&mcp->mc_fpstate;
2542 fpstate->sv_env.en_mxcsr &= cpu_mxcsr_mask;
2543 error = fpusetregs(td, fpstate, xfpustate, xfpustate_len);
2544 } else
2545 return (EINVAL);
2546 return (error);
2547 }
2548
2549 void
2550 fpstate_drop(struct thread *td)
2551 {
2552
2553 KASSERT(PCB_USER_FPU(td->td_pcb), ("fpstate_drop: kernel-owned fpu"));
2554 critical_enter();
2555 if (PCPU_GET(fpcurthread) == td)
2556 fpudrop();
2557 /*
2558 * XXX force a full drop of the fpu. The above only drops it if we
2559 * owned it.
2560 *
2561 * XXX I don't much like fpugetuserregs()'s semantics of doing a full
2562 * drop. Dropping only to the pcb matches fnsave's behaviour.
2563 * We only need to drop to !PCB_INITDONE in sendsig(). But
2564 * sendsig() is the only caller of fpugetuserregs()... perhaps we just
2565 * have too many layers.
2566 */
2567 clear_pcb_flags(curthread->td_pcb,
2568 PCB_FPUINITDONE | PCB_USERFPUINITDONE);
2569 critical_exit();
2570 }
2571
2572 int
2573 fill_dbregs(struct thread *td, struct dbreg *dbregs)
2574 {
2575 struct pcb *pcb;
2576
2577 if (td == NULL) {
2578 dbregs->dr[0] = rdr0();
2579 dbregs->dr[1] = rdr1();
2580 dbregs->dr[2] = rdr2();
2581 dbregs->dr[3] = rdr3();
2582 dbregs->dr[6] = rdr6();
2583 dbregs->dr[7] = rdr7();
2584 } else {
2585 pcb = td->td_pcb;
2586 dbregs->dr[0] = pcb->pcb_dr0;
2587 dbregs->dr[1] = pcb->pcb_dr1;
2588 dbregs->dr[2] = pcb->pcb_dr2;
2589 dbregs->dr[3] = pcb->pcb_dr3;
2590 dbregs->dr[6] = pcb->pcb_dr6;
2591 dbregs->dr[7] = pcb->pcb_dr7;
2592 }
2593 dbregs->dr[4] = 0;
2594 dbregs->dr[5] = 0;
2595 dbregs->dr[8] = 0;
2596 dbregs->dr[9] = 0;
2597 dbregs->dr[10] = 0;
2598 dbregs->dr[11] = 0;
2599 dbregs->dr[12] = 0;
2600 dbregs->dr[13] = 0;
2601 dbregs->dr[14] = 0;
2602 dbregs->dr[15] = 0;
2603 return (0);
2604 }
2605
2606 int
2607 set_dbregs(struct thread *td, struct dbreg *dbregs)
2608 {
2609 struct pcb *pcb;
2610 int i;
2611
2612 if (td == NULL) {
2613 load_dr0(dbregs->dr[0]);
2614 load_dr1(dbregs->dr[1]);
2615 load_dr2(dbregs->dr[2]);
2616 load_dr3(dbregs->dr[3]);
2617 load_dr6(dbregs->dr[6]);
2618 load_dr7(dbregs->dr[7]);
2619 } else {
2620 /*
2621 * Don't let an illegal value for dr7 get set. Specifically,
2622 * check for undefined settings. Setting these bit patterns
2623 * result in undefined behaviour and can lead to an unexpected
2624 * TRCTRAP or a general protection fault right here.
2625 * Upper bits of dr6 and dr7 must not be set
2626 */
2627 for (i = 0; i < 4; i++) {
2628 if (DBREG_DR7_ACCESS(dbregs->dr[7], i) == 0x02)
2629 return (EINVAL);
2630 if (td->td_frame->tf_cs == _ucode32sel &&
2631 DBREG_DR7_LEN(dbregs->dr[7], i) == DBREG_DR7_LEN_8)
2632 return (EINVAL);
2633 }
2634 if ((dbregs->dr[6] & 0xffffffff00000000ul) != 0 ||
2635 (dbregs->dr[7] & 0xffffffff00000000ul) != 0)
2636 return (EINVAL);
2637
2638 pcb = td->td_pcb;
2639
2640 /*
2641 * Don't let a process set a breakpoint that is not within the
2642 * process's address space. If a process could do this, it
2643 * could halt the system by setting a breakpoint in the kernel
2644 * (if ddb was enabled). Thus, we need to check to make sure
2645 * that no breakpoints are being enabled for addresses outside
2646 * process's address space.
2647 *
2648 * XXX - what about when the watched area of the user's
2649 * address space is written into from within the kernel
2650 * ... wouldn't that still cause a breakpoint to be generated
2651 * from within kernel mode?
2652 */
2653
2654 if (DBREG_DR7_ENABLED(dbregs->dr[7], 0)) {
2655 /* dr0 is enabled */
2656 if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS)
2657 return (EINVAL);
2658 }
2659 if (DBREG_DR7_ENABLED(dbregs->dr[7], 1)) {
2660 /* dr1 is enabled */
2661 if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS)
2662 return (EINVAL);
2663 }
2664 if (DBREG_DR7_ENABLED(dbregs->dr[7], 2)) {
2665 /* dr2 is enabled */
2666 if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS)
2667 return (EINVAL);
2668 }
2669 if (DBREG_DR7_ENABLED(dbregs->dr[7], 3)) {
2670 /* dr3 is enabled */
2671 if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS)
2672 return (EINVAL);
2673 }
2674
2675 pcb->pcb_dr0 = dbregs->dr[0];
2676 pcb->pcb_dr1 = dbregs->dr[1];
2677 pcb->pcb_dr2 = dbregs->dr[2];
2678 pcb->pcb_dr3 = dbregs->dr[3];
2679 pcb->pcb_dr6 = dbregs->dr[6];
2680 pcb->pcb_dr7 = dbregs->dr[7];
2681
2682 set_pcb_flags(pcb, PCB_DBREGS);
2683 }
2684
2685 return (0);
2686 }
2687
2688 void
2689 reset_dbregs(void)
2690 {
2691
2692 load_dr7(0); /* Turn off the control bits first */
2693 load_dr0(0);
2694 load_dr1(0);
2695 load_dr2(0);
2696 load_dr3(0);
2697 load_dr6(0);
2698 }
2699
2700 /*
2701 * Return > 0 if a hardware breakpoint has been hit, and the
2702 * breakpoint was in user space. Return 0, otherwise.
2703 */
2704 int
2705 user_dbreg_trap(void)
2706 {
2707 u_int64_t dr7, dr6; /* debug registers dr6 and dr7 */
2708 u_int64_t bp; /* breakpoint bits extracted from dr6 */
2709 int nbp; /* number of breakpoints that triggered */
2710 caddr_t addr[4]; /* breakpoint addresses */
2711 int i;
2712
2713 dr7 = rdr7();
2714 if ((dr7 & 0x000000ff) == 0) {
2715 /*
2716 * all GE and LE bits in the dr7 register are zero,
2717 * thus the trap couldn't have been caused by the
2718 * hardware debug registers
2719 */
2720 return 0;
2721 }
2722
2723 nbp = 0;
2724 dr6 = rdr6();
2725 bp = dr6 & 0x0000000f;
2726
2727 if (!bp) {
2728 /*
2729 * None of the breakpoint bits are set meaning this
2730 * trap was not caused by any of the debug registers
2731 */
2732 return 0;
2733 }
2734
2735 /*
2736 * at least one of the breakpoints were hit, check to see
2737 * which ones and if any of them are user space addresses
2738 */
2739
2740 if (bp & 0x01) {
2741 addr[nbp++] = (caddr_t)rdr0();
2742 }
2743 if (bp & 0x02) {
2744 addr[nbp++] = (caddr_t)rdr1();
2745 }
2746 if (bp & 0x04) {
2747 addr[nbp++] = (caddr_t)rdr2();
2748 }
2749 if (bp & 0x08) {
2750 addr[nbp++] = (caddr_t)rdr3();
2751 }
2752
2753 for (i = 0; i < nbp; i++) {
2754 if (addr[i] < (caddr_t)VM_MAXUSER_ADDRESS) {
2755 /*
2756 * addr[i] is in user space
2757 */
2758 return nbp;
2759 }
2760 }
2761
2762 /*
2763 * None of the breakpoints are in user space.
2764 */
2765 return 0;
2766 }
2767
2768 #ifdef KDB
2769
2770 /*
2771 * Provide inb() and outb() as functions. They are normally only available as
2772 * inline functions, thus cannot be called from the debugger.
2773 */
2774
2775 /* silence compiler warnings */
2776 u_char inb_(u_short);
2777 void outb_(u_short, u_char);
2778
2779 u_char
2780 inb_(u_short port)
2781 {
2782 return inb(port);
2783 }
2784
2785 void
2786 outb_(u_short port, u_char data)
2787 {
2788 outb(port, data);
2789 }
2790
2791 #endif /* KDB */
Cache object: 472be1f861e577304aeafbe404161b7d
|