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