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