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