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

Cache object: 3632d2970020e722125aebcee9924ee4


[ 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.