machdep.c revision 322523
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: stable/10/sys/amd64/amd64/machdep.c 322523 2017-08-14 23:46:10Z jkim $"); 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() */ 152CTASSERT(offsetof(struct pcpu, pc_curthread) == 0); 153 154extern 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 159static void cpu_startup(void *); 160static void get_fpcontext(struct thread *td, mcontext_t *mcp, 161 char *xfpusave, size_t xfpusave_len); 162static int set_fpcontext(struct thread *td, mcontext_t *mcp, 163 char *xfpustate, size_t xfpustate_len); 164SYSINIT(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 */ 170extern char kernphys[]; 171#ifdef DDB 172extern vm_offset_t ksym_start, ksym_end; 173#endif 174 175struct msgbuf *msgbufp; 176 177/* Intel ICH registers */ 178#define ICH_PMBASE 0x400 179#define ICH_SMI_EN ICH_PMBASE + 0x30 180 181int _udatasel, _ucodesel, _ucode32sel, _ufssel, _ugssel; 182 183int cold = 1; 184 185long Maxmem = 0; 186long 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 196vm_paddr_t phys_avail[PHYSMAP_SIZE + 2]; 197vm_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 203struct kva_md_info kmi; 204 205static struct trapframe proc0_tf; 206struct region_descriptor r_gdt, r_idt; 207 208struct pcpu __pcpu[MAXCPU]; 209 210struct mtx icu_lock; 211 212struct mem_range_softc mem_range_softc; 213 214struct mtx dt_lock; /* lock for GDT and LDT */ 215 216void (*vmm_resume_p)(void); 217 218static void 219cpu_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 */ 319void 320sendsig(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 */ 449int 450sys_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 555int 556freebsd4_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 */ 570void 571cpu_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 */ 579void 580cpu_flush_dcache(void *ptr, size_t len) 581{ 582 /* Not applicable */ 583} 584 585/* Get current clock frequency for the given cpu id. */ 586int 587cpu_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 */ 647void 648cpu_halt(void) 649{ 650 for (;;) 651 halt(); 652} 653 654void (*cpu_idle_hook)(sbintime_t) = NULL; /* ACPI idle hook. */ 655static int cpu_ident_amdc1e = 0; /* AMD C1E supported. */ 656static int idle_mwait = 1; /* Use MONITOR/MWAIT for short idle. */ 657TUNABLE_INT("machdep.idle_mwait", &idle_mwait); 658SYSCTL_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 665static void 666cpu_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 684static void 685cpu_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 716static void 717cpu_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 739static void 740cpu_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 774static void 775cpu_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 789void (*cpu_idle_fn)(sbintime_t) = cpu_idle_acpi; 790 791void 792cpu_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 } 831out: 832 CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done", 833 busy, curcpu); 834} 835 836int 837cpu_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 */ 858struct { 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 869static int 870idle_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 893SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD, 894 0, 0, idle_sysctl_available, "A", "list of available idle functions"); 895 896static int 897idle_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 930SYSCTL_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 */ 936void 937exec_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 997void 998cpu_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 1019struct user_segment_descriptor gdt[NGDT * MAXCPU];/* global descriptor tables */ 1020static struct gate_descriptor idt0[NIDT]; 1021struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */ 1022 1023static char dblfault_stack[PAGE_SIZE] __aligned(16); 1024 1025static char nmi0_stack[PAGE_SIZE] __aligned(16); 1026CTASSERT(sizeof(struct nmi_pcpu) == 16); 1027 1028struct 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 */ 1036struct 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 1156void 1157setidt(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 1172extern 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 */ 1191DB_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. */ 1210DB_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 1243DB_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 1255void 1256sdtossd(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 1271void 1272ssdtosd(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 1289void 1290ssdtosyssd(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 */ 1315intrmask_t 1316isa_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 1327u_int basemem; 1328 1329static int 1330add_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 1395static void 1396add_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 1429static void 1430add_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 1520static char bootmethod[16] = ""; 1521SYSCTL_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 */ 1536static void 1537getmemsize(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 1744skip_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++; 1776do_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 } 1788do_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 1820u_int64_t 1821hammer_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 identify_cpu(); 1857 identify_hypervisor(); 1858 1859 /* Init basic tunables, hz etc */ 1860 init_param1(); 1861 1862 /* 1863 * make gdt memory segments 1864 */ 1865 for (x = 0; x < NGDT; x++) { 1866 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1) && 1867 x != GUSERLDT_SEL && x != (GUSERLDT_SEL) + 1) 1868 ssdtosd(&gdt_segs[x], &gdt[x]); 1869 } 1870 gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&common_tss[0]; 1871 ssdtosyssd(&gdt_segs[GPROC0_SEL], 1872 (struct system_segment_descriptor *)&gdt[GPROC0_SEL]); 1873 1874 r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1; 1875 r_gdt.rd_base = (long) gdt; 1876 lgdt(&r_gdt); 1877 pc = &__pcpu[0]; 1878 1879 wrmsr(MSR_FSBASE, 0); /* User value */ 1880 wrmsr(MSR_GSBASE, (u_int64_t)pc); 1881 wrmsr(MSR_KGSBASE, 0); /* User value while in the kernel */ 1882 1883 pcpu_init(pc, 0, sizeof(struct pcpu)); 1884 dpcpu_init((void *)(physfree + KERNBASE), 0); 1885 physfree += DPCPU_SIZE; 1886 PCPU_SET(prvspace, pc); 1887 PCPU_SET(curthread, &thread0); 1888 PCPU_SET(tssp, &common_tss[0]); 1889 PCPU_SET(commontssp, &common_tss[0]); 1890 PCPU_SET(tss, (struct system_segment_descriptor *)&gdt[GPROC0_SEL]); 1891 PCPU_SET(ldt, (struct system_segment_descriptor *)&gdt[GUSERLDT_SEL]); 1892 PCPU_SET(fs32p, &gdt[GUFS32_SEL]); 1893 PCPU_SET(gs32p, &gdt[GUGS32_SEL]); 1894 1895 /* 1896 * Initialize mutexes. 1897 * 1898 * icu_lock: in order to allow an interrupt to occur in a critical 1899 * section, to set pcpu->ipending (etc...) properly, we 1900 * must be able to get the icu lock, so it can't be 1901 * under witness. 1902 */ 1903 mutex_init(); 1904 mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS); 1905 mtx_init(&dt_lock, "descriptor tables", NULL, MTX_DEF); 1906 1907 /* exceptions */ 1908 for (x = 0; x < NIDT; x++) 1909 setidt(x, &IDTVEC(rsvd), SDT_SYSIGT, SEL_KPL, 0); 1910 setidt(IDT_DE, &IDTVEC(div), SDT_SYSIGT, SEL_KPL, 0); 1911 setidt(IDT_DB, &IDTVEC(dbg), SDT_SYSIGT, SEL_KPL, 0); 1912 setidt(IDT_NMI, &IDTVEC(nmi), SDT_SYSIGT, SEL_KPL, 2); 1913 setidt(IDT_BP, &IDTVEC(bpt), SDT_SYSIGT, SEL_UPL, 0); 1914 setidt(IDT_OF, &IDTVEC(ofl), SDT_SYSIGT, SEL_KPL, 0); 1915 setidt(IDT_BR, &IDTVEC(bnd), SDT_SYSIGT, SEL_KPL, 0); 1916 setidt(IDT_UD, &IDTVEC(ill), SDT_SYSIGT, SEL_KPL, 0); 1917 setidt(IDT_NM, &IDTVEC(dna), SDT_SYSIGT, SEL_KPL, 0); 1918 setidt(IDT_DF, &IDTVEC(dblfault), SDT_SYSIGT, SEL_KPL, 1); 1919 setidt(IDT_FPUGP, &IDTVEC(fpusegm), SDT_SYSIGT, SEL_KPL, 0); 1920 setidt(IDT_TS, &IDTVEC(tss), SDT_SYSIGT, SEL_KPL, 0); 1921 setidt(IDT_NP, &IDTVEC(missing), SDT_SYSIGT, SEL_KPL, 0); 1922 setidt(IDT_SS, &IDTVEC(stk), SDT_SYSIGT, SEL_KPL, 0); 1923 setidt(IDT_GP, &IDTVEC(prot), SDT_SYSIGT, SEL_KPL, 0); 1924 setidt(IDT_PF, &IDTVEC(page), SDT_SYSIGT, SEL_KPL, 0); 1925 setidt(IDT_MF, &IDTVEC(fpu), SDT_SYSIGT, SEL_KPL, 0); 1926 setidt(IDT_AC, &IDTVEC(align), SDT_SYSIGT, SEL_KPL, 0); 1927 setidt(IDT_MC, &IDTVEC(mchk), SDT_SYSIGT, SEL_KPL, 0); 1928 setidt(IDT_XF, &IDTVEC(xmm), SDT_SYSIGT, SEL_KPL, 0); 1929#ifdef KDTRACE_HOOKS 1930 setidt(IDT_DTRACE_RET, &IDTVEC(dtrace_ret), SDT_SYSIGT, SEL_UPL, 0); 1931#endif 1932#ifdef XENHVM 1933 setidt(IDT_EVTCHN, &IDTVEC(xen_intr_upcall), SDT_SYSIGT, SEL_UPL, 0); 1934#endif 1935 1936 r_idt.rd_limit = sizeof(idt0) - 1; 1937 r_idt.rd_base = (long) idt; 1938 lidt(&r_idt); 1939 1940 /* 1941 * Initialize the i8254 before the console so that console 1942 * initialization can use DELAY(). 1943 */ 1944 i8254_init(); 1945 1946 /* 1947 * Use vt(4) by default for UEFI boot (during the sc(4)/vt(4) 1948 * transition). 1949 */ 1950 if (kmdp != NULL && preload_search_info(kmdp, 1951 MODINFO_METADATA | MODINFOMD_EFI_MAP) != NULL) 1952 vty_set_preferred(VTY_VT); 1953 1954 finishidentcpu(); /* Final stage of CPU initialization */ 1955 initializecpu(); /* Initialize CPU registers */ 1956 initializecpucache(); 1957 1958 /* doublefault stack space, runs on ist1 */ 1959 common_tss[0].tss_ist1 = (long)&dblfault_stack[sizeof(dblfault_stack)]; 1960 1961 /* 1962 * NMI stack, runs on ist2. The pcpu pointer is stored just 1963 * above the start of the ist2 stack. 1964 */ 1965 np = ((struct nmi_pcpu *) &nmi0_stack[sizeof(nmi0_stack)]) - 1; 1966 np->np_pcpu = (register_t) pc; 1967 common_tss[0].tss_ist2 = (long) np; 1968 1969 /* Set the IO permission bitmap (empty due to tss seg limit) */ 1970 common_tss[0].tss_iobase = sizeof(struct amd64tss) + 1971 IOPAGES * PAGE_SIZE; 1972 1973 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL); 1974 ltr(gsel_tss); 1975 1976 /* Set up the fast syscall stuff */ 1977 msr = rdmsr(MSR_EFER) | EFER_SCE; 1978 wrmsr(MSR_EFER, msr); 1979 wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall)); 1980 wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32)); 1981 msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) | 1982 ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48); 1983 wrmsr(MSR_STAR, msr); 1984 wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D); 1985 1986 getmemsize(kmdp, physfree); 1987 init_param2(physmem); 1988 1989 /* now running on new page tables, configured,and u/iom is accessible */ 1990 1991 cninit(); 1992 1993#ifdef DEV_ISA 1994#ifdef DEV_ATPIC 1995 elcr_probe(); 1996 atpic_startup(); 1997#else 1998 /* Reset and mask the atpics and leave them shut down. */ 1999 atpic_reset(); 2000 2001 /* 2002 * Point the ICU spurious interrupt vectors at the APIC spurious 2003 * interrupt handler. 2004 */ 2005 setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0); 2006 setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0); 2007#endif 2008#else 2009#error "have you forgotten the isa device?"; 2010#endif 2011 2012 kdb_init(); 2013 2014#ifdef KDB 2015 if (boothowto & RB_KDB) 2016 kdb_enter(KDB_WHY_BOOTFLAGS, 2017 "Boot flags requested debugger"); 2018#endif 2019 2020 msgbufinit(msgbufp, msgbufsize); 2021 fpuinit(); 2022 2023 /* 2024 * Set up thread0 pcb after fpuinit calculated pcb + fpu save 2025 * area size. Zero out the extended state header in fpu save 2026 * area. 2027 */ 2028 thread0.td_pcb = get_pcb_td(&thread0); 2029 thread0.td_pcb->pcb_save = get_pcb_user_save_td(&thread0); 2030 bzero(get_pcb_user_save_td(&thread0), cpu_max_ext_state_size); 2031 if (use_xsave) { 2032 xhdr = (struct xstate_hdr *)(get_pcb_user_save_td(&thread0) + 2033 1); 2034 xhdr->xstate_bv = xsave_mask; 2035 } 2036 /* make an initial tss so cpu can get interrupt stack on syscall! */ 2037 common_tss[0].tss_rsp0 = (vm_offset_t)thread0.td_pcb; 2038 /* Ensure the stack is aligned to 16 bytes */ 2039 common_tss[0].tss_rsp0 &= ~0xFul; 2040 PCPU_SET(rsp0, common_tss[0].tss_rsp0); 2041 PCPU_SET(curpcb, thread0.td_pcb); 2042 2043 /* transfer to user mode */ 2044 2045 _ucodesel = GSEL(GUCODE_SEL, SEL_UPL); 2046 _udatasel = GSEL(GUDATA_SEL, SEL_UPL); 2047 _ucode32sel = GSEL(GUCODE32_SEL, SEL_UPL); 2048 _ufssel = GSEL(GUFS32_SEL, SEL_UPL); 2049 _ugssel = GSEL(GUGS32_SEL, SEL_UPL); 2050 2051 load_ds(_udatasel); 2052 load_es(_udatasel); 2053 load_fs(_ufssel); 2054 2055 /* setup proc 0's pcb */ 2056 thread0.td_pcb->pcb_flags = 0; 2057 thread0.td_pcb->pcb_cr3 = KPML4phys; /* PCID 0 is reserved for kernel */ 2058 thread0.td_frame = &proc0_tf; 2059 2060 env = getenv("kernelname"); 2061 if (env != NULL) 2062 strlcpy(kernelname, env, sizeof(kernelname)); 2063 2064 cpu_probe_amdc1e(); 2065 2066#ifdef FDT 2067 x86_init_fdt(); 2068#endif 2069 2070 /* Location of kernel stack for locore */ 2071 return ((u_int64_t)thread0.td_pcb); 2072} 2073 2074void 2075cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size) 2076{ 2077 2078 pcpu->pc_acpi_id = 0xffffffff; 2079} 2080 2081static int 2082smap_sysctl_handler(SYSCTL_HANDLER_ARGS) 2083{ 2084 struct bios_smap *smapbase; 2085 struct bios_smap_xattr smap; 2086 caddr_t kmdp; 2087 uint32_t *smapattr; 2088 int count, error, i; 2089 2090 /* Retrieve the system memory map from the loader. */ 2091 kmdp = preload_search_by_type("elf kernel"); 2092 if (kmdp == NULL) 2093 kmdp = preload_search_by_type("elf64 kernel"); 2094 smapbase = (struct bios_smap *)preload_search_info(kmdp, 2095 MODINFO_METADATA | MODINFOMD_SMAP); 2096 if (smapbase == NULL) 2097 return (0); 2098 smapattr = (uint32_t *)preload_search_info(kmdp, 2099 MODINFO_METADATA | MODINFOMD_SMAP_XATTR); 2100 count = *((uint32_t *)smapbase - 1) / sizeof(*smapbase); 2101 error = 0; 2102 for (i = 0; i < count; i++) { 2103 smap.base = smapbase[i].base; 2104 smap.length = smapbase[i].length; 2105 smap.type = smapbase[i].type; 2106 if (smapattr != NULL) 2107 smap.xattr = smapattr[i]; 2108 else 2109 smap.xattr = 0; 2110 error = SYSCTL_OUT(req, &smap, sizeof(smap)); 2111 } 2112 return (error); 2113} 2114SYSCTL_PROC(_machdep, OID_AUTO, smap, CTLTYPE_OPAQUE|CTLFLAG_RD, NULL, 0, 2115 smap_sysctl_handler, "S,bios_smap_xattr", "Raw BIOS SMAP data"); 2116 2117static int 2118efi_map_sysctl_handler(SYSCTL_HANDLER_ARGS) 2119{ 2120 struct efi_map_header *efihdr; 2121 caddr_t kmdp; 2122 uint32_t efisize; 2123 2124 kmdp = preload_search_by_type("elf kernel"); 2125 if (kmdp == NULL) 2126 kmdp = preload_search_by_type("elf64 kernel"); 2127 efihdr = (struct efi_map_header *)preload_search_info(kmdp, 2128 MODINFO_METADATA | MODINFOMD_EFI_MAP); 2129 if (efihdr == NULL) 2130 return (0); 2131 efisize = *((uint32_t *)efihdr - 1); 2132 return (SYSCTL_OUT(req, efihdr, efisize)); 2133} 2134SYSCTL_PROC(_machdep, OID_AUTO, efi_map, CTLTYPE_OPAQUE|CTLFLAG_RD, NULL, 0, 2135 efi_map_sysctl_handler, "S,efi_map_header", "Raw EFI Memory Map"); 2136 2137void 2138spinlock_enter(void) 2139{ 2140 struct thread *td; 2141 register_t flags; 2142 2143 td = curthread; 2144 if (td->td_md.md_spinlock_count == 0) { 2145 flags = intr_disable(); 2146 td->td_md.md_spinlock_count = 1; 2147 td->td_md.md_saved_flags = flags; 2148 } else 2149 td->td_md.md_spinlock_count++; 2150 critical_enter(); 2151} 2152 2153void 2154spinlock_exit(void) 2155{ 2156 struct thread *td; 2157 register_t flags; 2158 2159 td = curthread; 2160 critical_exit(); 2161 flags = td->td_md.md_saved_flags; 2162 td->td_md.md_spinlock_count--; 2163 if (td->td_md.md_spinlock_count == 0) 2164 intr_restore(flags); 2165} 2166 2167/* 2168 * Construct a PCB from a trapframe. This is called from kdb_trap() where 2169 * we want to start a backtrace from the function that caused us to enter 2170 * the debugger. We have the context in the trapframe, but base the trace 2171 * on the PCB. The PCB doesn't have to be perfect, as long as it contains 2172 * enough for a backtrace. 2173 */ 2174void 2175makectx(struct trapframe *tf, struct pcb *pcb) 2176{ 2177 2178 pcb->pcb_r12 = tf->tf_r12; 2179 pcb->pcb_r13 = tf->tf_r13; 2180 pcb->pcb_r14 = tf->tf_r14; 2181 pcb->pcb_r15 = tf->tf_r15; 2182 pcb->pcb_rbp = tf->tf_rbp; 2183 pcb->pcb_rbx = tf->tf_rbx; 2184 pcb->pcb_rip = tf->tf_rip; 2185 pcb->pcb_rsp = tf->tf_rsp; 2186} 2187 2188int 2189ptrace_set_pc(struct thread *td, unsigned long addr) 2190{ 2191 2192 td->td_frame->tf_rip = addr; 2193 set_pcb_flags(td->td_pcb, PCB_FULL_IRET); 2194 return (0); 2195} 2196 2197int 2198ptrace_single_step(struct thread *td) 2199{ 2200 td->td_frame->tf_rflags |= PSL_T; 2201 return (0); 2202} 2203 2204int 2205ptrace_clear_single_step(struct thread *td) 2206{ 2207 td->td_frame->tf_rflags &= ~PSL_T; 2208 return (0); 2209} 2210 2211int 2212fill_regs(struct thread *td, struct reg *regs) 2213{ 2214 struct trapframe *tp; 2215 2216 tp = td->td_frame; 2217 return (fill_frame_regs(tp, regs)); 2218} 2219 2220int 2221fill_frame_regs(struct trapframe *tp, struct reg *regs) 2222{ 2223 regs->r_r15 = tp->tf_r15; 2224 regs->r_r14 = tp->tf_r14; 2225 regs->r_r13 = tp->tf_r13; 2226 regs->r_r12 = tp->tf_r12; 2227 regs->r_r11 = tp->tf_r11; 2228 regs->r_r10 = tp->tf_r10; 2229 regs->r_r9 = tp->tf_r9; 2230 regs->r_r8 = tp->tf_r8; 2231 regs->r_rdi = tp->tf_rdi; 2232 regs->r_rsi = tp->tf_rsi; 2233 regs->r_rbp = tp->tf_rbp; 2234 regs->r_rbx = tp->tf_rbx; 2235 regs->r_rdx = tp->tf_rdx; 2236 regs->r_rcx = tp->tf_rcx; 2237 regs->r_rax = tp->tf_rax; 2238 regs->r_rip = tp->tf_rip; 2239 regs->r_cs = tp->tf_cs; 2240 regs->r_rflags = tp->tf_rflags; 2241 regs->r_rsp = tp->tf_rsp; 2242 regs->r_ss = tp->tf_ss; 2243 if (tp->tf_flags & TF_HASSEGS) { 2244 regs->r_ds = tp->tf_ds; 2245 regs->r_es = tp->tf_es; 2246 regs->r_fs = tp->tf_fs; 2247 regs->r_gs = tp->tf_gs; 2248 } else { 2249 regs->r_ds = 0; 2250 regs->r_es = 0; 2251 regs->r_fs = 0; 2252 regs->r_gs = 0; 2253 } 2254 return (0); 2255} 2256 2257int 2258set_regs(struct thread *td, struct reg *regs) 2259{ 2260 struct trapframe *tp; 2261 register_t rflags; 2262 2263 tp = td->td_frame; 2264 rflags = regs->r_rflags & 0xffffffff; 2265 if (!EFL_SECURE(rflags, tp->tf_rflags) || !CS_SECURE(regs->r_cs)) 2266 return (EINVAL); 2267 tp->tf_r15 = regs->r_r15; 2268 tp->tf_r14 = regs->r_r14; 2269 tp->tf_r13 = regs->r_r13; 2270 tp->tf_r12 = regs->r_r12; 2271 tp->tf_r11 = regs->r_r11; 2272 tp->tf_r10 = regs->r_r10; 2273 tp->tf_r9 = regs->r_r9; 2274 tp->tf_r8 = regs->r_r8; 2275 tp->tf_rdi = regs->r_rdi; 2276 tp->tf_rsi = regs->r_rsi; 2277 tp->tf_rbp = regs->r_rbp; 2278 tp->tf_rbx = regs->r_rbx; 2279 tp->tf_rdx = regs->r_rdx; 2280 tp->tf_rcx = regs->r_rcx; 2281 tp->tf_rax = regs->r_rax; 2282 tp->tf_rip = regs->r_rip; 2283 tp->tf_cs = regs->r_cs; 2284 tp->tf_rflags = rflags; 2285 tp->tf_rsp = regs->r_rsp; 2286 tp->tf_ss = regs->r_ss; 2287 if (0) { /* XXXKIB */ 2288 tp->tf_ds = regs->r_ds; 2289 tp->tf_es = regs->r_es; 2290 tp->tf_fs = regs->r_fs; 2291 tp->tf_gs = regs->r_gs; 2292 tp->tf_flags = TF_HASSEGS; 2293 } 2294 set_pcb_flags(td->td_pcb, PCB_FULL_IRET); 2295 return (0); 2296} 2297 2298/* XXX check all this stuff! */ 2299/* externalize from sv_xmm */ 2300static void 2301fill_fpregs_xmm(struct savefpu *sv_xmm, struct fpreg *fpregs) 2302{ 2303 struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env; 2304 struct envxmm *penv_xmm = &sv_xmm->sv_env; 2305 int i; 2306 2307 /* pcb -> fpregs */ 2308 bzero(fpregs, sizeof(*fpregs)); 2309 2310 /* FPU control/status */ 2311 penv_fpreg->en_cw = penv_xmm->en_cw; 2312 penv_fpreg->en_sw = penv_xmm->en_sw; 2313 penv_fpreg->en_tw = penv_xmm->en_tw; 2314 penv_fpreg->en_opcode = penv_xmm->en_opcode; 2315 penv_fpreg->en_rip = penv_xmm->en_rip; 2316 penv_fpreg->en_rdp = penv_xmm->en_rdp; 2317 penv_fpreg->en_mxcsr = penv_xmm->en_mxcsr; 2318 penv_fpreg->en_mxcsr_mask = penv_xmm->en_mxcsr_mask; 2319 2320 /* FPU registers */ 2321 for (i = 0; i < 8; ++i) 2322 bcopy(sv_xmm->sv_fp[i].fp_acc.fp_bytes, fpregs->fpr_acc[i], 10); 2323 2324 /* SSE registers */ 2325 for (i = 0; i < 16; ++i) 2326 bcopy(sv_xmm->sv_xmm[i].xmm_bytes, fpregs->fpr_xacc[i], 16); 2327} 2328 2329/* internalize from fpregs into sv_xmm */ 2330static void 2331set_fpregs_xmm(struct fpreg *fpregs, struct savefpu *sv_xmm) 2332{ 2333 struct envxmm *penv_xmm = &sv_xmm->sv_env; 2334 struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env; 2335 int i; 2336 2337 /* fpregs -> pcb */ 2338 /* FPU control/status */ 2339 penv_xmm->en_cw = penv_fpreg->en_cw; 2340 penv_xmm->en_sw = penv_fpreg->en_sw; 2341 penv_xmm->en_tw = penv_fpreg->en_tw; 2342 penv_xmm->en_opcode = penv_fpreg->en_opcode; 2343 penv_xmm->en_rip = penv_fpreg->en_rip; 2344 penv_xmm->en_rdp = penv_fpreg->en_rdp; 2345 penv_xmm->en_mxcsr = penv_fpreg->en_mxcsr; 2346 penv_xmm->en_mxcsr_mask = penv_fpreg->en_mxcsr_mask & cpu_mxcsr_mask; 2347 2348 /* FPU registers */ 2349 for (i = 0; i < 8; ++i) 2350 bcopy(fpregs->fpr_acc[i], sv_xmm->sv_fp[i].fp_acc.fp_bytes, 10); 2351 2352 /* SSE registers */ 2353 for (i = 0; i < 16; ++i) 2354 bcopy(fpregs->fpr_xacc[i], sv_xmm->sv_xmm[i].xmm_bytes, 16); 2355} 2356 2357/* externalize from td->pcb */ 2358int 2359fill_fpregs(struct thread *td, struct fpreg *fpregs) 2360{ 2361 2362 KASSERT(td == curthread || TD_IS_SUSPENDED(td) || 2363 P_SHOULDSTOP(td->td_proc), 2364 ("not suspended thread %p", td)); 2365 fpugetregs(td); 2366 fill_fpregs_xmm(get_pcb_user_save_td(td), fpregs); 2367 return (0); 2368} 2369 2370/* internalize to td->pcb */ 2371int 2372set_fpregs(struct thread *td, struct fpreg *fpregs) 2373{ 2374 2375 set_fpregs_xmm(fpregs, get_pcb_user_save_td(td)); 2376 fpuuserinited(td); 2377 return (0); 2378} 2379 2380/* 2381 * Get machine context. 2382 */ 2383int 2384get_mcontext(struct thread *td, mcontext_t *mcp, int flags) 2385{ 2386 struct pcb *pcb; 2387 struct trapframe *tp; 2388 2389 pcb = td->td_pcb; 2390 tp = td->td_frame; 2391 PROC_LOCK(curthread->td_proc); 2392 mcp->mc_onstack = sigonstack(tp->tf_rsp); 2393 PROC_UNLOCK(curthread->td_proc); 2394 mcp->mc_r15 = tp->tf_r15; 2395 mcp->mc_r14 = tp->tf_r14; 2396 mcp->mc_r13 = tp->tf_r13; 2397 mcp->mc_r12 = tp->tf_r12; 2398 mcp->mc_r11 = tp->tf_r11; 2399 mcp->mc_r10 = tp->tf_r10; 2400 mcp->mc_r9 = tp->tf_r9; 2401 mcp->mc_r8 = tp->tf_r8; 2402 mcp->mc_rdi = tp->tf_rdi; 2403 mcp->mc_rsi = tp->tf_rsi; 2404 mcp->mc_rbp = tp->tf_rbp; 2405 mcp->mc_rbx = tp->tf_rbx; 2406 mcp->mc_rcx = tp->tf_rcx; 2407 mcp->mc_rflags = tp->tf_rflags; 2408 if (flags & GET_MC_CLEAR_RET) { 2409 mcp->mc_rax = 0; 2410 mcp->mc_rdx = 0; 2411 mcp->mc_rflags &= ~PSL_C; 2412 } else { 2413 mcp->mc_rax = tp->tf_rax; 2414 mcp->mc_rdx = tp->tf_rdx; 2415 } 2416 mcp->mc_rip = tp->tf_rip; 2417 mcp->mc_cs = tp->tf_cs; 2418 mcp->mc_rsp = tp->tf_rsp; 2419 mcp->mc_ss = tp->tf_ss; 2420 mcp->mc_ds = tp->tf_ds; 2421 mcp->mc_es = tp->tf_es; 2422 mcp->mc_fs = tp->tf_fs; 2423 mcp->mc_gs = tp->tf_gs; 2424 mcp->mc_flags = tp->tf_flags; 2425 mcp->mc_len = sizeof(*mcp); 2426 get_fpcontext(td, mcp, NULL, 0); 2427 mcp->mc_fsbase = pcb->pcb_fsbase; 2428 mcp->mc_gsbase = pcb->pcb_gsbase; 2429 mcp->mc_xfpustate = 0; 2430 mcp->mc_xfpustate_len = 0; 2431 bzero(mcp->mc_spare, sizeof(mcp->mc_spare)); 2432 return (0); 2433} 2434 2435/* 2436 * Set machine context. 2437 * 2438 * However, we don't set any but the user modifiable flags, and we won't 2439 * touch the cs selector. 2440 */ 2441int 2442set_mcontext(struct thread *td, mcontext_t *mcp) 2443{ 2444 struct pcb *pcb; 2445 struct trapframe *tp; 2446 char *xfpustate; 2447 long rflags; 2448 int ret; 2449 2450 pcb = td->td_pcb; 2451 tp = td->td_frame; 2452 if (mcp->mc_len != sizeof(*mcp) || 2453 (mcp->mc_flags & ~_MC_FLAG_MASK) != 0) 2454 return (EINVAL); 2455 rflags = (mcp->mc_rflags & PSL_USERCHANGE) | 2456 (tp->tf_rflags & ~PSL_USERCHANGE); 2457 if (mcp->mc_flags & _MC_HASFPXSTATE) { 2458 if (mcp->mc_xfpustate_len > cpu_max_ext_state_size - 2459 sizeof(struct savefpu)) 2460 return (EINVAL); 2461 xfpustate = __builtin_alloca(mcp->mc_xfpustate_len); 2462 ret = copyin((void *)mcp->mc_xfpustate, xfpustate, 2463 mcp->mc_xfpustate_len); 2464 if (ret != 0) 2465 return (ret); 2466 } else 2467 xfpustate = NULL; 2468 ret = set_fpcontext(td, mcp, xfpustate, mcp->mc_xfpustate_len); 2469 if (ret != 0) 2470 return (ret); 2471 tp->tf_r15 = mcp->mc_r15; 2472 tp->tf_r14 = mcp->mc_r14; 2473 tp->tf_r13 = mcp->mc_r13; 2474 tp->tf_r12 = mcp->mc_r12; 2475 tp->tf_r11 = mcp->mc_r11; 2476 tp->tf_r10 = mcp->mc_r10; 2477 tp->tf_r9 = mcp->mc_r9; 2478 tp->tf_r8 = mcp->mc_r8; 2479 tp->tf_rdi = mcp->mc_rdi; 2480 tp->tf_rsi = mcp->mc_rsi; 2481 tp->tf_rbp = mcp->mc_rbp; 2482 tp->tf_rbx = mcp->mc_rbx; 2483 tp->tf_rdx = mcp->mc_rdx; 2484 tp->tf_rcx = mcp->mc_rcx; 2485 tp->tf_rax = mcp->mc_rax; 2486 tp->tf_rip = mcp->mc_rip; 2487 tp->tf_rflags = rflags; 2488 tp->tf_rsp = mcp->mc_rsp; 2489 tp->tf_ss = mcp->mc_ss; 2490 tp->tf_flags = mcp->mc_flags; 2491 if (tp->tf_flags & TF_HASSEGS) { 2492 tp->tf_ds = mcp->mc_ds; 2493 tp->tf_es = mcp->mc_es; 2494 tp->tf_fs = mcp->mc_fs; 2495 tp->tf_gs = mcp->mc_gs; 2496 } 2497 if (mcp->mc_flags & _MC_HASBASES) { 2498 pcb->pcb_fsbase = mcp->mc_fsbase; 2499 pcb->pcb_gsbase = mcp->mc_gsbase; 2500 } 2501 set_pcb_flags(pcb, PCB_FULL_IRET); 2502 return (0); 2503} 2504 2505static void 2506get_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpusave, 2507 size_t xfpusave_len) 2508{ 2509 size_t max_len, len; 2510 2511 mcp->mc_ownedfp = fpugetregs(td); 2512 bcopy(get_pcb_user_save_td(td), &mcp->mc_fpstate[0], 2513 sizeof(mcp->mc_fpstate)); 2514 mcp->mc_fpformat = fpuformat(); 2515 if (!use_xsave || xfpusave_len == 0) 2516 return; 2517 max_len = cpu_max_ext_state_size - sizeof(struct savefpu); 2518 len = xfpusave_len; 2519 if (len > max_len) { 2520 len = max_len; 2521 bzero(xfpusave + max_len, len - max_len); 2522 } 2523 mcp->mc_flags |= _MC_HASFPXSTATE; 2524 mcp->mc_xfpustate_len = len; 2525 bcopy(get_pcb_user_save_td(td) + 1, xfpusave, len); 2526} 2527 2528static int 2529set_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpustate, 2530 size_t xfpustate_len) 2531{ 2532 struct savefpu *fpstate; 2533 int error; 2534 2535 if (mcp->mc_fpformat == _MC_FPFMT_NODEV) 2536 return (0); 2537 else if (mcp->mc_fpformat != _MC_FPFMT_XMM) 2538 return (EINVAL); 2539 else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE) { 2540 /* We don't care what state is left in the FPU or PCB. */ 2541 fpstate_drop(td); 2542 error = 0; 2543 } else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU || 2544 mcp->mc_ownedfp == _MC_FPOWNED_PCB) { 2545 fpstate = (struct savefpu *)&mcp->mc_fpstate; 2546 fpstate->sv_env.en_mxcsr &= cpu_mxcsr_mask; 2547 error = fpusetregs(td, fpstate, xfpustate, xfpustate_len); 2548 } else 2549 return (EINVAL); 2550 return (error); 2551} 2552 2553void 2554fpstate_drop(struct thread *td) 2555{ 2556 2557 KASSERT(PCB_USER_FPU(td->td_pcb), ("fpstate_drop: kernel-owned fpu")); 2558 critical_enter(); 2559 if (PCPU_GET(fpcurthread) == td) 2560 fpudrop(); 2561 /* 2562 * XXX force a full drop of the fpu. The above only drops it if we 2563 * owned it. 2564 * 2565 * XXX I don't much like fpugetuserregs()'s semantics of doing a full 2566 * drop. Dropping only to the pcb matches fnsave's behaviour. 2567 * We only need to drop to !PCB_INITDONE in sendsig(). But 2568 * sendsig() is the only caller of fpugetuserregs()... perhaps we just 2569 * have too many layers. 2570 */ 2571 clear_pcb_flags(curthread->td_pcb, 2572 PCB_FPUINITDONE | PCB_USERFPUINITDONE); 2573 critical_exit(); 2574} 2575 2576int 2577fill_dbregs(struct thread *td, struct dbreg *dbregs) 2578{ 2579 struct pcb *pcb; 2580 2581 if (td == NULL) { 2582 dbregs->dr[0] = rdr0(); 2583 dbregs->dr[1] = rdr1(); 2584 dbregs->dr[2] = rdr2(); 2585 dbregs->dr[3] = rdr3(); 2586 dbregs->dr[6] = rdr6(); 2587 dbregs->dr[7] = rdr7(); 2588 } else { 2589 pcb = td->td_pcb; 2590 dbregs->dr[0] = pcb->pcb_dr0; 2591 dbregs->dr[1] = pcb->pcb_dr1; 2592 dbregs->dr[2] = pcb->pcb_dr2; 2593 dbregs->dr[3] = pcb->pcb_dr3; 2594 dbregs->dr[6] = pcb->pcb_dr6; 2595 dbregs->dr[7] = pcb->pcb_dr7; 2596 } 2597 dbregs->dr[4] = 0; 2598 dbregs->dr[5] = 0; 2599 dbregs->dr[8] = 0; 2600 dbregs->dr[9] = 0; 2601 dbregs->dr[10] = 0; 2602 dbregs->dr[11] = 0; 2603 dbregs->dr[12] = 0; 2604 dbregs->dr[13] = 0; 2605 dbregs->dr[14] = 0; 2606 dbregs->dr[15] = 0; 2607 return (0); 2608} 2609 2610int 2611set_dbregs(struct thread *td, struct dbreg *dbregs) 2612{ 2613 struct pcb *pcb; 2614 int i; 2615 2616 if (td == NULL) { 2617 load_dr0(dbregs->dr[0]); 2618 load_dr1(dbregs->dr[1]); 2619 load_dr2(dbregs->dr[2]); 2620 load_dr3(dbregs->dr[3]); 2621 load_dr6(dbregs->dr[6]); 2622 load_dr7(dbregs->dr[7]); 2623 } else { 2624 /* 2625 * Don't let an illegal value for dr7 get set. Specifically, 2626 * check for undefined settings. Setting these bit patterns 2627 * result in undefined behaviour and can lead to an unexpected 2628 * TRCTRAP or a general protection fault right here. 2629 * Upper bits of dr6 and dr7 must not be set 2630 */ 2631 for (i = 0; i < 4; i++) { 2632 if (DBREG_DR7_ACCESS(dbregs->dr[7], i) == 0x02) 2633 return (EINVAL); 2634 if (td->td_frame->tf_cs == _ucode32sel && 2635 DBREG_DR7_LEN(dbregs->dr[7], i) == DBREG_DR7_LEN_8) 2636 return (EINVAL); 2637 } 2638 if ((dbregs->dr[6] & 0xffffffff00000000ul) != 0 || 2639 (dbregs->dr[7] & 0xffffffff00000000ul) != 0) 2640 return (EINVAL); 2641 2642 pcb = td->td_pcb; 2643 2644 /* 2645 * Don't let a process set a breakpoint that is not within the 2646 * process's address space. If a process could do this, it 2647 * could halt the system by setting a breakpoint in the kernel 2648 * (if ddb was enabled). Thus, we need to check to make sure 2649 * that no breakpoints are being enabled for addresses outside 2650 * process's address space. 2651 * 2652 * XXX - what about when the watched area of the user's 2653 * address space is written into from within the kernel 2654 * ... wouldn't that still cause a breakpoint to be generated 2655 * from within kernel mode? 2656 */ 2657 2658 if (DBREG_DR7_ENABLED(dbregs->dr[7], 0)) { 2659 /* dr0 is enabled */ 2660 if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS) 2661 return (EINVAL); 2662 } 2663 if (DBREG_DR7_ENABLED(dbregs->dr[7], 1)) { 2664 /* dr1 is enabled */ 2665 if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS) 2666 return (EINVAL); 2667 } 2668 if (DBREG_DR7_ENABLED(dbregs->dr[7], 2)) { 2669 /* dr2 is enabled */ 2670 if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS) 2671 return (EINVAL); 2672 } 2673 if (DBREG_DR7_ENABLED(dbregs->dr[7], 3)) { 2674 /* dr3 is enabled */ 2675 if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS) 2676 return (EINVAL); 2677 } 2678 2679 pcb->pcb_dr0 = dbregs->dr[0]; 2680 pcb->pcb_dr1 = dbregs->dr[1]; 2681 pcb->pcb_dr2 = dbregs->dr[2]; 2682 pcb->pcb_dr3 = dbregs->dr[3]; 2683 pcb->pcb_dr6 = dbregs->dr[6]; 2684 pcb->pcb_dr7 = dbregs->dr[7]; 2685 2686 set_pcb_flags(pcb, PCB_DBREGS); 2687 } 2688 2689 return (0); 2690} 2691 2692void 2693reset_dbregs(void) 2694{ 2695 2696 load_dr7(0); /* Turn off the control bits first */ 2697 load_dr0(0); 2698 load_dr1(0); 2699 load_dr2(0); 2700 load_dr3(0); 2701 load_dr6(0); 2702} 2703 2704/* 2705 * Return > 0 if a hardware breakpoint has been hit, and the 2706 * breakpoint was in user space. Return 0, otherwise. 2707 */ 2708int 2709user_dbreg_trap(void) 2710{ 2711 u_int64_t dr7, dr6; /* debug registers dr6 and dr7 */ 2712 u_int64_t bp; /* breakpoint bits extracted from dr6 */ 2713 int nbp; /* number of breakpoints that triggered */ 2714 caddr_t addr[4]; /* breakpoint addresses */ 2715 int i; 2716 2717 dr7 = rdr7(); 2718 if ((dr7 & 0x000000ff) == 0) { 2719 /* 2720 * all GE and LE bits in the dr7 register are zero, 2721 * thus the trap couldn't have been caused by the 2722 * hardware debug registers 2723 */ 2724 return 0; 2725 } 2726 2727 nbp = 0; 2728 dr6 = rdr6(); 2729 bp = dr6 & 0x0000000f; 2730 2731 if (!bp) { 2732 /* 2733 * None of the breakpoint bits are set meaning this 2734 * trap was not caused by any of the debug registers 2735 */ 2736 return 0; 2737 } 2738 2739 /* 2740 * at least one of the breakpoints were hit, check to see 2741 * which ones and if any of them are user space addresses 2742 */ 2743 2744 if (bp & 0x01) { 2745 addr[nbp++] = (caddr_t)rdr0(); 2746 } 2747 if (bp & 0x02) { 2748 addr[nbp++] = (caddr_t)rdr1(); 2749 } 2750 if (bp & 0x04) { 2751 addr[nbp++] = (caddr_t)rdr2(); 2752 } 2753 if (bp & 0x08) { 2754 addr[nbp++] = (caddr_t)rdr3(); 2755 } 2756 2757 for (i = 0; i < nbp; i++) { 2758 if (addr[i] < (caddr_t)VM_MAXUSER_ADDRESS) { 2759 /* 2760 * addr[i] is in user space 2761 */ 2762 return nbp; 2763 } 2764 } 2765 2766 /* 2767 * None of the breakpoints are in user space. 2768 */ 2769 return 0; 2770} 2771 2772#ifdef KDB 2773 2774/* 2775 * Provide inb() and outb() as functions. They are normally only available as 2776 * inline functions, thus cannot be called from the debugger. 2777 */ 2778 2779/* silence compiler warnings */ 2780u_char inb_(u_short); 2781void outb_(u_short, u_char); 2782 2783u_char 2784inb_(u_short port) 2785{ 2786 return inb(port); 2787} 2788 2789void 2790outb_(u_short port, u_char data) 2791{ 2792 outb(port, data); 2793} 2794 2795#endif /* KDB */ 2796