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