The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/amd64/amd64/machdep.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    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/7.3/sys/amd64/amd64/machdep.c 203047 2010-01-26 20:58:09Z jhb $");
   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_msgbuf.h"
   55 #include "opt_perfmon.h"
   56 
   57 #include <sys/param.h>
   58 #include <sys/proc.h>
   59 #include <sys/systm.h>
   60 #include <sys/bio.h>
   61 #include <sys/buf.h>
   62 #include <sys/bus.h>
   63 #include <sys/callout.h>
   64 #include <sys/clock.h>
   65 #include <sys/cons.h>
   66 #include <sys/cpu.h>
   67 #include <sys/eventhandler.h>
   68 #include <sys/exec.h>
   69 #include <sys/imgact.h>
   70 #include <sys/kdb.h>
   71 #include <sys/kernel.h>
   72 #include <sys/ktr.h>
   73 #include <sys/linker.h>
   74 #include <sys/lock.h>
   75 #include <sys/malloc.h>
   76 #include <sys/memrange.h>
   77 #include <sys/msgbuf.h>
   78 #include <sys/mutex.h>
   79 #include <sys/pcpu.h>
   80 #include <sys/ptrace.h>
   81 #include <sys/reboot.h>
   82 #include <sys/sched.h>
   83 #include <sys/signalvar.h>
   84 #include <sys/sysctl.h>
   85 #include <sys/sysent.h>
   86 #include <sys/sysproto.h>
   87 #include <sys/ucontext.h>
   88 #include <sys/vmmeter.h>
   89 
   90 #include <vm/vm.h>
   91 #include <vm/vm_extern.h>
   92 #include <vm/vm_kern.h>
   93 #include <vm/vm_page.h>
   94 #include <vm/vm_map.h>
   95 #include <vm/vm_object.h>
   96 #include <vm/vm_pager.h>
   97 #include <vm/vm_param.h>
   98 
   99 #ifdef DDB
  100 #ifndef KDB
  101 #error KDB must be enabled in order for DDB to work!
  102 #endif
  103 #endif
  104 #include <ddb/ddb.h>
  105 
  106 #include <net/netisr.h>
  107 
  108 #include <machine/clock.h>
  109 #include <machine/cpu.h>
  110 #include <machine/cputypes.h>
  111 #include <machine/intr_machdep.h>
  112 #include <machine/mca.h>
  113 #include <machine/md_var.h>
  114 #include <machine/metadata.h>
  115 #include <machine/pc/bios.h>
  116 #include <machine/pcb.h>
  117 #include <machine/proc.h>
  118 #include <machine/reg.h>
  119 #include <machine/sigframe.h>
  120 #include <machine/specialreg.h>
  121 #ifdef PERFMON
  122 #include <machine/perfmon.h>
  123 #endif
  124 #include <machine/tss.h>
  125 #ifdef SMP
  126 #include <machine/smp.h>
  127 #endif
  128 
  129 #ifdef DEV_ATPIC
  130 #include <amd64/isa/icu.h>
  131 #else
  132 #include <machine/apicvar.h>
  133 #endif
  134 
  135 #include <isa/isareg.h>
  136 #include <isa/rtc.h>
  137 
  138 /* Sanity check for __curthread() */
  139 CTASSERT(offsetof(struct pcpu, pc_curthread) == 0);
  140 
  141 extern u_int64_t hammer_time(u_int64_t, u_int64_t);
  142 
  143 extern void printcpuinfo(void); /* XXX header file */
  144 extern void identify_cpu(void);
  145 extern void panicifcpuunsupported(void);
  146 
  147 #define CS_SECURE(cs)           (ISPL(cs) == SEL_UPL)
  148 #define EFL_SECURE(ef, oef)     ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
  149 
  150 static void cpu_startup(void *);
  151 static void get_fpcontext(struct thread *td, mcontext_t *mcp);
  152 static int  set_fpcontext(struct thread *td, const mcontext_t *mcp);
  153 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
  154 
  155 #ifdef DDB
  156 extern vm_offset_t ksym_start, ksym_end;
  157 #endif
  158 
  159 /* Intel ICH registers */
  160 #define ICH_PMBASE      0x400
  161 #define ICH_SMI_EN      ICH_PMBASE + 0x30
  162 
  163 int     _udatasel, _ucodesel, _ucode32sel;
  164 
  165 int cold = 1;
  166 
  167 long Maxmem = 0;
  168 long realmem = 0;
  169 
  170 /*
  171  * The number of PHYSMAP entries must be one less than the number of
  172  * PHYSSEG entries because the PHYSMAP entry that spans the largest
  173  * physical address that is accessible by ISA DMA is split into two
  174  * PHYSSEG entries.
  175  */
  176 #define PHYSMAP_SIZE    (2 * (VM_PHYSSEG_MAX - 1))
  177 
  178 vm_paddr_t phys_avail[PHYSMAP_SIZE + 2];
  179 vm_paddr_t dump_avail[PHYSMAP_SIZE + 2];
  180 
  181 /* must be 2 less so 0 0 can signal end of chunks */
  182 #define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(phys_avail[0])) - 2)
  183 #define DUMP_AVAIL_ARRAY_END ((sizeof(dump_avail) / sizeof(dump_avail[0])) - 2)
  184 
  185 struct kva_md_info kmi;
  186 
  187 static struct trapframe proc0_tf;
  188 struct region_descriptor r_gdt, r_idt;
  189 
  190 struct pcpu __pcpu[MAXCPU];
  191 
  192 struct mtx icu_lock;
  193 
  194 struct mem_range_softc mem_range_softc;
  195 
  196 static void
  197 cpu_startup(dummy)
  198         void *dummy;
  199 {
  200         char *sysenv;
  201 
  202         /*
  203          * On MacBooks, we need to disallow the legacy USB circuit to
  204          * generate an SMI# because this can cause several problems,
  205          * namely: incorrect CPU frequency detection and failure to
  206          * start the APs.
  207          * We do this by disabling a bit in the SMI_EN (SMI Control and
  208          * Enable register) of the Intel ICH LPC Interface Bridge. 
  209          */
  210         sysenv = getenv("smbios.system.product");
  211         if (sysenv != NULL) {
  212                 if (strncmp(sysenv, "MacBook", 7) == 0) {
  213                         if (bootverbose)
  214                                 printf("Disabling LEGACY_USB_EN bit on "
  215                                     "Intel ICH.\n");
  216                         outl(ICH_SMI_EN, inl(ICH_SMI_EN) & ~0x8);
  217                 }
  218                 freeenv(sysenv);
  219         }
  220 
  221         /*
  222          * Good {morning,afternoon,evening,night}.
  223          */
  224         startrtclock();
  225         printcpuinfo();
  226         panicifcpuunsupported();
  227 #ifdef PERFMON
  228         perfmon_init();
  229 #endif
  230         printf("usable memory = %ju (%ju MB)\n", ptoa((uintmax_t)physmem),
  231             ptoa((uintmax_t)physmem) / 1048576);
  232         realmem = Maxmem;
  233         /*
  234          * Display any holes after the first chunk of extended memory.
  235          */
  236         if (bootverbose) {
  237                 int indx;
  238 
  239                 printf("Physical memory chunk(s):\n");
  240                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
  241                         vm_paddr_t size;
  242 
  243                         size = phys_avail[indx + 1] - phys_avail[indx];
  244                         printf(
  245                             "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
  246                             (uintmax_t)phys_avail[indx],
  247                             (uintmax_t)phys_avail[indx + 1] - 1,
  248                             (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
  249                 }
  250         }
  251 
  252         vm_ksubmap_init(&kmi);
  253 
  254         printf("avail memory  = %ju (%ju MB)\n",
  255             ptoa((uintmax_t)cnt.v_free_count),
  256             ptoa((uintmax_t)cnt.v_free_count) / 1048576);
  257 
  258         /*
  259          * Set up buffers, so they can be used to read disk labels.
  260          */
  261         bufinit();
  262         vm_pager_bufferinit();
  263 
  264         cpu_setregs();
  265         mca_init();
  266 }
  267 
  268 /*
  269  * Send an interrupt to process.
  270  *
  271  * Stack is set up to allow sigcode stored
  272  * at top to call routine, followed by kcall
  273  * to sigreturn routine below.  After sigreturn
  274  * resets the signal mask, the stack, and the
  275  * frame pointer, it returns to the user
  276  * specified pc, psl.
  277  */
  278 void
  279 sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
  280 {
  281         struct sigframe sf, *sfp;
  282         struct proc *p;
  283         struct thread *td;
  284         struct sigacts *psp;
  285         char *sp;
  286         struct trapframe *regs;
  287         int sig;
  288         int oonstack;
  289 
  290         td = curthread;
  291         p = td->td_proc;
  292         PROC_LOCK_ASSERT(p, MA_OWNED);
  293         sig = ksi->ksi_signo;
  294         psp = p->p_sigacts;
  295         mtx_assert(&psp->ps_mtx, MA_OWNED);
  296         regs = td->td_frame;
  297         oonstack = sigonstack(regs->tf_rsp);
  298 
  299         /* Save user context. */
  300         bzero(&sf, sizeof(sf));
  301         sf.sf_uc.uc_sigmask = *mask;
  302         sf.sf_uc.uc_stack = td->td_sigstk;
  303         sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
  304             ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
  305         sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
  306         bcopy(regs, &sf.sf_uc.uc_mcontext.mc_rdi, sizeof(*regs));
  307         sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext); /* magic */
  308         get_fpcontext(td, &sf.sf_uc.uc_mcontext);
  309         fpstate_drop(td);
  310 
  311         /* Allocate space for the signal handler context. */
  312         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
  313             SIGISMEMBER(psp->ps_sigonstack, sig)) {
  314                 sp = td->td_sigstk.ss_sp +
  315                     td->td_sigstk.ss_size - sizeof(struct sigframe);
  316 #if defined(COMPAT_43)
  317                 td->td_sigstk.ss_flags |= SS_ONSTACK;
  318 #endif
  319         } else
  320                 sp = (char *)regs->tf_rsp - sizeof(struct sigframe) - 128;
  321         /* Align to 16 bytes. */
  322         sfp = (struct sigframe *)((unsigned long)sp & ~0xFul);
  323 
  324         /* Translate the signal if appropriate. */
  325         if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
  326                 sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
  327 
  328         /* Build the argument list for the signal handler. */
  329         regs->tf_rdi = sig;                     /* arg 1 in %rdi */
  330         regs->tf_rdx = (register_t)&sfp->sf_uc; /* arg 3 in %rdx */
  331         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
  332                 /* Signal handler installed with SA_SIGINFO. */
  333                 regs->tf_rsi = (register_t)&sfp->sf_si; /* arg 2 in %rsi */
  334                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
  335 
  336                 /* Fill in POSIX parts */
  337                 sf.sf_si = ksi->ksi_info;
  338                 sf.sf_si.si_signo = sig; /* maybe a translated signal */
  339                 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
  340         } else {
  341                 /* Old FreeBSD-style arguments. */
  342                 regs->tf_rsi = ksi->ksi_code;   /* arg 2 in %rsi */
  343                 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
  344                 sf.sf_ahu.sf_handler = catcher;
  345         }
  346         mtx_unlock(&psp->ps_mtx);
  347         PROC_UNLOCK(p);
  348 
  349         /*
  350          * Copy the sigframe out to the user's stack.
  351          */
  352         if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
  353 #ifdef DEBUG
  354                 printf("process %ld has trashed its stack\n", (long)p->p_pid);
  355 #endif
  356                 PROC_LOCK(p);
  357                 sigexit(td, SIGILL);
  358         }
  359 
  360         regs->tf_rsp = (long)sfp;
  361         regs->tf_rip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
  362         regs->tf_rflags &= ~(PSL_T | PSL_D);
  363         regs->tf_cs = _ucodesel;
  364         PROC_LOCK(p);
  365         mtx_lock(&psp->ps_mtx);
  366 }
  367 
  368 /*
  369  * System call to cleanup state after a signal
  370  * has been taken.  Reset signal mask and
  371  * stack state from context left by sendsig (above).
  372  * Return to previous pc and psl as specified by
  373  * context left by sendsig. Check carefully to
  374  * make sure that the user has not modified the
  375  * state to gain improper privileges.
  376  *
  377  * MPSAFE
  378  */
  379 int
  380 sigreturn(td, uap)
  381         struct thread *td;
  382         struct sigreturn_args /* {
  383                 const struct __ucontext *sigcntxp;
  384         } */ *uap;
  385 {
  386         ucontext_t uc;
  387         struct proc *p = td->td_proc;
  388         struct trapframe *regs;
  389         const ucontext_t *ucp;
  390         long rflags;
  391         int cs, error, ret;
  392         ksiginfo_t ksi;
  393 
  394         error = copyin(uap->sigcntxp, &uc, sizeof(uc));
  395         if (error != 0)
  396                 return (error);
  397         ucp = &uc;
  398         regs = td->td_frame;
  399         rflags = ucp->uc_mcontext.mc_rflags;
  400         /*
  401          * Don't allow users to change privileged or reserved flags.
  402          */
  403         /*
  404          * XXX do allow users to change the privileged flag PSL_RF.
  405          * The cpu sets PSL_RF in tf_rflags for faults.  Debuggers
  406          * should sometimes set it there too.  tf_rflags is kept in
  407          * the signal context during signal handling and there is no
  408          * other place to remember it, so the PSL_RF bit may be
  409          * corrupted by the signal handler without us knowing.
  410          * Corruption of the PSL_RF bit at worst causes one more or
  411          * one less debugger trap, so allowing it is fairly harmless.
  412          */
  413         if (!EFL_SECURE(rflags & ~PSL_RF, regs->tf_rflags & ~PSL_RF)) {
  414                 printf("sigreturn: rflags = 0x%lx\n", rflags);
  415                 return (EINVAL);
  416         }
  417 
  418         /*
  419          * Don't allow users to load a valid privileged %cs.  Let the
  420          * hardware check for invalid selectors, excess privilege in
  421          * other selectors, invalid %eip's and invalid %esp's.
  422          */
  423         cs = ucp->uc_mcontext.mc_cs;
  424         if (!CS_SECURE(cs)) {
  425                 printf("sigreturn: cs = 0x%x\n", cs);
  426                 ksiginfo_init_trap(&ksi);
  427                 ksi.ksi_signo = SIGBUS;
  428                 ksi.ksi_code = BUS_OBJERR;
  429                 ksi.ksi_trapno = T_PROTFLT;
  430                 ksi.ksi_addr = (void *)regs->tf_rip;
  431                 trapsignal(td, &ksi);
  432                 return (EINVAL);
  433         }
  434 
  435         ret = set_fpcontext(td, &ucp->uc_mcontext);
  436         if (ret != 0)
  437                 return (ret);
  438         bcopy(&ucp->uc_mcontext.mc_rdi, regs, sizeof(*regs));
  439 
  440         PROC_LOCK(p);
  441 #if defined(COMPAT_43)
  442         if (ucp->uc_mcontext.mc_onstack & 1)
  443                 td->td_sigstk.ss_flags |= SS_ONSTACK;
  444         else
  445                 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
  446 #endif
  447 
  448         td->td_sigmask = ucp->uc_sigmask;
  449         SIG_CANTMASK(td->td_sigmask);
  450         signotify(td);
  451         PROC_UNLOCK(p);
  452         td->td_pcb->pcb_flags |= PCB_FULLCTX;
  453         return (EJUSTRETURN);
  454 }
  455 
  456 #ifdef COMPAT_FREEBSD4
  457 int
  458 freebsd4_sigreturn(struct thread *td, struct freebsd4_sigreturn_args *uap)
  459 {
  460  
  461         return sigreturn(td, (struct sigreturn_args *)uap);
  462 }
  463 #endif
  464 
  465 
  466 /*
  467  * Machine dependent boot() routine
  468  *
  469  * I haven't seen anything to put here yet
  470  * Possibly some stuff might be grafted back here from boot()
  471  */
  472 void
  473 cpu_boot(int howto)
  474 {
  475 }
  476 
  477 /* Get current clock frequency for the given cpu id. */
  478 int
  479 cpu_est_clockrate(int cpu_id, uint64_t *rate)
  480 {
  481         register_t reg;
  482         uint64_t tsc1, tsc2;
  483 
  484         if (pcpu_find(cpu_id) == NULL || rate == NULL)
  485                 return (EINVAL);
  486 
  487         /* If we're booting, trust the rate calibrated moments ago. */
  488         if (cold) {
  489                 *rate = tsc_freq;
  490                 return (0);
  491         }
  492 
  493 #ifdef SMP
  494         /* Schedule ourselves on the indicated cpu. */
  495         thread_lock(curthread);
  496         sched_bind(curthread, cpu_id);
  497         thread_unlock(curthread);
  498 #endif
  499 
  500         /* Calibrate by measuring a short delay. */
  501         reg = intr_disable();
  502         tsc1 = rdtsc();
  503         DELAY(1000);
  504         tsc2 = rdtsc();
  505         intr_restore(reg);
  506 
  507 #ifdef SMP
  508         thread_lock(curthread);
  509         sched_unbind(curthread);
  510         thread_unlock(curthread);
  511 #endif
  512 
  513         /*
  514          * Calculate the difference in readings, convert to Mhz, and
  515          * subtract 0.5% of the total.  Empirical testing has shown that
  516          * overhead in DELAY() works out to approximately this value.
  517          */
  518         tsc2 -= tsc1;
  519         *rate = tsc2 * 1000 - tsc2 * 5;
  520         return (0);
  521 }
  522 
  523 /*
  524  * Shutdown the CPU as much as possible
  525  */
  526 void
  527 cpu_halt(void)
  528 {
  529         for (;;)
  530                 __asm__ ("hlt");
  531 }
  532 
  533 /*
  534  * Hook to idle the CPU when possible.  In the SMP case we default to
  535  * off because a halted cpu will not currently pick up a new thread in the
  536  * run queue until the next timer tick.  If turned on this will result in
  537  * approximately a 4.2% loss in real time performance in buildworld tests
  538  * (but improves user and sys times oddly enough), and saves approximately
  539  * 5% in power consumption on an idle machine (tests w/2xCPU 1.1GHz P3).
  540  *
  541  * XXX we need to have a cpu mask of idle cpus and generate an IPI or
  542  * otherwise generate some sort of interrupt to wake up cpus sitting in HLT.
  543  * Then we can have our cake and eat it too.
  544  *
  545  * XXX I'm turning it on for SMP as well by default for now.  It seems to
  546  * help lock contention somewhat, and this is critical for HTT. -Peter
  547  */
  548 static int      cpu_idle_hlt = 1;
  549 TUNABLE_INT("machdep.cpu_idle_hlt", &cpu_idle_hlt);
  550 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hlt, CTLFLAG_RW,
  551     &cpu_idle_hlt, 0, "Idle loop HLT enable");
  552 
  553 static void
  554 cpu_idle_default(void)
  555 {
  556         /*
  557          * we must absolutely guarentee that hlt is the
  558          * absolute next instruction after sti or we
  559          * introduce a timing window.
  560          */
  561         __asm __volatile("sti; hlt");
  562 }
  563 
  564 /*
  565  * Note that we have to be careful here to avoid a race between checking
  566  * sched_runnable() and actually halting.  If we don't do this, we may waste
  567  * the time between calling hlt and the next interrupt even though there
  568  * is a runnable process.
  569  */
  570 void
  571 cpu_idle(void)
  572 {
  573 
  574 #ifdef SMP
  575         if (mp_grab_cpu_hlt())
  576                 return;
  577 #endif
  578         if (cpu_idle_hlt) {
  579                 disable_intr();
  580                 if (sched_runnable())
  581                         enable_intr();
  582                 else
  583                         (*cpu_idle_hook)();
  584         }
  585 }
  586 
  587 /* Other subsystems (e.g., ACPI) can hook this later. */
  588 void (*cpu_idle_hook)(void) = cpu_idle_default;
  589 
  590 /*
  591  * Reset registers to default values on exec.
  592  */
  593 void
  594 exec_setregs(td, entry, stack, ps_strings)
  595         struct thread *td;
  596         u_long entry;
  597         u_long stack;
  598         u_long ps_strings;
  599 {
  600         struct trapframe *regs = td->td_frame;
  601         struct pcb *pcb = td->td_pcb;
  602         
  603         critical_enter();
  604         wrmsr(MSR_FSBASE, 0);
  605         wrmsr(MSR_KGSBASE, 0);  /* User value while we're in the kernel */
  606         pcb->pcb_fsbase = 0;
  607         pcb->pcb_gsbase = 0;
  608         critical_exit();
  609         pcb->pcb_flags &= ~(PCB_32BIT | PCB_GS32BIT);
  610         load_ds(_udatasel);
  611         load_es(_udatasel);
  612         load_fs(_udatasel);
  613         load_gs(_udatasel);
  614         pcb->pcb_ds = _udatasel;
  615         pcb->pcb_es = _udatasel;
  616         pcb->pcb_fs = _udatasel;
  617         pcb->pcb_gs = _udatasel;
  618         pcb->pcb_initial_fpucw = __INITIAL_FPUCW__;
  619 
  620         bzero((char *)regs, sizeof(struct trapframe));
  621         regs->tf_rip = entry;
  622         regs->tf_rsp = ((stack - 8) & ~0xFul) + 8;
  623         regs->tf_rdi = stack;           /* argv */
  624         regs->tf_rflags = PSL_USER | (regs->tf_rflags & PSL_T);
  625         regs->tf_ss = _udatasel;
  626         regs->tf_cs = _ucodesel;
  627 
  628         /*
  629          * Reset the hardware debug registers if they were in use.
  630          * They won't have any meaning for the newly exec'd process.
  631          */
  632         if (pcb->pcb_flags & PCB_DBREGS) {
  633                 pcb->pcb_dr0 = 0;
  634                 pcb->pcb_dr1 = 0;
  635                 pcb->pcb_dr2 = 0;
  636                 pcb->pcb_dr3 = 0;
  637                 pcb->pcb_dr6 = 0;
  638                 pcb->pcb_dr7 = 0;
  639                 if (pcb == PCPU_GET(curpcb)) {
  640                         /*
  641                          * Clear the debug registers on the running
  642                          * CPU, otherwise they will end up affecting
  643                          * the next process we switch to.
  644                          */
  645                         reset_dbregs();
  646                 }
  647                 pcb->pcb_flags &= ~PCB_DBREGS;
  648         }
  649 
  650         /*
  651          * Drop the FP state if we hold it, so that the process gets a
  652          * clean FP state if it uses the FPU again.
  653          */
  654         fpstate_drop(td);
  655 }
  656 
  657 void
  658 cpu_setregs(void)
  659 {
  660         register_t cr0;
  661 
  662         cr0 = rcr0();
  663         /*
  664          * CR0_MP, CR0_NE and CR0_TS are also set by npx_probe() for the
  665          * BSP.  See the comments there about why we set them.
  666          */
  667         cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
  668         load_cr0(cr0);
  669 }
  670 
  671 /*
  672  * Initialize amd64 and configure to run kernel
  673  */
  674 
  675 /*
  676  * Initialize segments & interrupt table
  677  */
  678 
  679 struct user_segment_descriptor gdt[NGDT * MAXCPU];/* global descriptor tables */
  680 static struct gate_descriptor idt0[NIDT];
  681 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
  682 
  683 static char dblfault_stack[PAGE_SIZE] __aligned(16);
  684 
  685 static char nmi0_stack[PAGE_SIZE] __aligned(16);
  686 CTASSERT(sizeof(struct nmi_pcpu) == 16);
  687 
  688 struct amd64tss common_tss[MAXCPU];
  689 
  690 /* software prototypes -- in more palatable form */
  691 struct soft_segment_descriptor gdt_segs[] = {
  692 /* GNULL_SEL    0 Null Descriptor */
  693 {       0x0,                    /* segment base address  */
  694         0x0,                    /* length */
  695         0,                      /* segment type */
  696         0,                      /* segment descriptor priority level */
  697         0,                      /* segment descriptor present */
  698         0,                      /* long */
  699         0,                      /* default 32 vs 16 bit size */
  700         0                       /* limit granularity (byte/page units)*/ },
  701 /* GCODE_SEL    1 Code Descriptor for kernel */
  702 {       0x0,                    /* segment base address  */
  703         0xfffff,                /* length - all address space */
  704         SDT_MEMERA,             /* segment type */
  705         SEL_KPL,                /* segment descriptor priority level */
  706         1,                      /* segment descriptor present */
  707         1,                      /* long */
  708         0,                      /* default 32 vs 16 bit size */
  709         1                       /* limit granularity (byte/page units)*/ },
  710 /* GDATA_SEL    2 Data Descriptor for kernel */
  711 {       0x0,                    /* segment base address  */
  712         0xfffff,                /* length - all address space */
  713         SDT_MEMRWA,             /* segment type */
  714         SEL_KPL,                /* segment descriptor priority level */
  715         1,                      /* segment descriptor present */
  716         1,                      /* long */
  717         0,                      /* default 32 vs 16 bit size */
  718         1                       /* limit granularity (byte/page units)*/ },
  719 /* GUCODE32_SEL 3 32 bit Code Descriptor for user */
  720 {       0x0,                    /* segment base address  */
  721         0xfffff,                /* length - all address space */
  722         SDT_MEMERA,             /* segment type */
  723         SEL_UPL,                /* segment descriptor priority level */
  724         1,                      /* segment descriptor present */
  725         0,                      /* long */
  726         1,                      /* default 32 vs 16 bit size */
  727         1                       /* limit granularity (byte/page units)*/ },
  728 /* GUDATA_SEL   4 32/64 bit Data Descriptor for user */
  729 {       0x0,                    /* segment base address  */
  730         0xfffff,                /* length - all address space */
  731         SDT_MEMRWA,             /* segment type */
  732         SEL_UPL,                /* segment descriptor priority level */
  733         1,                      /* segment descriptor present */
  734         0,                      /* long */
  735         1,                      /* default 32 vs 16 bit size */
  736         1                       /* limit granularity (byte/page units)*/ },
  737 /* GUCODE_SEL   5 64 bit Code Descriptor for user */
  738 {       0x0,                    /* segment base address  */
  739         0xfffff,                /* length - all address space */
  740         SDT_MEMERA,             /* segment type */
  741         SEL_UPL,                /* segment descriptor priority level */
  742         1,                      /* segment descriptor present */
  743         1,                      /* long */
  744         0,                      /* default 32 vs 16 bit size */
  745         1                       /* limit granularity (byte/page units)*/ },
  746 /* GPROC0_SEL   6 Proc 0 Tss Descriptor */
  747 {
  748         0x0,                    /* segment base address */
  749         sizeof(struct amd64tss)-1,/* length */
  750         SDT_SYSTSS,             /* segment type */
  751         SEL_KPL,                /* segment descriptor priority level */
  752         1,                      /* segment descriptor present */
  753         0,                      /* long */
  754         0,                      /* unused - default 32 vs 16 bit size */
  755         0                       /* limit granularity (byte/page units)*/ },
  756 /* Actually, the TSS is a system descriptor which is double size */
  757 {       0x0,                    /* segment base address  */
  758         0x0,                    /* length */
  759         0,                      /* segment type */
  760         0,                      /* segment descriptor priority level */
  761         0,                      /* segment descriptor present */
  762         0,                      /* long */
  763         0,                      /* default 32 vs 16 bit size */
  764         0                       /* limit granularity (byte/page units)*/ },
  765 /* GUGS32_SEL   8 32 bit GS Descriptor for user */
  766 {       0x0,                    /* segment base address  */
  767         0xfffff,                /* length - all address space */
  768         SDT_MEMRWA,             /* segment type */
  769         SEL_UPL,                /* segment descriptor priority level */
  770         1,                      /* segment descriptor present */
  771         0,                      /* long */
  772         1,                      /* default 32 vs 16 bit size */
  773         1                       /* limit granularity (byte/page units)*/ },
  774 };
  775 
  776 void
  777 setidt(idx, func, typ, dpl, ist)
  778         int idx;
  779         inthand_t *func;
  780         int typ;
  781         int dpl;
  782         int ist;
  783 {
  784         struct gate_descriptor *ip;
  785 
  786         ip = idt + idx;
  787         ip->gd_looffset = (uintptr_t)func;
  788         ip->gd_selector = GSEL(GCODE_SEL, SEL_KPL);
  789         ip->gd_ist = ist;
  790         ip->gd_xx = 0;
  791         ip->gd_type = typ;
  792         ip->gd_dpl = dpl;
  793         ip->gd_p = 1;
  794         ip->gd_hioffset = ((uintptr_t)func)>>16 ;
  795 }
  796 
  797 extern inthand_t
  798         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
  799         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
  800         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
  801         IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
  802         IDTVEC(xmm), IDTVEC(dblfault),
  803         IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
  804 
  805 void
  806 sdtossd(sd, ssd)
  807         struct user_segment_descriptor *sd;
  808         struct soft_segment_descriptor *ssd;
  809 {
  810 
  811         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
  812         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
  813         ssd->ssd_type  = sd->sd_type;
  814         ssd->ssd_dpl   = sd->sd_dpl;
  815         ssd->ssd_p     = sd->sd_p;
  816         ssd->ssd_long  = sd->sd_long;
  817         ssd->ssd_def32 = sd->sd_def32;
  818         ssd->ssd_gran  = sd->sd_gran;
  819 }
  820 
  821 void
  822 ssdtosd(ssd, sd)
  823         struct soft_segment_descriptor *ssd;
  824         struct user_segment_descriptor *sd;
  825 {
  826 
  827         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
  828         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xff;
  829         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
  830         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
  831         sd->sd_type  = ssd->ssd_type;
  832         sd->sd_dpl   = ssd->ssd_dpl;
  833         sd->sd_p     = ssd->ssd_p;
  834         sd->sd_long  = ssd->ssd_long;
  835         sd->sd_def32 = ssd->ssd_def32;
  836         sd->sd_gran  = ssd->ssd_gran;
  837 }
  838 
  839 void
  840 ssdtosyssd(ssd, sd)
  841         struct soft_segment_descriptor *ssd;
  842         struct system_segment_descriptor *sd;
  843 {
  844 
  845         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
  846         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xfffffffffful;
  847         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
  848         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
  849         sd->sd_type  = ssd->ssd_type;
  850         sd->sd_dpl   = ssd->ssd_dpl;
  851         sd->sd_p     = ssd->ssd_p;
  852         sd->sd_gran  = ssd->ssd_gran;
  853 }
  854 
  855 #if !defined(DEV_ATPIC) && defined(DEV_ISA)
  856 #include <isa/isavar.h>
  857 u_int
  858 isa_irq_pending(void)
  859 {
  860 
  861         return (0);
  862 }
  863 #endif
  864 
  865 u_int basemem;
  866 
  867 static int
  868 add_smap_entry(struct bios_smap *smap, vm_paddr_t *physmap, int *physmap_idxp)
  869 {
  870         int i, insert_idx, physmap_idx;
  871 
  872         physmap_idx = *physmap_idxp;
  873 
  874         if (boothowto & RB_VERBOSE)
  875                 printf("SMAP type=%02x base=%016lx len=%016lx\n",
  876                     smap->type, smap->base, smap->length);
  877 
  878         if (smap->type != SMAP_TYPE_MEMORY)
  879                 return (1);
  880 
  881         if (smap->length == 0)
  882                 return (0);
  883 
  884         /*
  885          * Find insertion point while checking for overlap.  Start off by
  886          * assuming the new entry will be added to the end.
  887          */
  888         insert_idx = physmap_idx + 2;
  889         for (i = 0; i <= physmap_idx; i += 2) {
  890                 if (smap->base < physmap[i + 1]) {
  891                         if (smap->base + smap->length <= physmap[i]) {
  892                                 insert_idx = i;
  893                                 break;
  894                         }
  895                         if (boothowto & RB_VERBOSE)
  896                                 printf(
  897                     "Overlapping memory regions, ignoring second region\n");
  898                         return (1);
  899                 }
  900         }
  901 
  902         /* See if we can prepend to the next entry. */
  903         if (insert_idx <= physmap_idx &&
  904             smap->base + smap->length == physmap[insert_idx]) {
  905                 physmap[insert_idx] = smap->base;
  906                 return (1);
  907         }
  908 
  909         /* See if we can append to the previous entry. */
  910         if (insert_idx > 0 && smap->base == physmap[insert_idx - 1]) {
  911                 physmap[insert_idx - 1] += smap->length;
  912                 return (1);
  913         }
  914 
  915         physmap_idx += 2;
  916         *physmap_idxp = physmap_idx;
  917         if (physmap_idx == PHYSMAP_SIZE) {
  918                 printf(
  919                 "Too many segments in the physical address map, giving up\n");
  920                 return (0);
  921         }
  922 
  923         /*
  924          * Move the last 'N' entries down to make room for the new
  925          * entry if needed.
  926          */
  927         for (i = physmap_idx; i > insert_idx; i -= 2) {
  928                 physmap[i] = physmap[i - 2];
  929                 physmap[i + 1] = physmap[i - 1];
  930         }
  931 
  932         /* Insert the new entry. */
  933         physmap[insert_idx] = smap->base;
  934         physmap[insert_idx + 1] = smap->base + smap->length;
  935         return (1);
  936 }
  937 
  938 /*
  939  * Populate the (physmap) array with base/bound pairs describing the
  940  * available physical memory in the system, then test this memory and
  941  * build the phys_avail array describing the actually-available memory.
  942  *
  943  * If we cannot accurately determine the physical memory map, then use
  944  * value from the 0xE801 call, and failing that, the RTC.
  945  *
  946  * Total memory size may be set by the kernel environment variable
  947  * hw.physmem or the compile-time define MAXMEM.
  948  *
  949  * XXX first should be vm_paddr_t.
  950  */
  951 static void
  952 getmemsize(caddr_t kmdp, u_int64_t first)
  953 {
  954         int i, off, physmap_idx, pa_indx, da_indx;
  955         vm_paddr_t pa, physmap[PHYSMAP_SIZE];
  956         u_long physmem_tunable;
  957         pt_entry_t *pte;
  958         struct bios_smap *smapbase, *smap, *smapend;
  959         u_int32_t smapsize;
  960         quad_t dcons_addr, dcons_size;
  961 
  962         bzero(physmap, sizeof(physmap));
  963         basemem = 0;
  964         physmap_idx = 0;
  965 
  966         /*
  967          * get memory map from INT 15:E820, kindly supplied by the loader.
  968          *
  969          * subr_module.c says:
  970          * "Consumer may safely assume that size value precedes data."
  971          * ie: an int32_t immediately precedes smap.
  972          */
  973         smapbase = (struct bios_smap *)preload_search_info(kmdp,
  974             MODINFO_METADATA | MODINFOMD_SMAP);
  975         if (smapbase == NULL)
  976                 panic("No BIOS smap info from loader!");
  977 
  978         smapsize = *((u_int32_t *)smapbase - 1);
  979         smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
  980 
  981         for (smap = smapbase; smap < smapend; smap++)
  982                 if (!add_smap_entry(smap, physmap, &physmap_idx))
  983                         break;
  984 
  985         /*
  986          * Find the 'base memory' segment for SMP
  987          */
  988         basemem = 0;
  989         for (i = 0; i <= physmap_idx; i += 2) {
  990                 if (physmap[i] == 0x00000000) {
  991                         basemem = physmap[i + 1] / 1024;
  992                         break;
  993                 }
  994         }
  995         if (basemem == 0)
  996                 panic("BIOS smap did not include a basemem segment!");
  997 
  998 #ifdef SMP
  999         /* make hole for AP bootstrap code */
 1000         physmap[1] = mp_bootaddress(physmap[1] / 1024);
 1001 #endif
 1002 
 1003         /*
 1004          * Maxmem isn't the "maximum memory", it's one larger than the
 1005          * highest page of the physical address space.  It should be
 1006          * called something like "Maxphyspage".  We may adjust this
 1007          * based on ``hw.physmem'' and the results of the memory test.
 1008          */
 1009         Maxmem = atop(physmap[physmap_idx + 1]);
 1010 
 1011 #ifdef MAXMEM
 1012         Maxmem = MAXMEM / 4;
 1013 #endif
 1014 
 1015         if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
 1016                 Maxmem = atop(physmem_tunable);
 1017 
 1018         /*
 1019          * Don't allow MAXMEM or hw.physmem to extend the amount of memory
 1020          * in the system.
 1021          */
 1022         if (Maxmem > atop(physmap[physmap_idx + 1]))
 1023                 Maxmem = atop(physmap[physmap_idx + 1]);
 1024 
 1025         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
 1026             (boothowto & RB_VERBOSE))
 1027                 printf("Physical memory use set to %ldK\n", Maxmem * 4);
 1028 
 1029         /* call pmap initialization to make new kernel address space */
 1030         pmap_bootstrap(&first);
 1031 
 1032         /*
 1033          * Size up each available chunk of physical memory.
 1034          */
 1035         physmap[0] = PAGE_SIZE;         /* mask off page 0 */
 1036         pa_indx = 0;
 1037         da_indx = 1;
 1038         phys_avail[pa_indx++] = physmap[0];
 1039         phys_avail[pa_indx] = physmap[0];
 1040         dump_avail[da_indx] = physmap[0];
 1041         pte = CMAP1;
 1042 
 1043         /*
 1044          * Get dcons buffer address
 1045          */
 1046         if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
 1047             getenv_quad("dcons.size", &dcons_size) == 0)
 1048                 dcons_addr = 0;
 1049 
 1050         /*
 1051          * physmap is in bytes, so when converting to page boundaries,
 1052          * round up the start address and round down the end address.
 1053          */
 1054         for (i = 0; i <= physmap_idx; i += 2) {
 1055                 vm_paddr_t end;
 1056 
 1057                 end = ptoa((vm_paddr_t)Maxmem);
 1058                 if (physmap[i + 1] < end)
 1059                         end = trunc_page(physmap[i + 1]);
 1060                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
 1061                         int tmp, page_bad, full;
 1062                         int *ptr = (int *)CADDR1;
 1063 
 1064                         full = FALSE;
 1065                         /*
 1066                          * block out kernel memory as not available.
 1067                          */
 1068                         if (pa >= 0x100000 && pa < first)
 1069                                 goto do_dump_avail;
 1070 
 1071                         /*
 1072                          * block out dcons buffer
 1073                          */
 1074                         if (dcons_addr > 0
 1075                             && pa >= trunc_page(dcons_addr)
 1076                             && pa < dcons_addr + dcons_size)
 1077                                 goto do_dump_avail;
 1078 
 1079                         page_bad = FALSE;
 1080 
 1081                         /*
 1082                          * map page into kernel: valid, read/write,non-cacheable
 1083                          */
 1084                         *pte = pa | PG_V | PG_RW | PG_N;
 1085                         invltlb();
 1086 
 1087                         tmp = *(int *)ptr;
 1088                         /*
 1089                          * Test for alternating 1's and 0's
 1090                          */
 1091                         *(volatile int *)ptr = 0xaaaaaaaa;
 1092                         if (*(volatile int *)ptr != 0xaaaaaaaa)
 1093                                 page_bad = TRUE;
 1094                         /*
 1095                          * Test for alternating 0's and 1's
 1096                          */
 1097                         *(volatile int *)ptr = 0x55555555;
 1098                         if (*(volatile int *)ptr != 0x55555555)
 1099                                 page_bad = TRUE;
 1100                         /*
 1101                          * Test for all 1's
 1102                          */
 1103                         *(volatile int *)ptr = 0xffffffff;
 1104                         if (*(volatile int *)ptr != 0xffffffff)
 1105                                 page_bad = TRUE;
 1106                         /*
 1107                          * Test for all 0's
 1108                          */
 1109                         *(volatile int *)ptr = 0x0;
 1110                         if (*(volatile int *)ptr != 0x0)
 1111                                 page_bad = TRUE;
 1112                         /*
 1113                          * Restore original value.
 1114                          */
 1115                         *(int *)ptr = tmp;
 1116 
 1117                         /*
 1118                          * Adjust array of valid/good pages.
 1119                          */
 1120                         if (page_bad == TRUE)
 1121                                 continue;
 1122                         /*
 1123                          * If this good page is a continuation of the
 1124                          * previous set of good pages, then just increase
 1125                          * the end pointer. Otherwise start a new chunk.
 1126                          * Note that "end" points one higher than end,
 1127                          * making the range >= start and < end.
 1128                          * If we're also doing a speculative memory
 1129                          * test and we at or past the end, bump up Maxmem
 1130                          * so that we keep going. The first bad page
 1131                          * will terminate the loop.
 1132                          */
 1133                         if (phys_avail[pa_indx] == pa) {
 1134                                 phys_avail[pa_indx] += PAGE_SIZE;
 1135                         } else {
 1136                                 pa_indx++;
 1137                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
 1138                                         printf(
 1139                 "Too many holes in the physical address space, giving up\n");
 1140                                         pa_indx--;
 1141                                         full = TRUE;
 1142                                         goto do_dump_avail;
 1143                                 }
 1144                                 phys_avail[pa_indx++] = pa;     /* start */
 1145                                 phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
 1146                         }
 1147                         physmem++;
 1148 do_dump_avail:
 1149                         if (dump_avail[da_indx] == pa) {
 1150                                 dump_avail[da_indx] += PAGE_SIZE;
 1151                         } else {
 1152                                 da_indx++;
 1153                                 if (da_indx == DUMP_AVAIL_ARRAY_END) {
 1154                                         da_indx--;
 1155                                         goto do_next;
 1156                                 }
 1157                                 dump_avail[da_indx++] = pa; /* start */
 1158                                 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
 1159                         }
 1160 do_next:
 1161                         if (full)
 1162                                 break;
 1163                 }
 1164         }
 1165         *pte = 0;
 1166         invltlb();
 1167 
 1168         /*
 1169          * XXX
 1170          * The last chunk must contain at least one page plus the message
 1171          * buffer to avoid complicating other code (message buffer address
 1172          * calculation, etc.).
 1173          */
 1174         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
 1175             round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
 1176                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
 1177                 phys_avail[pa_indx--] = 0;
 1178                 phys_avail[pa_indx--] = 0;
 1179         }
 1180 
 1181         Maxmem = atop(phys_avail[pa_indx]);
 1182 
 1183         /* Trim off space for the message buffer. */
 1184         phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
 1185 
 1186         /* Map the message buffer. */
 1187         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
 1188                 pmap_kenter((vm_offset_t)msgbufp + off, phys_avail[pa_indx] +
 1189                     off);
 1190 }
 1191 
 1192 u_int64_t
 1193 hammer_time(u_int64_t modulep, u_int64_t physfree)
 1194 {
 1195         caddr_t kmdp;
 1196         int gsel_tss, x;
 1197         struct pcpu *pc;
 1198         struct nmi_pcpu *np;
 1199         u_int64_t msr;
 1200         char *env;
 1201 
 1202         thread0.td_kstack = physfree + KERNBASE;
 1203         bzero((void *)thread0.td_kstack, KSTACK_PAGES * PAGE_SIZE);
 1204         physfree += KSTACK_PAGES * PAGE_SIZE;
 1205         thread0.td_pcb = (struct pcb *)
 1206            (thread0.td_kstack + KSTACK_PAGES * PAGE_SIZE) - 1;
 1207 
 1208         /*
 1209          * This may be done better later if it gets more high level
 1210          * components in it. If so just link td->td_proc here.
 1211          */
 1212         proc_linkup0(&proc0, &thread0);
 1213 
 1214         preload_metadata = (caddr_t)(uintptr_t)(modulep + KERNBASE);
 1215         preload_bootstrap_relocate(KERNBASE);
 1216         kmdp = preload_search_by_type("elf kernel");
 1217         if (kmdp == NULL)
 1218                 kmdp = preload_search_by_type("elf64 kernel");
 1219         boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
 1220         kern_envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *) + KERNBASE;
 1221 #ifdef DDB
 1222         ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
 1223         ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
 1224 #endif
 1225 
 1226         /* Init basic tunables, hz etc */
 1227         init_param1();
 1228 
 1229         /*
 1230          * make gdt memory segments
 1231          */
 1232         gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&common_tss[0];
 1233 
 1234         for (x = 0; x < NGDT; x++) {
 1235                 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1))
 1236                         ssdtosd(&gdt_segs[x], &gdt[x]);
 1237         }
 1238         ssdtosyssd(&gdt_segs[GPROC0_SEL],
 1239             (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
 1240 
 1241         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
 1242         r_gdt.rd_base =  (long) gdt;
 1243         lgdt(&r_gdt);
 1244         pc = &__pcpu[0];
 1245 
 1246         wrmsr(MSR_FSBASE, 0);           /* User value */
 1247         wrmsr(MSR_GSBASE, (u_int64_t)pc);
 1248         wrmsr(MSR_KGSBASE, 0);          /* User value while in the kernel */
 1249 
 1250         pcpu_init(pc, 0, sizeof(struct pcpu));
 1251         PCPU_SET(prvspace, pc);
 1252         PCPU_SET(curthread, &thread0);
 1253         PCPU_SET(curpcb, thread0.td_pcb);
 1254         PCPU_SET(tssp, &common_tss[0]);
 1255         PCPU_SET(gs32p, &gdt[GUGS32_SEL]);
 1256 
 1257         /*
 1258          * Initialize mutexes.
 1259          *
 1260          * icu_lock: in order to allow an interrupt to occur in a critical
 1261          *           section, to set pcpu->ipending (etc...) properly, we
 1262          *           must be able to get the icu lock, so it can't be
 1263          *           under witness.
 1264          */
 1265         mutex_init();
 1266         mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS);
 1267 
 1268         /* exceptions */
 1269         for (x = 0; x < NIDT; x++)
 1270                 setidt(x, &IDTVEC(rsvd), SDT_SYSIGT, SEL_KPL, 0);
 1271         setidt(IDT_DE, &IDTVEC(div),  SDT_SYSIGT, SEL_KPL, 0);
 1272         setidt(IDT_DB, &IDTVEC(dbg),  SDT_SYSIGT, SEL_KPL, 0);
 1273         setidt(IDT_NMI, &IDTVEC(nmi),  SDT_SYSIGT, SEL_KPL, 2);
 1274         setidt(IDT_BP, &IDTVEC(bpt),  SDT_SYSIGT, SEL_UPL, 0);
 1275         setidt(IDT_OF, &IDTVEC(ofl),  SDT_SYSIGT, SEL_KPL, 0);
 1276         setidt(IDT_BR, &IDTVEC(bnd),  SDT_SYSIGT, SEL_KPL, 0);
 1277         setidt(IDT_UD, &IDTVEC(ill),  SDT_SYSIGT, SEL_KPL, 0);
 1278         setidt(IDT_NM, &IDTVEC(dna),  SDT_SYSIGT, SEL_KPL, 0);
 1279         setidt(IDT_DF, &IDTVEC(dblfault), SDT_SYSIGT, SEL_KPL, 1);
 1280         setidt(IDT_FPUGP, &IDTVEC(fpusegm),  SDT_SYSIGT, SEL_KPL, 0);
 1281         setidt(IDT_TS, &IDTVEC(tss),  SDT_SYSIGT, SEL_KPL, 0);
 1282         setidt(IDT_NP, &IDTVEC(missing),  SDT_SYSIGT, SEL_KPL, 0);
 1283         setidt(IDT_SS, &IDTVEC(stk),  SDT_SYSIGT, SEL_KPL, 0);
 1284         setidt(IDT_GP, &IDTVEC(prot),  SDT_SYSIGT, SEL_KPL, 0);
 1285         setidt(IDT_PF, &IDTVEC(page),  SDT_SYSIGT, SEL_KPL, 0);
 1286         setidt(IDT_MF, &IDTVEC(fpu),  SDT_SYSIGT, SEL_KPL, 0);
 1287         setidt(IDT_AC, &IDTVEC(align), SDT_SYSIGT, SEL_KPL, 0);
 1288         setidt(IDT_MC, &IDTVEC(mchk),  SDT_SYSIGT, SEL_KPL, 0);
 1289         setidt(IDT_XF, &IDTVEC(xmm), SDT_SYSIGT, SEL_KPL, 0);
 1290 
 1291         r_idt.rd_limit = sizeof(idt0) - 1;
 1292         r_idt.rd_base = (long) idt;
 1293         lidt(&r_idt);
 1294 
 1295         /*
 1296          * Initialize the i8254 before the console so that console
 1297          * initialization can use DELAY().
 1298          */
 1299         i8254_init();
 1300 
 1301         /*
 1302          * Initialize the console before we print anything out.
 1303          */
 1304         cninit();
 1305 
 1306 #ifdef DEV_ISA
 1307 #ifdef DEV_ATPIC
 1308         elcr_probe();
 1309         atpic_startup();
 1310 #else
 1311         /* Reset and mask the atpics and leave them shut down. */
 1312         atpic_reset();
 1313 
 1314         /*
 1315          * Point the ICU spurious interrupt vectors at the APIC spurious
 1316          * interrupt handler.
 1317          */
 1318         setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
 1319         setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
 1320 #endif
 1321 #else
 1322 #error "have you forgotten the isa device?";
 1323 #endif
 1324 
 1325         kdb_init();
 1326 
 1327 #ifdef KDB
 1328         if (boothowto & RB_KDB)
 1329                 kdb_enter_why(KDB_WHY_BOOTFLAGS,
 1330                     "Boot flags requested debugger");
 1331 #endif
 1332 
 1333         identify_cpu();         /* Final stage of CPU initialization */
 1334         initializecpu();        /* Initialize CPU registers */
 1335         initializecpucache();
 1336 
 1337         /* make an initial tss so cpu can get interrupt stack on syscall! */
 1338         common_tss[0].tss_rsp0 = thread0.td_kstack + \
 1339             KSTACK_PAGES * PAGE_SIZE - sizeof(struct pcb);
 1340         /* Ensure the stack is aligned to 16 bytes */
 1341         common_tss[0].tss_rsp0 &= ~0xFul;
 1342         PCPU_SET(rsp0, common_tss[0].tss_rsp0);
 1343 
 1344         /* doublefault stack space, runs on ist1 */
 1345         common_tss[0].tss_ist1 = (long)&dblfault_stack[sizeof(dblfault_stack)];
 1346 
 1347         /*
 1348          * NMI stack, runs on ist2.  The pcpu pointer is stored just
 1349          * above the start of the ist2 stack.
 1350          */
 1351         np = ((struct nmi_pcpu *) &nmi0_stack[sizeof(nmi0_stack)]) - 1;
 1352         np->np_pcpu = (register_t) pc;
 1353         common_tss[0].tss_ist2 = (long) np;
 1354 
 1355         /* Set the IO permission bitmap (empty due to tss seg limit) */
 1356         common_tss[0].tss_iobase = sizeof(struct amd64tss);
 1357 
 1358         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
 1359         ltr(gsel_tss);
 1360 
 1361         /* Set up the fast syscall stuff */
 1362         msr = rdmsr(MSR_EFER) | EFER_SCE;
 1363         wrmsr(MSR_EFER, msr);
 1364         wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
 1365         wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
 1366         msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
 1367               ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
 1368         wrmsr(MSR_STAR, msr);
 1369         wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
 1370 
 1371         getmemsize(kmdp, physfree);
 1372         init_param2(physmem);
 1373 
 1374         /* now running on new page tables, configured,and u/iom is accessible */
 1375 
 1376         msgbufinit(msgbufp, MSGBUF_SIZE);
 1377         fpuinit();
 1378 
 1379         /* transfer to user mode */
 1380 
 1381         _ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
 1382         _udatasel = GSEL(GUDATA_SEL, SEL_UPL);
 1383         _ucode32sel = GSEL(GUCODE32_SEL, SEL_UPL);
 1384 
 1385         /* setup proc 0's pcb */
 1386         thread0.td_pcb->pcb_flags = 0; /* XXXKSE */
 1387         thread0.td_pcb->pcb_cr3 = KPML4phys;
 1388         thread0.td_frame = &proc0_tf;
 1389 
 1390         env = getenv("kernelname");
 1391         if (env != NULL)
 1392                 strlcpy(kernelname, env, sizeof(kernelname));
 1393 
 1394         /* Location of kernel stack for locore */
 1395         return ((u_int64_t)thread0.td_pcb);
 1396 }
 1397 
 1398 void
 1399 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
 1400 {
 1401 
 1402         pcpu->pc_acpi_id = 0xffffffff;
 1403 }
 1404 
 1405 void
 1406 spinlock_enter(void)
 1407 {
 1408         struct thread *td;
 1409 
 1410         td = curthread;
 1411         if (td->td_md.md_spinlock_count == 0)
 1412                 td->td_md.md_saved_flags = intr_disable();
 1413         td->td_md.md_spinlock_count++;
 1414         critical_enter();
 1415 }
 1416 
 1417 void
 1418 spinlock_exit(void)
 1419 {
 1420         struct thread *td;
 1421 
 1422         td = curthread;
 1423         critical_exit();
 1424         td->td_md.md_spinlock_count--;
 1425         if (td->td_md.md_spinlock_count == 0)
 1426                 intr_restore(td->td_md.md_saved_flags);
 1427 }
 1428 
 1429 /*
 1430  * Construct a PCB from a trapframe. This is called from kdb_trap() where
 1431  * we want to start a backtrace from the function that caused us to enter
 1432  * the debugger. We have the context in the trapframe, but base the trace
 1433  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
 1434  * enough for a backtrace.
 1435  */
 1436 void
 1437 makectx(struct trapframe *tf, struct pcb *pcb)
 1438 {
 1439 
 1440         pcb->pcb_r12 = tf->tf_r12;
 1441         pcb->pcb_r13 = tf->tf_r13;
 1442         pcb->pcb_r14 = tf->tf_r14;
 1443         pcb->pcb_r15 = tf->tf_r15;
 1444         pcb->pcb_rbp = tf->tf_rbp;
 1445         pcb->pcb_rbx = tf->tf_rbx;
 1446         pcb->pcb_rip = tf->tf_rip;
 1447         pcb->pcb_rsp = (ISPL(tf->tf_cs)) ? tf->tf_rsp : (long)(tf + 1) - 8;
 1448 }
 1449 
 1450 int
 1451 ptrace_set_pc(struct thread *td, unsigned long addr)
 1452 {
 1453         td->td_frame->tf_rip = addr;
 1454         return (0);
 1455 }
 1456 
 1457 int
 1458 ptrace_single_step(struct thread *td)
 1459 {
 1460         td->td_frame->tf_rflags |= PSL_T;
 1461         return (0);
 1462 }
 1463 
 1464 int
 1465 ptrace_clear_single_step(struct thread *td)
 1466 {
 1467         td->td_frame->tf_rflags &= ~PSL_T;
 1468         return (0);
 1469 }
 1470 
 1471 int
 1472 fill_regs(struct thread *td, struct reg *regs)
 1473 {
 1474         struct trapframe *tp;
 1475 
 1476         tp = td->td_frame;
 1477         regs->r_r15 = tp->tf_r15;
 1478         regs->r_r14 = tp->tf_r14;
 1479         regs->r_r13 = tp->tf_r13;
 1480         regs->r_r12 = tp->tf_r12;
 1481         regs->r_r11 = tp->tf_r11;
 1482         regs->r_r10 = tp->tf_r10;
 1483         regs->r_r9  = tp->tf_r9;
 1484         regs->r_r8  = tp->tf_r8;
 1485         regs->r_rdi = tp->tf_rdi;
 1486         regs->r_rsi = tp->tf_rsi;
 1487         regs->r_rbp = tp->tf_rbp;
 1488         regs->r_rbx = tp->tf_rbx;
 1489         regs->r_rdx = tp->tf_rdx;
 1490         regs->r_rcx = tp->tf_rcx;
 1491         regs->r_rax = tp->tf_rax;
 1492         regs->r_rip = tp->tf_rip;
 1493         regs->r_cs = tp->tf_cs;
 1494         regs->r_rflags = tp->tf_rflags;
 1495         regs->r_rsp = tp->tf_rsp;
 1496         regs->r_ss = tp->tf_ss;
 1497         return (0);
 1498 }
 1499 
 1500 int
 1501 set_regs(struct thread *td, struct reg *regs)
 1502 {
 1503         struct trapframe *tp;
 1504         register_t rflags;
 1505 
 1506         tp = td->td_frame;
 1507         rflags = regs->r_rflags & 0xffffffff;
 1508         if (!EFL_SECURE(rflags, tp->tf_rflags) || !CS_SECURE(regs->r_cs))
 1509                 return (EINVAL);
 1510         tp->tf_r15 = regs->r_r15;
 1511         tp->tf_r14 = regs->r_r14;
 1512         tp->tf_r13 = regs->r_r13;
 1513         tp->tf_r12 = regs->r_r12;
 1514         tp->tf_r11 = regs->r_r11;
 1515         tp->tf_r10 = regs->r_r10;
 1516         tp->tf_r9  = regs->r_r9;
 1517         tp->tf_r8  = regs->r_r8;
 1518         tp->tf_rdi = regs->r_rdi;
 1519         tp->tf_rsi = regs->r_rsi;
 1520         tp->tf_rbp = regs->r_rbp;
 1521         tp->tf_rbx = regs->r_rbx;
 1522         tp->tf_rdx = regs->r_rdx;
 1523         tp->tf_rcx = regs->r_rcx;
 1524         tp->tf_rax = regs->r_rax;
 1525         tp->tf_rip = regs->r_rip;
 1526         tp->tf_cs = regs->r_cs;
 1527         tp->tf_rflags = rflags;
 1528         tp->tf_rsp = regs->r_rsp;
 1529         tp->tf_ss = regs->r_ss;
 1530         td->td_pcb->pcb_flags |= PCB_FULLCTX;
 1531         return (0);
 1532 }
 1533 
 1534 /* XXX check all this stuff! */
 1535 /* externalize from sv_xmm */
 1536 static void
 1537 fill_fpregs_xmm(struct savefpu *sv_xmm, struct fpreg *fpregs)
 1538 {
 1539         struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
 1540         struct envxmm *penv_xmm = &sv_xmm->sv_env;
 1541         int i;
 1542 
 1543         /* pcb -> fpregs */
 1544         bzero(fpregs, sizeof(*fpregs));
 1545 
 1546         /* FPU control/status */
 1547         penv_fpreg->en_cw = penv_xmm->en_cw;
 1548         penv_fpreg->en_sw = penv_xmm->en_sw;
 1549         penv_fpreg->en_tw = penv_xmm->en_tw;
 1550         penv_fpreg->en_opcode = penv_xmm->en_opcode;
 1551         penv_fpreg->en_rip = penv_xmm->en_rip;
 1552         penv_fpreg->en_rdp = penv_xmm->en_rdp;
 1553         penv_fpreg->en_mxcsr = penv_xmm->en_mxcsr;
 1554         penv_fpreg->en_mxcsr_mask = penv_xmm->en_mxcsr_mask;
 1555 
 1556         /* FPU registers */
 1557         for (i = 0; i < 8; ++i)
 1558                 bcopy(sv_xmm->sv_fp[i].fp_acc.fp_bytes, fpregs->fpr_acc[i], 10);
 1559 
 1560         /* SSE registers */
 1561         for (i = 0; i < 16; ++i)
 1562                 bcopy(sv_xmm->sv_xmm[i].xmm_bytes, fpregs->fpr_xacc[i], 16);
 1563 }
 1564 
 1565 /* internalize from fpregs into sv_xmm */
 1566 static void
 1567 set_fpregs_xmm(struct fpreg *fpregs, struct savefpu *sv_xmm)
 1568 {
 1569         struct envxmm *penv_xmm = &sv_xmm->sv_env;
 1570         struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
 1571         int i;
 1572 
 1573         /* fpregs -> pcb */
 1574         /* FPU control/status */
 1575         penv_xmm->en_cw = penv_fpreg->en_cw;
 1576         penv_xmm->en_sw = penv_fpreg->en_sw;
 1577         penv_xmm->en_tw = penv_fpreg->en_tw;
 1578         penv_xmm->en_opcode = penv_fpreg->en_opcode;
 1579         penv_xmm->en_rip = penv_fpreg->en_rip;
 1580         penv_xmm->en_rdp = penv_fpreg->en_rdp;
 1581         penv_xmm->en_mxcsr = penv_fpreg->en_mxcsr;
 1582         penv_xmm->en_mxcsr_mask = penv_fpreg->en_mxcsr_mask & cpu_mxcsr_mask;
 1583 
 1584         /* FPU registers */
 1585         for (i = 0; i < 8; ++i)
 1586                 bcopy(fpregs->fpr_acc[i], sv_xmm->sv_fp[i].fp_acc.fp_bytes, 10);
 1587 
 1588         /* SSE registers */
 1589         for (i = 0; i < 16; ++i)
 1590                 bcopy(fpregs->fpr_xacc[i], sv_xmm->sv_xmm[i].xmm_bytes, 16);
 1591 }
 1592 
 1593 /* externalize from td->pcb */
 1594 int
 1595 fill_fpregs(struct thread *td, struct fpreg *fpregs)
 1596 {
 1597 
 1598         fill_fpregs_xmm(&td->td_pcb->pcb_save, fpregs);
 1599         return (0);
 1600 }
 1601 
 1602 /* internalize to td->pcb */
 1603 int
 1604 set_fpregs(struct thread *td, struct fpreg *fpregs)
 1605 {
 1606 
 1607         set_fpregs_xmm(fpregs, &td->td_pcb->pcb_save);
 1608         return (0);
 1609 }
 1610 
 1611 /*
 1612  * Get machine context.
 1613  */
 1614 int
 1615 get_mcontext(struct thread *td, mcontext_t *mcp, int flags)
 1616 {
 1617         struct trapframe *tp;
 1618 
 1619         tp = td->td_frame;
 1620         PROC_LOCK(curthread->td_proc);
 1621         mcp->mc_onstack = sigonstack(tp->tf_rsp);
 1622         PROC_UNLOCK(curthread->td_proc);
 1623         mcp->mc_r15 = tp->tf_r15;
 1624         mcp->mc_r14 = tp->tf_r14;
 1625         mcp->mc_r13 = tp->tf_r13;
 1626         mcp->mc_r12 = tp->tf_r12;
 1627         mcp->mc_r11 = tp->tf_r11;
 1628         mcp->mc_r10 = tp->tf_r10;
 1629         mcp->mc_r9  = tp->tf_r9;
 1630         mcp->mc_r8  = tp->tf_r8;
 1631         mcp->mc_rdi = tp->tf_rdi;
 1632         mcp->mc_rsi = tp->tf_rsi;
 1633         mcp->mc_rbp = tp->tf_rbp;
 1634         mcp->mc_rbx = tp->tf_rbx;
 1635         mcp->mc_rcx = tp->tf_rcx;
 1636         mcp->mc_rflags = tp->tf_rflags;
 1637         if (flags & GET_MC_CLEAR_RET) {
 1638                 mcp->mc_rax = 0;
 1639                 mcp->mc_rdx = 0;
 1640                 mcp->mc_rflags &= ~PSL_C;
 1641         } else {
 1642                 mcp->mc_rax = tp->tf_rax;
 1643                 mcp->mc_rdx = tp->tf_rdx;
 1644         }
 1645         mcp->mc_rip = tp->tf_rip;
 1646         mcp->mc_cs = tp->tf_cs;
 1647         mcp->mc_rsp = tp->tf_rsp;
 1648         mcp->mc_ss = tp->tf_ss;
 1649         mcp->mc_len = sizeof(*mcp);
 1650         get_fpcontext(td, mcp);
 1651         return (0);
 1652 }
 1653 
 1654 /*
 1655  * Set machine context.
 1656  *
 1657  * However, we don't set any but the user modifiable flags, and we won't
 1658  * touch the cs selector.
 1659  */
 1660 int
 1661 set_mcontext(struct thread *td, const mcontext_t *mcp)
 1662 {
 1663         struct trapframe *tp;
 1664         long rflags;
 1665         int ret;
 1666 
 1667         tp = td->td_frame;
 1668         if (mcp->mc_len != sizeof(*mcp))
 1669                 return (EINVAL);
 1670         rflags = (mcp->mc_rflags & PSL_USERCHANGE) |
 1671             (tp->tf_rflags & ~PSL_USERCHANGE);
 1672         ret = set_fpcontext(td, mcp);
 1673         if (ret != 0)
 1674                 return (ret);
 1675         tp->tf_r15 = mcp->mc_r15;
 1676         tp->tf_r14 = mcp->mc_r14;
 1677         tp->tf_r13 = mcp->mc_r13;
 1678         tp->tf_r12 = mcp->mc_r12;
 1679         tp->tf_r11 = mcp->mc_r11;
 1680         tp->tf_r10 = mcp->mc_r10;
 1681         tp->tf_r9  = mcp->mc_r9;
 1682         tp->tf_r8  = mcp->mc_r8;
 1683         tp->tf_rdi = mcp->mc_rdi;
 1684         tp->tf_rsi = mcp->mc_rsi;
 1685         tp->tf_rbp = mcp->mc_rbp;
 1686         tp->tf_rbx = mcp->mc_rbx;
 1687         tp->tf_rdx = mcp->mc_rdx;
 1688         tp->tf_rcx = mcp->mc_rcx;
 1689         tp->tf_rax = mcp->mc_rax;
 1690         tp->tf_rip = mcp->mc_rip;
 1691         tp->tf_rflags = rflags;
 1692         tp->tf_rsp = mcp->mc_rsp;
 1693         tp->tf_ss = mcp->mc_ss;
 1694         td->td_pcb->pcb_flags |= PCB_FULLCTX;
 1695         return (0);
 1696 }
 1697 
 1698 static void
 1699 get_fpcontext(struct thread *td, mcontext_t *mcp)
 1700 {
 1701 
 1702         mcp->mc_ownedfp = fpugetregs(td, (struct savefpu *)&mcp->mc_fpstate);
 1703         mcp->mc_fpformat = fpuformat();
 1704 }
 1705 
 1706 static int
 1707 set_fpcontext(struct thread *td, const mcontext_t *mcp)
 1708 {
 1709         struct savefpu *fpstate;
 1710 
 1711         if (mcp->mc_fpformat == _MC_FPFMT_NODEV)
 1712                 return (0);
 1713         else if (mcp->mc_fpformat != _MC_FPFMT_XMM)
 1714                 return (EINVAL);
 1715         else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE)
 1716                 /* We don't care what state is left in the FPU or PCB. */
 1717                 fpstate_drop(td);
 1718         else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU ||
 1719             mcp->mc_ownedfp == _MC_FPOWNED_PCB) {
 1720                 /*
 1721                  * XXX we violate the dubious requirement that fpusetregs()
 1722                  * be called with interrupts disabled.
 1723                  * XXX obsolete on trap-16 systems?
 1724                  */
 1725                 fpstate = (struct savefpu *)&mcp->mc_fpstate;
 1726                 fpstate->sv_env.en_mxcsr &= cpu_mxcsr_mask;
 1727                 fpusetregs(td, fpstate);
 1728         } else
 1729                 return (EINVAL);
 1730         return (0);
 1731 }
 1732 
 1733 void
 1734 fpstate_drop(struct thread *td)
 1735 {
 1736         register_t s;
 1737 
 1738         s = intr_disable();
 1739         if (PCPU_GET(fpcurthread) == td)
 1740                 fpudrop();
 1741         /*
 1742          * XXX force a full drop of the fpu.  The above only drops it if we
 1743          * owned it.
 1744          *
 1745          * XXX I don't much like fpugetregs()'s semantics of doing a full
 1746          * drop.  Dropping only to the pcb matches fnsave's behaviour.
 1747          * We only need to drop to !PCB_INITDONE in sendsig().  But
 1748          * sendsig() is the only caller of fpugetregs()... perhaps we just
 1749          * have too many layers.
 1750          */
 1751         curthread->td_pcb->pcb_flags &= ~PCB_FPUINITDONE;
 1752         intr_restore(s);
 1753 }
 1754 
 1755 int
 1756 fill_dbregs(struct thread *td, struct dbreg *dbregs)
 1757 {
 1758         struct pcb *pcb;
 1759 
 1760         if (td == NULL) {
 1761                 dbregs->dr[0] = rdr0();
 1762                 dbregs->dr[1] = rdr1();
 1763                 dbregs->dr[2] = rdr2();
 1764                 dbregs->dr[3] = rdr3();
 1765                 dbregs->dr[6] = rdr6();
 1766                 dbregs->dr[7] = rdr7();
 1767         } else {
 1768                 pcb = td->td_pcb;
 1769                 dbregs->dr[0] = pcb->pcb_dr0;
 1770                 dbregs->dr[1] = pcb->pcb_dr1;
 1771                 dbregs->dr[2] = pcb->pcb_dr2;
 1772                 dbregs->dr[3] = pcb->pcb_dr3;
 1773                 dbregs->dr[6] = pcb->pcb_dr6;
 1774                 dbregs->dr[7] = pcb->pcb_dr7;
 1775         }
 1776         dbregs->dr[4] = 0;
 1777         dbregs->dr[5] = 0;
 1778         dbregs->dr[8] = 0;
 1779         dbregs->dr[9] = 0;
 1780         dbregs->dr[10] = 0;
 1781         dbregs->dr[11] = 0;
 1782         dbregs->dr[12] = 0;
 1783         dbregs->dr[13] = 0;
 1784         dbregs->dr[14] = 0;
 1785         dbregs->dr[15] = 0;
 1786         return (0);
 1787 }
 1788 
 1789 int
 1790 set_dbregs(struct thread *td, struct dbreg *dbregs)
 1791 {
 1792         struct pcb *pcb;
 1793         int i;
 1794 
 1795         if (td == NULL) {
 1796                 load_dr0(dbregs->dr[0]);
 1797                 load_dr1(dbregs->dr[1]);
 1798                 load_dr2(dbregs->dr[2]);
 1799                 load_dr3(dbregs->dr[3]);
 1800                 load_dr6(dbregs->dr[6]);
 1801                 load_dr7(dbregs->dr[7]);
 1802         } else {
 1803                 /*
 1804                  * Don't let an illegal value for dr7 get set.  Specifically,
 1805                  * check for undefined settings.  Setting these bit patterns
 1806                  * result in undefined behaviour and can lead to an unexpected
 1807                  * TRCTRAP or a general protection fault right here.
 1808                  * Upper bits of dr6 and dr7 must not be set
 1809                  */
 1810                 for (i = 0; i < 4; i++) {
 1811                         if (DBREG_DR7_ACCESS(dbregs->dr[7], i) == 0x02)
 1812                                 return (EINVAL);
 1813                         if (td->td_frame->tf_cs == _ucode32sel &&
 1814                             DBREG_DR7_LEN(dbregs->dr[7], i) == DBREG_DR7_LEN_8)
 1815                                 return (EINVAL);
 1816                 }
 1817                 if ((dbregs->dr[6] & 0xffffffff00000000ul) != 0 ||
 1818                     (dbregs->dr[7] & 0xffffffff00000000ul) != 0)
 1819                         return (EINVAL);
 1820 
 1821                 pcb = td->td_pcb;
 1822 
 1823                 /*
 1824                  * Don't let a process set a breakpoint that is not within the
 1825                  * process's address space.  If a process could do this, it
 1826                  * could halt the system by setting a breakpoint in the kernel
 1827                  * (if ddb was enabled).  Thus, we need to check to make sure
 1828                  * that no breakpoints are being enabled for addresses outside
 1829                  * process's address space.
 1830                  *
 1831                  * XXX - what about when the watched area of the user's
 1832                  * address space is written into from within the kernel
 1833                  * ... wouldn't that still cause a breakpoint to be generated
 1834                  * from within kernel mode?
 1835                  */
 1836 
 1837                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 0)) {
 1838                         /* dr0 is enabled */
 1839                         if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS)
 1840                                 return (EINVAL);
 1841                 }
 1842                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 1)) {
 1843                         /* dr1 is enabled */
 1844                         if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS)
 1845                                 return (EINVAL);
 1846                 }
 1847                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 2)) {
 1848                         /* dr2 is enabled */
 1849                         if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS)
 1850                                 return (EINVAL);
 1851                 }
 1852                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 3)) {
 1853                         /* dr3 is enabled */
 1854                         if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS)
 1855                                 return (EINVAL);
 1856                 }
 1857 
 1858                 pcb->pcb_dr0 = dbregs->dr[0];
 1859                 pcb->pcb_dr1 = dbregs->dr[1];
 1860                 pcb->pcb_dr2 = dbregs->dr[2];
 1861                 pcb->pcb_dr3 = dbregs->dr[3];
 1862                 pcb->pcb_dr6 = dbregs->dr[6];
 1863                 pcb->pcb_dr7 = dbregs->dr[7];
 1864 
 1865                 pcb->pcb_flags |= PCB_DBREGS;
 1866         }
 1867 
 1868         return (0);
 1869 }
 1870 
 1871 void
 1872 reset_dbregs(void)
 1873 {
 1874 
 1875         load_dr7(0);    /* Turn off the control bits first */
 1876         load_dr0(0);
 1877         load_dr1(0);
 1878         load_dr2(0);
 1879         load_dr3(0);
 1880         load_dr6(0);
 1881 }
 1882 
 1883 /*
 1884  * Return > 0 if a hardware breakpoint has been hit, and the
 1885  * breakpoint was in user space.  Return 0, otherwise.
 1886  */
 1887 int
 1888 user_dbreg_trap(void)
 1889 {
 1890         u_int64_t dr7, dr6; /* debug registers dr6 and dr7 */
 1891         u_int64_t bp;       /* breakpoint bits extracted from dr6 */
 1892         int nbp;            /* number of breakpoints that triggered */
 1893         caddr_t addr[4];    /* breakpoint addresses */
 1894         int i;
 1895         
 1896         dr7 = rdr7();
 1897         if ((dr7 & 0x000000ff) == 0) {
 1898                 /*
 1899                  * all GE and LE bits in the dr7 register are zero,
 1900                  * thus the trap couldn't have been caused by the
 1901                  * hardware debug registers
 1902                  */
 1903                 return 0;
 1904         }
 1905 
 1906         nbp = 0;
 1907         dr6 = rdr6();
 1908         bp = dr6 & 0x0000000f;
 1909 
 1910         if (!bp) {
 1911                 /*
 1912                  * None of the breakpoint bits are set meaning this
 1913                  * trap was not caused by any of the debug registers
 1914                  */
 1915                 return 0;
 1916         }
 1917 
 1918         /*
 1919          * at least one of the breakpoints were hit, check to see
 1920          * which ones and if any of them are user space addresses
 1921          */
 1922 
 1923         if (bp & 0x01) {
 1924                 addr[nbp++] = (caddr_t)rdr0();
 1925         }
 1926         if (bp & 0x02) {
 1927                 addr[nbp++] = (caddr_t)rdr1();
 1928         }
 1929         if (bp & 0x04) {
 1930                 addr[nbp++] = (caddr_t)rdr2();
 1931         }
 1932         if (bp & 0x08) {
 1933                 addr[nbp++] = (caddr_t)rdr3();
 1934         }
 1935 
 1936         for (i = 0; i < nbp; i++) {
 1937                 if (addr[i] < (caddr_t)VM_MAXUSER_ADDRESS) {
 1938                         /*
 1939                          * addr[i] is in user space
 1940                          */
 1941                         return nbp;
 1942                 }
 1943         }
 1944 
 1945         /*
 1946          * None of the breakpoints are in user space.
 1947          */
 1948         return 0;
 1949 }
 1950 
 1951 #ifdef KDB
 1952 
 1953 /*
 1954  * Provide inb() and outb() as functions.  They are normally only
 1955  * available as macros calling inlined functions, thus cannot be
 1956  * called from the debugger.
 1957  *
 1958  * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
 1959  */
 1960 
 1961 #undef inb
 1962 #undef outb
 1963 
 1964 /* silence compiler warnings */
 1965 u_char inb(u_int);
 1966 void outb(u_int, u_char);
 1967 
 1968 u_char
 1969 inb(u_int port)
 1970 {
 1971         u_char  data;
 1972         /*
 1973          * We use %%dx and not %1 here because i/o is done at %dx and not at
 1974          * %edx, while gcc generates inferior code (movw instead of movl)
 1975          * if we tell it to load (u_short) port.
 1976          */
 1977         __asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
 1978         return (data);
 1979 }
 1980 
 1981 void
 1982 outb(u_int port, u_char data)
 1983 {
 1984         u_char  al;
 1985         /*
 1986          * Use an unnecessary assignment to help gcc's register allocator.
 1987          * This make a large difference for gcc-1.40 and a tiny difference
 1988          * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
 1989          * best results.  gcc-2.6.0 can't handle this.
 1990          */
 1991         al = data;
 1992         __asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
 1993 }
 1994 
 1995 #endif /* KDB */

Cache object: 8fe3317b0983f017ac3585783a17f411


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.