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-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
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/8.3/sys/amd64/amd64/machdep.c 230472 2012-01-22 21:25:47Z gavin $");
   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_perfmon.h"
   55 #include "opt_sched.h"
   56 #include "opt_kdtrace.h"
   57 
   58 #include <sys/param.h>
   59 #include <sys/proc.h>
   60 #include <sys/systm.h>
   61 #include <sys/bio.h>
   62 #include <sys/buf.h>
   63 #include <sys/bus.h>
   64 #include <sys/callout.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/msgbuf.h>
   77 #include <sys/mutex.h>
   78 #include <sys/pcpu.h>
   79 #include <sys/ptrace.h>
   80 #include <sys/reboot.h>
   81 #include <sys/sched.h>
   82 #include <sys/signalvar.h>
   83 #include <sys/sysctl.h>
   84 #include <sys/sysent.h>
   85 #include <sys/sysproto.h>
   86 #include <sys/ucontext.h>
   87 #include <sys/vmmeter.h>
   88 
   89 #include <vm/vm.h>
   90 #include <vm/vm_extern.h>
   91 #include <vm/vm_kern.h>
   92 #include <vm/vm_page.h>
   93 #include <vm/vm_map.h>
   94 #include <vm/vm_object.h>
   95 #include <vm/vm_pager.h>
   96 #include <vm/vm_param.h>
   97 
   98 #ifdef DDB
   99 #ifndef KDB
  100 #error KDB must be enabled in order for DDB to work!
  101 #endif
  102 #include <ddb/ddb.h>
  103 #include <ddb/db_sym.h>
  104 #endif
  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 struct msgbuf *msgbufp;
  160 
  161 /* Intel ICH registers */
  162 #define ICH_PMBASE      0x400
  163 #define ICH_SMI_EN      ICH_PMBASE + 0x30
  164 
  165 int     _udatasel, _ucodesel, _ucode32sel, _ufssel, _ugssel;
  166 
  167 int cold = 1;
  168 
  169 long Maxmem = 0;
  170 long realmem = 0;
  171 
  172 /*
  173  * The number of PHYSMAP entries must be one less than the number of
  174  * PHYSSEG entries because the PHYSMAP entry that spans the largest
  175  * physical address that is accessible by ISA DMA is split into two
  176  * PHYSSEG entries.
  177  */
  178 #define PHYSMAP_SIZE    (2 * (VM_PHYSSEG_MAX - 1))
  179 
  180 vm_paddr_t phys_avail[PHYSMAP_SIZE + 2];
  181 vm_paddr_t dump_avail[PHYSMAP_SIZE + 2];
  182 
  183 /* must be 2 less so 0 0 can signal end of chunks */
  184 #define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(phys_avail[0])) - 2)
  185 #define DUMP_AVAIL_ARRAY_END ((sizeof(dump_avail) / sizeof(dump_avail[0])) - 2)
  186 
  187 struct kva_md_info kmi;
  188 
  189 static struct trapframe proc0_tf;
  190 struct region_descriptor r_gdt, r_idt;
  191 
  192 struct pcpu __pcpu[MAXCPU];
  193 
  194 struct mtx icu_lock;
  195 
  196 struct mtx dt_lock;     /* lock for GDT and LDT */
  197 
  198 static void
  199 cpu_startup(dummy)
  200         void *dummy;
  201 {
  202         uintmax_t memsize;
  203         char *sysenv;
  204 
  205         /*
  206          * On MacBooks, we need to disallow the legacy USB circuit to
  207          * generate an SMI# because this can cause several problems,
  208          * namely: incorrect CPU frequency detection and failure to
  209          * start the APs.
  210          * We do this by disabling a bit in the SMI_EN (SMI Control and
  211          * Enable register) of the Intel ICH LPC Interface Bridge. 
  212          */
  213         sysenv = getenv("smbios.system.product");
  214         if (sysenv != NULL) {
  215                 if (strncmp(sysenv, "MacBook1,1", 10) == 0 ||
  216                     strncmp(sysenv, "MacBook3,1", 10) == 0 ||
  217                     strncmp(sysenv, "MacBookPro1,1", 13) == 0 ||
  218                     strncmp(sysenv, "MacBookPro1,2", 13) == 0 ||
  219                     strncmp(sysenv, "MacBookPro3,1", 13) == 0 ||
  220                     strncmp(sysenv, "Macmini1,1", 10) == 0) {
  221                         if (bootverbose)
  222                                 printf("Disabling LEGACY_USB_EN bit on "
  223                                     "Intel ICH.\n");
  224                         outl(ICH_SMI_EN, inl(ICH_SMI_EN) & ~0x8);
  225                 }
  226                 freeenv(sysenv);
  227         }
  228 
  229         /*
  230          * Good {morning,afternoon,evening,night}.
  231          */
  232         startrtclock();
  233         printcpuinfo();
  234         panicifcpuunsupported();
  235 #ifdef PERFMON
  236         perfmon_init();
  237 #endif
  238         realmem = Maxmem;
  239 
  240         /*
  241          * Display physical memory if SMBIOS reports reasonable amount.
  242          */
  243         memsize = 0;
  244         sysenv = getenv("smbios.memory.enabled");
  245         if (sysenv != NULL) {
  246                 memsize = (uintmax_t)strtoul(sysenv, (char **)NULL, 10) << 10;
  247                 freeenv(sysenv);
  248         }
  249         if (memsize < ptoa((uintmax_t)cnt.v_free_count))
  250                 memsize = ptoa((uintmax_t)Maxmem);
  251         printf("real memory  = %ju (%ju MB)\n", memsize, memsize >> 20);
  252 
  253         /*
  254          * Display any holes after the first chunk of extended memory.
  255          */
  256         if (bootverbose) {
  257                 int indx;
  258 
  259                 printf("Physical memory chunk(s):\n");
  260                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
  261                         vm_paddr_t size;
  262 
  263                         size = phys_avail[indx + 1] - phys_avail[indx];
  264                         printf(
  265                             "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
  266                             (uintmax_t)phys_avail[indx],
  267                             (uintmax_t)phys_avail[indx + 1] - 1,
  268                             (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
  269                 }
  270         }
  271 
  272         vm_ksubmap_init(&kmi);
  273 
  274         printf("avail memory = %ju (%ju MB)\n",
  275             ptoa((uintmax_t)cnt.v_free_count),
  276             ptoa((uintmax_t)cnt.v_free_count) / 1048576);
  277 
  278         /*
  279          * Set up buffers, so they can be used to read disk labels.
  280          */
  281         bufinit();
  282         vm_pager_bufferinit();
  283 
  284         cpu_setregs();
  285 }
  286 
  287 /*
  288  * Send an interrupt to process.
  289  *
  290  * Stack is set up to allow sigcode stored
  291  * at top to call routine, followed by call
  292  * to sigreturn routine below.  After sigreturn
  293  * resets the signal mask, the stack, and the
  294  * frame pointer, it returns to the user
  295  * specified pc, psl.
  296  */
  297 void
  298 sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
  299 {
  300         struct sigframe sf, *sfp;
  301         struct pcb *pcb;
  302         struct proc *p;
  303         struct thread *td;
  304         struct sigacts *psp;
  305         char *sp;
  306         struct trapframe *regs;
  307         int sig;
  308         int oonstack;
  309 
  310         td = curthread;
  311         pcb = td->td_pcb;
  312         p = td->td_proc;
  313         PROC_LOCK_ASSERT(p, MA_OWNED);
  314         sig = ksi->ksi_signo;
  315         psp = p->p_sigacts;
  316         mtx_assert(&psp->ps_mtx, MA_OWNED);
  317         regs = td->td_frame;
  318         oonstack = sigonstack(regs->tf_rsp);
  319 
  320         /* Save user context. */
  321         bzero(&sf, sizeof(sf));
  322         sf.sf_uc.uc_sigmask = *mask;
  323         sf.sf_uc.uc_stack = td->td_sigstk;
  324         sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
  325             ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
  326         sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
  327         bcopy(regs, &sf.sf_uc.uc_mcontext.mc_rdi, sizeof(*regs));
  328         sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext); /* magic */
  329         get_fpcontext(td, &sf.sf_uc.uc_mcontext);
  330         fpstate_drop(td);
  331         sf.sf_uc.uc_mcontext.mc_fsbase = pcb->pcb_fsbase;
  332         sf.sf_uc.uc_mcontext.mc_gsbase = pcb->pcb_gsbase;
  333         bzero(sf.sf_uc.uc_mcontext.mc_spare,
  334             sizeof(sf.sf_uc.uc_mcontext.mc_spare));
  335         bzero(sf.sf_uc.__spare__, sizeof(sf.sf_uc.__spare__));
  336 
  337         /* Allocate space for the signal handler context. */
  338         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
  339             SIGISMEMBER(psp->ps_sigonstack, sig)) {
  340                 sp = td->td_sigstk.ss_sp +
  341                     td->td_sigstk.ss_size - sizeof(struct sigframe);
  342 #if defined(COMPAT_43)
  343                 td->td_sigstk.ss_flags |= SS_ONSTACK;
  344 #endif
  345         } else
  346                 sp = (char *)regs->tf_rsp - sizeof(struct sigframe) - 128;
  347         /* Align to 16 bytes. */
  348         sfp = (struct sigframe *)((unsigned long)sp & ~0xFul);
  349 
  350         /* Translate the signal if appropriate. */
  351         if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
  352                 sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
  353 
  354         /* Build the argument list for the signal handler. */
  355         regs->tf_rdi = sig;                     /* arg 1 in %rdi */
  356         regs->tf_rdx = (register_t)&sfp->sf_uc; /* arg 3 in %rdx */
  357         bzero(&sf.sf_si, sizeof(sf.sf_si));
  358         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
  359                 /* Signal handler installed with SA_SIGINFO. */
  360                 regs->tf_rsi = (register_t)&sfp->sf_si; /* arg 2 in %rsi */
  361                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
  362 
  363                 /* Fill in POSIX parts */
  364                 sf.sf_si = ksi->ksi_info;
  365                 sf.sf_si.si_signo = sig; /* maybe a translated signal */
  366                 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
  367         } else {
  368                 /* Old FreeBSD-style arguments. */
  369                 regs->tf_rsi = ksi->ksi_code;   /* arg 2 in %rsi */
  370                 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
  371                 sf.sf_ahu.sf_handler = catcher;
  372         }
  373         mtx_unlock(&psp->ps_mtx);
  374         PROC_UNLOCK(p);
  375 
  376         /*
  377          * Copy the sigframe out to the user's stack.
  378          */
  379         if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
  380 #ifdef DEBUG
  381                 printf("process %ld has trashed its stack\n", (long)p->p_pid);
  382 #endif
  383                 PROC_LOCK(p);
  384                 sigexit(td, SIGILL);
  385         }
  386 
  387         regs->tf_rsp = (long)sfp;
  388         regs->tf_rip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
  389         regs->tf_rflags &= ~(PSL_T | PSL_D);
  390         regs->tf_cs = _ucodesel;
  391         regs->tf_ds = _udatasel;
  392         regs->tf_es = _udatasel;
  393         regs->tf_fs = _ufssel;
  394         regs->tf_gs = _ugssel;
  395         regs->tf_flags = TF_HASSEGS;
  396         set_pcb_flags(pcb, PCB_FULL_IRET);
  397         PROC_LOCK(p);
  398         mtx_lock(&psp->ps_mtx);
  399 }
  400 
  401 /*
  402  * System call to cleanup state after a signal
  403  * has been taken.  Reset signal mask and
  404  * stack state from context left by sendsig (above).
  405  * Return to previous pc and psl as specified by
  406  * context left by sendsig. Check carefully to
  407  * make sure that the user has not modified the
  408  * state to gain improper privileges.
  409  *
  410  * MPSAFE
  411  */
  412 int
  413 sigreturn(td, uap)
  414         struct thread *td;
  415         struct sigreturn_args /* {
  416                 const struct __ucontext *sigcntxp;
  417         } */ *uap;
  418 {
  419         ucontext_t uc;
  420         struct pcb *pcb;
  421         struct proc *p;
  422         struct trapframe *regs;
  423         ucontext_t *ucp;
  424         long rflags;
  425         int cs, error, ret;
  426         ksiginfo_t ksi;
  427 
  428         pcb = td->td_pcb;
  429         p = td->td_proc;
  430 
  431         error = copyin(uap->sigcntxp, &uc, sizeof(uc));
  432         if (error != 0) {
  433                 uprintf("pid %d (%s): sigreturn copyin failed\n",
  434                     p->p_pid, td->td_name);
  435                 return (error);
  436         }
  437         ucp = &uc;
  438         if ((ucp->uc_mcontext.mc_flags & ~_MC_FLAG_MASK) != 0) {
  439                 uprintf("pid %d (%s): sigreturn mc_flags %x\n", p->p_pid,
  440                     td->td_name, ucp->uc_mcontext.mc_flags);
  441                 return (EINVAL);
  442         }
  443         regs = td->td_frame;
  444         rflags = ucp->uc_mcontext.mc_rflags;
  445         /*
  446          * Don't allow users to change privileged or reserved flags.
  447          */
  448         /*
  449          * XXX do allow users to change the privileged flag PSL_RF.
  450          * The cpu sets PSL_RF in tf_rflags for faults.  Debuggers
  451          * should sometimes set it there too.  tf_rflags is kept in
  452          * the signal context during signal handling and there is no
  453          * other place to remember it, so the PSL_RF bit may be
  454          * corrupted by the signal handler without us knowing.
  455          * Corruption of the PSL_RF bit at worst causes one more or
  456          * one less debugger trap, so allowing it is fairly harmless.
  457          */
  458         if (!EFL_SECURE(rflags & ~PSL_RF, regs->tf_rflags & ~PSL_RF)) {
  459                 uprintf("pid %d (%s): sigreturn rflags = 0x%lx\n", p->p_pid,
  460                     td->td_name, rflags);
  461                 return (EINVAL);
  462         }
  463 
  464         /*
  465          * Don't allow users to load a valid privileged %cs.  Let the
  466          * hardware check for invalid selectors, excess privilege in
  467          * other selectors, invalid %eip's and invalid %esp's.
  468          */
  469         cs = ucp->uc_mcontext.mc_cs;
  470         if (!CS_SECURE(cs)) {
  471                 uprintf("pid %d (%s): sigreturn cs = 0x%x\n", p->p_pid,
  472                     td->td_name, cs);
  473                 ksiginfo_init_trap(&ksi);
  474                 ksi.ksi_signo = SIGBUS;
  475                 ksi.ksi_code = BUS_OBJERR;
  476                 ksi.ksi_trapno = T_PROTFLT;
  477                 ksi.ksi_addr = (void *)regs->tf_rip;
  478                 trapsignal(td, &ksi);
  479                 return (EINVAL);
  480         }
  481 
  482         ret = set_fpcontext(td, &ucp->uc_mcontext);
  483         if (ret != 0) {
  484                 uprintf("pid %d (%s): sigreturn set_fpcontext err %d\n",
  485                     p->p_pid, td->td_name, ret);
  486                 return (ret);
  487         }
  488         bcopy(&ucp->uc_mcontext.mc_rdi, regs, sizeof(*regs));
  489         pcb->pcb_fsbase = ucp->uc_mcontext.mc_fsbase;
  490         pcb->pcb_gsbase = ucp->uc_mcontext.mc_gsbase;
  491 
  492 #if defined(COMPAT_43)
  493         if (ucp->uc_mcontext.mc_onstack & 1)
  494                 td->td_sigstk.ss_flags |= SS_ONSTACK;
  495         else
  496                 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
  497 #endif
  498 
  499         kern_sigprocmask(td, SIG_SETMASK, &ucp->uc_sigmask, NULL, 0);
  500         set_pcb_flags(pcb, PCB_FULL_IRET);
  501         return (EJUSTRETURN);
  502 }
  503 
  504 #ifdef COMPAT_FREEBSD4
  505 int
  506 freebsd4_sigreturn(struct thread *td, struct freebsd4_sigreturn_args *uap)
  507 {
  508  
  509         return sigreturn(td, (struct sigreturn_args *)uap);
  510 }
  511 #endif
  512 
  513 
  514 /*
  515  * Machine dependent boot() routine
  516  *
  517  * I haven't seen anything to put here yet
  518  * Possibly some stuff might be grafted back here from boot()
  519  */
  520 void
  521 cpu_boot(int howto)
  522 {
  523 }
  524 
  525 /*
  526  * Flush the D-cache for non-DMA I/O so that the I-cache can
  527  * be made coherent later.
  528  */
  529 void
  530 cpu_flush_dcache(void *ptr, size_t len)
  531 {
  532         /* Not applicable */
  533 }
  534 
  535 /* Get current clock frequency for the given cpu id. */
  536 int
  537 cpu_est_clockrate(int cpu_id, uint64_t *rate)
  538 {
  539         register_t reg;
  540         uint64_t tsc1, tsc2;
  541 
  542         if (pcpu_find(cpu_id) == NULL || rate == NULL)
  543                 return (EINVAL);
  544 
  545         /* If we're booting, trust the rate calibrated moments ago. */
  546         if (cold) {
  547                 *rate = tsc_freq;
  548                 return (0);
  549         }
  550 
  551 #ifdef SMP
  552         /* Schedule ourselves on the indicated cpu. */
  553         thread_lock(curthread);
  554         sched_bind(curthread, cpu_id);
  555         thread_unlock(curthread);
  556 #endif
  557 
  558         /* Calibrate by measuring a short delay. */
  559         reg = intr_disable();
  560         tsc1 = rdtsc();
  561         DELAY(1000);
  562         tsc2 = rdtsc();
  563         intr_restore(reg);
  564 
  565 #ifdef SMP
  566         thread_lock(curthread);
  567         sched_unbind(curthread);
  568         thread_unlock(curthread);
  569 #endif
  570 
  571         /*
  572          * Calculate the difference in readings, convert to Mhz, and
  573          * subtract 0.5% of the total.  Empirical testing has shown that
  574          * overhead in DELAY() works out to approximately this value.
  575          */
  576         tsc2 -= tsc1;
  577         *rate = tsc2 * 1000 - tsc2 * 5;
  578         return (0);
  579 }
  580 
  581 /*
  582  * Shutdown the CPU as much as possible
  583  */
  584 void
  585 cpu_halt(void)
  586 {
  587         for (;;)
  588                 __asm__ ("hlt");
  589 }
  590 
  591 void (*cpu_idle_hook)(void) = NULL;     /* ACPI idle hook. */
  592 
  593 static void
  594 cpu_idle_hlt(int busy)
  595 {
  596         /*
  597          * we must absolutely guarentee that hlt is the next instruction
  598          * after sti or we introduce a timing window.
  599          */
  600         disable_intr();
  601         if (sched_runnable())
  602                 enable_intr();
  603         else
  604                 __asm __volatile("sti; hlt");
  605 }
  606 
  607 static void
  608 cpu_idle_acpi(int busy)
  609 {
  610         disable_intr();
  611         if (sched_runnable())
  612                 enable_intr();
  613         else if (cpu_idle_hook)
  614                 cpu_idle_hook();
  615         else
  616                 __asm __volatile("sti; hlt");
  617 }
  618 
  619 static int cpu_ident_amdc1e = 0;
  620 
  621 static int
  622 cpu_probe_amdc1e(void)
  623 {
  624         int i;
  625 
  626         /*
  627          * Forget it, if we're not using local APIC timer.
  628          */
  629         if (resource_disabled("apic", 0) ||
  630             (resource_int_value("apic", 0, "clock", &i) == 0 && i == 0))
  631                 return (0);
  632 
  633         /*
  634          * Detect the presence of C1E capability mostly on latest
  635          * dual-cores (or future) k8 family.
  636          */
  637         if (cpu_vendor_id == CPU_VENDOR_AMD &&
  638             (cpu_id & 0x00000f00) == 0x00000f00 &&
  639             (cpu_id & 0x0fff0000) >=  0x00040000) {
  640                 cpu_ident_amdc1e = 1;
  641                 return (1);
  642         }
  643 
  644         return (0);
  645 }
  646 
  647 /*
  648  * C1E renders the local APIC timer dead, so we disable it by
  649  * reading the Interrupt Pending Message register and clearing
  650  * both C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
  651  * 
  652  * Reference:
  653  *   "BIOS and Kernel Developer's Guide for AMD NPT Family 0Fh Processors"
  654  *   #32559 revision 3.00+
  655  */
  656 #define MSR_AMDK8_IPM           0xc0010055
  657 #define AMDK8_SMIONCMPHALT      (1ULL << 27)
  658 #define AMDK8_C1EONCMPHALT      (1ULL << 28)
  659 #define AMDK8_CMPHALT           (AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
  660 
  661 static void
  662 cpu_idle_amdc1e(int busy)
  663 {
  664 
  665         disable_intr();
  666         if (sched_runnable())
  667                 enable_intr();
  668         else {
  669                 uint64_t msr;
  670 
  671                 msr = rdmsr(MSR_AMDK8_IPM);
  672                 if (msr & AMDK8_CMPHALT)
  673                         wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
  674 
  675                 if (cpu_idle_hook)
  676                         cpu_idle_hook();
  677                 else
  678                         __asm __volatile("sti; hlt");
  679         }
  680 }
  681 
  682 static void
  683 cpu_idle_spin(int busy)
  684 {
  685         return;
  686 }
  687 
  688 void (*cpu_idle_fn)(int) = cpu_idle_acpi;
  689 
  690 void
  691 cpu_idle(int busy)
  692 {
  693 #ifdef SMP
  694         if (mp_grab_cpu_hlt())
  695                 return;
  696 #endif
  697         cpu_idle_fn(busy);
  698 }
  699 
  700 /*
  701  * mwait cpu power states.  Lower 4 bits are sub-states.
  702  */
  703 #define MWAIT_C0        0xf0
  704 #define MWAIT_C1        0x00
  705 #define MWAIT_C2        0x10
  706 #define MWAIT_C3        0x20
  707 #define MWAIT_C4        0x30
  708 
  709 #define MWAIT_DISABLED  0x0
  710 #define MWAIT_WOKEN     0x1
  711 #define MWAIT_WAITING   0x2
  712 
  713 static void
  714 cpu_idle_mwait(int busy)
  715 {
  716         int *mwait;
  717 
  718         mwait = (int *)PCPU_PTR(monitorbuf);
  719         *mwait = MWAIT_WAITING;
  720         if (sched_runnable())
  721                 return;
  722         cpu_monitor(mwait, 0, 0);
  723         if (*mwait == MWAIT_WAITING)
  724                 cpu_mwait(0, MWAIT_C1);
  725 }
  726 
  727 static void
  728 cpu_idle_mwait_hlt(int busy)
  729 {
  730         int *mwait;
  731 
  732         mwait = (int *)PCPU_PTR(monitorbuf);
  733         if (busy == 0) {
  734                 *mwait = MWAIT_DISABLED;
  735                 cpu_idle_hlt(busy);
  736                 return;
  737         }
  738         *mwait = MWAIT_WAITING;
  739         if (sched_runnable())
  740                 return;
  741         cpu_monitor(mwait, 0, 0);
  742         if (*mwait == MWAIT_WAITING)
  743                 cpu_mwait(0, MWAIT_C1);
  744 }
  745 
  746 int
  747 cpu_idle_wakeup(int cpu)
  748 {
  749         struct pcpu *pcpu;
  750         int *mwait;
  751 
  752         if (cpu_idle_fn == cpu_idle_spin)
  753                 return (1);
  754         if (cpu_idle_fn != cpu_idle_mwait && cpu_idle_fn != cpu_idle_mwait_hlt)
  755                 return (0);
  756         pcpu = pcpu_find(cpu);
  757         mwait = (int *)pcpu->pc_monitorbuf;
  758         /*
  759          * This doesn't need to be atomic since missing the race will
  760          * simply result in unnecessary IPIs.
  761          */
  762         if (cpu_idle_fn == cpu_idle_mwait_hlt && *mwait == MWAIT_DISABLED)
  763                 return (0);
  764         *mwait = MWAIT_WOKEN;
  765 
  766         return (1);
  767 }
  768 
  769 /*
  770  * Ordered by speed/power consumption.
  771  */
  772 struct {
  773         void    *id_fn;
  774         char    *id_name;
  775 } idle_tbl[] = {
  776         { cpu_idle_spin, "spin" },
  777         { cpu_idle_mwait, "mwait" },
  778         { cpu_idle_mwait_hlt, "mwait_hlt" },
  779         { cpu_idle_amdc1e, "amdc1e" },
  780         { cpu_idle_hlt, "hlt" },
  781         { cpu_idle_acpi, "acpi" },
  782         { NULL, NULL }
  783 };
  784 
  785 static int
  786 idle_sysctl_available(SYSCTL_HANDLER_ARGS)
  787 {
  788         char *avail, *p;
  789         int error;
  790         int i;
  791 
  792         avail = malloc(256, M_TEMP, M_WAITOK);
  793         p = avail;
  794         for (i = 0; idle_tbl[i].id_name != NULL; i++) {
  795                 if (strstr(idle_tbl[i].id_name, "mwait") &&
  796                     (cpu_feature2 & CPUID2_MON) == 0)
  797                         continue;
  798                 if (strcmp(idle_tbl[i].id_name, "amdc1e") == 0 &&
  799                     cpu_ident_amdc1e == 0)
  800                         continue;
  801                 p += sprintf(p, "%s, ", idle_tbl[i].id_name);
  802         }
  803         error = sysctl_handle_string(oidp, avail, 0, req);
  804         free(avail, M_TEMP);
  805         return (error);
  806 }
  807 
  808 static int
  809 idle_sysctl(SYSCTL_HANDLER_ARGS)
  810 {
  811         char buf[16];
  812         int error;
  813         char *p;
  814         int i;
  815 
  816         p = "unknown";
  817         for (i = 0; idle_tbl[i].id_name != NULL; i++) {
  818                 if (idle_tbl[i].id_fn == cpu_idle_fn) {
  819                         p = idle_tbl[i].id_name;
  820                         break;
  821                 }
  822         }
  823         strncpy(buf, p, sizeof(buf));
  824         error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
  825         if (error != 0 || req->newptr == NULL)
  826                 return (error);
  827         for (i = 0; idle_tbl[i].id_name != NULL; i++) {
  828                 if (strstr(idle_tbl[i].id_name, "mwait") &&
  829                     (cpu_feature2 & CPUID2_MON) == 0)
  830                         continue;
  831                 if (strcmp(idle_tbl[i].id_name, "amdc1e") == 0 &&
  832                     cpu_ident_amdc1e == 0)
  833                         continue;
  834                 if (strcmp(idle_tbl[i].id_name, buf))
  835                         continue;
  836                 cpu_idle_fn = idle_tbl[i].id_fn;
  837                 return (0);
  838         }
  839         return (EINVAL);
  840 }
  841 
  842 SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
  843     0, 0, idle_sysctl_available, "A", "list of available idle functions");
  844 
  845 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
  846     idle_sysctl, "A", "currently selected idle function");
  847 
  848 /*
  849  * Reset registers to default values on exec.
  850  */
  851 void
  852 exec_setregs(td, entry, stack, ps_strings)
  853         struct thread *td;
  854         u_long entry;
  855         u_long stack;
  856         u_long ps_strings;
  857 {
  858         struct trapframe *regs = td->td_frame;
  859         struct pcb *pcb = td->td_pcb;
  860 
  861         mtx_lock(&dt_lock);
  862         if (td->td_proc->p_md.md_ldt != NULL)
  863                 user_ldt_free(td);
  864         else
  865                 mtx_unlock(&dt_lock);
  866         
  867         pcb->pcb_fsbase = 0;
  868         pcb->pcb_gsbase = 0;
  869         clear_pcb_flags(pcb, PCB_32BIT | PCB_GS32BIT);
  870         pcb->pcb_initial_fpucw = __INITIAL_FPUCW__;
  871         set_pcb_flags(pcb, PCB_FULL_IRET);
  872 
  873         bzero((char *)regs, sizeof(struct trapframe));
  874         regs->tf_rip = entry;
  875         regs->tf_rsp = ((stack - 8) & ~0xFul) + 8;
  876         regs->tf_rdi = stack;           /* argv */
  877         regs->tf_rflags = PSL_USER | (regs->tf_rflags & PSL_T);
  878         regs->tf_ss = _udatasel;
  879         regs->tf_cs = _ucodesel;
  880         regs->tf_ds = _udatasel;
  881         regs->tf_es = _udatasel;
  882         regs->tf_fs = _ufssel;
  883         regs->tf_gs = _ugssel;
  884         regs->tf_flags = TF_HASSEGS;
  885         td->td_retval[1] = 0;
  886 
  887         /*
  888          * Reset the hardware debug registers if they were in use.
  889          * They won't have any meaning for the newly exec'd process.
  890          */
  891         if (pcb->pcb_flags & PCB_DBREGS) {
  892                 pcb->pcb_dr0 = 0;
  893                 pcb->pcb_dr1 = 0;
  894                 pcb->pcb_dr2 = 0;
  895                 pcb->pcb_dr3 = 0;
  896                 pcb->pcb_dr6 = 0;
  897                 pcb->pcb_dr7 = 0;
  898                 if (pcb == PCPU_GET(curpcb)) {
  899                         /*
  900                          * Clear the debug registers on the running
  901                          * CPU, otherwise they will end up affecting
  902                          * the next process we switch to.
  903                          */
  904                         reset_dbregs();
  905                 }
  906                 clear_pcb_flags(pcb, PCB_DBREGS);
  907         }
  908 
  909         /*
  910          * Drop the FP state if we hold it, so that the process gets a
  911          * clean FP state if it uses the FPU again.
  912          */
  913         fpstate_drop(td);
  914 }
  915 
  916 void
  917 cpu_setregs(void)
  918 {
  919         register_t cr0;
  920 
  921         cr0 = rcr0();
  922         /*
  923          * CR0_MP, CR0_NE and CR0_TS are also set by npx_probe() for the
  924          * BSP.  See the comments there about why we set them.
  925          */
  926         cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
  927         load_cr0(cr0);
  928 }
  929 
  930 /*
  931  * Initialize amd64 and configure to run kernel
  932  */
  933 
  934 /*
  935  * Initialize segments & interrupt table
  936  */
  937 
  938 struct user_segment_descriptor gdt[NGDT * MAXCPU];/* global descriptor tables */
  939 static struct gate_descriptor idt0[NIDT];
  940 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
  941 
  942 static char dblfault_stack[PAGE_SIZE] __aligned(16);
  943 
  944 static char nmi0_stack[PAGE_SIZE] __aligned(16);
  945 CTASSERT(sizeof(struct nmi_pcpu) == 16);
  946 
  947 struct amd64tss common_tss[MAXCPU];
  948 
  949 /*
  950  * Software prototypes -- in more palatable form.
  951  *
  952  * Keep GUFS32, GUGS32, GUCODE32 and GUDATA at the same
  953  * slots as corresponding segments for i386 kernel.
  954  */
  955 struct soft_segment_descriptor gdt_segs[] = {
  956 /* GNULL_SEL    0 Null Descriptor */
  957 {       .ssd_base = 0x0,
  958         .ssd_limit = 0x0,
  959         .ssd_type = 0,
  960         .ssd_dpl = 0,
  961         .ssd_p = 0,
  962         .ssd_long = 0,
  963         .ssd_def32 = 0,
  964         .ssd_gran = 0           },
  965 /* GNULL2_SEL   1 Null Descriptor */
  966 {       .ssd_base = 0x0,
  967         .ssd_limit = 0x0,
  968         .ssd_type = 0,
  969         .ssd_dpl = 0,
  970         .ssd_p = 0,
  971         .ssd_long = 0,
  972         .ssd_def32 = 0,
  973         .ssd_gran = 0           },
  974 /* GUFS32_SEL   2 32 bit %gs Descriptor for user */
  975 {       .ssd_base = 0x0,
  976         .ssd_limit = 0xfffff,
  977         .ssd_type = SDT_MEMRWA,
  978         .ssd_dpl = SEL_UPL,
  979         .ssd_p = 1,
  980         .ssd_long = 0,
  981         .ssd_def32 = 1,
  982         .ssd_gran = 1           },
  983 /* GUGS32_SEL   3 32 bit %fs Descriptor for user */
  984 {       .ssd_base = 0x0,
  985         .ssd_limit = 0xfffff,
  986         .ssd_type = SDT_MEMRWA,
  987         .ssd_dpl = SEL_UPL,
  988         .ssd_p = 1,
  989         .ssd_long = 0,
  990         .ssd_def32 = 1,
  991         .ssd_gran = 1           },
  992 /* GCODE_SEL    4 Code Descriptor for kernel */
  993 {       .ssd_base = 0x0,
  994         .ssd_limit = 0xfffff,
  995         .ssd_type = SDT_MEMERA,
  996         .ssd_dpl = SEL_KPL,
  997         .ssd_p = 1,
  998         .ssd_long = 1,
  999         .ssd_def32 = 0,
 1000         .ssd_gran = 1           },
 1001 /* GDATA_SEL    5 Data Descriptor for kernel */
 1002 {       .ssd_base = 0x0,
 1003         .ssd_limit = 0xfffff,
 1004         .ssd_type = SDT_MEMRWA,
 1005         .ssd_dpl = SEL_KPL,
 1006         .ssd_p = 1,
 1007         .ssd_long = 1,
 1008         .ssd_def32 = 0,
 1009         .ssd_gran = 1           },
 1010 /* GUCODE32_SEL 6 32 bit Code Descriptor for user */
 1011 {       .ssd_base = 0x0,
 1012         .ssd_limit = 0xfffff,
 1013         .ssd_type = SDT_MEMERA,
 1014         .ssd_dpl = SEL_UPL,
 1015         .ssd_p = 1,
 1016         .ssd_long = 0,
 1017         .ssd_def32 = 1,
 1018         .ssd_gran = 1           },
 1019 /* GUDATA_SEL   7 32/64 bit Data Descriptor for user */
 1020 {       .ssd_base = 0x0,
 1021         .ssd_limit = 0xfffff,
 1022         .ssd_type = SDT_MEMRWA,
 1023         .ssd_dpl = SEL_UPL,
 1024         .ssd_p = 1,
 1025         .ssd_long = 0,
 1026         .ssd_def32 = 1,
 1027         .ssd_gran = 1           },
 1028 /* GUCODE_SEL   8 64 bit Code Descriptor for user */
 1029 {       .ssd_base = 0x0,
 1030         .ssd_limit = 0xfffff,
 1031         .ssd_type = SDT_MEMERA,
 1032         .ssd_dpl = SEL_UPL,
 1033         .ssd_p = 1,
 1034         .ssd_long = 1,
 1035         .ssd_def32 = 0,
 1036         .ssd_gran = 1           },
 1037 /* GPROC0_SEL   9 Proc 0 Tss Descriptor */
 1038 {       .ssd_base = 0x0,
 1039         .ssd_limit = sizeof(struct amd64tss) + IOPAGES * PAGE_SIZE - 1,
 1040         .ssd_type = SDT_SYSTSS,
 1041         .ssd_dpl = SEL_KPL,
 1042         .ssd_p = 1,
 1043         .ssd_long = 0,
 1044         .ssd_def32 = 0,
 1045         .ssd_gran = 0           },
 1046 /* Actually, the TSS is a system descriptor which is double size */
 1047 {       .ssd_base = 0x0,
 1048         .ssd_limit = 0x0,
 1049         .ssd_type = 0,
 1050         .ssd_dpl = 0,
 1051         .ssd_p = 0,
 1052         .ssd_long = 0,
 1053         .ssd_def32 = 0,
 1054         .ssd_gran = 0           },
 1055 /* GUSERLDT_SEL 11 LDT Descriptor */
 1056 {       .ssd_base = 0x0,
 1057         .ssd_limit = 0x0,
 1058         .ssd_type = 0,
 1059         .ssd_dpl = 0,
 1060         .ssd_p = 0,
 1061         .ssd_long = 0,
 1062         .ssd_def32 = 0,
 1063         .ssd_gran = 0           },
 1064 /* GUSERLDT_SEL 12 LDT Descriptor, double size */
 1065 {       .ssd_base = 0x0,
 1066         .ssd_limit = 0x0,
 1067         .ssd_type = 0,
 1068         .ssd_dpl = 0,
 1069         .ssd_p = 0,
 1070         .ssd_long = 0,
 1071         .ssd_def32 = 0,
 1072         .ssd_gran = 0           },
 1073 };
 1074 
 1075 void
 1076 setidt(idx, func, typ, dpl, ist)
 1077         int idx;
 1078         inthand_t *func;
 1079         int typ;
 1080         int dpl;
 1081         int ist;
 1082 {
 1083         struct gate_descriptor *ip;
 1084 
 1085         ip = idt + idx;
 1086         ip->gd_looffset = (uintptr_t)func;
 1087         ip->gd_selector = GSEL(GCODE_SEL, SEL_KPL);
 1088         ip->gd_ist = ist;
 1089         ip->gd_xx = 0;
 1090         ip->gd_type = typ;
 1091         ip->gd_dpl = dpl;
 1092         ip->gd_p = 1;
 1093         ip->gd_hioffset = ((uintptr_t)func)>>16 ;
 1094 }
 1095 
 1096 extern inthand_t
 1097         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
 1098         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
 1099         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
 1100         IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
 1101         IDTVEC(xmm), IDTVEC(dblfault),
 1102 #ifdef KDTRACE_HOOKS
 1103         IDTVEC(dtrace_ret),
 1104 #endif
 1105         IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
 1106 
 1107 #ifdef DDB
 1108 /*
 1109  * Display the index and function name of any IDT entries that don't use
 1110  * the default 'rsvd' entry point.
 1111  */
 1112 DB_SHOW_COMMAND(idt, db_show_idt)
 1113 {
 1114         struct gate_descriptor *ip;
 1115         int idx;
 1116         uintptr_t func;
 1117 
 1118         ip = idt;
 1119         for (idx = 0; idx < NIDT && !db_pager_quit; idx++) {
 1120                 func = ((long)ip->gd_hioffset << 16 | ip->gd_looffset);
 1121                 if (func != (uintptr_t)&IDTVEC(rsvd)) {
 1122                         db_printf("%3d\t", idx);
 1123                         db_printsym(func, DB_STGY_PROC);
 1124                         db_printf("\n");
 1125                 }
 1126                 ip++;
 1127         }
 1128 }
 1129 #endif
 1130 
 1131 void
 1132 sdtossd(sd, ssd)
 1133         struct user_segment_descriptor *sd;
 1134         struct soft_segment_descriptor *ssd;
 1135 {
 1136 
 1137         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
 1138         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
 1139         ssd->ssd_type  = sd->sd_type;
 1140         ssd->ssd_dpl   = sd->sd_dpl;
 1141         ssd->ssd_p     = sd->sd_p;
 1142         ssd->ssd_long  = sd->sd_long;
 1143         ssd->ssd_def32 = sd->sd_def32;
 1144         ssd->ssd_gran  = sd->sd_gran;
 1145 }
 1146 
 1147 void
 1148 ssdtosd(ssd, sd)
 1149         struct soft_segment_descriptor *ssd;
 1150         struct user_segment_descriptor *sd;
 1151 {
 1152 
 1153         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
 1154         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xff;
 1155         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
 1156         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
 1157         sd->sd_type  = ssd->ssd_type;
 1158         sd->sd_dpl   = ssd->ssd_dpl;
 1159         sd->sd_p     = ssd->ssd_p;
 1160         sd->sd_long  = ssd->ssd_long;
 1161         sd->sd_def32 = ssd->ssd_def32;
 1162         sd->sd_gran  = ssd->ssd_gran;
 1163 }
 1164 
 1165 void
 1166 ssdtosyssd(ssd, sd)
 1167         struct soft_segment_descriptor *ssd;
 1168         struct system_segment_descriptor *sd;
 1169 {
 1170 
 1171         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
 1172         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xfffffffffful;
 1173         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
 1174         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
 1175         sd->sd_type  = ssd->ssd_type;
 1176         sd->sd_dpl   = ssd->ssd_dpl;
 1177         sd->sd_p     = ssd->ssd_p;
 1178         sd->sd_gran  = ssd->ssd_gran;
 1179 }
 1180 
 1181 #if !defined(DEV_ATPIC) && defined(DEV_ISA)
 1182 #include <isa/isavar.h>
 1183 #include <isa/isareg.h>
 1184 /*
 1185  * Return a bitmap of the current interrupt requests.  This is 8259-specific
 1186  * and is only suitable for use at probe time.
 1187  * This is only here to pacify sio.  It is NOT FATAL if this doesn't work.
 1188  * It shouldn't be here.  There should probably be an APIC centric
 1189  * implementation in the apic driver code, if at all.
 1190  */
 1191 intrmask_t
 1192 isa_irq_pending(void)
 1193 {
 1194         u_char irr1;
 1195         u_char irr2;
 1196 
 1197         irr1 = inb(IO_ICU1);
 1198         irr2 = inb(IO_ICU2);
 1199         return ((irr2 << 8) | irr1);
 1200 }
 1201 #endif
 1202 
 1203 u_int basemem;
 1204 
 1205 static int
 1206 add_smap_entry(struct bios_smap *smap, vm_paddr_t *physmap, int *physmap_idxp)
 1207 {
 1208         int i, insert_idx, physmap_idx;
 1209 
 1210         physmap_idx = *physmap_idxp;
 1211 
 1212         if (boothowto & RB_VERBOSE)
 1213                 printf("SMAP type=%02x base=%016lx len=%016lx\n",
 1214                     smap->type, smap->base, smap->length);
 1215 
 1216         if (smap->type != SMAP_TYPE_MEMORY)
 1217                 return (1);
 1218 
 1219         if (smap->length == 0)
 1220                 return (0);
 1221 
 1222         /*
 1223          * Find insertion point while checking for overlap.  Start off by
 1224          * assuming the new entry will be added to the end.
 1225          */
 1226         insert_idx = physmap_idx + 2;
 1227         for (i = 0; i <= physmap_idx; i += 2) {
 1228                 if (smap->base < physmap[i + 1]) {
 1229                         if (smap->base + smap->length <= physmap[i]) {
 1230                                 insert_idx = i;
 1231                                 break;
 1232                         }
 1233                         if (boothowto & RB_VERBOSE)
 1234                                 printf(
 1235                     "Overlapping memory regions, ignoring second region\n");
 1236                         return (1);
 1237                 }
 1238         }
 1239 
 1240         /* See if we can prepend to the next entry. */
 1241         if (insert_idx <= physmap_idx &&
 1242             smap->base + smap->length == physmap[insert_idx]) {
 1243                 physmap[insert_idx] = smap->base;
 1244                 return (1);
 1245         }
 1246 
 1247         /* See if we can append to the previous entry. */
 1248         if (insert_idx > 0 && smap->base == physmap[insert_idx - 1]) {
 1249                 physmap[insert_idx - 1] += smap->length;
 1250                 return (1);
 1251         }
 1252 
 1253         physmap_idx += 2;
 1254         *physmap_idxp = physmap_idx;
 1255         if (physmap_idx == PHYSMAP_SIZE) {
 1256                 printf(
 1257                 "Too many segments in the physical address map, giving up\n");
 1258                 return (0);
 1259         }
 1260 
 1261         /*
 1262          * Move the last 'N' entries down to make room for the new
 1263          * entry if needed.
 1264          */
 1265         for (i = physmap_idx; i > insert_idx; i -= 2) {
 1266                 physmap[i] = physmap[i - 2];
 1267                 physmap[i + 1] = physmap[i - 1];
 1268         }
 1269 
 1270         /* Insert the new entry. */
 1271         physmap[insert_idx] = smap->base;
 1272         physmap[insert_idx + 1] = smap->base + smap->length;
 1273         return (1);
 1274 }
 1275 
 1276 /*
 1277  * Populate the (physmap) array with base/bound pairs describing the
 1278  * available physical memory in the system, then test this memory and
 1279  * build the phys_avail array describing the actually-available memory.
 1280  *
 1281  * Total memory size may be set by the kernel environment variable
 1282  * hw.physmem or the compile-time define MAXMEM.
 1283  *
 1284  * XXX first should be vm_paddr_t.
 1285  */
 1286 static void
 1287 getmemsize(caddr_t kmdp, u_int64_t first)
 1288 {
 1289         int i, physmap_idx, pa_indx, da_indx;
 1290         vm_paddr_t pa, physmap[PHYSMAP_SIZE];
 1291         u_long physmem_tunable, memtest;
 1292         pt_entry_t *pte;
 1293         struct bios_smap *smapbase, *smap, *smapend;
 1294         u_int32_t smapsize;
 1295         quad_t dcons_addr, dcons_size;
 1296 
 1297         bzero(physmap, sizeof(physmap));
 1298         basemem = 0;
 1299         physmap_idx = 0;
 1300 
 1301         /*
 1302          * get memory map from INT 15:E820, kindly supplied by the loader.
 1303          *
 1304          * subr_module.c says:
 1305          * "Consumer may safely assume that size value precedes data."
 1306          * ie: an int32_t immediately precedes smap.
 1307          */
 1308         smapbase = (struct bios_smap *)preload_search_info(kmdp,
 1309             MODINFO_METADATA | MODINFOMD_SMAP);
 1310         if (smapbase == NULL)
 1311                 panic("No BIOS smap info from loader!");
 1312 
 1313         smapsize = *((u_int32_t *)smapbase - 1);
 1314         smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
 1315 
 1316         for (smap = smapbase; smap < smapend; smap++)
 1317                 if (!add_smap_entry(smap, physmap, &physmap_idx))
 1318                         break;
 1319 
 1320         /*
 1321          * Find the 'base memory' segment for SMP
 1322          */
 1323         basemem = 0;
 1324         for (i = 0; i <= physmap_idx; i += 2) {
 1325                 if (physmap[i] == 0x00000000) {
 1326                         basemem = physmap[i + 1] / 1024;
 1327                         break;
 1328                 }
 1329         }
 1330         if (basemem == 0)
 1331                 panic("BIOS smap did not include a basemem segment!");
 1332 
 1333 #ifdef SMP
 1334         /* make hole for AP bootstrap code */
 1335         physmap[1] = mp_bootaddress(physmap[1] / 1024);
 1336 #endif
 1337 
 1338         /*
 1339          * Maxmem isn't the "maximum memory", it's one larger than the
 1340          * highest page of the physical address space.  It should be
 1341          * called something like "Maxphyspage".  We may adjust this
 1342          * based on ``hw.physmem'' and the results of the memory test.
 1343          */
 1344         Maxmem = atop(physmap[physmap_idx + 1]);
 1345 
 1346 #ifdef MAXMEM
 1347         Maxmem = MAXMEM / 4;
 1348 #endif
 1349 
 1350         if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
 1351                 Maxmem = atop(physmem_tunable);
 1352 
 1353         /*
 1354          * By default enable the memory test on real hardware, and disable
 1355          * it if we appear to be running in a VM.  This avoids touching all
 1356          * pages unnecessarily, which doesn't matter on real hardware but is
 1357          * bad for shared VM hosts.  Use a general name so that
 1358          * one could eventually do more with the code than just disable it.
 1359          */
 1360         memtest = (vm_guest > VM_GUEST_NO) ? 0 : 1;
 1361         TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
 1362 
 1363         /*
 1364          * Don't allow MAXMEM or hw.physmem to extend the amount of memory
 1365          * in the system.
 1366          */
 1367         if (Maxmem > atop(physmap[physmap_idx + 1]))
 1368                 Maxmem = atop(physmap[physmap_idx + 1]);
 1369 
 1370         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
 1371             (boothowto & RB_VERBOSE))
 1372                 printf("Physical memory use set to %ldK\n", Maxmem * 4);
 1373 
 1374         /* call pmap initialization to make new kernel address space */
 1375         pmap_bootstrap(&first);
 1376 
 1377         /*
 1378          * Size up each available chunk of physical memory.
 1379          */
 1380         physmap[0] = PAGE_SIZE;         /* mask off page 0 */
 1381         pa_indx = 0;
 1382         da_indx = 1;
 1383         phys_avail[pa_indx++] = physmap[0];
 1384         phys_avail[pa_indx] = physmap[0];
 1385         dump_avail[da_indx] = physmap[0];
 1386         pte = CMAP1;
 1387 
 1388         /*
 1389          * Get dcons buffer address
 1390          */
 1391         if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
 1392             getenv_quad("dcons.size", &dcons_size) == 0)
 1393                 dcons_addr = 0;
 1394 
 1395         /*
 1396          * physmap is in bytes, so when converting to page boundaries,
 1397          * round up the start address and round down the end address.
 1398          */
 1399         for (i = 0; i <= physmap_idx; i += 2) {
 1400                 vm_paddr_t end;
 1401 
 1402                 end = ptoa((vm_paddr_t)Maxmem);
 1403                 if (physmap[i + 1] < end)
 1404                         end = trunc_page(physmap[i + 1]);
 1405                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
 1406                         int tmp, page_bad, full;
 1407                         int *ptr = (int *)CADDR1;
 1408 
 1409                         full = FALSE;
 1410                         /*
 1411                          * block out kernel memory as not available.
 1412                          */
 1413                         if (pa >= 0x100000 && pa < first)
 1414                                 goto do_dump_avail;
 1415 
 1416                         /*
 1417                          * block out dcons buffer
 1418                          */
 1419                         if (dcons_addr > 0
 1420                             && pa >= trunc_page(dcons_addr)
 1421                             && pa < dcons_addr + dcons_size)
 1422                                 goto do_dump_avail;
 1423 
 1424                         page_bad = FALSE;
 1425                         if (memtest == 0)
 1426                                 goto skip_memtest;
 1427 
 1428                         /*
 1429                          * map page into kernel: valid, read/write,non-cacheable
 1430                          */
 1431                         *pte = pa | PG_V | PG_RW | PG_N;
 1432                         invltlb();
 1433 
 1434                         tmp = *(int *)ptr;
 1435                         /*
 1436                          * Test for alternating 1's and 0's
 1437                          */
 1438                         *(volatile int *)ptr = 0xaaaaaaaa;
 1439                         if (*(volatile int *)ptr != 0xaaaaaaaa)
 1440                                 page_bad = TRUE;
 1441                         /*
 1442                          * Test for alternating 0's and 1's
 1443                          */
 1444                         *(volatile int *)ptr = 0x55555555;
 1445                         if (*(volatile int *)ptr != 0x55555555)
 1446                                 page_bad = TRUE;
 1447                         /*
 1448                          * Test for all 1's
 1449                          */
 1450                         *(volatile int *)ptr = 0xffffffff;
 1451                         if (*(volatile int *)ptr != 0xffffffff)
 1452                                 page_bad = TRUE;
 1453                         /*
 1454                          * Test for all 0's
 1455                          */
 1456                         *(volatile int *)ptr = 0x0;
 1457                         if (*(volatile int *)ptr != 0x0)
 1458                                 page_bad = TRUE;
 1459                         /*
 1460                          * Restore original value.
 1461                          */
 1462                         *(int *)ptr = tmp;
 1463 
 1464 skip_memtest:
 1465                         /*
 1466                          * Adjust array of valid/good pages.
 1467                          */
 1468                         if (page_bad == TRUE)
 1469                                 continue;
 1470                         /*
 1471                          * If this good page is a continuation of the
 1472                          * previous set of good pages, then just increase
 1473                          * the end pointer. Otherwise start a new chunk.
 1474                          * Note that "end" points one higher than end,
 1475                          * making the range >= start and < end.
 1476                          * If we're also doing a speculative memory
 1477                          * test and we at or past the end, bump up Maxmem
 1478                          * so that we keep going. The first bad page
 1479                          * will terminate the loop.
 1480                          */
 1481                         if (phys_avail[pa_indx] == pa) {
 1482                                 phys_avail[pa_indx] += PAGE_SIZE;
 1483                         } else {
 1484                                 pa_indx++;
 1485                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
 1486                                         printf(
 1487                 "Too many holes in the physical address space, giving up\n");
 1488                                         pa_indx--;
 1489                                         full = TRUE;
 1490                                         goto do_dump_avail;
 1491                                 }
 1492                                 phys_avail[pa_indx++] = pa;     /* start */
 1493                                 phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
 1494                         }
 1495                         physmem++;
 1496 do_dump_avail:
 1497                         if (dump_avail[da_indx] == pa) {
 1498                                 dump_avail[da_indx] += PAGE_SIZE;
 1499                         } else {
 1500                                 da_indx++;
 1501                                 if (da_indx == DUMP_AVAIL_ARRAY_END) {
 1502                                         da_indx--;
 1503                                         goto do_next;
 1504                                 }
 1505                                 dump_avail[da_indx++] = pa; /* start */
 1506                                 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
 1507                         }
 1508 do_next:
 1509                         if (full)
 1510                                 break;
 1511                 }
 1512         }
 1513         *pte = 0;
 1514         invltlb();
 1515 
 1516         /*
 1517          * XXX
 1518          * The last chunk must contain at least one page plus the message
 1519          * buffer to avoid complicating other code (message buffer address
 1520          * calculation, etc.).
 1521          */
 1522         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
 1523             round_page(msgbufsize) >= phys_avail[pa_indx]) {
 1524                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
 1525                 phys_avail[pa_indx--] = 0;
 1526                 phys_avail[pa_indx--] = 0;
 1527         }
 1528 
 1529         Maxmem = atop(phys_avail[pa_indx]);
 1530 
 1531         /* Trim off space for the message buffer. */
 1532         phys_avail[pa_indx] -= round_page(msgbufsize);
 1533 
 1534         /* Map the message buffer. */
 1535         msgbufp = (struct msgbuf *)PHYS_TO_DMAP(phys_avail[pa_indx]);
 1536 }
 1537 
 1538 u_int64_t
 1539 hammer_time(u_int64_t modulep, u_int64_t physfree)
 1540 {
 1541         caddr_t kmdp;
 1542         int gsel_tss, x;
 1543         struct pcpu *pc;
 1544         struct nmi_pcpu *np;
 1545         u_int64_t msr;
 1546         char *env;
 1547 
 1548         thread0.td_kstack = physfree + KERNBASE;
 1549         bzero((void *)thread0.td_kstack, KSTACK_PAGES * PAGE_SIZE);
 1550         physfree += KSTACK_PAGES * PAGE_SIZE;
 1551         thread0.td_pcb = (struct pcb *)
 1552            (thread0.td_kstack + KSTACK_PAGES * PAGE_SIZE) - 1;
 1553 
 1554         /*
 1555          * This may be done better later if it gets more high level
 1556          * components in it. If so just link td->td_proc here.
 1557          */
 1558         proc_linkup0(&proc0, &thread0);
 1559 
 1560         preload_metadata = (caddr_t)(uintptr_t)(modulep + KERNBASE);
 1561         preload_bootstrap_relocate(KERNBASE);
 1562         kmdp = preload_search_by_type("elf kernel");
 1563         if (kmdp == NULL)
 1564                 kmdp = preload_search_by_type("elf64 kernel");
 1565         boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
 1566         kern_envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *) + KERNBASE;
 1567 #ifdef DDB
 1568         ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
 1569         ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
 1570 #endif
 1571 
 1572         /* Init basic tunables, hz etc */
 1573         init_param1();
 1574 
 1575         /*
 1576          * make gdt memory segments
 1577          */
 1578         for (x = 0; x < NGDT; x++) {
 1579                 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1) &&
 1580                     x != GUSERLDT_SEL && x != (GUSERLDT_SEL) + 1)
 1581                         ssdtosd(&gdt_segs[x], &gdt[x]);
 1582         }
 1583         gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&common_tss[0];
 1584         ssdtosyssd(&gdt_segs[GPROC0_SEL],
 1585             (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
 1586 
 1587         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
 1588         r_gdt.rd_base =  (long) gdt;
 1589         lgdt(&r_gdt);
 1590         pc = &__pcpu[0];
 1591 
 1592         wrmsr(MSR_FSBASE, 0);           /* User value */
 1593         wrmsr(MSR_GSBASE, (u_int64_t)pc);
 1594         wrmsr(MSR_KGSBASE, 0);          /* User value while in the kernel */
 1595 
 1596         pcpu_init(pc, 0, sizeof(struct pcpu));
 1597         dpcpu_init((void *)(physfree + KERNBASE), 0);
 1598         physfree += DPCPU_SIZE;
 1599         PCPU_SET(prvspace, pc);
 1600         PCPU_SET(curthread, &thread0);
 1601         PCPU_SET(curpcb, thread0.td_pcb);
 1602         PCPU_SET(tssp, &common_tss[0]);
 1603         PCPU_SET(commontssp, &common_tss[0]);
 1604         PCPU_SET(tss, (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
 1605         PCPU_SET(ldt, (struct system_segment_descriptor *)&gdt[GUSERLDT_SEL]);
 1606         PCPU_SET(fs32p, &gdt[GUFS32_SEL]);
 1607         PCPU_SET(gs32p, &gdt[GUGS32_SEL]);
 1608 
 1609         /*
 1610          * Initialize mutexes.
 1611          *
 1612          * icu_lock: in order to allow an interrupt to occur in a critical
 1613          *           section, to set pcpu->ipending (etc...) properly, we
 1614          *           must be able to get the icu lock, so it can't be
 1615          *           under witness.
 1616          */
 1617         mutex_init();
 1618         mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS);
 1619         mtx_init(&dt_lock, "descriptor tables", NULL, MTX_DEF);
 1620 
 1621         /* exceptions */
 1622         for (x = 0; x < NIDT; x++)
 1623                 setidt(x, &IDTVEC(rsvd), SDT_SYSIGT, SEL_KPL, 0);
 1624         setidt(IDT_DE, &IDTVEC(div),  SDT_SYSIGT, SEL_KPL, 0);
 1625         setidt(IDT_DB, &IDTVEC(dbg),  SDT_SYSIGT, SEL_KPL, 0);
 1626         setidt(IDT_NMI, &IDTVEC(nmi),  SDT_SYSIGT, SEL_KPL, 2);
 1627         setidt(IDT_BP, &IDTVEC(bpt),  SDT_SYSIGT, SEL_UPL, 0);
 1628         setidt(IDT_OF, &IDTVEC(ofl),  SDT_SYSIGT, SEL_KPL, 0);
 1629         setidt(IDT_BR, &IDTVEC(bnd),  SDT_SYSIGT, SEL_KPL, 0);
 1630         setidt(IDT_UD, &IDTVEC(ill),  SDT_SYSIGT, SEL_KPL, 0);
 1631         setidt(IDT_NM, &IDTVEC(dna),  SDT_SYSIGT, SEL_KPL, 0);
 1632         setidt(IDT_DF, &IDTVEC(dblfault), SDT_SYSIGT, SEL_KPL, 1);
 1633         setidt(IDT_FPUGP, &IDTVEC(fpusegm),  SDT_SYSIGT, SEL_KPL, 0);
 1634         setidt(IDT_TS, &IDTVEC(tss),  SDT_SYSIGT, SEL_KPL, 0);
 1635         setidt(IDT_NP, &IDTVEC(missing),  SDT_SYSIGT, SEL_KPL, 0);
 1636         setidt(IDT_SS, &IDTVEC(stk),  SDT_SYSIGT, SEL_KPL, 0);
 1637         setidt(IDT_GP, &IDTVEC(prot),  SDT_SYSIGT, SEL_KPL, 0);
 1638         setidt(IDT_PF, &IDTVEC(page),  SDT_SYSIGT, SEL_KPL, 0);
 1639         setidt(IDT_MF, &IDTVEC(fpu),  SDT_SYSIGT, SEL_KPL, 0);
 1640         setidt(IDT_AC, &IDTVEC(align), SDT_SYSIGT, SEL_KPL, 0);
 1641         setidt(IDT_MC, &IDTVEC(mchk),  SDT_SYSIGT, SEL_KPL, 0);
 1642         setidt(IDT_XF, &IDTVEC(xmm), SDT_SYSIGT, SEL_KPL, 0);
 1643 #ifdef KDTRACE_HOOKS
 1644         setidt(IDT_DTRACE_RET, &IDTVEC(dtrace_ret), SDT_SYSIGT, SEL_UPL, 0);
 1645 #endif
 1646 
 1647         r_idt.rd_limit = sizeof(idt0) - 1;
 1648         r_idt.rd_base = (long) idt;
 1649         lidt(&r_idt);
 1650 
 1651         /*
 1652          * Initialize the i8254 before the console so that console
 1653          * initialization can use DELAY().
 1654          */
 1655         i8254_init();
 1656 
 1657         /*
 1658          * Initialize the console before we print anything out.
 1659          */
 1660         cninit();
 1661 
 1662 #ifdef DEV_ISA
 1663 #ifdef DEV_ATPIC
 1664         elcr_probe();
 1665         atpic_startup();
 1666 #else
 1667         /* Reset and mask the atpics and leave them shut down. */
 1668         atpic_reset();
 1669 
 1670         /*
 1671          * Point the ICU spurious interrupt vectors at the APIC spurious
 1672          * interrupt handler.
 1673          */
 1674         setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
 1675         setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
 1676 #endif
 1677 #else
 1678 #error "have you forgotten the isa device?";
 1679 #endif
 1680 
 1681         kdb_init();
 1682 
 1683 #ifdef KDB
 1684         if (boothowto & RB_KDB)
 1685                 kdb_enter(KDB_WHY_BOOTFLAGS,
 1686                     "Boot flags requested debugger");
 1687 #endif
 1688 
 1689         identify_cpu();         /* Final stage of CPU initialization */
 1690         initializecpu();        /* Initialize CPU registers */
 1691         initializecpucache();
 1692 
 1693         /* make an initial tss so cpu can get interrupt stack on syscall! */
 1694         common_tss[0].tss_rsp0 = thread0.td_kstack + \
 1695             KSTACK_PAGES * PAGE_SIZE - sizeof(struct pcb);
 1696         /* Ensure the stack is aligned to 16 bytes */
 1697         common_tss[0].tss_rsp0 &= ~0xFul;
 1698         PCPU_SET(rsp0, common_tss[0].tss_rsp0);
 1699 
 1700         /* doublefault stack space, runs on ist1 */
 1701         common_tss[0].tss_ist1 = (long)&dblfault_stack[sizeof(dblfault_stack)];
 1702 
 1703         /*
 1704          * NMI stack, runs on ist2.  The pcpu pointer is stored just
 1705          * above the start of the ist2 stack.
 1706          */
 1707         np = ((struct nmi_pcpu *) &nmi0_stack[sizeof(nmi0_stack)]) - 1;
 1708         np->np_pcpu = (register_t) pc;
 1709         common_tss[0].tss_ist2 = (long) np;
 1710 
 1711         /* Set the IO permission bitmap (empty due to tss seg limit) */
 1712         common_tss[0].tss_iobase = sizeof(struct amd64tss) +
 1713             IOPAGES * PAGE_SIZE;
 1714 
 1715         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
 1716         ltr(gsel_tss);
 1717 
 1718         /* Set up the fast syscall stuff */
 1719         msr = rdmsr(MSR_EFER) | EFER_SCE;
 1720         wrmsr(MSR_EFER, msr);
 1721         wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
 1722         wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
 1723         msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
 1724               ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
 1725         wrmsr(MSR_STAR, msr);
 1726         wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
 1727 
 1728         getmemsize(kmdp, physfree);
 1729         init_param2(physmem);
 1730 
 1731         /* now running on new page tables, configured,and u/iom is accessible */
 1732 
 1733         msgbufinit(msgbufp, msgbufsize);
 1734         fpuinit();
 1735 
 1736         /* transfer to user mode */
 1737 
 1738         _ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
 1739         _udatasel = GSEL(GUDATA_SEL, SEL_UPL);
 1740         _ucode32sel = GSEL(GUCODE32_SEL, SEL_UPL);
 1741         _ufssel = GSEL(GUFS32_SEL, SEL_UPL);
 1742         _ugssel = GSEL(GUGS32_SEL, SEL_UPL);
 1743 
 1744         load_ds(_udatasel);
 1745         load_es(_udatasel);
 1746         load_fs(_ufssel);
 1747 
 1748         /* setup proc 0's pcb */
 1749         thread0.td_pcb->pcb_flags = 0;
 1750         thread0.td_pcb->pcb_cr3 = KPML4phys;
 1751         thread0.td_frame = &proc0_tf;
 1752 
 1753         env = getenv("kernelname");
 1754         if (env != NULL)
 1755                 strlcpy(kernelname, env, sizeof(kernelname));
 1756 
 1757 #ifdef XENHVM
 1758         if (inw(0x10) == 0x49d2) {
 1759                 if (bootverbose)
 1760                         printf("Xen detected: disabling emulated block and network devices\n");
 1761                 outw(0x10, 3);
 1762         }
 1763 #endif
 1764 
 1765         if (cpu_probe_amdc1e())
 1766                 cpu_idle_fn = cpu_idle_amdc1e;
 1767 
 1768         /* Location of kernel stack for locore */
 1769         return ((u_int64_t)thread0.td_pcb);
 1770 }
 1771 
 1772 void
 1773 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
 1774 {
 1775 
 1776         pcpu->pc_acpi_id = 0xffffffff;
 1777 }
 1778 
 1779 void
 1780 spinlock_enter(void)
 1781 {
 1782         struct thread *td;
 1783         register_t flags;
 1784 
 1785         td = curthread;
 1786         if (td->td_md.md_spinlock_count == 0) {
 1787                 flags = intr_disable();
 1788                 td->td_md.md_spinlock_count = 1;
 1789                 td->td_md.md_saved_flags = flags;
 1790         } else
 1791                 td->td_md.md_spinlock_count++;
 1792         critical_enter();
 1793 }
 1794 
 1795 void
 1796 spinlock_exit(void)
 1797 {
 1798         struct thread *td;
 1799         register_t flags;
 1800 
 1801         td = curthread;
 1802         critical_exit();
 1803         flags = td->td_md.md_saved_flags;
 1804         td->td_md.md_spinlock_count--;
 1805         if (td->td_md.md_spinlock_count == 0)
 1806                 intr_restore(flags);
 1807 }
 1808 
 1809 /*
 1810  * Construct a PCB from a trapframe. This is called from kdb_trap() where
 1811  * we want to start a backtrace from the function that caused us to enter
 1812  * the debugger. We have the context in the trapframe, but base the trace
 1813  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
 1814  * enough for a backtrace.
 1815  */
 1816 void
 1817 makectx(struct trapframe *tf, struct pcb *pcb)
 1818 {
 1819 
 1820         pcb->pcb_r12 = tf->tf_r12;
 1821         pcb->pcb_r13 = tf->tf_r13;
 1822         pcb->pcb_r14 = tf->tf_r14;
 1823         pcb->pcb_r15 = tf->tf_r15;
 1824         pcb->pcb_rbp = tf->tf_rbp;
 1825         pcb->pcb_rbx = tf->tf_rbx;
 1826         pcb->pcb_rip = tf->tf_rip;
 1827         pcb->pcb_rsp = tf->tf_rsp;
 1828 }
 1829 
 1830 int
 1831 ptrace_set_pc(struct thread *td, unsigned long addr)
 1832 {
 1833         td->td_frame->tf_rip = addr;
 1834         return (0);
 1835 }
 1836 
 1837 int
 1838 ptrace_single_step(struct thread *td)
 1839 {
 1840         td->td_frame->tf_rflags |= PSL_T;
 1841         return (0);
 1842 }
 1843 
 1844 int
 1845 ptrace_clear_single_step(struct thread *td)
 1846 {
 1847         td->td_frame->tf_rflags &= ~PSL_T;
 1848         return (0);
 1849 }
 1850 
 1851 int
 1852 fill_regs(struct thread *td, struct reg *regs)
 1853 {
 1854         struct trapframe *tp;
 1855 
 1856         tp = td->td_frame;
 1857         return (fill_frame_regs(tp, regs));
 1858 }
 1859 
 1860 int
 1861 fill_frame_regs(struct trapframe *tp, struct reg *regs)
 1862 {
 1863         regs->r_r15 = tp->tf_r15;
 1864         regs->r_r14 = tp->tf_r14;
 1865         regs->r_r13 = tp->tf_r13;
 1866         regs->r_r12 = tp->tf_r12;
 1867         regs->r_r11 = tp->tf_r11;
 1868         regs->r_r10 = tp->tf_r10;
 1869         regs->r_r9  = tp->tf_r9;
 1870         regs->r_r8  = tp->tf_r8;
 1871         regs->r_rdi = tp->tf_rdi;
 1872         regs->r_rsi = tp->tf_rsi;
 1873         regs->r_rbp = tp->tf_rbp;
 1874         regs->r_rbx = tp->tf_rbx;
 1875         regs->r_rdx = tp->tf_rdx;
 1876         regs->r_rcx = tp->tf_rcx;
 1877         regs->r_rax = tp->tf_rax;
 1878         regs->r_rip = tp->tf_rip;
 1879         regs->r_cs = tp->tf_cs;
 1880         regs->r_rflags = tp->tf_rflags;
 1881         regs->r_rsp = tp->tf_rsp;
 1882         regs->r_ss = tp->tf_ss;
 1883         if (tp->tf_flags & TF_HASSEGS) {
 1884                 regs->r_ds = tp->tf_ds;
 1885                 regs->r_es = tp->tf_es;
 1886                 regs->r_fs = tp->tf_fs;
 1887                 regs->r_gs = tp->tf_gs;
 1888         } else {
 1889                 regs->r_ds = 0;
 1890                 regs->r_es = 0;
 1891                 regs->r_fs = 0;
 1892                 regs->r_gs = 0;
 1893         }
 1894         return (0);
 1895 }
 1896 
 1897 int
 1898 set_regs(struct thread *td, struct reg *regs)
 1899 {
 1900         struct trapframe *tp;
 1901         register_t rflags;
 1902 
 1903         tp = td->td_frame;
 1904         rflags = regs->r_rflags & 0xffffffff;
 1905         if (!EFL_SECURE(rflags, tp->tf_rflags) || !CS_SECURE(regs->r_cs))
 1906                 return (EINVAL);
 1907         tp->tf_r15 = regs->r_r15;
 1908         tp->tf_r14 = regs->r_r14;
 1909         tp->tf_r13 = regs->r_r13;
 1910         tp->tf_r12 = regs->r_r12;
 1911         tp->tf_r11 = regs->r_r11;
 1912         tp->tf_r10 = regs->r_r10;
 1913         tp->tf_r9  = regs->r_r9;
 1914         tp->tf_r8  = regs->r_r8;
 1915         tp->tf_rdi = regs->r_rdi;
 1916         tp->tf_rsi = regs->r_rsi;
 1917         tp->tf_rbp = regs->r_rbp;
 1918         tp->tf_rbx = regs->r_rbx;
 1919         tp->tf_rdx = regs->r_rdx;
 1920         tp->tf_rcx = regs->r_rcx;
 1921         tp->tf_rax = regs->r_rax;
 1922         tp->tf_rip = regs->r_rip;
 1923         tp->tf_cs = regs->r_cs;
 1924         tp->tf_rflags = rflags;
 1925         tp->tf_rsp = regs->r_rsp;
 1926         tp->tf_ss = regs->r_ss;
 1927         if (0) {        /* XXXKIB */
 1928                 tp->tf_ds = regs->r_ds;
 1929                 tp->tf_es = regs->r_es;
 1930                 tp->tf_fs = regs->r_fs;
 1931                 tp->tf_gs = regs->r_gs;
 1932                 tp->tf_flags = TF_HASSEGS;
 1933                 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
 1934         }
 1935         return (0);
 1936 }
 1937 
 1938 /* XXX check all this stuff! */
 1939 /* externalize from sv_xmm */
 1940 static void
 1941 fill_fpregs_xmm(struct savefpu *sv_xmm, struct fpreg *fpregs)
 1942 {
 1943         struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
 1944         struct envxmm *penv_xmm = &sv_xmm->sv_env;
 1945         int i;
 1946 
 1947         /* pcb -> fpregs */
 1948         bzero(fpregs, sizeof(*fpregs));
 1949 
 1950         /* FPU control/status */
 1951         penv_fpreg->en_cw = penv_xmm->en_cw;
 1952         penv_fpreg->en_sw = penv_xmm->en_sw;
 1953         penv_fpreg->en_tw = penv_xmm->en_tw;
 1954         penv_fpreg->en_opcode = penv_xmm->en_opcode;
 1955         penv_fpreg->en_rip = penv_xmm->en_rip;
 1956         penv_fpreg->en_rdp = penv_xmm->en_rdp;
 1957         penv_fpreg->en_mxcsr = penv_xmm->en_mxcsr;
 1958         penv_fpreg->en_mxcsr_mask = penv_xmm->en_mxcsr_mask;
 1959 
 1960         /* FPU registers */
 1961         for (i = 0; i < 8; ++i)
 1962                 bcopy(sv_xmm->sv_fp[i].fp_acc.fp_bytes, fpregs->fpr_acc[i], 10);
 1963 
 1964         /* SSE registers */
 1965         for (i = 0; i < 16; ++i)
 1966                 bcopy(sv_xmm->sv_xmm[i].xmm_bytes, fpregs->fpr_xacc[i], 16);
 1967 }
 1968 
 1969 /* internalize from fpregs into sv_xmm */
 1970 static void
 1971 set_fpregs_xmm(struct fpreg *fpregs, struct savefpu *sv_xmm)
 1972 {
 1973         struct envxmm *penv_xmm = &sv_xmm->sv_env;
 1974         struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
 1975         int i;
 1976 
 1977         /* fpregs -> pcb */
 1978         /* FPU control/status */
 1979         penv_xmm->en_cw = penv_fpreg->en_cw;
 1980         penv_xmm->en_sw = penv_fpreg->en_sw;
 1981         penv_xmm->en_tw = penv_fpreg->en_tw;
 1982         penv_xmm->en_opcode = penv_fpreg->en_opcode;
 1983         penv_xmm->en_rip = penv_fpreg->en_rip;
 1984         penv_xmm->en_rdp = penv_fpreg->en_rdp;
 1985         penv_xmm->en_mxcsr = penv_fpreg->en_mxcsr;
 1986         penv_xmm->en_mxcsr_mask = penv_fpreg->en_mxcsr_mask & cpu_mxcsr_mask;
 1987 
 1988         /* FPU registers */
 1989         for (i = 0; i < 8; ++i)
 1990                 bcopy(fpregs->fpr_acc[i], sv_xmm->sv_fp[i].fp_acc.fp_bytes, 10);
 1991 
 1992         /* SSE registers */
 1993         for (i = 0; i < 16; ++i)
 1994                 bcopy(fpregs->fpr_xacc[i], sv_xmm->sv_xmm[i].xmm_bytes, 16);
 1995 }
 1996 
 1997 /* externalize from td->pcb */
 1998 int
 1999 fill_fpregs(struct thread *td, struct fpreg *fpregs)
 2000 {
 2001 
 2002         KASSERT(td == curthread || TD_IS_SUSPENDED(td) ||
 2003             P_SHOULDSTOP(td->td_proc),
 2004             ("not suspended thread %p", td));
 2005         fpugetregs(td);
 2006         fill_fpregs_xmm(&td->td_pcb->pcb_user_save, fpregs);
 2007         return (0);
 2008 }
 2009 
 2010 /* internalize to td->pcb */
 2011 int
 2012 set_fpregs(struct thread *td, struct fpreg *fpregs)
 2013 {
 2014 
 2015         set_fpregs_xmm(fpregs, &td->td_pcb->pcb_user_save);
 2016         fpuuserinited(td);
 2017         return (0);
 2018 }
 2019 
 2020 /*
 2021  * Get machine context.
 2022  */
 2023 int
 2024 get_mcontext(struct thread *td, mcontext_t *mcp, int flags)
 2025 {
 2026         struct pcb *pcb;
 2027         struct trapframe *tp;
 2028 
 2029         pcb = td->td_pcb;
 2030         tp = td->td_frame;
 2031         PROC_LOCK(curthread->td_proc);
 2032         mcp->mc_onstack = sigonstack(tp->tf_rsp);
 2033         PROC_UNLOCK(curthread->td_proc);
 2034         mcp->mc_r15 = tp->tf_r15;
 2035         mcp->mc_r14 = tp->tf_r14;
 2036         mcp->mc_r13 = tp->tf_r13;
 2037         mcp->mc_r12 = tp->tf_r12;
 2038         mcp->mc_r11 = tp->tf_r11;
 2039         mcp->mc_r10 = tp->tf_r10;
 2040         mcp->mc_r9  = tp->tf_r9;
 2041         mcp->mc_r8  = tp->tf_r8;
 2042         mcp->mc_rdi = tp->tf_rdi;
 2043         mcp->mc_rsi = tp->tf_rsi;
 2044         mcp->mc_rbp = tp->tf_rbp;
 2045         mcp->mc_rbx = tp->tf_rbx;
 2046         mcp->mc_rcx = tp->tf_rcx;
 2047         mcp->mc_rflags = tp->tf_rflags;
 2048         if (flags & GET_MC_CLEAR_RET) {
 2049                 mcp->mc_rax = 0;
 2050                 mcp->mc_rdx = 0;
 2051                 mcp->mc_rflags &= ~PSL_C;
 2052         } else {
 2053                 mcp->mc_rax = tp->tf_rax;
 2054                 mcp->mc_rdx = tp->tf_rdx;
 2055         }
 2056         mcp->mc_rip = tp->tf_rip;
 2057         mcp->mc_cs = tp->tf_cs;
 2058         mcp->mc_rsp = tp->tf_rsp;
 2059         mcp->mc_ss = tp->tf_ss;
 2060         mcp->mc_ds = tp->tf_ds;
 2061         mcp->mc_es = tp->tf_es;
 2062         mcp->mc_fs = tp->tf_fs;
 2063         mcp->mc_gs = tp->tf_gs;
 2064         mcp->mc_flags = tp->tf_flags;
 2065         mcp->mc_len = sizeof(*mcp);
 2066         get_fpcontext(td, mcp);
 2067         mcp->mc_fsbase = pcb->pcb_fsbase;
 2068         mcp->mc_gsbase = pcb->pcb_gsbase;
 2069         bzero(mcp->mc_spare, sizeof(mcp->mc_spare));
 2070         return (0);
 2071 }
 2072 
 2073 /*
 2074  * Set machine context.
 2075  *
 2076  * However, we don't set any but the user modifiable flags, and we won't
 2077  * touch the cs selector.
 2078  */
 2079 int
 2080 set_mcontext(struct thread *td, const mcontext_t *mcp)
 2081 {
 2082         struct pcb *pcb;
 2083         struct trapframe *tp;
 2084         long rflags;
 2085         int ret;
 2086 
 2087         pcb = td->td_pcb;
 2088         tp = td->td_frame;
 2089         if (mcp->mc_len != sizeof(*mcp) ||
 2090             (mcp->mc_flags & ~_MC_FLAG_MASK) != 0)
 2091                 return (EINVAL);
 2092         rflags = (mcp->mc_rflags & PSL_USERCHANGE) |
 2093             (tp->tf_rflags & ~PSL_USERCHANGE);
 2094         ret = set_fpcontext(td, mcp);
 2095         if (ret != 0)
 2096                 return (ret);
 2097         tp->tf_r15 = mcp->mc_r15;
 2098         tp->tf_r14 = mcp->mc_r14;
 2099         tp->tf_r13 = mcp->mc_r13;
 2100         tp->tf_r12 = mcp->mc_r12;
 2101         tp->tf_r11 = mcp->mc_r11;
 2102         tp->tf_r10 = mcp->mc_r10;
 2103         tp->tf_r9  = mcp->mc_r9;
 2104         tp->tf_r8  = mcp->mc_r8;
 2105         tp->tf_rdi = mcp->mc_rdi;
 2106         tp->tf_rsi = mcp->mc_rsi;
 2107         tp->tf_rbp = mcp->mc_rbp;
 2108         tp->tf_rbx = mcp->mc_rbx;
 2109         tp->tf_rdx = mcp->mc_rdx;
 2110         tp->tf_rcx = mcp->mc_rcx;
 2111         tp->tf_rax = mcp->mc_rax;
 2112         tp->tf_rip = mcp->mc_rip;
 2113         tp->tf_rflags = rflags;
 2114         tp->tf_rsp = mcp->mc_rsp;
 2115         tp->tf_ss = mcp->mc_ss;
 2116         tp->tf_flags = mcp->mc_flags;
 2117         if (tp->tf_flags & TF_HASSEGS) {
 2118                 tp->tf_ds = mcp->mc_ds;
 2119                 tp->tf_es = mcp->mc_es;
 2120                 tp->tf_fs = mcp->mc_fs;
 2121                 tp->tf_gs = mcp->mc_gs;
 2122         }
 2123         if (mcp->mc_flags & _MC_HASBASES) {
 2124                 pcb->pcb_fsbase = mcp->mc_fsbase;
 2125                 pcb->pcb_gsbase = mcp->mc_gsbase;
 2126         }
 2127         set_pcb_flags(pcb, PCB_FULL_IRET);
 2128         return (0);
 2129 }
 2130 
 2131 static void
 2132 get_fpcontext(struct thread *td, mcontext_t *mcp)
 2133 {
 2134 
 2135         mcp->mc_ownedfp = fpugetregs(td);
 2136         bcopy(&td->td_pcb->pcb_user_save, &mcp->mc_fpstate,
 2137             sizeof(mcp->mc_fpstate));
 2138         mcp->mc_fpformat = fpuformat();
 2139 }
 2140 
 2141 static int
 2142 set_fpcontext(struct thread *td, const mcontext_t *mcp)
 2143 {
 2144         struct savefpu *fpstate;
 2145 
 2146         if (mcp->mc_fpformat == _MC_FPFMT_NODEV)
 2147                 return (0);
 2148         else if (mcp->mc_fpformat != _MC_FPFMT_XMM)
 2149                 return (EINVAL);
 2150         else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE)
 2151                 /* We don't care what state is left in the FPU or PCB. */
 2152                 fpstate_drop(td);
 2153         else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU ||
 2154             mcp->mc_ownedfp == _MC_FPOWNED_PCB) {
 2155                 fpstate = (struct savefpu *)&mcp->mc_fpstate;
 2156                 fpstate->sv_env.en_mxcsr &= cpu_mxcsr_mask;
 2157                 fpusetregs(td, fpstate);
 2158         } else
 2159                 return (EINVAL);
 2160         return (0);
 2161 }
 2162 
 2163 void
 2164 fpstate_drop(struct thread *td)
 2165 {
 2166 
 2167         KASSERT(PCB_USER_FPU(td->td_pcb), ("fpstate_drop: kernel-owned fpu"));
 2168         critical_enter();
 2169         if (PCPU_GET(fpcurthread) == td)
 2170                 fpudrop();
 2171         /*
 2172          * XXX force a full drop of the fpu.  The above only drops it if we
 2173          * owned it.
 2174          *
 2175          * XXX I don't much like fpugetuserregs()'s semantics of doing a full
 2176          * drop.  Dropping only to the pcb matches fnsave's behaviour.
 2177          * We only need to drop to !PCB_INITDONE in sendsig().  But
 2178          * sendsig() is the only caller of fpugetuserregs()... perhaps we just
 2179          * have too many layers.
 2180          */
 2181         clear_pcb_flags(curthread->td_pcb,
 2182             PCB_FPUINITDONE | PCB_USERFPUINITDONE);
 2183         critical_exit();
 2184 }
 2185 
 2186 int
 2187 fill_dbregs(struct thread *td, struct dbreg *dbregs)
 2188 {
 2189         struct pcb *pcb;
 2190 
 2191         if (td == NULL) {
 2192                 dbregs->dr[0] = rdr0();
 2193                 dbregs->dr[1] = rdr1();
 2194                 dbregs->dr[2] = rdr2();
 2195                 dbregs->dr[3] = rdr3();
 2196                 dbregs->dr[6] = rdr6();
 2197                 dbregs->dr[7] = rdr7();
 2198         } else {
 2199                 pcb = td->td_pcb;
 2200                 dbregs->dr[0] = pcb->pcb_dr0;
 2201                 dbregs->dr[1] = pcb->pcb_dr1;
 2202                 dbregs->dr[2] = pcb->pcb_dr2;
 2203                 dbregs->dr[3] = pcb->pcb_dr3;
 2204                 dbregs->dr[6] = pcb->pcb_dr6;
 2205                 dbregs->dr[7] = pcb->pcb_dr7;
 2206         }
 2207         dbregs->dr[4] = 0;
 2208         dbregs->dr[5] = 0;
 2209         dbregs->dr[8] = 0;
 2210         dbregs->dr[9] = 0;
 2211         dbregs->dr[10] = 0;
 2212         dbregs->dr[11] = 0;
 2213         dbregs->dr[12] = 0;
 2214         dbregs->dr[13] = 0;
 2215         dbregs->dr[14] = 0;
 2216         dbregs->dr[15] = 0;
 2217         return (0);
 2218 }
 2219 
 2220 int
 2221 set_dbregs(struct thread *td, struct dbreg *dbregs)
 2222 {
 2223         struct pcb *pcb;
 2224         int i;
 2225 
 2226         if (td == NULL) {
 2227                 load_dr0(dbregs->dr[0]);
 2228                 load_dr1(dbregs->dr[1]);
 2229                 load_dr2(dbregs->dr[2]);
 2230                 load_dr3(dbregs->dr[3]);
 2231                 load_dr6(dbregs->dr[6]);
 2232                 load_dr7(dbregs->dr[7]);
 2233         } else {
 2234                 /*
 2235                  * Don't let an illegal value for dr7 get set.  Specifically,
 2236                  * check for undefined settings.  Setting these bit patterns
 2237                  * result in undefined behaviour and can lead to an unexpected
 2238                  * TRCTRAP or a general protection fault right here.
 2239                  * Upper bits of dr6 and dr7 must not be set
 2240                  */
 2241                 for (i = 0; i < 4; i++) {
 2242                         if (DBREG_DR7_ACCESS(dbregs->dr[7], i) == 0x02)
 2243                                 return (EINVAL);
 2244                         if (td->td_frame->tf_cs == _ucode32sel &&
 2245                             DBREG_DR7_LEN(dbregs->dr[7], i) == DBREG_DR7_LEN_8)
 2246                                 return (EINVAL);
 2247                 }
 2248                 if ((dbregs->dr[6] & 0xffffffff00000000ul) != 0 ||
 2249                     (dbregs->dr[7] & 0xffffffff00000000ul) != 0)
 2250                         return (EINVAL);
 2251 
 2252                 pcb = td->td_pcb;
 2253 
 2254                 /*
 2255                  * Don't let a process set a breakpoint that is not within the
 2256                  * process's address space.  If a process could do this, it
 2257                  * could halt the system by setting a breakpoint in the kernel
 2258                  * (if ddb was enabled).  Thus, we need to check to make sure
 2259                  * that no breakpoints are being enabled for addresses outside
 2260                  * process's address space.
 2261                  *
 2262                  * XXX - what about when the watched area of the user's
 2263                  * address space is written into from within the kernel
 2264                  * ... wouldn't that still cause a breakpoint to be generated
 2265                  * from within kernel mode?
 2266                  */
 2267 
 2268                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 0)) {
 2269                         /* dr0 is enabled */
 2270                         if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS)
 2271                                 return (EINVAL);
 2272                 }
 2273                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 1)) {
 2274                         /* dr1 is enabled */
 2275                         if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS)
 2276                                 return (EINVAL);
 2277                 }
 2278                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 2)) {
 2279                         /* dr2 is enabled */
 2280                         if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS)
 2281                                 return (EINVAL);
 2282                 }
 2283                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 3)) {
 2284                         /* dr3 is enabled */
 2285                         if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS)
 2286                                 return (EINVAL);
 2287                 }
 2288 
 2289                 pcb->pcb_dr0 = dbregs->dr[0];
 2290                 pcb->pcb_dr1 = dbregs->dr[1];
 2291                 pcb->pcb_dr2 = dbregs->dr[2];
 2292                 pcb->pcb_dr3 = dbregs->dr[3];
 2293                 pcb->pcb_dr6 = dbregs->dr[6];
 2294                 pcb->pcb_dr7 = dbregs->dr[7];
 2295 
 2296                 set_pcb_flags(pcb, PCB_DBREGS);
 2297         }
 2298 
 2299         return (0);
 2300 }
 2301 
 2302 void
 2303 reset_dbregs(void)
 2304 {
 2305 
 2306         load_dr7(0);    /* Turn off the control bits first */
 2307         load_dr0(0);
 2308         load_dr1(0);
 2309         load_dr2(0);
 2310         load_dr3(0);
 2311         load_dr6(0);
 2312 }
 2313 
 2314 /*
 2315  * Return > 0 if a hardware breakpoint has been hit, and the
 2316  * breakpoint was in user space.  Return 0, otherwise.
 2317  */
 2318 int
 2319 user_dbreg_trap(void)
 2320 {
 2321         u_int64_t dr7, dr6; /* debug registers dr6 and dr7 */
 2322         u_int64_t bp;       /* breakpoint bits extracted from dr6 */
 2323         int nbp;            /* number of breakpoints that triggered */
 2324         caddr_t addr[4];    /* breakpoint addresses */
 2325         int i;
 2326         
 2327         dr7 = rdr7();
 2328         if ((dr7 & 0x000000ff) == 0) {
 2329                 /*
 2330                  * all GE and LE bits in the dr7 register are zero,
 2331                  * thus the trap couldn't have been caused by the
 2332                  * hardware debug registers
 2333                  */
 2334                 return 0;
 2335         }
 2336 
 2337         nbp = 0;
 2338         dr6 = rdr6();
 2339         bp = dr6 & 0x0000000f;
 2340 
 2341         if (!bp) {
 2342                 /*
 2343                  * None of the breakpoint bits are set meaning this
 2344                  * trap was not caused by any of the debug registers
 2345                  */
 2346                 return 0;
 2347         }
 2348 
 2349         /*
 2350          * at least one of the breakpoints were hit, check to see
 2351          * which ones and if any of them are user space addresses
 2352          */
 2353 
 2354         if (bp & 0x01) {
 2355                 addr[nbp++] = (caddr_t)rdr0();
 2356         }
 2357         if (bp & 0x02) {
 2358                 addr[nbp++] = (caddr_t)rdr1();
 2359         }
 2360         if (bp & 0x04) {
 2361                 addr[nbp++] = (caddr_t)rdr2();
 2362         }
 2363         if (bp & 0x08) {
 2364                 addr[nbp++] = (caddr_t)rdr3();
 2365         }
 2366 
 2367         for (i = 0; i < nbp; i++) {
 2368                 if (addr[i] < (caddr_t)VM_MAXUSER_ADDRESS) {
 2369                         /*
 2370                          * addr[i] is in user space
 2371                          */
 2372                         return nbp;
 2373                 }
 2374         }
 2375 
 2376         /*
 2377          * None of the breakpoints are in user space.
 2378          */
 2379         return 0;
 2380 }
 2381 
 2382 #ifdef KDB
 2383 
 2384 /*
 2385  * Provide inb() and outb() as functions.  They are normally only available as
 2386  * inline functions, thus cannot be called from the debugger.
 2387  */
 2388 
 2389 /* silence compiler warnings */
 2390 u_char inb_(u_short);
 2391 void outb_(u_short, u_char);
 2392 
 2393 u_char
 2394 inb_(u_short port)
 2395 {
 2396         return inb(port);
 2397 }
 2398 
 2399 void
 2400 outb_(u_short port, u_char data)
 2401 {
 2402         outb(port, data);
 2403 }
 2404 
 2405 #endif /* KDB */

Cache object: 37eaa0ff9af1556e6288171ff03ac5f4


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