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