machdep.c revision 268471
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 268471 2014-07-09 21:39:40Z kib $");
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/efi.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/rwlock.h>
83#include <sys/sched.h>
84#include <sys/signalvar.h>
85#ifdef SMP
86#include <sys/smp.h>
87#endif
88#include <sys/syscallsubr.h>
89#include <sys/sysctl.h>
90#include <sys/sysent.h>
91#include <sys/sysproto.h>
92#include <sys/ucontext.h>
93#include <sys/vmmeter.h>
94
95#include <vm/vm.h>
96#include <vm/vm_extern.h>
97#include <vm/vm_kern.h>
98#include <vm/vm_page.h>
99#include <vm/vm_map.h>
100#include <vm/vm_object.h>
101#include <vm/vm_pager.h>
102#include <vm/vm_param.h>
103
104#ifdef DDB
105#ifndef KDB
106#error KDB must be enabled in order for DDB to work!
107#endif
108#include <ddb/ddb.h>
109#include <ddb/db_sym.h>
110#endif
111
112#include <net/netisr.h>
113
114#include <machine/clock.h>
115#include <machine/cpu.h>
116#include <machine/cputypes.h>
117#include <machine/intr_machdep.h>
118#include <x86/mca.h>
119#include <machine/md_var.h>
120#include <machine/metadata.h>
121#include <machine/mp_watchdog.h>
122#include <machine/pc/bios.h>
123#include <machine/pcb.h>
124#include <machine/proc.h>
125#include <machine/reg.h>
126#include <machine/sigframe.h>
127#include <machine/specialreg.h>
128#ifdef PERFMON
129#include <machine/perfmon.h>
130#endif
131#include <machine/tss.h>
132#ifdef SMP
133#include <machine/smp.h>
134#endif
135#ifdef FDT
136#include <x86/fdt.h>
137#endif
138
139#ifdef DEV_ATPIC
140#include <x86/isa/icu.h>
141#else
142#include <x86/apicvar.h>
143#endif
144
145#include <isa/isareg.h>
146#include <isa/rtc.h>
147#include <x86/init.h>
148
149/* Sanity check for __curthread() */
150CTASSERT(offsetof(struct pcpu, pc_curthread) == 0);
151
152extern u_int64_t hammer_time(u_int64_t, u_int64_t);
153
154extern void printcpuinfo(void);	/* XXX header file */
155extern void identify_cpu(void);
156extern void panicifcpuunsupported(void);
157
158#define	CS_SECURE(cs)		(ISPL(cs) == SEL_UPL)
159#define	EFL_SECURE(ef, oef)	((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
160
161static void cpu_startup(void *);
162static void get_fpcontext(struct thread *td, mcontext_t *mcp,
163    char *xfpusave, size_t xfpusave_len);
164static int  set_fpcontext(struct thread *td, const mcontext_t *mcp,
165    char *xfpustate, size_t xfpustate_len);
166SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
167
168/* Preload data parse function */
169static caddr_t native_parse_preload_data(u_int64_t);
170
171/* Native function to fetch and parse the e820 map */
172static void native_parse_memmap(caddr_t, vm_paddr_t *, int *);
173
174/* Default init_ops implementation. */
175struct init_ops init_ops = {
176	.parse_preload_data =	native_parse_preload_data,
177	.early_clock_source_init =	i8254_init,
178	.early_delay =			i8254_delay,
179	.parse_memmap =			native_parse_memmap,
180#ifdef SMP
181	.mp_bootaddress =		mp_bootaddress,
182	.start_all_aps =		native_start_all_aps,
183#endif
184};
185
186/*
187 * The file "conf/ldscript.amd64" defines the symbol "kernphys".  Its value is
188 * the physical address at which the kernel is loaded.
189 */
190extern char kernphys[];
191#ifdef DDB
192extern vm_offset_t ksym_start, ksym_end;
193#endif
194
195struct msgbuf *msgbufp;
196
197/* Intel ICH registers */
198#define ICH_PMBASE	0x400
199#define ICH_SMI_EN	ICH_PMBASE + 0x30
200
201int	_udatasel, _ucodesel, _ucode32sel, _ufssel, _ugssel;
202
203int cold = 1;
204
205long Maxmem = 0;
206long realmem = 0;
207
208/*
209 * The number of PHYSMAP entries must be one less than the number of
210 * PHYSSEG entries because the PHYSMAP entry that spans the largest
211 * physical address that is accessible by ISA DMA is split into two
212 * PHYSSEG entries.
213 */
214#define	PHYSMAP_SIZE	(2 * (VM_PHYSSEG_MAX - 1))
215
216vm_paddr_t phys_avail[PHYSMAP_SIZE + 2];
217vm_paddr_t dump_avail[PHYSMAP_SIZE + 2];
218
219/* must be 2 less so 0 0 can signal end of chunks */
220#define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(phys_avail[0])) - 2)
221#define DUMP_AVAIL_ARRAY_END ((sizeof(dump_avail) / sizeof(dump_avail[0])) - 2)
222
223struct kva_md_info kmi;
224
225static struct trapframe proc0_tf;
226struct region_descriptor r_gdt, r_idt;
227
228struct pcpu __pcpu[MAXCPU];
229
230struct mtx icu_lock;
231
232struct mem_range_softc mem_range_softc;
233
234struct mtx dt_lock;	/* lock for GDT and LDT */
235
236void (*vmm_resume_p)(void);
237
238static void
239cpu_startup(dummy)
240	void *dummy;
241{
242	uintmax_t memsize;
243	char *sysenv;
244
245	/*
246	 * On MacBooks, we need to disallow the legacy USB circuit to
247	 * generate an SMI# because this can cause several problems,
248	 * namely: incorrect CPU frequency detection and failure to
249	 * start the APs.
250	 * We do this by disabling a bit in the SMI_EN (SMI Control and
251	 * Enable register) of the Intel ICH LPC Interface Bridge.
252	 */
253	sysenv = getenv("smbios.system.product");
254	if (sysenv != NULL) {
255		if (strncmp(sysenv, "MacBook1,1", 10) == 0 ||
256		    strncmp(sysenv, "MacBook3,1", 10) == 0 ||
257		    strncmp(sysenv, "MacBookPro1,1", 13) == 0 ||
258		    strncmp(sysenv, "MacBookPro1,2", 13) == 0 ||
259		    strncmp(sysenv, "MacBookPro3,1", 13) == 0 ||
260		    strncmp(sysenv, "Macmini1,1", 10) == 0) {
261			if (bootverbose)
262				printf("Disabling LEGACY_USB_EN bit on "
263				    "Intel ICH.\n");
264			outl(ICH_SMI_EN, inl(ICH_SMI_EN) & ~0x8);
265		}
266		freeenv(sysenv);
267	}
268
269	/*
270	 * Good {morning,afternoon,evening,night}.
271	 */
272	startrtclock();
273	printcpuinfo();
274	panicifcpuunsupported();
275#ifdef PERFMON
276	perfmon_init();
277#endif
278
279	/*
280	 * Display physical memory if SMBIOS reports reasonable amount.
281	 */
282	memsize = 0;
283	sysenv = getenv("smbios.memory.enabled");
284	if (sysenv != NULL) {
285		memsize = (uintmax_t)strtoul(sysenv, (char **)NULL, 10) << 10;
286		freeenv(sysenv);
287	}
288	if (memsize < ptoa((uintmax_t)vm_cnt.v_free_count))
289		memsize = ptoa((uintmax_t)Maxmem);
290	printf("real memory  = %ju (%ju MB)\n", memsize, memsize >> 20);
291	realmem = atop(memsize);
292
293	/*
294	 * Display any holes after the first chunk of extended memory.
295	 */
296	if (bootverbose) {
297		int indx;
298
299		printf("Physical memory chunk(s):\n");
300		for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
301			vm_paddr_t size;
302
303			size = phys_avail[indx + 1] - phys_avail[indx];
304			printf(
305			    "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
306			    (uintmax_t)phys_avail[indx],
307			    (uintmax_t)phys_avail[indx + 1] - 1,
308			    (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
309		}
310	}
311
312	vm_ksubmap_init(&kmi);
313
314	printf("avail memory = %ju (%ju MB)\n",
315	    ptoa((uintmax_t)vm_cnt.v_free_count),
316	    ptoa((uintmax_t)vm_cnt.v_free_count) / 1048576);
317
318	/*
319	 * Set up buffers, so they can be used to read disk labels.
320	 */
321	bufinit();
322	vm_pager_bufferinit();
323
324	cpu_setregs();
325}
326
327/*
328 * Send an interrupt to process.
329 *
330 * Stack is set up to allow sigcode stored
331 * at top to call routine, followed by call
332 * to sigreturn routine below.  After sigreturn
333 * resets the signal mask, the stack, and the
334 * frame pointer, it returns to the user
335 * specified pc, psl.
336 */
337void
338sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
339{
340	struct sigframe sf, *sfp;
341	struct pcb *pcb;
342	struct proc *p;
343	struct thread *td;
344	struct sigacts *psp;
345	char *sp;
346	struct trapframe *regs;
347	char *xfpusave;
348	size_t xfpusave_len;
349	int sig;
350	int oonstack;
351
352	td = curthread;
353	pcb = td->td_pcb;
354	p = td->td_proc;
355	PROC_LOCK_ASSERT(p, MA_OWNED);
356	sig = ksi->ksi_signo;
357	psp = p->p_sigacts;
358	mtx_assert(&psp->ps_mtx, MA_OWNED);
359	regs = td->td_frame;
360	oonstack = sigonstack(regs->tf_rsp);
361
362	if (cpu_max_ext_state_size > sizeof(struct savefpu) && use_xsave) {
363		xfpusave_len = cpu_max_ext_state_size - sizeof(struct savefpu);
364		xfpusave = __builtin_alloca(xfpusave_len);
365	} else {
366		xfpusave_len = 0;
367		xfpusave = NULL;
368	}
369
370	/* Save user context. */
371	bzero(&sf, sizeof(sf));
372	sf.sf_uc.uc_sigmask = *mask;
373	sf.sf_uc.uc_stack = td->td_sigstk;
374	sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
375	    ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
376	sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
377	bcopy(regs, &sf.sf_uc.uc_mcontext.mc_rdi, sizeof(*regs));
378	sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext); /* magic */
379	get_fpcontext(td, &sf.sf_uc.uc_mcontext, xfpusave, xfpusave_len);
380	fpstate_drop(td);
381	sf.sf_uc.uc_mcontext.mc_fsbase = pcb->pcb_fsbase;
382	sf.sf_uc.uc_mcontext.mc_gsbase = pcb->pcb_gsbase;
383	bzero(sf.sf_uc.uc_mcontext.mc_spare,
384	    sizeof(sf.sf_uc.uc_mcontext.mc_spare));
385	bzero(sf.sf_uc.__spare__, sizeof(sf.sf_uc.__spare__));
386
387	/* Allocate space for the signal handler context. */
388	if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
389	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
390		sp = td->td_sigstk.ss_sp + td->td_sigstk.ss_size;
391#if defined(COMPAT_43)
392		td->td_sigstk.ss_flags |= SS_ONSTACK;
393#endif
394	} else
395		sp = (char *)regs->tf_rsp - 128;
396	if (xfpusave != NULL) {
397		sp -= xfpusave_len;
398		sp = (char *)((unsigned long)sp & ~0x3Ful);
399		sf.sf_uc.uc_mcontext.mc_xfpustate = (register_t)sp;
400	}
401	sp -= sizeof(struct sigframe);
402	/* Align to 16 bytes. */
403	sfp = (struct sigframe *)((unsigned long)sp & ~0xFul);
404
405	/* Translate the signal if appropriate. */
406	if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
407		sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
408
409	/* Build the argument list for the signal handler. */
410	regs->tf_rdi = sig;			/* arg 1 in %rdi */
411	regs->tf_rdx = (register_t)&sfp->sf_uc;	/* arg 3 in %rdx */
412	bzero(&sf.sf_si, sizeof(sf.sf_si));
413	if (SIGISMEMBER(psp->ps_siginfo, sig)) {
414		/* Signal handler installed with SA_SIGINFO. */
415		regs->tf_rsi = (register_t)&sfp->sf_si;	/* arg 2 in %rsi */
416		sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
417
418		/* Fill in POSIX parts */
419		sf.sf_si = ksi->ksi_info;
420		sf.sf_si.si_signo = sig; /* maybe a translated signal */
421		regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
422	} else {
423		/* Old FreeBSD-style arguments. */
424		regs->tf_rsi = ksi->ksi_code;	/* arg 2 in %rsi */
425		regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
426		sf.sf_ahu.sf_handler = catcher;
427	}
428	mtx_unlock(&psp->ps_mtx);
429	PROC_UNLOCK(p);
430
431	/*
432	 * Copy the sigframe out to the user's stack.
433	 */
434	if (copyout(&sf, sfp, sizeof(*sfp)) != 0 ||
435	    (xfpusave != NULL && copyout(xfpusave,
436	    (void *)sf.sf_uc.uc_mcontext.mc_xfpustate, xfpusave_len)
437	    != 0)) {
438#ifdef DEBUG
439		printf("process %ld has trashed its stack\n", (long)p->p_pid);
440#endif
441		PROC_LOCK(p);
442		sigexit(td, SIGILL);
443	}
444
445	regs->tf_rsp = (long)sfp;
446	regs->tf_rip = p->p_sysent->sv_sigcode_base;
447	regs->tf_rflags &= ~(PSL_T | PSL_D);
448	regs->tf_cs = _ucodesel;
449	regs->tf_ds = _udatasel;
450	regs->tf_es = _udatasel;
451	regs->tf_fs = _ufssel;
452	regs->tf_gs = _ugssel;
453	regs->tf_flags = TF_HASSEGS;
454	set_pcb_flags(pcb, PCB_FULL_IRET);
455	PROC_LOCK(p);
456	mtx_lock(&psp->ps_mtx);
457}
458
459/*
460 * System call to cleanup state after a signal
461 * has been taken.  Reset signal mask and
462 * stack state from context left by sendsig (above).
463 * Return to previous pc and psl as specified by
464 * context left by sendsig. Check carefully to
465 * make sure that the user has not modified the
466 * state to gain improper privileges.
467 *
468 * MPSAFE
469 */
470int
471sys_sigreturn(td, uap)
472	struct thread *td;
473	struct sigreturn_args /* {
474		const struct __ucontext *sigcntxp;
475	} */ *uap;
476{
477	ucontext_t uc;
478	struct pcb *pcb;
479	struct proc *p;
480	struct trapframe *regs;
481	ucontext_t *ucp;
482	char *xfpustate;
483	size_t xfpustate_len;
484	long rflags;
485	int cs, error, ret;
486	ksiginfo_t ksi;
487
488	pcb = td->td_pcb;
489	p = td->td_proc;
490
491	error = copyin(uap->sigcntxp, &uc, sizeof(uc));
492	if (error != 0) {
493		uprintf("pid %d (%s): sigreturn copyin failed\n",
494		    p->p_pid, td->td_name);
495		return (error);
496	}
497	ucp = &uc;
498	if ((ucp->uc_mcontext.mc_flags & ~_MC_FLAG_MASK) != 0) {
499		uprintf("pid %d (%s): sigreturn mc_flags %x\n", p->p_pid,
500		    td->td_name, ucp->uc_mcontext.mc_flags);
501		return (EINVAL);
502	}
503	regs = td->td_frame;
504	rflags = ucp->uc_mcontext.mc_rflags;
505	/*
506	 * Don't allow users to change privileged or reserved flags.
507	 */
508	if (!EFL_SECURE(rflags, regs->tf_rflags)) {
509		uprintf("pid %d (%s): sigreturn rflags = 0x%lx\n", p->p_pid,
510		    td->td_name, rflags);
511		return (EINVAL);
512	}
513
514	/*
515	 * Don't allow users to load a valid privileged %cs.  Let the
516	 * hardware check for invalid selectors, excess privilege in
517	 * other selectors, invalid %eip's and invalid %esp's.
518	 */
519	cs = ucp->uc_mcontext.mc_cs;
520	if (!CS_SECURE(cs)) {
521		uprintf("pid %d (%s): sigreturn cs = 0x%x\n", p->p_pid,
522		    td->td_name, cs);
523		ksiginfo_init_trap(&ksi);
524		ksi.ksi_signo = SIGBUS;
525		ksi.ksi_code = BUS_OBJERR;
526		ksi.ksi_trapno = T_PROTFLT;
527		ksi.ksi_addr = (void *)regs->tf_rip;
528		trapsignal(td, &ksi);
529		return (EINVAL);
530	}
531
532	if ((uc.uc_mcontext.mc_flags & _MC_HASFPXSTATE) != 0) {
533		xfpustate_len = uc.uc_mcontext.mc_xfpustate_len;
534		if (xfpustate_len > cpu_max_ext_state_size -
535		    sizeof(struct savefpu)) {
536			uprintf("pid %d (%s): sigreturn xfpusave_len = 0x%zx\n",
537			    p->p_pid, td->td_name, xfpustate_len);
538			return (EINVAL);
539		}
540		xfpustate = __builtin_alloca(xfpustate_len);
541		error = copyin((const void *)uc.uc_mcontext.mc_xfpustate,
542		    xfpustate, xfpustate_len);
543		if (error != 0) {
544			uprintf(
545	"pid %d (%s): sigreturn copying xfpustate failed\n",
546			    p->p_pid, td->td_name);
547			return (error);
548		}
549	} else {
550		xfpustate = NULL;
551		xfpustate_len = 0;
552	}
553	ret = set_fpcontext(td, &ucp->uc_mcontext, xfpustate, xfpustate_len);
554	if (ret != 0) {
555		uprintf("pid %d (%s): sigreturn set_fpcontext err %d\n",
556		    p->p_pid, td->td_name, ret);
557		return (ret);
558	}
559	bcopy(&ucp->uc_mcontext.mc_rdi, regs, sizeof(*regs));
560	pcb->pcb_fsbase = ucp->uc_mcontext.mc_fsbase;
561	pcb->pcb_gsbase = ucp->uc_mcontext.mc_gsbase;
562
563#if defined(COMPAT_43)
564	if (ucp->uc_mcontext.mc_onstack & 1)
565		td->td_sigstk.ss_flags |= SS_ONSTACK;
566	else
567		td->td_sigstk.ss_flags &= ~SS_ONSTACK;
568#endif
569
570	kern_sigprocmask(td, SIG_SETMASK, &ucp->uc_sigmask, NULL, 0);
571	set_pcb_flags(pcb, PCB_FULL_IRET);
572	return (EJUSTRETURN);
573}
574
575#ifdef COMPAT_FREEBSD4
576int
577freebsd4_sigreturn(struct thread *td, struct freebsd4_sigreturn_args *uap)
578{
579
580	return sys_sigreturn(td, (struct sigreturn_args *)uap);
581}
582#endif
583
584
585/*
586 * Machine dependent boot() routine
587 *
588 * I haven't seen anything to put here yet
589 * Possibly some stuff might be grafted back here from boot()
590 */
591void
592cpu_boot(int howto)
593{
594}
595
596/*
597 * Flush the D-cache for non-DMA I/O so that the I-cache can
598 * be made coherent later.
599 */
600void
601cpu_flush_dcache(void *ptr, size_t len)
602{
603	/* Not applicable */
604}
605
606/* Get current clock frequency for the given cpu id. */
607int
608cpu_est_clockrate(int cpu_id, uint64_t *rate)
609{
610	uint64_t tsc1, tsc2;
611	uint64_t acnt, mcnt, perf;
612	register_t reg;
613
614	if (pcpu_find(cpu_id) == NULL || rate == NULL)
615		return (EINVAL);
616
617	/*
618	 * If TSC is P-state invariant and APERF/MPERF MSRs do not exist,
619	 * DELAY(9) based logic fails.
620	 */
621	if (tsc_is_invariant && !tsc_perf_stat)
622		return (EOPNOTSUPP);
623
624#ifdef SMP
625	if (smp_cpus > 1) {
626		/* Schedule ourselves on the indicated cpu. */
627		thread_lock(curthread);
628		sched_bind(curthread, cpu_id);
629		thread_unlock(curthread);
630	}
631#endif
632
633	/* Calibrate by measuring a short delay. */
634	reg = intr_disable();
635	if (tsc_is_invariant) {
636		wrmsr(MSR_MPERF, 0);
637		wrmsr(MSR_APERF, 0);
638		tsc1 = rdtsc();
639		DELAY(1000);
640		mcnt = rdmsr(MSR_MPERF);
641		acnt = rdmsr(MSR_APERF);
642		tsc2 = rdtsc();
643		intr_restore(reg);
644		perf = 1000 * acnt / mcnt;
645		*rate = (tsc2 - tsc1) * perf;
646	} else {
647		tsc1 = rdtsc();
648		DELAY(1000);
649		tsc2 = rdtsc();
650		intr_restore(reg);
651		*rate = (tsc2 - tsc1) * 1000;
652	}
653
654#ifdef SMP
655	if (smp_cpus > 1) {
656		thread_lock(curthread);
657		sched_unbind(curthread);
658		thread_unlock(curthread);
659	}
660#endif
661
662	return (0);
663}
664
665/*
666 * Shutdown the CPU as much as possible
667 */
668void
669cpu_halt(void)
670{
671	for (;;)
672		halt();
673}
674
675void (*cpu_idle_hook)(sbintime_t) = NULL;	/* ACPI idle hook. */
676static int	cpu_ident_amdc1e = 0;	/* AMD C1E supported. */
677static int	idle_mwait = 1;		/* Use MONITOR/MWAIT for short idle. */
678SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RWTUN, &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) + IOPERM_BITMAP_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
1434#define efi_next_descriptor(ptr, size) \
1435	((struct efi_md *)(((uint8_t *) ptr) + size))
1436
1437static void
1438add_efi_map_entries(struct efi_map_header *efihdr, vm_paddr_t *physmap,
1439    int *physmap_idx)
1440{
1441	struct efi_md *map, *p;
1442	const char *type;
1443	size_t efisz;
1444	int ndesc, i;
1445
1446	static const char *types[] = {
1447		"Reserved",
1448		"LoaderCode",
1449		"LoaderData",
1450		"BootServicesCode",
1451		"BootServicesData",
1452		"RuntimeServicesCode",
1453		"RuntimeServicesData",
1454		"ConventionalMemory",
1455		"UnusableMemory",
1456		"ACPIReclaimMemory",
1457		"ACPIMemoryNVS",
1458		"MemoryMappedIO",
1459		"MemoryMappedIOPortSpace",
1460		"PalCode"
1461	};
1462
1463	/*
1464	 * Memory map data provided by UEFI via the GetMemoryMap
1465	 * Boot Services API.
1466	 */
1467	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
1468	map = (struct efi_md *)((uint8_t *)efihdr + efisz);
1469
1470	if (efihdr->descriptor_size == 0)
1471		return;
1472	ndesc = efihdr->memory_size / efihdr->descriptor_size;
1473
1474	if (boothowto & RB_VERBOSE)
1475		printf("%23s %12s %12s %8s %4s\n",
1476		    "Type", "Physical", "Virtual", "#Pages", "Attr");
1477
1478	for (i = 0, p = map; i < ndesc; i++,
1479	    p = efi_next_descriptor(p, efihdr->descriptor_size)) {
1480		if (boothowto & RB_VERBOSE) {
1481			if (p->md_type <= EFI_MD_TYPE_PALCODE)
1482				type = types[p->md_type];
1483			else
1484				type = "<INVALID>";
1485			printf("%23s %012lx %12p %08lx ", type, p->md_phys,
1486			    p->md_virt, p->md_pages);
1487			if (p->md_attr & EFI_MD_ATTR_UC)
1488				printf("UC ");
1489			if (p->md_attr & EFI_MD_ATTR_WC)
1490				printf("WC ");
1491			if (p->md_attr & EFI_MD_ATTR_WT)
1492				printf("WT ");
1493			if (p->md_attr & EFI_MD_ATTR_WB)
1494				printf("WB ");
1495			if (p->md_attr & EFI_MD_ATTR_UCE)
1496				printf("UCE ");
1497			if (p->md_attr & EFI_MD_ATTR_WP)
1498				printf("WP ");
1499			if (p->md_attr & EFI_MD_ATTR_RP)
1500				printf("RP ");
1501			if (p->md_attr & EFI_MD_ATTR_XP)
1502				printf("XP ");
1503			if (p->md_attr & EFI_MD_ATTR_RT)
1504				printf("RUNTIME");
1505			printf("\n");
1506		}
1507
1508		switch (p->md_type) {
1509		case EFI_MD_TYPE_CODE:
1510		case EFI_MD_TYPE_DATA:
1511		case EFI_MD_TYPE_BS_CODE:
1512		case EFI_MD_TYPE_BS_DATA:
1513		case EFI_MD_TYPE_FREE:
1514			/*
1515			 * We're allowed to use any entry with these types.
1516			 */
1517			break;
1518		default:
1519			continue;
1520		}
1521
1522		if (!add_physmap_entry(p->md_phys, (p->md_pages * PAGE_SIZE),
1523		    physmap, physmap_idx))
1524			break;
1525	}
1526}
1527
1528static char bootmethod[16] = "";
1529SYSCTL_STRING(_machdep, OID_AUTO, bootmethod, CTLFLAG_RD, bootmethod, 0,
1530    "System firmware boot method");
1531
1532static void
1533native_parse_memmap(caddr_t kmdp, vm_paddr_t *physmap, int *physmap_idx)
1534{
1535	struct bios_smap *smap;
1536	struct efi_map_header *efihdr;
1537	u_int32_t size;
1538
1539	/*
1540	 * Memory map from INT 15:E820.
1541	 *
1542	 * subr_module.c says:
1543	 * "Consumer may safely assume that size value precedes data."
1544	 * ie: an int32_t immediately precedes smap.
1545	 */
1546
1547	efihdr = (struct efi_map_header *)preload_search_info(kmdp,
1548	    MODINFO_METADATA | MODINFOMD_EFI_MAP);
1549	smap = (struct bios_smap *)preload_search_info(kmdp,
1550	    MODINFO_METADATA | MODINFOMD_SMAP);
1551	if (efihdr == NULL && smap == NULL)
1552		panic("No BIOS smap or EFI map info from loader!");
1553
1554	if (efihdr != NULL) {
1555		add_efi_map_entries(efihdr, physmap, physmap_idx);
1556		strlcpy(bootmethod, "UEFI", sizeof(bootmethod));
1557	} else {
1558		size = *((u_int32_t *)smap - 1);
1559		bios_add_smap_entries(smap, size, physmap, physmap_idx);
1560		strlcpy(bootmethod, "BIOS", sizeof(bootmethod));
1561	}
1562}
1563
1564/*
1565 * Populate the (physmap) array with base/bound pairs describing the
1566 * available physical memory in the system, then test this memory and
1567 * build the phys_avail array describing the actually-available memory.
1568 *
1569 * Total memory size may be set by the kernel environment variable
1570 * hw.physmem or the compile-time define MAXMEM.
1571 *
1572 * XXX first should be vm_paddr_t.
1573 */
1574static void
1575getmemsize(caddr_t kmdp, u_int64_t first)
1576{
1577	int i, physmap_idx, pa_indx, da_indx;
1578	vm_paddr_t pa, physmap[PHYSMAP_SIZE];
1579	u_long physmem_start, physmem_tunable, memtest;
1580	pt_entry_t *pte;
1581	quad_t dcons_addr, dcons_size;
1582
1583	bzero(physmap, sizeof(physmap));
1584	basemem = 0;
1585	physmap_idx = 0;
1586
1587	init_ops.parse_memmap(kmdp, physmap, &physmap_idx);
1588
1589	/*
1590	 * Find the 'base memory' segment for SMP
1591	 */
1592	basemem = 0;
1593	for (i = 0; i <= physmap_idx; i += 2) {
1594		if (physmap[i] == 0x00000000) {
1595			basemem = physmap[i + 1] / 1024;
1596			break;
1597		}
1598	}
1599	if (basemem == 0)
1600		panic("BIOS smap did not include a basemem segment!");
1601
1602	/*
1603	 * Make hole for "AP -> long mode" bootstrap code.  The
1604	 * mp_bootaddress vector is only available when the kernel
1605	 * is configured to support APs and APs for the system start
1606	 * in 32bit mode (e.g. SMP bare metal).
1607	 */
1608	if (init_ops.mp_bootaddress)
1609		physmap[1] = init_ops.mp_bootaddress(physmap[1] / 1024);
1610
1611	/*
1612	 * Maxmem isn't the "maximum memory", it's one larger than the
1613	 * highest page of the physical address space.  It should be
1614	 * called something like "Maxphyspage".  We may adjust this
1615	 * based on ``hw.physmem'' and the results of the memory test.
1616	 */
1617	Maxmem = atop(physmap[physmap_idx + 1]);
1618
1619#ifdef MAXMEM
1620	Maxmem = MAXMEM / 4;
1621#endif
1622
1623	if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
1624		Maxmem = atop(physmem_tunable);
1625
1626	/*
1627	 * The boot memory test is disabled by default, as it takes a
1628	 * significant amount of time on large-memory systems, and is
1629	 * unfriendly to virtual machines as it unnecessarily touches all
1630	 * pages.
1631	 *
1632	 * A general name is used as the code may be extended to support
1633	 * additional tests beyond the current "page present" test.
1634	 */
1635	memtest = 0;
1636	TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
1637
1638	/*
1639	 * Don't allow MAXMEM or hw.physmem to extend the amount of memory
1640	 * in the system.
1641	 */
1642	if (Maxmem > atop(physmap[physmap_idx + 1]))
1643		Maxmem = atop(physmap[physmap_idx + 1]);
1644
1645	if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1646	    (boothowto & RB_VERBOSE))
1647		printf("Physical memory use set to %ldK\n", Maxmem * 4);
1648
1649	/* call pmap initialization to make new kernel address space */
1650	pmap_bootstrap(&first);
1651
1652	/*
1653	 * Size up each available chunk of physical memory.
1654	 *
1655	 * XXX Some BIOSes corrupt low 64KB between suspend and resume.
1656	 * By default, mask off the first 16 pages unless we appear to be
1657	 * running in a VM.
1658	 */
1659	physmem_start = (vm_guest > VM_GUEST_NO ? 1 : 16) << PAGE_SHIFT;
1660	TUNABLE_ULONG_FETCH("hw.physmem.start", &physmem_start);
1661	if (physmem_start < PAGE_SIZE)
1662		physmap[0] = PAGE_SIZE;
1663	else if (physmem_start >= physmap[1])
1664		physmap[0] = round_page(physmap[1] - PAGE_SIZE);
1665	else
1666		physmap[0] = round_page(physmem_start);
1667	pa_indx = 0;
1668	da_indx = 1;
1669	phys_avail[pa_indx++] = physmap[0];
1670	phys_avail[pa_indx] = physmap[0];
1671	dump_avail[da_indx] = physmap[0];
1672	pte = CMAP1;
1673
1674	/*
1675	 * Get dcons buffer address
1676	 */
1677	if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
1678	    getenv_quad("dcons.size", &dcons_size) == 0)
1679		dcons_addr = 0;
1680
1681	/*
1682	 * physmap is in bytes, so when converting to page boundaries,
1683	 * round up the start address and round down the end address.
1684	 */
1685	for (i = 0; i <= physmap_idx; i += 2) {
1686		vm_paddr_t end;
1687
1688		end = ptoa((vm_paddr_t)Maxmem);
1689		if (physmap[i + 1] < end)
1690			end = trunc_page(physmap[i + 1]);
1691		for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1692			int tmp, page_bad, full;
1693			int *ptr = (int *)CADDR1;
1694
1695			full = FALSE;
1696			/*
1697			 * block out kernel memory as not available.
1698			 */
1699			if (pa >= (vm_paddr_t)kernphys && pa < first)
1700				goto do_dump_avail;
1701
1702			/*
1703			 * block out dcons buffer
1704			 */
1705			if (dcons_addr > 0
1706			    && pa >= trunc_page(dcons_addr)
1707			    && pa < dcons_addr + dcons_size)
1708				goto do_dump_avail;
1709
1710			page_bad = FALSE;
1711			if (memtest == 0)
1712				goto skip_memtest;
1713
1714			/*
1715			 * map page into kernel: valid, read/write,non-cacheable
1716			 */
1717			*pte = pa | PG_V | PG_RW | PG_NC_PWT | PG_NC_PCD;
1718			invltlb();
1719
1720			tmp = *(int *)ptr;
1721			/*
1722			 * Test for alternating 1's and 0's
1723			 */
1724			*(volatile int *)ptr = 0xaaaaaaaa;
1725			if (*(volatile int *)ptr != 0xaaaaaaaa)
1726				page_bad = TRUE;
1727			/*
1728			 * Test for alternating 0's and 1's
1729			 */
1730			*(volatile int *)ptr = 0x55555555;
1731			if (*(volatile int *)ptr != 0x55555555)
1732				page_bad = TRUE;
1733			/*
1734			 * Test for all 1's
1735			 */
1736			*(volatile int *)ptr = 0xffffffff;
1737			if (*(volatile int *)ptr != 0xffffffff)
1738				page_bad = TRUE;
1739			/*
1740			 * Test for all 0's
1741			 */
1742			*(volatile int *)ptr = 0x0;
1743			if (*(volatile int *)ptr != 0x0)
1744				page_bad = TRUE;
1745			/*
1746			 * Restore original value.
1747			 */
1748			*(int *)ptr = tmp;
1749
1750skip_memtest:
1751			/*
1752			 * Adjust array of valid/good pages.
1753			 */
1754			if (page_bad == TRUE)
1755				continue;
1756			/*
1757			 * If this good page is a continuation of the
1758			 * previous set of good pages, then just increase
1759			 * the end pointer. Otherwise start a new chunk.
1760			 * Note that "end" points one higher than end,
1761			 * making the range >= start and < end.
1762			 * If we're also doing a speculative memory
1763			 * test and we at or past the end, bump up Maxmem
1764			 * so that we keep going. The first bad page
1765			 * will terminate the loop.
1766			 */
1767			if (phys_avail[pa_indx] == pa) {
1768				phys_avail[pa_indx] += PAGE_SIZE;
1769			} else {
1770				pa_indx++;
1771				if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1772					printf(
1773		"Too many holes in the physical address space, giving up\n");
1774					pa_indx--;
1775					full = TRUE;
1776					goto do_dump_avail;
1777				}
1778				phys_avail[pa_indx++] = pa;	/* start */
1779				phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
1780			}
1781			physmem++;
1782do_dump_avail:
1783			if (dump_avail[da_indx] == pa) {
1784				dump_avail[da_indx] += PAGE_SIZE;
1785			} else {
1786				da_indx++;
1787				if (da_indx == DUMP_AVAIL_ARRAY_END) {
1788					da_indx--;
1789					goto do_next;
1790				}
1791				dump_avail[da_indx++] = pa; /* start */
1792				dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
1793			}
1794do_next:
1795			if (full)
1796				break;
1797		}
1798	}
1799	*pte = 0;
1800	invltlb();
1801
1802	/*
1803	 * XXX
1804	 * The last chunk must contain at least one page plus the message
1805	 * buffer to avoid complicating other code (message buffer address
1806	 * calculation, etc.).
1807	 */
1808	while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1809	    round_page(msgbufsize) >= phys_avail[pa_indx]) {
1810		physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1811		phys_avail[pa_indx--] = 0;
1812		phys_avail[pa_indx--] = 0;
1813	}
1814
1815	Maxmem = atop(phys_avail[pa_indx]);
1816
1817	/* Trim off space for the message buffer. */
1818	phys_avail[pa_indx] -= round_page(msgbufsize);
1819
1820	/* Map the message buffer. */
1821	msgbufp = (struct msgbuf *)PHYS_TO_DMAP(phys_avail[pa_indx]);
1822}
1823
1824static caddr_t
1825native_parse_preload_data(u_int64_t modulep)
1826{
1827	caddr_t kmdp;
1828
1829	preload_metadata = (caddr_t)(uintptr_t)(modulep + KERNBASE);
1830	preload_bootstrap_relocate(KERNBASE);
1831	kmdp = preload_search_by_type("elf kernel");
1832	if (kmdp == NULL)
1833		kmdp = preload_search_by_type("elf64 kernel");
1834	boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
1835	kern_envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *) + KERNBASE;
1836#ifdef DDB
1837	ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
1838	ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
1839#endif
1840
1841	return (kmdp);
1842}
1843
1844u_int64_t
1845hammer_time(u_int64_t modulep, u_int64_t physfree)
1846{
1847	caddr_t kmdp;
1848	int gsel_tss, x;
1849	struct pcpu *pc;
1850	struct nmi_pcpu *np;
1851	struct xstate_hdr *xhdr;
1852	u_int64_t msr;
1853	char *env;
1854	size_t kstack0_sz;
1855
1856	thread0.td_kstack = physfree + KERNBASE;
1857	thread0.td_kstack_pages = KSTACK_PAGES;
1858	kstack0_sz = thread0.td_kstack_pages * PAGE_SIZE;
1859	bzero((void *)thread0.td_kstack, kstack0_sz);
1860	physfree += kstack0_sz;
1861
1862	/*
1863 	 * This may be done better later if it gets more high level
1864 	 * components in it. If so just link td->td_proc here.
1865	 */
1866	proc_linkup0(&proc0, &thread0);
1867
1868	kmdp = init_ops.parse_preload_data(modulep);
1869
1870	/* Init basic tunables, hz etc */
1871	init_param1();
1872
1873	/*
1874	 * make gdt memory segments
1875	 */
1876	for (x = 0; x < NGDT; x++) {
1877		if (x != GPROC0_SEL && x != (GPROC0_SEL + 1) &&
1878		    x != GUSERLDT_SEL && x != (GUSERLDT_SEL) + 1)
1879			ssdtosd(&gdt_segs[x], &gdt[x]);
1880	}
1881	gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&common_tss[0];
1882	ssdtosyssd(&gdt_segs[GPROC0_SEL],
1883	    (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1884
1885	r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1886	r_gdt.rd_base =  (long) gdt;
1887	lgdt(&r_gdt);
1888	pc = &__pcpu[0];
1889
1890	wrmsr(MSR_FSBASE, 0);		/* User value */
1891	wrmsr(MSR_GSBASE, (u_int64_t)pc);
1892	wrmsr(MSR_KGSBASE, 0);		/* User value while in the kernel */
1893
1894	pcpu_init(pc, 0, sizeof(struct pcpu));
1895	dpcpu_init((void *)(physfree + KERNBASE), 0);
1896	physfree += DPCPU_SIZE;
1897	PCPU_SET(prvspace, pc);
1898	PCPU_SET(curthread, &thread0);
1899	PCPU_SET(tssp, &common_tss[0]);
1900	PCPU_SET(commontssp, &common_tss[0]);
1901	PCPU_SET(tss, (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1902	PCPU_SET(ldt, (struct system_segment_descriptor *)&gdt[GUSERLDT_SEL]);
1903	PCPU_SET(fs32p, &gdt[GUFS32_SEL]);
1904	PCPU_SET(gs32p, &gdt[GUGS32_SEL]);
1905
1906	/*
1907	 * Initialize mutexes.
1908	 *
1909	 * icu_lock: in order to allow an interrupt to occur in a critical
1910	 * 	     section, to set pcpu->ipending (etc...) properly, we
1911	 *	     must be able to get the icu lock, so it can't be
1912	 *	     under witness.
1913	 */
1914	mutex_init();
1915	mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS);
1916	mtx_init(&dt_lock, "descriptor tables", NULL, MTX_DEF);
1917
1918	/* exceptions */
1919	for (x = 0; x < NIDT; x++)
1920		setidt(x, &IDTVEC(rsvd), SDT_SYSIGT, SEL_KPL, 0);
1921	setidt(IDT_DE, &IDTVEC(div),  SDT_SYSIGT, SEL_KPL, 0);
1922	setidt(IDT_DB, &IDTVEC(dbg),  SDT_SYSIGT, SEL_KPL, 0);
1923	setidt(IDT_NMI, &IDTVEC(nmi),  SDT_SYSIGT, SEL_KPL, 2);
1924 	setidt(IDT_BP, &IDTVEC(bpt),  SDT_SYSIGT, SEL_UPL, 0);
1925	setidt(IDT_OF, &IDTVEC(ofl),  SDT_SYSIGT, SEL_KPL, 0);
1926	setidt(IDT_BR, &IDTVEC(bnd),  SDT_SYSIGT, SEL_KPL, 0);
1927	setidt(IDT_UD, &IDTVEC(ill),  SDT_SYSIGT, SEL_KPL, 0);
1928	setidt(IDT_NM, &IDTVEC(dna),  SDT_SYSIGT, SEL_KPL, 0);
1929	setidt(IDT_DF, &IDTVEC(dblfault), SDT_SYSIGT, SEL_KPL, 1);
1930	setidt(IDT_FPUGP, &IDTVEC(fpusegm),  SDT_SYSIGT, SEL_KPL, 0);
1931	setidt(IDT_TS, &IDTVEC(tss),  SDT_SYSIGT, SEL_KPL, 0);
1932	setidt(IDT_NP, &IDTVEC(missing),  SDT_SYSIGT, SEL_KPL, 0);
1933	setidt(IDT_SS, &IDTVEC(stk),  SDT_SYSIGT, SEL_KPL, 0);
1934	setidt(IDT_GP, &IDTVEC(prot),  SDT_SYSIGT, SEL_KPL, 0);
1935	setidt(IDT_PF, &IDTVEC(page),  SDT_SYSIGT, SEL_KPL, 0);
1936	setidt(IDT_MF, &IDTVEC(fpu),  SDT_SYSIGT, SEL_KPL, 0);
1937	setidt(IDT_AC, &IDTVEC(align), SDT_SYSIGT, SEL_KPL, 0);
1938	setidt(IDT_MC, &IDTVEC(mchk),  SDT_SYSIGT, SEL_KPL, 0);
1939	setidt(IDT_XF, &IDTVEC(xmm), SDT_SYSIGT, SEL_KPL, 0);
1940#ifdef KDTRACE_HOOKS
1941	setidt(IDT_DTRACE_RET, &IDTVEC(dtrace_ret), SDT_SYSIGT, SEL_UPL, 0);
1942#endif
1943#ifdef XENHVM
1944	setidt(IDT_EVTCHN, &IDTVEC(xen_intr_upcall), SDT_SYSIGT, SEL_UPL, 0);
1945#endif
1946
1947	r_idt.rd_limit = sizeof(idt0) - 1;
1948	r_idt.rd_base = (long) idt;
1949	lidt(&r_idt);
1950
1951	/*
1952	 * Initialize the clock before the console so that console
1953	 * initialization can use DELAY().
1954	 */
1955	clock_init();
1956
1957	/*
1958	 * Use vt(4) by default for UEFI boot (during the sc(4)/vt(4)
1959	 * transition).
1960	 */
1961	if (preload_search_info(kmdp, MODINFO_METADATA | MODINFOMD_EFI_MAP) !=
1962	    NULL)
1963		vty_set_preferred(VTY_VT);
1964
1965	/*
1966	 * Initialize the console before we print anything out.
1967	 */
1968	cninit();
1969
1970#ifdef DEV_ISA
1971#ifdef DEV_ATPIC
1972	elcr_probe();
1973	atpic_startup();
1974#else
1975	/* Reset and mask the atpics and leave them shut down. */
1976	atpic_reset();
1977
1978	/*
1979	 * Point the ICU spurious interrupt vectors at the APIC spurious
1980	 * interrupt handler.
1981	 */
1982	setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1983	setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1984#endif
1985#else
1986#error "have you forgotten the isa device?";
1987#endif
1988
1989	kdb_init();
1990
1991#ifdef KDB
1992	if (boothowto & RB_KDB)
1993		kdb_enter(KDB_WHY_BOOTFLAGS,
1994		    "Boot flags requested debugger");
1995#endif
1996
1997	identify_cpu();		/* Final stage of CPU initialization */
1998	initializecpu();	/* Initialize CPU registers */
1999	initializecpucache();
2000
2001	/* doublefault stack space, runs on ist1 */
2002	common_tss[0].tss_ist1 = (long)&dblfault_stack[sizeof(dblfault_stack)];
2003
2004	/*
2005	 * NMI stack, runs on ist2.  The pcpu pointer is stored just
2006	 * above the start of the ist2 stack.
2007	 */
2008	np = ((struct nmi_pcpu *) &nmi0_stack[sizeof(nmi0_stack)]) - 1;
2009	np->np_pcpu = (register_t) pc;
2010	common_tss[0].tss_ist2 = (long) np;
2011
2012	/* Set the IO permission bitmap (empty due to tss seg limit) */
2013	common_tss[0].tss_iobase = sizeof(struct amd64tss) + IOPERM_BITMAP_SIZE;
2014
2015	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
2016	ltr(gsel_tss);
2017
2018	/* Set up the fast syscall stuff */
2019	msr = rdmsr(MSR_EFER) | EFER_SCE;
2020	wrmsr(MSR_EFER, msr);
2021	wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
2022	wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
2023	msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
2024	      ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
2025	wrmsr(MSR_STAR, msr);
2026	wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
2027
2028	getmemsize(kmdp, physfree);
2029	init_param2(physmem);
2030
2031	/* now running on new page tables, configured,and u/iom is accessible */
2032
2033	msgbufinit(msgbufp, msgbufsize);
2034	fpuinit();
2035
2036	/*
2037	 * Set up thread0 pcb after fpuinit calculated pcb + fpu save
2038	 * area size.  Zero out the extended state header in fpu save
2039	 * area.
2040	 */
2041	thread0.td_pcb = get_pcb_td(&thread0);
2042	bzero(get_pcb_user_save_td(&thread0), cpu_max_ext_state_size);
2043	if (use_xsave) {
2044		xhdr = (struct xstate_hdr *)(get_pcb_user_save_td(&thread0) +
2045		    1);
2046		xhdr->xstate_bv = xsave_mask;
2047	}
2048	/* make an initial tss so cpu can get interrupt stack on syscall! */
2049	common_tss[0].tss_rsp0 = (vm_offset_t)thread0.td_pcb;
2050	/* Ensure the stack is aligned to 16 bytes */
2051	common_tss[0].tss_rsp0 &= ~0xFul;
2052	PCPU_SET(rsp0, common_tss[0].tss_rsp0);
2053	PCPU_SET(curpcb, thread0.td_pcb);
2054
2055	/* transfer to user mode */
2056
2057	_ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
2058	_udatasel = GSEL(GUDATA_SEL, SEL_UPL);
2059	_ucode32sel = GSEL(GUCODE32_SEL, SEL_UPL);
2060	_ufssel = GSEL(GUFS32_SEL, SEL_UPL);
2061	_ugssel = GSEL(GUGS32_SEL, SEL_UPL);
2062
2063	load_ds(_udatasel);
2064	load_es(_udatasel);
2065	load_fs(_ufssel);
2066
2067	/* setup proc 0's pcb */
2068	thread0.td_pcb->pcb_flags = 0;
2069	thread0.td_pcb->pcb_cr3 = KPML4phys; /* PCID 0 is reserved for kernel */
2070	thread0.td_frame = &proc0_tf;
2071
2072        env = getenv("kernelname");
2073	if (env != NULL)
2074		strlcpy(kernelname, env, sizeof(kernelname));
2075
2076	cpu_probe_amdc1e();
2077
2078#ifdef FDT
2079	x86_init_fdt();
2080#endif
2081
2082	/* Location of kernel stack for locore */
2083	return ((u_int64_t)thread0.td_pcb);
2084}
2085
2086void
2087cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
2088{
2089
2090	pcpu->pc_acpi_id = 0xffffffff;
2091}
2092
2093void
2094spinlock_enter(void)
2095{
2096	struct thread *td;
2097	register_t flags;
2098
2099	td = curthread;
2100	if (td->td_md.md_spinlock_count == 0) {
2101		flags = intr_disable();
2102		td->td_md.md_spinlock_count = 1;
2103		td->td_md.md_saved_flags = flags;
2104	} else
2105		td->td_md.md_spinlock_count++;
2106	critical_enter();
2107}
2108
2109void
2110spinlock_exit(void)
2111{
2112	struct thread *td;
2113	register_t flags;
2114
2115	td = curthread;
2116	critical_exit();
2117	flags = td->td_md.md_saved_flags;
2118	td->td_md.md_spinlock_count--;
2119	if (td->td_md.md_spinlock_count == 0)
2120		intr_restore(flags);
2121}
2122
2123/*
2124 * Construct a PCB from a trapframe. This is called from kdb_trap() where
2125 * we want to start a backtrace from the function that caused us to enter
2126 * the debugger. We have the context in the trapframe, but base the trace
2127 * on the PCB. The PCB doesn't have to be perfect, as long as it contains
2128 * enough for a backtrace.
2129 */
2130void
2131makectx(struct trapframe *tf, struct pcb *pcb)
2132{
2133
2134	pcb->pcb_r12 = tf->tf_r12;
2135	pcb->pcb_r13 = tf->tf_r13;
2136	pcb->pcb_r14 = tf->tf_r14;
2137	pcb->pcb_r15 = tf->tf_r15;
2138	pcb->pcb_rbp = tf->tf_rbp;
2139	pcb->pcb_rbx = tf->tf_rbx;
2140	pcb->pcb_rip = tf->tf_rip;
2141	pcb->pcb_rsp = tf->tf_rsp;
2142}
2143
2144int
2145ptrace_set_pc(struct thread *td, unsigned long addr)
2146{
2147
2148	td->td_frame->tf_rip = addr;
2149	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
2150	return (0);
2151}
2152
2153int
2154ptrace_single_step(struct thread *td)
2155{
2156	td->td_frame->tf_rflags |= PSL_T;
2157	return (0);
2158}
2159
2160int
2161ptrace_clear_single_step(struct thread *td)
2162{
2163	td->td_frame->tf_rflags &= ~PSL_T;
2164	return (0);
2165}
2166
2167int
2168fill_regs(struct thread *td, struct reg *regs)
2169{
2170	struct trapframe *tp;
2171
2172	tp = td->td_frame;
2173	return (fill_frame_regs(tp, regs));
2174}
2175
2176int
2177fill_frame_regs(struct trapframe *tp, struct reg *regs)
2178{
2179	regs->r_r15 = tp->tf_r15;
2180	regs->r_r14 = tp->tf_r14;
2181	regs->r_r13 = tp->tf_r13;
2182	regs->r_r12 = tp->tf_r12;
2183	regs->r_r11 = tp->tf_r11;
2184	regs->r_r10 = tp->tf_r10;
2185	regs->r_r9  = tp->tf_r9;
2186	regs->r_r8  = tp->tf_r8;
2187	regs->r_rdi = tp->tf_rdi;
2188	regs->r_rsi = tp->tf_rsi;
2189	regs->r_rbp = tp->tf_rbp;
2190	regs->r_rbx = tp->tf_rbx;
2191	regs->r_rdx = tp->tf_rdx;
2192	regs->r_rcx = tp->tf_rcx;
2193	regs->r_rax = tp->tf_rax;
2194	regs->r_rip = tp->tf_rip;
2195	regs->r_cs = tp->tf_cs;
2196	regs->r_rflags = tp->tf_rflags;
2197	regs->r_rsp = tp->tf_rsp;
2198	regs->r_ss = tp->tf_ss;
2199	if (tp->tf_flags & TF_HASSEGS) {
2200		regs->r_ds = tp->tf_ds;
2201		regs->r_es = tp->tf_es;
2202		regs->r_fs = tp->tf_fs;
2203		regs->r_gs = tp->tf_gs;
2204	} else {
2205		regs->r_ds = 0;
2206		regs->r_es = 0;
2207		regs->r_fs = 0;
2208		regs->r_gs = 0;
2209	}
2210	return (0);
2211}
2212
2213int
2214set_regs(struct thread *td, struct reg *regs)
2215{
2216	struct trapframe *tp;
2217	register_t rflags;
2218
2219	tp = td->td_frame;
2220	rflags = regs->r_rflags & 0xffffffff;
2221	if (!EFL_SECURE(rflags, tp->tf_rflags) || !CS_SECURE(regs->r_cs))
2222		return (EINVAL);
2223	tp->tf_r15 = regs->r_r15;
2224	tp->tf_r14 = regs->r_r14;
2225	tp->tf_r13 = regs->r_r13;
2226	tp->tf_r12 = regs->r_r12;
2227	tp->tf_r11 = regs->r_r11;
2228	tp->tf_r10 = regs->r_r10;
2229	tp->tf_r9  = regs->r_r9;
2230	tp->tf_r8  = regs->r_r8;
2231	tp->tf_rdi = regs->r_rdi;
2232	tp->tf_rsi = regs->r_rsi;
2233	tp->tf_rbp = regs->r_rbp;
2234	tp->tf_rbx = regs->r_rbx;
2235	tp->tf_rdx = regs->r_rdx;
2236	tp->tf_rcx = regs->r_rcx;
2237	tp->tf_rax = regs->r_rax;
2238	tp->tf_rip = regs->r_rip;
2239	tp->tf_cs = regs->r_cs;
2240	tp->tf_rflags = rflags;
2241	tp->tf_rsp = regs->r_rsp;
2242	tp->tf_ss = regs->r_ss;
2243	if (0) {	/* XXXKIB */
2244		tp->tf_ds = regs->r_ds;
2245		tp->tf_es = regs->r_es;
2246		tp->tf_fs = regs->r_fs;
2247		tp->tf_gs = regs->r_gs;
2248		tp->tf_flags = TF_HASSEGS;
2249	}
2250	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
2251	return (0);
2252}
2253
2254/* XXX check all this stuff! */
2255/* externalize from sv_xmm */
2256static void
2257fill_fpregs_xmm(struct savefpu *sv_xmm, struct fpreg *fpregs)
2258{
2259	struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
2260	struct envxmm *penv_xmm = &sv_xmm->sv_env;
2261	int i;
2262
2263	/* pcb -> fpregs */
2264	bzero(fpregs, sizeof(*fpregs));
2265
2266	/* FPU control/status */
2267	penv_fpreg->en_cw = penv_xmm->en_cw;
2268	penv_fpreg->en_sw = penv_xmm->en_sw;
2269	penv_fpreg->en_tw = penv_xmm->en_tw;
2270	penv_fpreg->en_opcode = penv_xmm->en_opcode;
2271	penv_fpreg->en_rip = penv_xmm->en_rip;
2272	penv_fpreg->en_rdp = penv_xmm->en_rdp;
2273	penv_fpreg->en_mxcsr = penv_xmm->en_mxcsr;
2274	penv_fpreg->en_mxcsr_mask = penv_xmm->en_mxcsr_mask;
2275
2276	/* FPU registers */
2277	for (i = 0; i < 8; ++i)
2278		bcopy(sv_xmm->sv_fp[i].fp_acc.fp_bytes, fpregs->fpr_acc[i], 10);
2279
2280	/* SSE registers */
2281	for (i = 0; i < 16; ++i)
2282		bcopy(sv_xmm->sv_xmm[i].xmm_bytes, fpregs->fpr_xacc[i], 16);
2283}
2284
2285/* internalize from fpregs into sv_xmm */
2286static void
2287set_fpregs_xmm(struct fpreg *fpregs, struct savefpu *sv_xmm)
2288{
2289	struct envxmm *penv_xmm = &sv_xmm->sv_env;
2290	struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
2291	int i;
2292
2293	/* fpregs -> pcb */
2294	/* FPU control/status */
2295	penv_xmm->en_cw = penv_fpreg->en_cw;
2296	penv_xmm->en_sw = penv_fpreg->en_sw;
2297	penv_xmm->en_tw = penv_fpreg->en_tw;
2298	penv_xmm->en_opcode = penv_fpreg->en_opcode;
2299	penv_xmm->en_rip = penv_fpreg->en_rip;
2300	penv_xmm->en_rdp = penv_fpreg->en_rdp;
2301	penv_xmm->en_mxcsr = penv_fpreg->en_mxcsr;
2302	penv_xmm->en_mxcsr_mask = penv_fpreg->en_mxcsr_mask & cpu_mxcsr_mask;
2303
2304	/* FPU registers */
2305	for (i = 0; i < 8; ++i)
2306		bcopy(fpregs->fpr_acc[i], sv_xmm->sv_fp[i].fp_acc.fp_bytes, 10);
2307
2308	/* SSE registers */
2309	for (i = 0; i < 16; ++i)
2310		bcopy(fpregs->fpr_xacc[i], sv_xmm->sv_xmm[i].xmm_bytes, 16);
2311}
2312
2313/* externalize from td->pcb */
2314int
2315fill_fpregs(struct thread *td, struct fpreg *fpregs)
2316{
2317
2318	KASSERT(td == curthread || TD_IS_SUSPENDED(td) ||
2319	    P_SHOULDSTOP(td->td_proc),
2320	    ("not suspended thread %p", td));
2321	fpugetregs(td);
2322	fill_fpregs_xmm(get_pcb_user_save_td(td), fpregs);
2323	return (0);
2324}
2325
2326/* internalize to td->pcb */
2327int
2328set_fpregs(struct thread *td, struct fpreg *fpregs)
2329{
2330
2331	set_fpregs_xmm(fpregs, get_pcb_user_save_td(td));
2332	fpuuserinited(td);
2333	return (0);
2334}
2335
2336/*
2337 * Get machine context.
2338 */
2339int
2340get_mcontext(struct thread *td, mcontext_t *mcp, int flags)
2341{
2342	struct pcb *pcb;
2343	struct trapframe *tp;
2344
2345	pcb = td->td_pcb;
2346	tp = td->td_frame;
2347	PROC_LOCK(curthread->td_proc);
2348	mcp->mc_onstack = sigonstack(tp->tf_rsp);
2349	PROC_UNLOCK(curthread->td_proc);
2350	mcp->mc_r15 = tp->tf_r15;
2351	mcp->mc_r14 = tp->tf_r14;
2352	mcp->mc_r13 = tp->tf_r13;
2353	mcp->mc_r12 = tp->tf_r12;
2354	mcp->mc_r11 = tp->tf_r11;
2355	mcp->mc_r10 = tp->tf_r10;
2356	mcp->mc_r9  = tp->tf_r9;
2357	mcp->mc_r8  = tp->tf_r8;
2358	mcp->mc_rdi = tp->tf_rdi;
2359	mcp->mc_rsi = tp->tf_rsi;
2360	mcp->mc_rbp = tp->tf_rbp;
2361	mcp->mc_rbx = tp->tf_rbx;
2362	mcp->mc_rcx = tp->tf_rcx;
2363	mcp->mc_rflags = tp->tf_rflags;
2364	if (flags & GET_MC_CLEAR_RET) {
2365		mcp->mc_rax = 0;
2366		mcp->mc_rdx = 0;
2367		mcp->mc_rflags &= ~PSL_C;
2368	} else {
2369		mcp->mc_rax = tp->tf_rax;
2370		mcp->mc_rdx = tp->tf_rdx;
2371	}
2372	mcp->mc_rip = tp->tf_rip;
2373	mcp->mc_cs = tp->tf_cs;
2374	mcp->mc_rsp = tp->tf_rsp;
2375	mcp->mc_ss = tp->tf_ss;
2376	mcp->mc_ds = tp->tf_ds;
2377	mcp->mc_es = tp->tf_es;
2378	mcp->mc_fs = tp->tf_fs;
2379	mcp->mc_gs = tp->tf_gs;
2380	mcp->mc_flags = tp->tf_flags;
2381	mcp->mc_len = sizeof(*mcp);
2382	get_fpcontext(td, mcp, NULL, 0);
2383	mcp->mc_fsbase = pcb->pcb_fsbase;
2384	mcp->mc_gsbase = pcb->pcb_gsbase;
2385	mcp->mc_xfpustate = 0;
2386	mcp->mc_xfpustate_len = 0;
2387	bzero(mcp->mc_spare, sizeof(mcp->mc_spare));
2388	return (0);
2389}
2390
2391/*
2392 * Set machine context.
2393 *
2394 * However, we don't set any but the user modifiable flags, and we won't
2395 * touch the cs selector.
2396 */
2397int
2398set_mcontext(struct thread *td, const mcontext_t *mcp)
2399{
2400	struct pcb *pcb;
2401	struct trapframe *tp;
2402	char *xfpustate;
2403	long rflags;
2404	int ret;
2405
2406	pcb = td->td_pcb;
2407	tp = td->td_frame;
2408	if (mcp->mc_len != sizeof(*mcp) ||
2409	    (mcp->mc_flags & ~_MC_FLAG_MASK) != 0)
2410		return (EINVAL);
2411	rflags = (mcp->mc_rflags & PSL_USERCHANGE) |
2412	    (tp->tf_rflags & ~PSL_USERCHANGE);
2413	if (mcp->mc_flags & _MC_HASFPXSTATE) {
2414		if (mcp->mc_xfpustate_len > cpu_max_ext_state_size -
2415		    sizeof(struct savefpu))
2416			return (EINVAL);
2417		xfpustate = __builtin_alloca(mcp->mc_xfpustate_len);
2418		ret = copyin((void *)mcp->mc_xfpustate, xfpustate,
2419		    mcp->mc_xfpustate_len);
2420		if (ret != 0)
2421			return (ret);
2422	} else
2423		xfpustate = NULL;
2424	ret = set_fpcontext(td, mcp, xfpustate, mcp->mc_xfpustate_len);
2425	if (ret != 0)
2426		return (ret);
2427	tp->tf_r15 = mcp->mc_r15;
2428	tp->tf_r14 = mcp->mc_r14;
2429	tp->tf_r13 = mcp->mc_r13;
2430	tp->tf_r12 = mcp->mc_r12;
2431	tp->tf_r11 = mcp->mc_r11;
2432	tp->tf_r10 = mcp->mc_r10;
2433	tp->tf_r9  = mcp->mc_r9;
2434	tp->tf_r8  = mcp->mc_r8;
2435	tp->tf_rdi = mcp->mc_rdi;
2436	tp->tf_rsi = mcp->mc_rsi;
2437	tp->tf_rbp = mcp->mc_rbp;
2438	tp->tf_rbx = mcp->mc_rbx;
2439	tp->tf_rdx = mcp->mc_rdx;
2440	tp->tf_rcx = mcp->mc_rcx;
2441	tp->tf_rax = mcp->mc_rax;
2442	tp->tf_rip = mcp->mc_rip;
2443	tp->tf_rflags = rflags;
2444	tp->tf_rsp = mcp->mc_rsp;
2445	tp->tf_ss = mcp->mc_ss;
2446	tp->tf_flags = mcp->mc_flags;
2447	if (tp->tf_flags & TF_HASSEGS) {
2448		tp->tf_ds = mcp->mc_ds;
2449		tp->tf_es = mcp->mc_es;
2450		tp->tf_fs = mcp->mc_fs;
2451		tp->tf_gs = mcp->mc_gs;
2452	}
2453	if (mcp->mc_flags & _MC_HASBASES) {
2454		pcb->pcb_fsbase = mcp->mc_fsbase;
2455		pcb->pcb_gsbase = mcp->mc_gsbase;
2456	}
2457	set_pcb_flags(pcb, PCB_FULL_IRET);
2458	return (0);
2459}
2460
2461static void
2462get_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpusave,
2463    size_t xfpusave_len)
2464{
2465	size_t max_len, len;
2466
2467	mcp->mc_ownedfp = fpugetregs(td);
2468	bcopy(get_pcb_user_save_td(td), &mcp->mc_fpstate[0],
2469	    sizeof(mcp->mc_fpstate));
2470	mcp->mc_fpformat = fpuformat();
2471	if (!use_xsave || xfpusave_len == 0)
2472		return;
2473	max_len = cpu_max_ext_state_size - sizeof(struct savefpu);
2474	len = xfpusave_len;
2475	if (len > max_len) {
2476		len = max_len;
2477		bzero(xfpusave + max_len, len - max_len);
2478	}
2479	mcp->mc_flags |= _MC_HASFPXSTATE;
2480	mcp->mc_xfpustate_len = len;
2481	bcopy(get_pcb_user_save_td(td) + 1, xfpusave, len);
2482}
2483
2484static int
2485set_fpcontext(struct thread *td, const mcontext_t *mcp, char *xfpustate,
2486    size_t xfpustate_len)
2487{
2488	struct savefpu *fpstate;
2489	int error;
2490
2491	if (mcp->mc_fpformat == _MC_FPFMT_NODEV)
2492		return (0);
2493	else if (mcp->mc_fpformat != _MC_FPFMT_XMM)
2494		return (EINVAL);
2495	else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE) {
2496		/* We don't care what state is left in the FPU or PCB. */
2497		fpstate_drop(td);
2498		error = 0;
2499	} else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU ||
2500	    mcp->mc_ownedfp == _MC_FPOWNED_PCB) {
2501		fpstate = (struct savefpu *)&mcp->mc_fpstate;
2502		fpstate->sv_env.en_mxcsr &= cpu_mxcsr_mask;
2503		error = fpusetregs(td, fpstate, xfpustate, xfpustate_len);
2504	} else
2505		return (EINVAL);
2506	return (error);
2507}
2508
2509void
2510fpstate_drop(struct thread *td)
2511{
2512
2513	KASSERT(PCB_USER_FPU(td->td_pcb), ("fpstate_drop: kernel-owned fpu"));
2514	critical_enter();
2515	if (PCPU_GET(fpcurthread) == td)
2516		fpudrop();
2517	/*
2518	 * XXX force a full drop of the fpu.  The above only drops it if we
2519	 * owned it.
2520	 *
2521	 * XXX I don't much like fpugetuserregs()'s semantics of doing a full
2522	 * drop.  Dropping only to the pcb matches fnsave's behaviour.
2523	 * We only need to drop to !PCB_INITDONE in sendsig().  But
2524	 * sendsig() is the only caller of fpugetuserregs()... perhaps we just
2525	 * have too many layers.
2526	 */
2527	clear_pcb_flags(curthread->td_pcb,
2528	    PCB_FPUINITDONE | PCB_USERFPUINITDONE);
2529	critical_exit();
2530}
2531
2532int
2533fill_dbregs(struct thread *td, struct dbreg *dbregs)
2534{
2535	struct pcb *pcb;
2536
2537	if (td == NULL) {
2538		dbregs->dr[0] = rdr0();
2539		dbregs->dr[1] = rdr1();
2540		dbregs->dr[2] = rdr2();
2541		dbregs->dr[3] = rdr3();
2542		dbregs->dr[6] = rdr6();
2543		dbregs->dr[7] = rdr7();
2544	} else {
2545		pcb = td->td_pcb;
2546		dbregs->dr[0] = pcb->pcb_dr0;
2547		dbregs->dr[1] = pcb->pcb_dr1;
2548		dbregs->dr[2] = pcb->pcb_dr2;
2549		dbregs->dr[3] = pcb->pcb_dr3;
2550		dbregs->dr[6] = pcb->pcb_dr6;
2551		dbregs->dr[7] = pcb->pcb_dr7;
2552	}
2553	dbregs->dr[4] = 0;
2554	dbregs->dr[5] = 0;
2555	dbregs->dr[8] = 0;
2556	dbregs->dr[9] = 0;
2557	dbregs->dr[10] = 0;
2558	dbregs->dr[11] = 0;
2559	dbregs->dr[12] = 0;
2560	dbregs->dr[13] = 0;
2561	dbregs->dr[14] = 0;
2562	dbregs->dr[15] = 0;
2563	return (0);
2564}
2565
2566int
2567set_dbregs(struct thread *td, struct dbreg *dbregs)
2568{
2569	struct pcb *pcb;
2570	int i;
2571
2572	if (td == NULL) {
2573		load_dr0(dbregs->dr[0]);
2574		load_dr1(dbregs->dr[1]);
2575		load_dr2(dbregs->dr[2]);
2576		load_dr3(dbregs->dr[3]);
2577		load_dr6(dbregs->dr[6]);
2578		load_dr7(dbregs->dr[7]);
2579	} else {
2580		/*
2581		 * Don't let an illegal value for dr7 get set.  Specifically,
2582		 * check for undefined settings.  Setting these bit patterns
2583		 * result in undefined behaviour and can lead to an unexpected
2584		 * TRCTRAP or a general protection fault right here.
2585		 * Upper bits of dr6 and dr7 must not be set
2586		 */
2587		for (i = 0; i < 4; i++) {
2588			if (DBREG_DR7_ACCESS(dbregs->dr[7], i) == 0x02)
2589				return (EINVAL);
2590			if (td->td_frame->tf_cs == _ucode32sel &&
2591			    DBREG_DR7_LEN(dbregs->dr[7], i) == DBREG_DR7_LEN_8)
2592				return (EINVAL);
2593		}
2594		if ((dbregs->dr[6] & 0xffffffff00000000ul) != 0 ||
2595		    (dbregs->dr[7] & 0xffffffff00000000ul) != 0)
2596			return (EINVAL);
2597
2598		pcb = td->td_pcb;
2599
2600		/*
2601		 * Don't let a process set a breakpoint that is not within the
2602		 * process's address space.  If a process could do this, it
2603		 * could halt the system by setting a breakpoint in the kernel
2604		 * (if ddb was enabled).  Thus, we need to check to make sure
2605		 * that no breakpoints are being enabled for addresses outside
2606		 * process's address space.
2607		 *
2608		 * XXX - what about when the watched area of the user's
2609		 * address space is written into from within the kernel
2610		 * ... wouldn't that still cause a breakpoint to be generated
2611		 * from within kernel mode?
2612		 */
2613
2614		if (DBREG_DR7_ENABLED(dbregs->dr[7], 0)) {
2615			/* dr0 is enabled */
2616			if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS)
2617				return (EINVAL);
2618		}
2619		if (DBREG_DR7_ENABLED(dbregs->dr[7], 1)) {
2620			/* dr1 is enabled */
2621			if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS)
2622				return (EINVAL);
2623		}
2624		if (DBREG_DR7_ENABLED(dbregs->dr[7], 2)) {
2625			/* dr2 is enabled */
2626			if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS)
2627				return (EINVAL);
2628		}
2629		if (DBREG_DR7_ENABLED(dbregs->dr[7], 3)) {
2630			/* dr3 is enabled */
2631			if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS)
2632				return (EINVAL);
2633		}
2634
2635		pcb->pcb_dr0 = dbregs->dr[0];
2636		pcb->pcb_dr1 = dbregs->dr[1];
2637		pcb->pcb_dr2 = dbregs->dr[2];
2638		pcb->pcb_dr3 = dbregs->dr[3];
2639		pcb->pcb_dr6 = dbregs->dr[6];
2640		pcb->pcb_dr7 = dbregs->dr[7];
2641
2642		set_pcb_flags(pcb, PCB_DBREGS);
2643	}
2644
2645	return (0);
2646}
2647
2648void
2649reset_dbregs(void)
2650{
2651
2652	load_dr7(0);	/* Turn off the control bits first */
2653	load_dr0(0);
2654	load_dr1(0);
2655	load_dr2(0);
2656	load_dr3(0);
2657	load_dr6(0);
2658}
2659
2660/*
2661 * Return > 0 if a hardware breakpoint has been hit, and the
2662 * breakpoint was in user space.  Return 0, otherwise.
2663 */
2664int
2665user_dbreg_trap(void)
2666{
2667        u_int64_t dr7, dr6; /* debug registers dr6 and dr7 */
2668        u_int64_t bp;       /* breakpoint bits extracted from dr6 */
2669        int nbp;            /* number of breakpoints that triggered */
2670        caddr_t addr[4];    /* breakpoint addresses */
2671        int i;
2672
2673        dr7 = rdr7();
2674        if ((dr7 & 0x000000ff) == 0) {
2675                /*
2676                 * all GE and LE bits in the dr7 register are zero,
2677                 * thus the trap couldn't have been caused by the
2678                 * hardware debug registers
2679                 */
2680                return 0;
2681        }
2682
2683        nbp = 0;
2684        dr6 = rdr6();
2685        bp = dr6 & 0x0000000f;
2686
2687        if (!bp) {
2688                /*
2689                 * None of the breakpoint bits are set meaning this
2690                 * trap was not caused by any of the debug registers
2691                 */
2692                return 0;
2693        }
2694
2695        /*
2696         * at least one of the breakpoints were hit, check to see
2697         * which ones and if any of them are user space addresses
2698         */
2699
2700        if (bp & 0x01) {
2701                addr[nbp++] = (caddr_t)rdr0();
2702        }
2703        if (bp & 0x02) {
2704                addr[nbp++] = (caddr_t)rdr1();
2705        }
2706        if (bp & 0x04) {
2707                addr[nbp++] = (caddr_t)rdr2();
2708        }
2709        if (bp & 0x08) {
2710                addr[nbp++] = (caddr_t)rdr3();
2711        }
2712
2713        for (i = 0; i < nbp; i++) {
2714                if (addr[i] < (caddr_t)VM_MAXUSER_ADDRESS) {
2715                        /*
2716                         * addr[i] is in user space
2717                         */
2718                        return nbp;
2719                }
2720        }
2721
2722        /*
2723         * None of the breakpoints are in user space.
2724         */
2725        return 0;
2726}
2727
2728#ifdef KDB
2729
2730/*
2731 * Provide inb() and outb() as functions.  They are normally only available as
2732 * inline functions, thus cannot be called from the debugger.
2733 */
2734
2735/* silence compiler warnings */
2736u_char inb_(u_short);
2737void outb_(u_short, u_char);
2738
2739u_char
2740inb_(u_short port)
2741{
2742	return inb(port);
2743}
2744
2745void
2746outb_(u_short port, u_char data)
2747{
2748	outb(port, data);
2749}
2750
2751#endif /* KDB */
2752