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