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