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.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
38 * from: @(#)machdep.c 7.4 (Berkeley) 6/3/91
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
44 #include "opt_atalk.h"
45 #include "opt_atpic.h"
46 #include "opt_compat.h"
52 #include "opt_kstack_pages.h"
53 #include "opt_maxmem.h"
54 #include "opt_msgbuf.h"
55 #include "opt_perfmon.h"
56 #include "opt_sched.h"
58 #include <sys/param.h>
60 #include <sys/systm.h>
64 #include <sys/callout.h>
67 #include <sys/eventhandler.h>
69 #include <sys/imgact.h>
71 #include <sys/kernel.h>
73 #include <sys/linker.h>
75 #include <sys/malloc.h>
76 #include <sys/memrange.h>
77 #include <sys/msgbuf.h>
78 #include <sys/mutex.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>
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>
101 #error KDB must be enabled in order for DDB to work!
104 #include <ddb/db_sym.h>
107 #include <net/netisr.h>
109 #include <machine/clock.h>
110 #include <machine/cpu.h>
111 #include <machine/cputypes.h>
112 #include <machine/intr_machdep.h>
113 #include <machine/mca.h>
114 #include <machine/md_var.h>
115 #include <machine/metadata.h>
116 #include <machine/pc/bios.h>
117 #include <machine/pcb.h>
118 #include <machine/proc.h>
119 #include <machine/reg.h>
120 #include <machine/sigframe.h>
121 #include <machine/specialreg.h>
123 #include <machine/perfmon.h>
125 #include <machine/tss.h>
127 #include <machine/smp.h>
131 #include <amd64/isa/icu.h>
133 #include <machine/apicvar.h>
136 #include <isa/isareg.h>
139 /* Sanity check for __curthread() */
140 CTASSERT(offsetof(struct pcpu, pc_curthread) == 0);
142 extern u_int64_t hammer_time(u_int64_t, u_int64_t);
144 extern void printcpuinfo(void); /* XXX header file */
145 extern void identify_cpu(void);
146 extern void panicifcpuunsupported(void);
148 #define CS_SECURE(cs) (ISPL(cs) == SEL_UPL)
149 #define EFL_SECURE(ef, oef) ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
151 static void cpu_startup(void *);
152 static void get_fpcontext(struct thread *td, mcontext_t *mcp);
153 static int set_fpcontext(struct thread *td, const mcontext_t *mcp);
154 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
157 extern vm_offset_t ksym_start, ksym_end;
160 /* Intel ICH registers */
161 #define ICH_PMBASE 0x400
162 #define ICH_SMI_EN ICH_PMBASE + 0x30
164 int _udatasel, _ucodesel, _ucode32sel, _ufssel, _ugssel;
172 * The number of PHYSMAP entries must be one less than the number of
173 * PHYSSEG entries because the PHYSMAP entry that spans the largest
174 * physical address that is accessible by ISA DMA is split into two
177 #define PHYSMAP_SIZE (2 * (VM_PHYSSEG_MAX - 1))
179 vm_paddr_t phys_avail[PHYSMAP_SIZE + 2];
180 vm_paddr_t dump_avail[PHYSMAP_SIZE + 2];
182 /* must be 2 less so 0 0 can signal end of chunks */
183 #define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(phys_avail[0])) - 2)
184 #define DUMP_AVAIL_ARRAY_END ((sizeof(dump_avail) / sizeof(dump_avail[0])) - 2)
186 struct kva_md_info kmi;
188 static struct trapframe proc0_tf;
189 struct region_descriptor r_gdt, r_idt;
191 struct pcpu __pcpu[MAXCPU];
195 struct mem_range_softc mem_range_softc;
197 struct mtx dt_lock; /* lock for GDT and LDT */
207 * On MacBooks, we need to disallow the legacy USB circuit to
208 * generate an SMI# because this can cause several problems,
209 * namely: incorrect CPU frequency detection and failure to
211 * We do this by disabling a bit in the SMI_EN (SMI Control and
212 * Enable register) of the Intel ICH LPC Interface Bridge.
214 sysenv = getenv("smbios.system.product");
215 if (sysenv != NULL) {
216 if (strncmp(sysenv, "MacBook1,1", 10) == 0 ||
217 strncmp(sysenv, "MacBook3,1", 10) == 0 ||
218 strncmp(sysenv, "MacBookPro1,1", 13) == 0 ||
219 strncmp(sysenv, "MacBookPro1,2", 13) == 0 ||
220 strncmp(sysenv, "MacBookPro3,1", 13) == 0 ||
221 strncmp(sysenv, "Macmini1,1", 10) == 0) {
223 printf("Disabling LEGACY_USB_EN bit on "
225 outl(ICH_SMI_EN, inl(ICH_SMI_EN) & ~0x8);
231 * Good {morning,afternoon,evening,night}.
235 panicifcpuunsupported();
242 * Display physical memory if SMBIOS reports reasonable amount.
245 sysenv = getenv("smbios.memory.enabled");
246 if (sysenv != NULL) {
247 memsize = (uintmax_t)strtoul(sysenv, (char **)NULL, 10) << 10;
250 if (memsize < ptoa((uintmax_t)cnt.v_free_count))
251 memsize = ptoa((uintmax_t)Maxmem);
252 printf("real memory = %ju (%ju MB)\n", memsize, memsize >> 20);
255 * Display any holes after the first chunk of extended memory.
260 printf("Physical memory chunk(s):\n");
261 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
264 size = phys_avail[indx + 1] - phys_avail[indx];
266 "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
267 (uintmax_t)phys_avail[indx],
268 (uintmax_t)phys_avail[indx + 1] - 1,
269 (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
273 vm_ksubmap_init(&kmi);
275 printf("avail memory = %ju (%ju MB)\n",
276 ptoa((uintmax_t)cnt.v_free_count),
277 ptoa((uintmax_t)cnt.v_free_count) / 1048576);
280 * Set up buffers, so they can be used to read disk labels.
283 vm_pager_bufferinit();
289 * Send an interrupt to process.
291 * Stack is set up to allow sigcode stored
292 * at top to call routine, followed by call
293 * to sigreturn routine below. After sigreturn
294 * resets the signal mask, the stack, and the
295 * frame pointer, it returns to the user
299 sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
301 struct sigframe sf, *sfp;
306 struct trapframe *regs;
312 PROC_LOCK_ASSERT(p, MA_OWNED);
313 sig = ksi->ksi_signo;
315 mtx_assert(&psp->ps_mtx, MA_OWNED);
317 oonstack = sigonstack(regs->tf_rsp);
319 /* Save user context. */
320 bzero(&sf, sizeof(sf));
321 sf.sf_uc.uc_sigmask = *mask;
322 sf.sf_uc.uc_stack = td->td_sigstk;
323 sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
324 ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
325 sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
326 bcopy(regs, &sf.sf_uc.uc_mcontext.mc_rdi, sizeof(*regs));
327 sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext); /* magic */
328 get_fpcontext(td, &sf.sf_uc.uc_mcontext);
330 sf.sf_uc.uc_mcontext.mc_fsbase = td->td_pcb->pcb_fsbase;
331 sf.sf_uc.uc_mcontext.mc_gsbase = td->td_pcb->pcb_gsbase;
333 /* Allocate space for the signal handler context. */
334 if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
335 SIGISMEMBER(psp->ps_sigonstack, sig)) {
336 sp = td->td_sigstk.ss_sp +
337 td->td_sigstk.ss_size - sizeof(struct sigframe);
338 #if defined(COMPAT_43)
339 td->td_sigstk.ss_flags |= SS_ONSTACK;
342 sp = (char *)regs->tf_rsp - sizeof(struct sigframe) - 128;
343 /* Align to 16 bytes. */
344 sfp = (struct sigframe *)((unsigned long)sp & ~0xFul);
346 /* Translate the signal if appropriate. */
347 if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
348 sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
350 /* Build the argument list for the signal handler. */
351 regs->tf_rdi = sig; /* arg 1 in %rdi */
352 regs->tf_rdx = (register_t)&sfp->sf_uc; /* arg 3 in %rdx */
353 if (SIGISMEMBER(psp->ps_siginfo, sig)) {
354 /* Signal handler installed with SA_SIGINFO. */
355 regs->tf_rsi = (register_t)&sfp->sf_si; /* arg 2 in %rsi */
356 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
358 /* Fill in POSIX parts */
359 sf.sf_si = ksi->ksi_info;
360 sf.sf_si.si_signo = sig; /* maybe a translated signal */
361 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
363 /* Old FreeBSD-style arguments. */
364 regs->tf_rsi = ksi->ksi_code; /* arg 2 in %rsi */
365 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
366 sf.sf_ahu.sf_handler = catcher;
368 mtx_unlock(&psp->ps_mtx);
372 * Copy the sigframe out to the user's stack.
374 if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
376 printf("process %ld has trashed its stack\n", (long)p->p_pid);
382 regs->tf_rsp = (long)sfp;
383 regs->tf_rip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
384 regs->tf_rflags &= ~(PSL_T | PSL_D);
385 regs->tf_cs = _ucodesel;
386 regs->tf_ds = _udatasel;
387 regs->tf_es = _udatasel;
388 regs->tf_fs = _ufssel;
389 regs->tf_gs = _ugssel;
390 regs->tf_flags = TF_HASSEGS;
391 td->td_pcb->pcb_full_iret = 1;
393 mtx_lock(&psp->ps_mtx);
397 * System call to cleanup state after a signal
398 * has been taken. Reset signal mask and
399 * stack state from context left by sendsig (above).
400 * Return to previous pc and psl as specified by
401 * context left by sendsig. Check carefully to
402 * make sure that the user has not modified the
403 * state to gain improper privileges.
410 struct sigreturn_args /* {
411 const struct __ucontext *sigcntxp;
415 struct proc *p = td->td_proc;
416 struct trapframe *regs;
422 error = copyin(uap->sigcntxp, &uc, sizeof(uc));
424 uprintf("pid %d (%s): sigreturn copyin failed\n",
425 p->p_pid, td->td_name);
429 if ((ucp->uc_mcontext.mc_flags & ~_MC_FLAG_MASK) != 0) {
430 uprintf("pid %d (%s): sigreturn mc_flags %x\n", p->p_pid,
431 td->td_name, ucp->uc_mcontext.mc_flags);
435 rflags = ucp->uc_mcontext.mc_rflags;
437 * Don't allow users to change privileged or reserved flags.
440 * XXX do allow users to change the privileged flag PSL_RF.
441 * The cpu sets PSL_RF in tf_rflags for faults. Debuggers
442 * should sometimes set it there too. tf_rflags is kept in
443 * the signal context during signal handling and there is no
444 * other place to remember it, so the PSL_RF bit may be
445 * corrupted by the signal handler without us knowing.
446 * Corruption of the PSL_RF bit at worst causes one more or
447 * one less debugger trap, so allowing it is fairly harmless.
449 if (!EFL_SECURE(rflags & ~PSL_RF, regs->tf_rflags & ~PSL_RF)) {
450 uprintf("pid %d (%s): sigreturn rflags = 0x%lx\n", p->p_pid,
451 td->td_name, rflags);
456 * Don't allow users to load a valid privileged %cs. Let the
457 * hardware check for invalid selectors, excess privilege in
458 * other selectors, invalid %eip's and invalid %esp's.
460 cs = ucp->uc_mcontext.mc_cs;
461 if (!CS_SECURE(cs)) {
462 uprintf("pid %d (%s): sigreturn cs = 0x%x\n", p->p_pid,
464 ksiginfo_init_trap(&ksi);
465 ksi.ksi_signo = SIGBUS;
466 ksi.ksi_code = BUS_OBJERR;
467 ksi.ksi_trapno = T_PROTFLT;
468 ksi.ksi_addr = (void *)regs->tf_rip;
469 trapsignal(td, &ksi);
473 ret = set_fpcontext(td, &ucp->uc_mcontext);
475 uprintf("pid %d (%s): sigreturn set_fpcontext err %d\n",
476 p->p_pid, td->td_name, ret);
479 bcopy(&ucp->uc_mcontext.mc_rdi, regs, sizeof(*regs));
480 td->td_pcb->pcb_fsbase = ucp->uc_mcontext.mc_fsbase;
481 td->td_pcb->pcb_gsbase = ucp->uc_mcontext.mc_gsbase;
483 #if defined(COMPAT_43)
484 if (ucp->uc_mcontext.mc_onstack & 1)
485 td->td_sigstk.ss_flags |= SS_ONSTACK;
487 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
490 kern_sigprocmask(td, SIG_SETMASK, &ucp->uc_sigmask, NULL, 0);
491 td->td_pcb->pcb_full_iret = 1;
492 return (EJUSTRETURN);
495 #ifdef COMPAT_FREEBSD4
497 freebsd4_sigreturn(struct thread *td, struct freebsd4_sigreturn_args *uap)
500 return sigreturn(td, (struct sigreturn_args *)uap);
506 * Machine dependent boot() routine
508 * I haven't seen anything to put here yet
509 * Possibly some stuff might be grafted back here from boot()
517 * Flush the D-cache for non-DMA I/O so that the I-cache can
518 * be made coherent later.
521 cpu_flush_dcache(void *ptr, size_t len)
526 /* Get current clock frequency for the given cpu id. */
528 cpu_est_clockrate(int cpu_id, uint64_t *rate)
533 if (pcpu_find(cpu_id) == NULL || rate == NULL)
536 /* If we're booting, trust the rate calibrated moments ago. */
543 /* Schedule ourselves on the indicated cpu. */
544 thread_lock(curthread);
545 sched_bind(curthread, cpu_id);
546 thread_unlock(curthread);
549 /* Calibrate by measuring a short delay. */
550 reg = intr_disable();
557 thread_lock(curthread);
558 sched_unbind(curthread);
559 thread_unlock(curthread);
563 * Calculate the difference in readings, convert to Mhz, and
564 * subtract 0.5% of the total. Empirical testing has shown that
565 * overhead in DELAY() works out to approximately this value.
568 *rate = tsc2 * 1000 - tsc2 * 5;
573 * Shutdown the CPU as much as possible
582 void (*cpu_idle_hook)(void) = NULL; /* ACPI idle hook. */
585 cpu_idle_hlt(int busy)
588 * we must absolutely guarentee that hlt is the next instruction
589 * after sti or we introduce a timing window.
592 if (sched_runnable())
595 __asm __volatile("sti; hlt");
599 cpu_idle_acpi(int busy)
602 if (sched_runnable())
604 else if (cpu_idle_hook)
607 __asm __volatile("sti; hlt");
610 static int cpu_ident_amdc1e = 0;
613 cpu_probe_amdc1e(void)
618 * Forget it, if we're not using local APIC timer.
620 if (resource_disabled("apic", 0) ||
621 (resource_int_value("apic", 0, "clock", &i) == 0 && i == 0))
625 * Detect the presence of C1E capability mostly on latest
626 * dual-cores (or future) k8 family.
628 if (cpu_vendor_id == CPU_VENDOR_AMD &&
629 (cpu_id & 0x00000f00) == 0x00000f00 &&
630 (cpu_id & 0x0fff0000) >= 0x00040000) {
631 cpu_ident_amdc1e = 1;
639 * C1E renders the local APIC timer dead, so we disable it by
640 * reading the Interrupt Pending Message register and clearing
641 * both C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
644 * "BIOS and Kernel Developer's Guide for AMD NPT Family 0Fh Processors"
645 * #32559 revision 3.00+
647 #define MSR_AMDK8_IPM 0xc0010055
648 #define AMDK8_SMIONCMPHALT (1ULL << 27)
649 #define AMDK8_C1EONCMPHALT (1ULL << 28)
650 #define AMDK8_CMPHALT (AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
653 cpu_idle_amdc1e(int busy)
657 if (sched_runnable())
662 msr = rdmsr(MSR_AMDK8_IPM);
663 if (msr & AMDK8_CMPHALT)
664 wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
669 __asm __volatile("sti; hlt");
674 cpu_idle_spin(int busy)
679 void (*cpu_idle_fn)(int) = cpu_idle_acpi;
685 if (mp_grab_cpu_hlt())
692 * mwait cpu power states. Lower 4 bits are sub-states.
694 #define MWAIT_C0 0xf0
695 #define MWAIT_C1 0x00
696 #define MWAIT_C2 0x10
697 #define MWAIT_C3 0x20
698 #define MWAIT_C4 0x30
700 #define MWAIT_DISABLED 0x0
701 #define MWAIT_WOKEN 0x1
702 #define MWAIT_WAITING 0x2
705 cpu_idle_mwait(int busy)
709 mwait = (int *)PCPU_PTR(monitorbuf);
710 *mwait = MWAIT_WAITING;
711 if (sched_runnable())
713 cpu_monitor(mwait, 0, 0);
714 if (*mwait == MWAIT_WAITING)
715 cpu_mwait(0, MWAIT_C1);
719 cpu_idle_mwait_hlt(int busy)
723 mwait = (int *)PCPU_PTR(monitorbuf);
725 *mwait = MWAIT_DISABLED;
729 *mwait = MWAIT_WAITING;
730 if (sched_runnable())
732 cpu_monitor(mwait, 0, 0);
733 if (*mwait == MWAIT_WAITING)
734 cpu_mwait(0, MWAIT_C1);
738 cpu_idle_wakeup(int cpu)
743 if (cpu_idle_fn == cpu_idle_spin)
745 if (cpu_idle_fn != cpu_idle_mwait && cpu_idle_fn != cpu_idle_mwait_hlt)
747 pcpu = pcpu_find(cpu);
748 mwait = (int *)pcpu->pc_monitorbuf;
750 * This doesn't need to be atomic since missing the race will
751 * simply result in unnecessary IPIs.
753 if (cpu_idle_fn == cpu_idle_mwait_hlt && *mwait == MWAIT_DISABLED)
755 *mwait = MWAIT_WOKEN;
761 * Ordered by speed/power consumption.
767 { cpu_idle_spin, "spin" },
768 { cpu_idle_mwait, "mwait" },
769 { cpu_idle_mwait_hlt, "mwait_hlt" },
770 { cpu_idle_amdc1e, "amdc1e" },
771 { cpu_idle_hlt, "hlt" },
772 { cpu_idle_acpi, "acpi" },
777 idle_sysctl_available(SYSCTL_HANDLER_ARGS)
783 avail = malloc(256, M_TEMP, M_WAITOK);
785 for (i = 0; idle_tbl[i].id_name != NULL; i++) {
786 if (strstr(idle_tbl[i].id_name, "mwait") &&
787 (cpu_feature2 & CPUID2_MON) == 0)
789 if (strcmp(idle_tbl[i].id_name, "amdc1e") == 0 &&
790 cpu_ident_amdc1e == 0)
792 p += sprintf(p, "%s, ", idle_tbl[i].id_name);
794 error = sysctl_handle_string(oidp, avail, 0, req);
800 idle_sysctl(SYSCTL_HANDLER_ARGS)
808 for (i = 0; idle_tbl[i].id_name != NULL; i++) {
809 if (idle_tbl[i].id_fn == cpu_idle_fn) {
810 p = idle_tbl[i].id_name;
814 strncpy(buf, p, sizeof(buf));
815 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
816 if (error != 0 || req->newptr == NULL)
818 for (i = 0; idle_tbl[i].id_name != NULL; i++) {
819 if (strstr(idle_tbl[i].id_name, "mwait") &&
820 (cpu_feature2 & CPUID2_MON) == 0)
822 if (strcmp(idle_tbl[i].id_name, "amdc1e") == 0 &&
823 cpu_ident_amdc1e == 0)
825 if (strcmp(idle_tbl[i].id_name, buf))
827 cpu_idle_fn = idle_tbl[i].id_fn;
833 SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
834 0, 0, idle_sysctl_available, "A", "list of available idle functions");
836 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
837 idle_sysctl, "A", "currently selected idle function");
840 * Reset registers to default values on exec.
843 exec_setregs(td, entry, stack, ps_strings)
849 struct trapframe *regs = td->td_frame;
850 struct pcb *pcb = td->td_pcb;
853 if (td->td_proc->p_md.md_ldt != NULL)
856 mtx_unlock(&dt_lock);
860 pcb->pcb_flags &= ~(PCB_32BIT | PCB_GS32BIT);
861 pcb->pcb_initial_fpucw = __INITIAL_FPUCW__;
862 pcb->pcb_full_iret = 1;
864 bzero((char *)regs, sizeof(struct trapframe));
865 regs->tf_rip = entry;
866 regs->tf_rsp = ((stack - 8) & ~0xFul) + 8;
867 regs->tf_rdi = stack; /* argv */
868 regs->tf_rflags = PSL_USER | (regs->tf_rflags & PSL_T);
869 regs->tf_ss = _udatasel;
870 regs->tf_cs = _ucodesel;
871 regs->tf_ds = _udatasel;
872 regs->tf_es = _udatasel;
873 regs->tf_fs = _ufssel;
874 regs->tf_gs = _ugssel;
875 regs->tf_flags = TF_HASSEGS;
876 td->td_retval[1] = 0;
879 * Reset the hardware debug registers if they were in use.
880 * They won't have any meaning for the newly exec'd process.
882 if (pcb->pcb_flags & PCB_DBREGS) {
889 if (pcb == PCPU_GET(curpcb)) {
891 * Clear the debug registers on the running
892 * CPU, otherwise they will end up affecting
893 * the next process we switch to.
897 pcb->pcb_flags &= ~PCB_DBREGS;
901 * Drop the FP state if we hold it, so that the process gets a
902 * clean FP state if it uses the FPU again.
914 * CR0_MP, CR0_NE and CR0_TS are also set by npx_probe() for the
915 * BSP. See the comments there about why we set them.
917 cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
922 * Initialize amd64 and configure to run kernel
926 * Initialize segments & interrupt table
929 struct user_segment_descriptor gdt[NGDT * MAXCPU];/* global descriptor tables */
930 static struct gate_descriptor idt0[NIDT];
931 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
933 static char dblfault_stack[PAGE_SIZE] __aligned(16);
935 static char nmi0_stack[PAGE_SIZE] __aligned(16);
936 CTASSERT(sizeof(struct nmi_pcpu) == 16);
938 struct amd64tss common_tss[MAXCPU];
941 * Software prototypes -- in more palatable form.
943 * Keep GUFS32, GUGS32, GUCODE32 and GUDATA at the same
944 * slots as corresponding segments for i386 kernel.
946 struct soft_segment_descriptor gdt_segs[] = {
947 /* GNULL_SEL 0 Null Descriptor */
956 /* GNULL2_SEL 1 Null Descriptor */
965 /* GUFS32_SEL 2 32 bit %gs Descriptor for user */
967 .ssd_limit = 0xfffff,
968 .ssd_type = SDT_MEMRWA,
974 /* GUGS32_SEL 3 32 bit %fs Descriptor for user */
976 .ssd_limit = 0xfffff,
977 .ssd_type = SDT_MEMRWA,
983 /* GCODE_SEL 4 Code Descriptor for kernel */
985 .ssd_limit = 0xfffff,
986 .ssd_type = SDT_MEMERA,
992 /* GDATA_SEL 5 Data Descriptor for kernel */
994 .ssd_limit = 0xfffff,
995 .ssd_type = SDT_MEMRWA,
1001 /* GUCODE32_SEL 6 32 bit Code Descriptor for user */
1003 .ssd_limit = 0xfffff,
1004 .ssd_type = SDT_MEMERA,
1010 /* GUDATA_SEL 7 32/64 bit Data Descriptor for user */
1012 .ssd_limit = 0xfffff,
1013 .ssd_type = SDT_MEMRWA,
1019 /* GUCODE_SEL 8 64 bit Code Descriptor for user */
1021 .ssd_limit = 0xfffff,
1022 .ssd_type = SDT_MEMERA,
1028 /* GPROC0_SEL 9 Proc 0 Tss Descriptor */
1030 .ssd_limit = sizeof(struct amd64tss) + IOPAGES * PAGE_SIZE - 1,
1031 .ssd_type = SDT_SYSTSS,
1037 /* Actually, the TSS is a system descriptor which is double size */
1046 /* GUSERLDT_SEL 11 LDT Descriptor */
1055 /* GUSERLDT_SEL 12 LDT Descriptor, double size */
1067 setidt(idx, func, typ, dpl, ist)
1074 struct gate_descriptor *ip;
1077 ip->gd_looffset = (uintptr_t)func;
1078 ip->gd_selector = GSEL(GCODE_SEL, SEL_KPL);
1084 ip->gd_hioffset = ((uintptr_t)func)>>16 ;
1088 IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1089 IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1090 IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1091 IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1092 IDTVEC(xmm), IDTVEC(dblfault),
1093 IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
1097 * Display the index and function name of any IDT entries that don't use
1098 * the default 'rsvd' entry point.
1100 DB_SHOW_COMMAND(idt, db_show_idt)
1102 struct gate_descriptor *ip;
1107 for (idx = 0; idx < NIDT && !db_pager_quit; idx++) {
1108 func = ((long)ip->gd_hioffset << 16 | ip->gd_looffset);
1109 if (func != (uintptr_t)&IDTVEC(rsvd)) {
1110 db_printf("%3d\t", idx);
1111 db_printsym(func, DB_STGY_PROC);
1121 struct user_segment_descriptor *sd;
1122 struct soft_segment_descriptor *ssd;
1125 ssd->ssd_base = (sd->sd_hibase << 24) | sd->sd_lobase;
1126 ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1127 ssd->ssd_type = sd->sd_type;
1128 ssd->ssd_dpl = sd->sd_dpl;
1129 ssd->ssd_p = sd->sd_p;
1130 ssd->ssd_long = sd->sd_long;
1131 ssd->ssd_def32 = sd->sd_def32;
1132 ssd->ssd_gran = sd->sd_gran;
1137 struct soft_segment_descriptor *ssd;
1138 struct user_segment_descriptor *sd;
1141 sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
1142 sd->sd_hibase = (ssd->ssd_base >> 24) & 0xff;
1143 sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
1144 sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
1145 sd->sd_type = ssd->ssd_type;
1146 sd->sd_dpl = ssd->ssd_dpl;
1147 sd->sd_p = ssd->ssd_p;
1148 sd->sd_long = ssd->ssd_long;
1149 sd->sd_def32 = ssd->ssd_def32;
1150 sd->sd_gran = ssd->ssd_gran;
1155 struct soft_segment_descriptor *ssd;
1156 struct system_segment_descriptor *sd;
1159 sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
1160 sd->sd_hibase = (ssd->ssd_base >> 24) & 0xfffffffffful;
1161 sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
1162 sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
1163 sd->sd_type = ssd->ssd_type;
1164 sd->sd_dpl = ssd->ssd_dpl;
1165 sd->sd_p = ssd->ssd_p;
1166 sd->sd_gran = ssd->ssd_gran;
1169 #if !defined(DEV_ATPIC) && defined(DEV_ISA)
1170 #include <isa/isavar.h>
1171 #include <isa/isareg.h>
1173 * Return a bitmap of the current interrupt requests. This is 8259-specific
1174 * and is only suitable for use at probe time.
1175 * This is only here to pacify sio. It is NOT FATAL if this doesn't work.
1176 * It shouldn't be here. There should probably be an APIC centric
1177 * implementation in the apic driver code, if at all.
1180 isa_irq_pending(void)
1185 irr1 = inb(IO_ICU1);
1186 irr2 = inb(IO_ICU2);
1187 return ((irr2 << 8) | irr1);
1194 add_smap_entry(struct bios_smap *smap, vm_paddr_t *physmap, int *physmap_idxp)
1196 int i, insert_idx, physmap_idx;
1198 physmap_idx = *physmap_idxp;
1200 if (boothowto & RB_VERBOSE)
1201 printf("SMAP type=%02x base=%016lx len=%016lx\n",
1202 smap->type, smap->base, smap->length);
1204 if (smap->type != SMAP_TYPE_MEMORY)
1207 if (smap->length == 0)
1211 * Find insertion point while checking for overlap. Start off by
1212 * assuming the new entry will be added to the end.
1214 insert_idx = physmap_idx + 2;
1215 for (i = 0; i <= physmap_idx; i += 2) {
1216 if (smap->base < physmap[i + 1]) {
1217 if (smap->base + smap->length <= physmap[i]) {
1221 if (boothowto & RB_VERBOSE)
1223 "Overlapping memory regions, ignoring second region\n");
1228 /* See if we can prepend to the next entry. */
1229 if (insert_idx <= physmap_idx &&
1230 smap->base + smap->length == physmap[insert_idx]) {
1231 physmap[insert_idx] = smap->base;
1235 /* See if we can append to the previous entry. */
1236 if (insert_idx > 0 && smap->base == physmap[insert_idx - 1]) {
1237 physmap[insert_idx - 1] += smap->length;
1242 *physmap_idxp = physmap_idx;
1243 if (physmap_idx == PHYSMAP_SIZE) {
1245 "Too many segments in the physical address map, giving up\n");
1250 * Move the last 'N' entries down to make room for the new
1253 for (i = physmap_idx; i > insert_idx; i -= 2) {
1254 physmap[i] = physmap[i - 2];
1255 physmap[i + 1] = physmap[i - 1];
1258 /* Insert the new entry. */
1259 physmap[insert_idx] = smap->base;
1260 physmap[insert_idx + 1] = smap->base + smap->length;
1265 * Populate the (physmap) array with base/bound pairs describing the
1266 * available physical memory in the system, then test this memory and
1267 * build the phys_avail array describing the actually-available memory.
1269 * If we cannot accurately determine the physical memory map, then use
1270 * value from the 0xE801 call, and failing that, the RTC.
1272 * Total memory size may be set by the kernel environment variable
1273 * hw.physmem or the compile-time define MAXMEM.
1275 * XXX first should be vm_paddr_t.
1278 getmemsize(caddr_t kmdp, u_int64_t first)
1280 int i, off, physmap_idx, pa_indx, da_indx;
1281 vm_paddr_t pa, physmap[PHYSMAP_SIZE];
1282 u_long physmem_tunable;
1284 struct bios_smap *smapbase, *smap, *smapend;
1286 quad_t dcons_addr, dcons_size;
1288 bzero(physmap, sizeof(physmap));
1293 * get memory map from INT 15:E820, kindly supplied by the loader.
1295 * subr_module.c says:
1296 * "Consumer may safely assume that size value precedes data."
1297 * ie: an int32_t immediately precedes smap.
1299 smapbase = (struct bios_smap *)preload_search_info(kmdp,
1300 MODINFO_METADATA | MODINFOMD_SMAP);
1301 if (smapbase == NULL)
1302 panic("No BIOS smap info from loader!");
1304 smapsize = *((u_int32_t *)smapbase - 1);
1305 smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
1307 for (smap = smapbase; smap < smapend; smap++)
1308 if (!add_smap_entry(smap, physmap, &physmap_idx))
1312 * Find the 'base memory' segment for SMP
1315 for (i = 0; i <= physmap_idx; i += 2) {
1316 if (physmap[i] == 0x00000000) {
1317 basemem = physmap[i + 1] / 1024;
1322 panic("BIOS smap did not include a basemem segment!");
1325 /* make hole for AP bootstrap code */
1326 physmap[1] = mp_bootaddress(physmap[1] / 1024);
1330 * Maxmem isn't the "maximum memory", it's one larger than the
1331 * highest page of the physical address space. It should be
1332 * called something like "Maxphyspage". We may adjust this
1333 * based on ``hw.physmem'' and the results of the memory test.
1335 Maxmem = atop(physmap[physmap_idx + 1]);
1338 Maxmem = MAXMEM / 4;
1341 if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
1342 Maxmem = atop(physmem_tunable);
1345 * Don't allow MAXMEM or hw.physmem to extend the amount of memory
1348 if (Maxmem > atop(physmap[physmap_idx + 1]))
1349 Maxmem = atop(physmap[physmap_idx + 1]);
1351 if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1352 (boothowto & RB_VERBOSE))
1353 printf("Physical memory use set to %ldK\n", Maxmem * 4);
1355 /* call pmap initialization to make new kernel address space */
1356 pmap_bootstrap(&first);
1359 * Size up each available chunk of physical memory.
1361 physmap[0] = PAGE_SIZE; /* mask off page 0 */
1364 phys_avail[pa_indx++] = physmap[0];
1365 phys_avail[pa_indx] = physmap[0];
1366 dump_avail[da_indx] = physmap[0];
1370 * Get dcons buffer address
1372 if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
1373 getenv_quad("dcons.size", &dcons_size) == 0)
1377 * physmap is in bytes, so when converting to page boundaries,
1378 * round up the start address and round down the end address.
1380 for (i = 0; i <= physmap_idx; i += 2) {
1383 end = ptoa((vm_paddr_t)Maxmem);
1384 if (physmap[i + 1] < end)
1385 end = trunc_page(physmap[i + 1]);
1386 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1387 int tmp, page_bad, full;
1388 int *ptr = (int *)CADDR1;
1392 * block out kernel memory as not available.
1394 if (pa >= 0x100000 && pa < first)
1398 * block out dcons buffer
1401 && pa >= trunc_page(dcons_addr)
1402 && pa < dcons_addr + dcons_size)
1408 * map page into kernel: valid, read/write,non-cacheable
1410 *pte = pa | PG_V | PG_RW | PG_N;
1415 * Test for alternating 1's and 0's
1417 *(volatile int *)ptr = 0xaaaaaaaa;
1418 if (*(volatile int *)ptr != 0xaaaaaaaa)
1421 * Test for alternating 0's and 1's
1423 *(volatile int *)ptr = 0x55555555;
1424 if (*(volatile int *)ptr != 0x55555555)
1429 *(volatile int *)ptr = 0xffffffff;
1430 if (*(volatile int *)ptr != 0xffffffff)
1435 *(volatile int *)ptr = 0x0;
1436 if (*(volatile int *)ptr != 0x0)
1439 * Restore original value.
1444 * Adjust array of valid/good pages.
1446 if (page_bad == TRUE)
1449 * If this good page is a continuation of the
1450 * previous set of good pages, then just increase
1451 * the end pointer. Otherwise start a new chunk.
1452 * Note that "end" points one higher than end,
1453 * making the range >= start and < end.
1454 * If we're also doing a speculative memory
1455 * test and we at or past the end, bump up Maxmem
1456 * so that we keep going. The first bad page
1457 * will terminate the loop.
1459 if (phys_avail[pa_indx] == pa) {
1460 phys_avail[pa_indx] += PAGE_SIZE;
1463 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1465 "Too many holes in the physical address space, giving up\n");
1470 phys_avail[pa_indx++] = pa; /* start */
1471 phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
1475 if (dump_avail[da_indx] == pa) {
1476 dump_avail[da_indx] += PAGE_SIZE;
1479 if (da_indx == DUMP_AVAIL_ARRAY_END) {
1483 dump_avail[da_indx++] = pa; /* start */
1484 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
1496 * The last chunk must contain at least one page plus the message
1497 * buffer to avoid complicating other code (message buffer address
1498 * calculation, etc.).
1500 while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1501 round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
1502 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1503 phys_avail[pa_indx--] = 0;
1504 phys_avail[pa_indx--] = 0;
1507 Maxmem = atop(phys_avail[pa_indx]);
1509 /* Trim off space for the message buffer. */
1510 phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
1512 /* Map the message buffer. */
1513 for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
1514 pmap_kenter((vm_offset_t)msgbufp + off, phys_avail[pa_indx] +
1519 hammer_time(u_int64_t modulep, u_int64_t physfree)
1524 struct nmi_pcpu *np;
1528 thread0.td_kstack = physfree + KERNBASE;
1529 bzero((void *)thread0.td_kstack, KSTACK_PAGES * PAGE_SIZE);
1530 physfree += KSTACK_PAGES * PAGE_SIZE;
1531 thread0.td_pcb = (struct pcb *)
1532 (thread0.td_kstack + KSTACK_PAGES * PAGE_SIZE) - 1;
1535 * This may be done better later if it gets more high level
1536 * components in it. If so just link td->td_proc here.
1538 proc_linkup0(&proc0, &thread0);
1540 preload_metadata = (caddr_t)(uintptr_t)(modulep + KERNBASE);
1541 preload_bootstrap_relocate(KERNBASE);
1542 kmdp = preload_search_by_type("elf kernel");
1544 kmdp = preload_search_by_type("elf64 kernel");
1545 boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
1546 kern_envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *) + KERNBASE;
1548 ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
1549 ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
1552 /* Init basic tunables, hz etc */
1556 * make gdt memory segments
1558 for (x = 0; x < NGDT; x++) {
1559 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1) &&
1560 x != GUSERLDT_SEL && x != (GUSERLDT_SEL) + 1)
1561 ssdtosd(&gdt_segs[x], &gdt[x]);
1563 gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&common_tss[0];
1564 ssdtosyssd(&gdt_segs[GPROC0_SEL],
1565 (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1567 r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1568 r_gdt.rd_base = (long) gdt;
1572 wrmsr(MSR_FSBASE, 0); /* User value */
1573 wrmsr(MSR_GSBASE, (u_int64_t)pc);
1574 wrmsr(MSR_KGSBASE, 0); /* User value while in the kernel */
1576 pcpu_init(pc, 0, sizeof(struct pcpu));
1577 dpcpu_init((void *)(physfree + KERNBASE), 0);
1578 physfree += DPCPU_SIZE;
1579 PCPU_SET(prvspace, pc);
1580 PCPU_SET(curthread, &thread0);
1581 PCPU_SET(curpcb, thread0.td_pcb);
1582 PCPU_SET(tssp, &common_tss[0]);
1583 PCPU_SET(commontssp, &common_tss[0]);
1584 PCPU_SET(tss, (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1585 PCPU_SET(ldt, (struct system_segment_descriptor *)&gdt[GUSERLDT_SEL]);
1586 PCPU_SET(fs32p, &gdt[GUFS32_SEL]);
1587 PCPU_SET(gs32p, &gdt[GUGS32_SEL]);
1590 * Initialize mutexes.
1592 * icu_lock: in order to allow an interrupt to occur in a critical
1593 * section, to set pcpu->ipending (etc...) properly, we
1594 * must be able to get the icu lock, so it can't be
1598 mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS);
1599 mtx_init(&dt_lock, "descriptor tables", NULL, MTX_DEF);
1602 for (x = 0; x < NIDT; x++)
1603 setidt(x, &IDTVEC(rsvd), SDT_SYSIGT, SEL_KPL, 0);
1604 setidt(IDT_DE, &IDTVEC(div), SDT_SYSIGT, SEL_KPL, 0);
1605 setidt(IDT_DB, &IDTVEC(dbg), SDT_SYSIGT, SEL_KPL, 0);
1606 setidt(IDT_NMI, &IDTVEC(nmi), SDT_SYSIGT, SEL_KPL, 2);
1607 setidt(IDT_BP, &IDTVEC(bpt), SDT_SYSIGT, SEL_UPL, 0);
1608 setidt(IDT_OF, &IDTVEC(ofl), SDT_SYSIGT, SEL_KPL, 0);
1609 setidt(IDT_BR, &IDTVEC(bnd), SDT_SYSIGT, SEL_KPL, 0);
1610 setidt(IDT_UD, &IDTVEC(ill), SDT_SYSIGT, SEL_KPL, 0);
1611 setidt(IDT_NM, &IDTVEC(dna), SDT_SYSIGT, SEL_KPL, 0);
1612 setidt(IDT_DF, &IDTVEC(dblfault), SDT_SYSIGT, SEL_KPL, 1);
1613 setidt(IDT_FPUGP, &IDTVEC(fpusegm), SDT_SYSIGT, SEL_KPL, 0);
1614 setidt(IDT_TS, &IDTVEC(tss), SDT_SYSIGT, SEL_KPL, 0);
1615 setidt(IDT_NP, &IDTVEC(missing), SDT_SYSIGT, SEL_KPL, 0);
1616 setidt(IDT_SS, &IDTVEC(stk), SDT_SYSIGT, SEL_KPL, 0);
1617 setidt(IDT_GP, &IDTVEC(prot), SDT_SYSIGT, SEL_KPL, 0);
1618 setidt(IDT_PF, &IDTVEC(page), SDT_SYSIGT, SEL_KPL, 0);
1619 setidt(IDT_MF, &IDTVEC(fpu), SDT_SYSIGT, SEL_KPL, 0);
1620 setidt(IDT_AC, &IDTVEC(align), SDT_SYSIGT, SEL_KPL, 0);
1621 setidt(IDT_MC, &IDTVEC(mchk), SDT_SYSIGT, SEL_KPL, 0);
1622 setidt(IDT_XF, &IDTVEC(xmm), SDT_SYSIGT, SEL_KPL, 0);
1624 r_idt.rd_limit = sizeof(idt0) - 1;
1625 r_idt.rd_base = (long) idt;
1629 * Initialize the i8254 before the console so that console
1630 * initialization can use DELAY().
1635 * Initialize the console before we print anything out.
1644 /* Reset and mask the atpics and leave them shut down. */
1648 * Point the ICU spurious interrupt vectors at the APIC spurious
1649 * interrupt handler.
1651 setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1652 setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1655 #error "have you forgotten the isa device?";
1661 if (boothowto & RB_KDB)
1662 kdb_enter(KDB_WHY_BOOTFLAGS,
1663 "Boot flags requested debugger");
1666 identify_cpu(); /* Final stage of CPU initialization */
1667 initializecpu(); /* Initialize CPU registers */
1668 initializecpucache();
1670 /* make an initial tss so cpu can get interrupt stack on syscall! */
1671 common_tss[0].tss_rsp0 = thread0.td_kstack + \
1672 KSTACK_PAGES * PAGE_SIZE - sizeof(struct pcb);
1673 /* Ensure the stack is aligned to 16 bytes */
1674 common_tss[0].tss_rsp0 &= ~0xFul;
1675 PCPU_SET(rsp0, common_tss[0].tss_rsp0);
1677 /* doublefault stack space, runs on ist1 */
1678 common_tss[0].tss_ist1 = (long)&dblfault_stack[sizeof(dblfault_stack)];
1681 * NMI stack, runs on ist2. The pcpu pointer is stored just
1682 * above the start of the ist2 stack.
1684 np = ((struct nmi_pcpu *) &nmi0_stack[sizeof(nmi0_stack)]) - 1;
1685 np->np_pcpu = (register_t) pc;
1686 common_tss[0].tss_ist2 = (long) np;
1688 /* Set the IO permission bitmap (empty due to tss seg limit) */
1689 common_tss[0].tss_iobase = sizeof(struct amd64tss) +
1690 IOPAGES * PAGE_SIZE;
1692 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1695 /* Set up the fast syscall stuff */
1696 msr = rdmsr(MSR_EFER) | EFER_SCE;
1697 wrmsr(MSR_EFER, msr);
1698 wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
1699 wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
1700 msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
1701 ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
1702 wrmsr(MSR_STAR, msr);
1703 wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
1705 getmemsize(kmdp, physfree);
1706 init_param2(physmem);
1708 /* now running on new page tables, configured,and u/iom is accessible */
1710 msgbufinit(msgbufp, MSGBUF_SIZE);
1713 /* transfer to user mode */
1715 _ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
1716 _udatasel = GSEL(GUDATA_SEL, SEL_UPL);
1717 _ucode32sel = GSEL(GUCODE32_SEL, SEL_UPL);
1718 _ufssel = GSEL(GUFS32_SEL, SEL_UPL);
1719 _ugssel = GSEL(GUGS32_SEL, SEL_UPL);
1725 /* setup proc 0's pcb */
1726 thread0.td_pcb->pcb_flags = 0;
1727 thread0.td_pcb->pcb_cr3 = KPML4phys;
1728 thread0.td_frame = &proc0_tf;
1730 env = getenv("kernelname");
1732 strlcpy(kernelname, env, sizeof(kernelname));
1735 if (inw(0x10) == 0x49d2) {
1737 printf("Xen detected: disabling emulated block and network devices\n");
1742 if (cpu_probe_amdc1e())
1743 cpu_idle_fn = cpu_idle_amdc1e;
1745 /* Location of kernel stack for locore */
1746 return ((u_int64_t)thread0.td_pcb);
1750 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
1753 pcpu->pc_acpi_id = 0xffffffff;
1757 spinlock_enter(void)
1762 if (td->td_md.md_spinlock_count == 0)
1763 td->td_md.md_saved_flags = intr_disable();
1764 td->td_md.md_spinlock_count++;
1775 td->td_md.md_spinlock_count--;
1776 if (td->td_md.md_spinlock_count == 0)
1777 intr_restore(td->td_md.md_saved_flags);
1781 * Construct a PCB from a trapframe. This is called from kdb_trap() where
1782 * we want to start a backtrace from the function that caused us to enter
1783 * the debugger. We have the context in the trapframe, but base the trace
1784 * on the PCB. The PCB doesn't have to be perfect, as long as it contains
1785 * enough for a backtrace.
1788 makectx(struct trapframe *tf, struct pcb *pcb)
1791 pcb->pcb_r12 = tf->tf_r12;
1792 pcb->pcb_r13 = tf->tf_r13;
1793 pcb->pcb_r14 = tf->tf_r14;
1794 pcb->pcb_r15 = tf->tf_r15;
1795 pcb->pcb_rbp = tf->tf_rbp;
1796 pcb->pcb_rbx = tf->tf_rbx;
1797 pcb->pcb_rip = tf->tf_rip;
1798 pcb->pcb_rsp = tf->tf_rsp;
1802 ptrace_set_pc(struct thread *td, unsigned long addr)
1804 td->td_frame->tf_rip = addr;
1809 ptrace_single_step(struct thread *td)
1811 td->td_frame->tf_rflags |= PSL_T;
1816 ptrace_clear_single_step(struct thread *td)
1818 td->td_frame->tf_rflags &= ~PSL_T;
1823 fill_regs(struct thread *td, struct reg *regs)
1825 struct trapframe *tp;
1828 regs->r_r15 = tp->tf_r15;
1829 regs->r_r14 = tp->tf_r14;
1830 regs->r_r13 = tp->tf_r13;
1831 regs->r_r12 = tp->tf_r12;
1832 regs->r_r11 = tp->tf_r11;
1833 regs->r_r10 = tp->tf_r10;
1834 regs->r_r9 = tp->tf_r9;
1835 regs->r_r8 = tp->tf_r8;
1836 regs->r_rdi = tp->tf_rdi;
1837 regs->r_rsi = tp->tf_rsi;
1838 regs->r_rbp = tp->tf_rbp;
1839 regs->r_rbx = tp->tf_rbx;
1840 regs->r_rdx = tp->tf_rdx;
1841 regs->r_rcx = tp->tf_rcx;
1842 regs->r_rax = tp->tf_rax;
1843 regs->r_rip = tp->tf_rip;
1844 regs->r_cs = tp->tf_cs;
1845 regs->r_rflags = tp->tf_rflags;
1846 regs->r_rsp = tp->tf_rsp;
1847 regs->r_ss = tp->tf_ss;
1848 if (tp->tf_flags & TF_HASSEGS) {
1849 regs->r_ds = tp->tf_ds;
1850 regs->r_es = tp->tf_es;
1851 regs->r_fs = tp->tf_fs;
1852 regs->r_gs = tp->tf_gs;
1863 set_regs(struct thread *td, struct reg *regs)
1865 struct trapframe *tp;
1869 rflags = regs->r_rflags & 0xffffffff;
1870 if (!EFL_SECURE(rflags, tp->tf_rflags) || !CS_SECURE(regs->r_cs))
1872 tp->tf_r15 = regs->r_r15;
1873 tp->tf_r14 = regs->r_r14;
1874 tp->tf_r13 = regs->r_r13;
1875 tp->tf_r12 = regs->r_r12;
1876 tp->tf_r11 = regs->r_r11;
1877 tp->tf_r10 = regs->r_r10;
1878 tp->tf_r9 = regs->r_r9;
1879 tp->tf_r8 = regs->r_r8;
1880 tp->tf_rdi = regs->r_rdi;
1881 tp->tf_rsi = regs->r_rsi;
1882 tp->tf_rbp = regs->r_rbp;
1883 tp->tf_rbx = regs->r_rbx;
1884 tp->tf_rdx = regs->r_rdx;
1885 tp->tf_rcx = regs->r_rcx;
1886 tp->tf_rax = regs->r_rax;
1887 tp->tf_rip = regs->r_rip;
1888 tp->tf_cs = regs->r_cs;
1889 tp->tf_rflags = rflags;
1890 tp->tf_rsp = regs->r_rsp;
1891 tp->tf_ss = regs->r_ss;
1892 if (0) { /* XXXKIB */
1893 tp->tf_ds = regs->r_ds;
1894 tp->tf_es = regs->r_es;
1895 tp->tf_fs = regs->r_fs;
1896 tp->tf_gs = regs->r_gs;
1897 tp->tf_flags = TF_HASSEGS;
1898 td->td_pcb->pcb_full_iret = 1;
1903 /* XXX check all this stuff! */
1904 /* externalize from sv_xmm */
1906 fill_fpregs_xmm(struct savefpu *sv_xmm, struct fpreg *fpregs)
1908 struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
1909 struct envxmm *penv_xmm = &sv_xmm->sv_env;
1913 bzero(fpregs, sizeof(*fpregs));
1915 /* FPU control/status */
1916 penv_fpreg->en_cw = penv_xmm->en_cw;
1917 penv_fpreg->en_sw = penv_xmm->en_sw;
1918 penv_fpreg->en_tw = penv_xmm->en_tw;
1919 penv_fpreg->en_opcode = penv_xmm->en_opcode;
1920 penv_fpreg->en_rip = penv_xmm->en_rip;
1921 penv_fpreg->en_rdp = penv_xmm->en_rdp;
1922 penv_fpreg->en_mxcsr = penv_xmm->en_mxcsr;
1923 penv_fpreg->en_mxcsr_mask = penv_xmm->en_mxcsr_mask;
1926 for (i = 0; i < 8; ++i)
1927 bcopy(sv_xmm->sv_fp[i].fp_acc.fp_bytes, fpregs->fpr_acc[i], 10);
1930 for (i = 0; i < 16; ++i)
1931 bcopy(sv_xmm->sv_xmm[i].xmm_bytes, fpregs->fpr_xacc[i], 16);
1934 /* internalize from fpregs into sv_xmm */
1936 set_fpregs_xmm(struct fpreg *fpregs, struct savefpu *sv_xmm)
1938 struct envxmm *penv_xmm = &sv_xmm->sv_env;
1939 struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
1943 /* FPU control/status */
1944 penv_xmm->en_cw = penv_fpreg->en_cw;
1945 penv_xmm->en_sw = penv_fpreg->en_sw;
1946 penv_xmm->en_tw = penv_fpreg->en_tw;
1947 penv_xmm->en_opcode = penv_fpreg->en_opcode;
1948 penv_xmm->en_rip = penv_fpreg->en_rip;
1949 penv_xmm->en_rdp = penv_fpreg->en_rdp;
1950 penv_xmm->en_mxcsr = penv_fpreg->en_mxcsr;
1951 penv_xmm->en_mxcsr_mask = penv_fpreg->en_mxcsr_mask & cpu_mxcsr_mask;
1954 for (i = 0; i < 8; ++i)
1955 bcopy(fpregs->fpr_acc[i], sv_xmm->sv_fp[i].fp_acc.fp_bytes, 10);
1958 for (i = 0; i < 16; ++i)
1959 bcopy(fpregs->fpr_xacc[i], sv_xmm->sv_xmm[i].xmm_bytes, 16);
1962 /* externalize from td->pcb */
1964 fill_fpregs(struct thread *td, struct fpreg *fpregs)
1967 KASSERT(td == curthread || TD_IS_SUSPENDED(td),
1968 ("not suspended thread %p", td));
1970 fill_fpregs_xmm(&td->td_pcb->pcb_user_save, fpregs);
1974 /* internalize to td->pcb */
1976 set_fpregs(struct thread *td, struct fpreg *fpregs)
1979 set_fpregs_xmm(fpregs, &td->td_pcb->pcb_user_save);
1985 * Get machine context.
1988 get_mcontext(struct thread *td, mcontext_t *mcp, int flags)
1990 struct trapframe *tp;
1993 PROC_LOCK(curthread->td_proc);
1994 mcp->mc_onstack = sigonstack(tp->tf_rsp);
1995 PROC_UNLOCK(curthread->td_proc);
1996 mcp->mc_r15 = tp->tf_r15;
1997 mcp->mc_r14 = tp->tf_r14;
1998 mcp->mc_r13 = tp->tf_r13;
1999 mcp->mc_r12 = tp->tf_r12;
2000 mcp->mc_r11 = tp->tf_r11;
2001 mcp->mc_r10 = tp->tf_r10;
2002 mcp->mc_r9 = tp->tf_r9;
2003 mcp->mc_r8 = tp->tf_r8;
2004 mcp->mc_rdi = tp->tf_rdi;
2005 mcp->mc_rsi = tp->tf_rsi;
2006 mcp->mc_rbp = tp->tf_rbp;
2007 mcp->mc_rbx = tp->tf_rbx;
2008 mcp->mc_rcx = tp->tf_rcx;
2009 mcp->mc_rflags = tp->tf_rflags;
2010 if (flags & GET_MC_CLEAR_RET) {
2013 mcp->mc_rflags &= ~PSL_C;
2015 mcp->mc_rax = tp->tf_rax;
2016 mcp->mc_rdx = tp->tf_rdx;
2018 mcp->mc_rip = tp->tf_rip;
2019 mcp->mc_cs = tp->tf_cs;
2020 mcp->mc_rsp = tp->tf_rsp;
2021 mcp->mc_ss = tp->tf_ss;
2022 mcp->mc_ds = tp->tf_ds;
2023 mcp->mc_es = tp->tf_es;
2024 mcp->mc_fs = tp->tf_fs;
2025 mcp->mc_gs = tp->tf_gs;
2026 mcp->mc_flags = tp->tf_flags;
2027 mcp->mc_len = sizeof(*mcp);
2028 get_fpcontext(td, mcp);
2029 mcp->mc_fsbase = td->td_pcb->pcb_fsbase;
2030 mcp->mc_gsbase = td->td_pcb->pcb_gsbase;
2035 * Set machine context.
2037 * However, we don't set any but the user modifiable flags, and we won't
2038 * touch the cs selector.
2041 set_mcontext(struct thread *td, const mcontext_t *mcp)
2043 struct trapframe *tp;
2048 if (mcp->mc_len != sizeof(*mcp) ||
2049 (mcp->mc_flags & ~_MC_FLAG_MASK) != 0)
2051 rflags = (mcp->mc_rflags & PSL_USERCHANGE) |
2052 (tp->tf_rflags & ~PSL_USERCHANGE);
2053 ret = set_fpcontext(td, mcp);
2056 tp->tf_r15 = mcp->mc_r15;
2057 tp->tf_r14 = mcp->mc_r14;
2058 tp->tf_r13 = mcp->mc_r13;
2059 tp->tf_r12 = mcp->mc_r12;
2060 tp->tf_r11 = mcp->mc_r11;
2061 tp->tf_r10 = mcp->mc_r10;
2062 tp->tf_r9 = mcp->mc_r9;
2063 tp->tf_r8 = mcp->mc_r8;
2064 tp->tf_rdi = mcp->mc_rdi;
2065 tp->tf_rsi = mcp->mc_rsi;
2066 tp->tf_rbp = mcp->mc_rbp;
2067 tp->tf_rbx = mcp->mc_rbx;
2068 tp->tf_rdx = mcp->mc_rdx;
2069 tp->tf_rcx = mcp->mc_rcx;
2070 tp->tf_rax = mcp->mc_rax;
2071 tp->tf_rip = mcp->mc_rip;
2072 tp->tf_rflags = rflags;
2073 tp->tf_rsp = mcp->mc_rsp;
2074 tp->tf_ss = mcp->mc_ss;
2075 tp->tf_flags = mcp->mc_flags;
2076 if (tp->tf_flags & TF_HASSEGS) {
2077 tp->tf_ds = mcp->mc_ds;
2078 tp->tf_es = mcp->mc_es;
2079 tp->tf_fs = mcp->mc_fs;
2080 tp->tf_gs = mcp->mc_gs;
2082 if (mcp->mc_flags & _MC_HASBASES) {
2083 td->td_pcb->pcb_fsbase = mcp->mc_fsbase;
2084 td->td_pcb->pcb_gsbase = mcp->mc_gsbase;
2086 td->td_pcb->pcb_full_iret = 1;
2091 get_fpcontext(struct thread *td, mcontext_t *mcp)
2094 mcp->mc_ownedfp = fpugetregs(td);
2095 bcopy(&td->td_pcb->pcb_user_save, &mcp->mc_fpstate,
2096 sizeof(mcp->mc_fpstate));
2097 mcp->mc_fpformat = fpuformat();
2101 set_fpcontext(struct thread *td, const mcontext_t *mcp)
2103 struct savefpu *fpstate;
2105 if (mcp->mc_fpformat == _MC_FPFMT_NODEV)
2107 else if (mcp->mc_fpformat != _MC_FPFMT_XMM)
2109 else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE)
2110 /* We don't care what state is left in the FPU or PCB. */
2112 else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU ||
2113 mcp->mc_ownedfp == _MC_FPOWNED_PCB) {
2114 fpstate = (struct savefpu *)&mcp->mc_fpstate;
2115 fpstate->sv_env.en_mxcsr &= cpu_mxcsr_mask;
2116 fpusetregs(td, fpstate);
2123 fpstate_drop(struct thread *td)
2126 KASSERT(PCB_USER_FPU(td->td_pcb), ("fpstate_drop: kernel-owned fpu"));
2128 if (PCPU_GET(fpcurthread) == td)
2131 * XXX force a full drop of the fpu. The above only drops it if we
2134 * XXX I don't much like fpugetuserregs()'s semantics of doing a full
2135 * drop. Dropping only to the pcb matches fnsave's behaviour.
2136 * We only need to drop to !PCB_INITDONE in sendsig(). But
2137 * sendsig() is the only caller of fpugetuserregs()... perhaps we just
2138 * have too many layers.
2140 curthread->td_pcb->pcb_flags &= ~(PCB_FPUINITDONE |
2141 PCB_USERFPUINITDONE);
2146 fill_dbregs(struct thread *td, struct dbreg *dbregs)
2151 dbregs->dr[0] = rdr0();
2152 dbregs->dr[1] = rdr1();
2153 dbregs->dr[2] = rdr2();
2154 dbregs->dr[3] = rdr3();
2155 dbregs->dr[6] = rdr6();
2156 dbregs->dr[7] = rdr7();
2159 dbregs->dr[0] = pcb->pcb_dr0;
2160 dbregs->dr[1] = pcb->pcb_dr1;
2161 dbregs->dr[2] = pcb->pcb_dr2;
2162 dbregs->dr[3] = pcb->pcb_dr3;
2163 dbregs->dr[6] = pcb->pcb_dr6;
2164 dbregs->dr[7] = pcb->pcb_dr7;
2180 set_dbregs(struct thread *td, struct dbreg *dbregs)
2186 load_dr0(dbregs->dr[0]);
2187 load_dr1(dbregs->dr[1]);
2188 load_dr2(dbregs->dr[2]);
2189 load_dr3(dbregs->dr[3]);
2190 load_dr6(dbregs->dr[6]);
2191 load_dr7(dbregs->dr[7]);
2194 * Don't let an illegal value for dr7 get set. Specifically,
2195 * check for undefined settings. Setting these bit patterns
2196 * result in undefined behaviour and can lead to an unexpected
2197 * TRCTRAP or a general protection fault right here.
2198 * Upper bits of dr6 and dr7 must not be set
2200 for (i = 0; i < 4; i++) {
2201 if (DBREG_DR7_ACCESS(dbregs->dr[7], i) == 0x02)
2203 if (td->td_frame->tf_cs == _ucode32sel &&
2204 DBREG_DR7_LEN(dbregs->dr[7], i) == DBREG_DR7_LEN_8)
2207 if ((dbregs->dr[6] & 0xffffffff00000000ul) != 0 ||
2208 (dbregs->dr[7] & 0xffffffff00000000ul) != 0)
2214 * Don't let a process set a breakpoint that is not within the
2215 * process's address space. If a process could do this, it
2216 * could halt the system by setting a breakpoint in the kernel
2217 * (if ddb was enabled). Thus, we need to check to make sure
2218 * that no breakpoints are being enabled for addresses outside
2219 * process's address space.
2221 * XXX - what about when the watched area of the user's
2222 * address space is written into from within the kernel
2223 * ... wouldn't that still cause a breakpoint to be generated
2224 * from within kernel mode?
2227 if (DBREG_DR7_ENABLED(dbregs->dr[7], 0)) {
2228 /* dr0 is enabled */
2229 if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS)
2232 if (DBREG_DR7_ENABLED(dbregs->dr[7], 1)) {
2233 /* dr1 is enabled */
2234 if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS)
2237 if (DBREG_DR7_ENABLED(dbregs->dr[7], 2)) {
2238 /* dr2 is enabled */
2239 if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS)
2242 if (DBREG_DR7_ENABLED(dbregs->dr[7], 3)) {
2243 /* dr3 is enabled */
2244 if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS)
2248 pcb->pcb_dr0 = dbregs->dr[0];
2249 pcb->pcb_dr1 = dbregs->dr[1];
2250 pcb->pcb_dr2 = dbregs->dr[2];
2251 pcb->pcb_dr3 = dbregs->dr[3];
2252 pcb->pcb_dr6 = dbregs->dr[6];
2253 pcb->pcb_dr7 = dbregs->dr[7];
2255 pcb->pcb_flags |= PCB_DBREGS;
2265 load_dr7(0); /* Turn off the control bits first */
2274 * Return > 0 if a hardware breakpoint has been hit, and the
2275 * breakpoint was in user space. Return 0, otherwise.
2278 user_dbreg_trap(void)
2280 u_int64_t dr7, dr6; /* debug registers dr6 and dr7 */
2281 u_int64_t bp; /* breakpoint bits extracted from dr6 */
2282 int nbp; /* number of breakpoints that triggered */
2283 caddr_t addr[4]; /* breakpoint addresses */
2287 if ((dr7 & 0x000000ff) == 0) {
2289 * all GE and LE bits in the dr7 register are zero,
2290 * thus the trap couldn't have been caused by the
2291 * hardware debug registers
2298 bp = dr6 & 0x0000000f;
2302 * None of the breakpoint bits are set meaning this
2303 * trap was not caused by any of the debug registers
2309 * at least one of the breakpoints were hit, check to see
2310 * which ones and if any of them are user space addresses
2314 addr[nbp++] = (caddr_t)rdr0();
2317 addr[nbp++] = (caddr_t)rdr1();
2320 addr[nbp++] = (caddr_t)rdr2();
2323 addr[nbp++] = (caddr_t)rdr3();
2326 for (i = 0; i < nbp; i++) {
2327 if (addr[i] < (caddr_t)VM_MAXUSER_ADDRESS) {
2329 * addr[i] is in user space
2336 * None of the breakpoints are in user space.
2344 * Provide inb() and outb() as functions. They are normally only available as
2345 * inline functions, thus cannot be called from the debugger.
2348 /* silence compiler warnings */
2349 u_char inb_(u_short);
2350 void outb_(u_short, u_char);
2359 outb_(u_short port, u_char data)