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