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