machdep.c revision 164303
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 164303 2006-11-15 19:53:48Z jhb $");
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;
517SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hlt, CTLFLAG_RW,
518    &cpu_idle_hlt, 0, "Idle loop HLT enable");
519
520static void
521cpu_idle_default(void)
522{
523	/*
524	 * we must absolutely guarentee that hlt is the
525	 * absolute next instruction after sti or we
526	 * introduce a timing window.
527	 */
528	__asm __volatile("sti; hlt");
529}
530
531/*
532 * Note that we have to be careful here to avoid a race between checking
533 * sched_runnable() and actually halting.  If we don't do this, we may waste
534 * the time between calling hlt and the next interrupt even though there
535 * is a runnable process.
536 */
537void
538cpu_idle(void)
539{
540
541#ifdef SMP
542	if (mp_grab_cpu_hlt())
543		return;
544#endif
545	if (cpu_idle_hlt) {
546		disable_intr();
547  		if (sched_runnable())
548			enable_intr();
549		else
550			(*cpu_idle_hook)();
551	}
552}
553
554/* Other subsystems (e.g., ACPI) can hook this later. */
555void (*cpu_idle_hook)(void) = cpu_idle_default;
556
557/*
558 * Clear registers on exec
559 */
560void
561exec_setregs(td, entry, stack, ps_strings)
562	struct thread *td;
563	u_long entry;
564	u_long stack;
565	u_long ps_strings;
566{
567	struct trapframe *regs = td->td_frame;
568	struct pcb *pcb = td->td_pcb;
569
570	critical_enter();
571	wrmsr(MSR_FSBASE, 0);
572	wrmsr(MSR_KGSBASE, 0);	/* User value while we're in the kernel */
573	pcb->pcb_fsbase = 0;
574	pcb->pcb_gsbase = 0;
575	critical_exit();
576	load_ds(_udatasel);
577	load_es(_udatasel);
578	load_fs(_udatasel);
579	load_gs(_udatasel);
580	pcb->pcb_ds = _udatasel;
581	pcb->pcb_es = _udatasel;
582	pcb->pcb_fs = _udatasel;
583	pcb->pcb_gs = _udatasel;
584
585	bzero((char *)regs, sizeof(struct trapframe));
586	regs->tf_rip = entry;
587	regs->tf_rsp = ((stack - 8) & ~0xFul) + 8;
588	regs->tf_rdi = stack;		/* argv */
589	regs->tf_rflags = PSL_USER | (regs->tf_rflags & PSL_T);
590	regs->tf_ss = _udatasel;
591	regs->tf_cs = _ucodesel;
592
593	/*
594	 * Reset the hardware debug registers if they were in use.
595	 * They won't have any meaning for the newly exec'd process.
596	 */
597	if (pcb->pcb_flags & PCB_DBREGS) {
598		pcb->pcb_dr0 = 0;
599		pcb->pcb_dr1 = 0;
600		pcb->pcb_dr2 = 0;
601		pcb->pcb_dr3 = 0;
602		pcb->pcb_dr6 = 0;
603		pcb->pcb_dr7 = 0;
604		if (pcb == PCPU_GET(curpcb)) {
605			/*
606			 * Clear the debug registers on the running
607			 * CPU, otherwise they will end up affecting
608			 * the next process we switch to.
609			 */
610			reset_dbregs();
611		}
612		pcb->pcb_flags &= ~PCB_DBREGS;
613	}
614
615	/*
616	 * Drop the FP state if we hold it, so that the process gets a
617	 * clean FP state if it uses the FPU again.
618	 */
619	fpstate_drop(td);
620}
621
622void
623cpu_setregs(void)
624{
625	register_t cr0;
626
627	cr0 = rcr0();
628	/*
629	 * CR0_MP, CR0_NE and CR0_TS are also set by npx_probe() for the
630	 * BSP.  See the comments there about why we set them.
631	 */
632	cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
633	load_cr0(cr0);
634}
635
636/*
637 * Initialize amd64 and configure to run kernel
638 */
639
640/*
641 * Initialize segments & interrupt table
642 */
643
644struct user_segment_descriptor gdt[NGDT * MAXCPU];/* global descriptor table */
645static struct gate_descriptor idt0[NIDT];
646struct gate_descriptor *idt = &idt0[0];	/* interrupt descriptor table */
647
648static char dblfault_stack[PAGE_SIZE] __aligned(16);
649
650struct amd64tss common_tss[MAXCPU];
651
652/* software prototypes -- in more palatable form */
653struct soft_segment_descriptor gdt_segs[] = {
654/* GNULL_SEL	0 Null Descriptor */
655{	0x0,			/* segment base address  */
656	0x0,			/* length */
657	0,			/* segment type */
658	0,			/* segment descriptor priority level */
659	0,			/* segment descriptor present */
660	0,			/* long */
661	0,			/* default 32 vs 16 bit size */
662	0  			/* limit granularity (byte/page units)*/ },
663/* GCODE_SEL	1 Code Descriptor for kernel */
664{	0x0,			/* segment base address  */
665	0xfffff,		/* length - all address space */
666	SDT_MEMERA,		/* segment type */
667	SEL_KPL,		/* segment descriptor priority level */
668	1,			/* segment descriptor present */
669	1,			/* long */
670	0,			/* default 32 vs 16 bit size */
671	1  			/* limit granularity (byte/page units)*/ },
672/* GDATA_SEL	2 Data Descriptor for kernel */
673{	0x0,			/* segment base address  */
674	0xfffff,		/* length - all address space */
675	SDT_MEMRWA,		/* segment type */
676	SEL_KPL,		/* segment descriptor priority level */
677	1,			/* segment descriptor present */
678	1,			/* long */
679	0,			/* default 32 vs 16 bit size */
680	1  			/* limit granularity (byte/page units)*/ },
681/* GUCODE32_SEL	3 32 bit Code Descriptor for user */
682{	0x0,			/* segment base address  */
683	0xfffff,		/* length - all address space */
684	SDT_MEMERA,		/* segment type */
685	SEL_UPL,		/* segment descriptor priority level */
686	1,			/* segment descriptor present */
687	0,			/* long */
688	1,			/* default 32 vs 16 bit size */
689	1  			/* limit granularity (byte/page units)*/ },
690/* GUDATA_SEL	4 32/64 bit Data Descriptor for user */
691{	0x0,			/* segment base address  */
692	0xfffff,		/* length - all address space */
693	SDT_MEMRWA,		/* segment type */
694	SEL_UPL,		/* segment descriptor priority level */
695	1,			/* segment descriptor present */
696	0,			/* long */
697	1,			/* default 32 vs 16 bit size */
698	1  			/* limit granularity (byte/page units)*/ },
699/* GUCODE_SEL	5 64 bit Code Descriptor for user */
700{	0x0,			/* segment base address  */
701	0xfffff,		/* length - all address space */
702	SDT_MEMERA,		/* segment type */
703	SEL_UPL,		/* segment descriptor priority level */
704	1,			/* segment descriptor present */
705	1,			/* long */
706	0,			/* default 32 vs 16 bit size */
707	1  			/* limit granularity (byte/page units)*/ },
708/* GPROC0_SEL	6 Proc 0 Tss Descriptor */
709{
710	0x0,			/* segment base address */
711	sizeof(struct amd64tss)-1,/* length - all address space */
712	SDT_SYSTSS,		/* segment type */
713	SEL_KPL,		/* segment descriptor priority level */
714	1,			/* segment descriptor present */
715	0,			/* long */
716	0,			/* unused - default 32 vs 16 bit size */
717	0  			/* limit granularity (byte/page units)*/ },
718/* Actually, the TSS is a system descriptor which is double size */
719{	0x0,			/* segment base address  */
720	0x0,			/* length */
721	0,			/* segment type */
722	0,			/* segment descriptor priority level */
723	0,			/* segment descriptor present */
724	0,			/* long */
725	0,			/* default 32 vs 16 bit size */
726	0  			/* limit granularity (byte/page units)*/ },
727};
728
729void
730setidt(idx, func, typ, dpl, ist)
731	int idx;
732	inthand_t *func;
733	int typ;
734	int dpl;
735	int ist;
736{
737	struct gate_descriptor *ip;
738
739	ip = idt + idx;
740	ip->gd_looffset = (uintptr_t)func;
741	ip->gd_selector = GSEL(GCODE_SEL, SEL_KPL);
742	ip->gd_ist = ist;
743	ip->gd_xx = 0;
744	ip->gd_type = typ;
745	ip->gd_dpl = dpl;
746	ip->gd_p = 1;
747	ip->gd_hioffset = ((uintptr_t)func)>>16 ;
748}
749
750extern inthand_t
751	IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
752	IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
753	IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
754	IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
755	IDTVEC(xmm), IDTVEC(dblfault),
756	IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
757
758void
759sdtossd(sd, ssd)
760	struct user_segment_descriptor *sd;
761	struct soft_segment_descriptor *ssd;
762{
763
764	ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
765	ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
766	ssd->ssd_type  = sd->sd_type;
767	ssd->ssd_dpl   = sd->sd_dpl;
768	ssd->ssd_p     = sd->sd_p;
769	ssd->ssd_long  = sd->sd_long;
770	ssd->ssd_def32 = sd->sd_def32;
771	ssd->ssd_gran  = sd->sd_gran;
772}
773
774void
775ssdtosd(ssd, sd)
776	struct soft_segment_descriptor *ssd;
777	struct user_segment_descriptor *sd;
778{
779
780	sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
781	sd->sd_hibase = (ssd->ssd_base >> 24) & 0xff;
782	sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
783	sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
784	sd->sd_type  = ssd->ssd_type;
785	sd->sd_dpl   = ssd->ssd_dpl;
786	sd->sd_p     = ssd->ssd_p;
787	sd->sd_long  = ssd->ssd_long;
788	sd->sd_def32 = ssd->ssd_def32;
789	sd->sd_gran  = ssd->ssd_gran;
790}
791
792void
793ssdtosyssd(ssd, sd)
794	struct soft_segment_descriptor *ssd;
795	struct system_segment_descriptor *sd;
796{
797
798	sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
799	sd->sd_hibase = (ssd->ssd_base >> 24) & 0xfffffffffful;
800	sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
801	sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
802	sd->sd_type  = ssd->ssd_type;
803	sd->sd_dpl   = ssd->ssd_dpl;
804	sd->sd_p     = ssd->ssd_p;
805	sd->sd_gran  = ssd->ssd_gran;
806}
807
808#if !defined(DEV_ATPIC) && defined(DEV_ISA)
809#include <isa/isavar.h>
810u_int
811isa_irq_pending(void)
812{
813
814	return (0);
815}
816#endif
817
818u_int basemem;
819
820/*
821 * Populate the (physmap) array with base/bound pairs describing the
822 * available physical memory in the system, then test this memory and
823 * build the phys_avail array describing the actually-available memory.
824 *
825 * If we cannot accurately determine the physical memory map, then use
826 * value from the 0xE801 call, and failing that, the RTC.
827 *
828 * Total memory size may be set by the kernel environment variable
829 * hw.physmem or the compile-time define MAXMEM.
830 *
831 * XXX first should be vm_paddr_t.
832 */
833static void
834getmemsize(caddr_t kmdp, u_int64_t first)
835{
836	int i, physmap_idx, pa_indx, da_indx;
837	vm_paddr_t pa, physmap[PHYSMAP_SIZE];
838	u_long physmem_tunable;
839	pt_entry_t *pte;
840	struct bios_smap *smapbase, *smap, *smapend;
841	u_int32_t smapsize;
842	quad_t dcons_addr, dcons_size;
843
844	bzero(physmap, sizeof(physmap));
845	basemem = 0;
846	physmap_idx = 0;
847
848	/*
849	 * get memory map from INT 15:E820, kindly supplied by the loader.
850	 *
851	 * subr_module.c says:
852	 * "Consumer may safely assume that size value precedes data."
853	 * ie: an int32_t immediately precedes smap.
854	 */
855	smapbase = (struct bios_smap *)preload_search_info(kmdp,
856	    MODINFO_METADATA | MODINFOMD_SMAP);
857	if (smapbase == NULL)
858		panic("No BIOS smap info from loader!");
859
860	smapsize = *((u_int32_t *)smapbase - 1);
861	smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
862
863	for (smap = smapbase; smap < smapend; smap++) {
864		if (boothowto & RB_VERBOSE)
865			printf("SMAP type=%02x base=%016lx len=%016lx\n",
866			    smap->type, smap->base, smap->length);
867
868		if (smap->type != 0x01)
869			continue;
870
871		if (smap->length == 0)
872			continue;
873
874		for (i = 0; i <= physmap_idx; i += 2) {
875			if (smap->base < physmap[i + 1]) {
876				if (boothowto & RB_VERBOSE)
877					printf(
878	"Overlapping or non-monotonic memory region, ignoring second region\n");
879				continue;
880			}
881		}
882
883		if (smap->base == physmap[physmap_idx + 1]) {
884			physmap[physmap_idx + 1] += smap->length;
885			continue;
886		}
887
888		physmap_idx += 2;
889		if (physmap_idx == PHYSMAP_SIZE) {
890			printf(
891		"Too many segments in the physical address map, giving up\n");
892			break;
893		}
894		physmap[physmap_idx] = smap->base;
895		physmap[physmap_idx + 1] = smap->base + smap->length;
896	}
897
898	/*
899	 * Find the 'base memory' segment for SMP
900	 */
901	basemem = 0;
902	for (i = 0; i <= physmap_idx; i += 2) {
903		if (physmap[i] == 0x00000000) {
904			basemem = physmap[i + 1] / 1024;
905			break;
906		}
907	}
908	if (basemem == 0)
909		panic("BIOS smap did not include a basemem segment!");
910
911#ifdef SMP
912	/* make hole for AP bootstrap code */
913	physmap[1] = mp_bootaddress(physmap[1] / 1024);
914#endif
915
916	/*
917	 * Maxmem isn't the "maximum memory", it's one larger than the
918	 * highest page of the physical address space.  It should be
919	 * called something like "Maxphyspage".  We may adjust this
920	 * based on ``hw.physmem'' and the results of the memory test.
921	 */
922	Maxmem = atop(physmap[physmap_idx + 1]);
923
924#ifdef MAXMEM
925	Maxmem = MAXMEM / 4;
926#endif
927
928	if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
929		Maxmem = atop(physmem_tunable);
930
931	/*
932	 * Don't allow MAXMEM or hw.physmem to extend the amount of memory
933	 * in the system.
934	 */
935	if (Maxmem > atop(physmap[physmap_idx + 1]))
936		Maxmem = atop(physmap[physmap_idx + 1]);
937
938	if (atop(physmap[physmap_idx + 1]) != Maxmem &&
939	    (boothowto & RB_VERBOSE))
940		printf("Physical memory use set to %ldK\n", Maxmem * 4);
941
942	/* call pmap initialization to make new kernel address space */
943	pmap_bootstrap(&first);
944
945	/*
946	 * Size up each available chunk of physical memory.
947	 */
948	physmap[0] = PAGE_SIZE;		/* mask off page 0 */
949	pa_indx = 0;
950	da_indx = 1;
951	phys_avail[pa_indx++] = physmap[0];
952	phys_avail[pa_indx] = physmap[0];
953	dump_avail[da_indx] = physmap[0];
954	pte = CMAP1;
955
956	/*
957	 * Get dcons buffer address
958	 */
959	if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
960	    getenv_quad("dcons.size", &dcons_size) == 0)
961		dcons_addr = 0;
962
963	/*
964	 * physmap is in bytes, so when converting to page boundaries,
965	 * round up the start address and round down the end address.
966	 */
967	for (i = 0; i <= physmap_idx; i += 2) {
968		vm_paddr_t end;
969
970		end = ptoa((vm_paddr_t)Maxmem);
971		if (physmap[i + 1] < end)
972			end = trunc_page(physmap[i + 1]);
973		for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
974			int tmp, page_bad, full;
975			int *ptr = (int *)CADDR1;
976
977			full = FALSE;
978			/*
979			 * block out kernel memory as not available.
980			 */
981			if (pa >= 0x100000 && pa < first)
982				goto do_dump_avail;
983
984			/*
985			 * block out dcons buffer
986			 */
987			if (dcons_addr > 0
988			    && pa >= trunc_page(dcons_addr)
989			    && pa < dcons_addr + dcons_size)
990				goto do_dump_avail;
991
992			page_bad = FALSE;
993
994			/*
995			 * map page into kernel: valid, read/write,non-cacheable
996			 */
997			*pte = pa | PG_V | PG_RW | PG_N;
998			invltlb();
999
1000			tmp = *(int *)ptr;
1001			/*
1002			 * Test for alternating 1's and 0's
1003			 */
1004			*(volatile int *)ptr = 0xaaaaaaaa;
1005			if (*(volatile int *)ptr != 0xaaaaaaaa)
1006				page_bad = TRUE;
1007			/*
1008			 * Test for alternating 0's and 1's
1009			 */
1010			*(volatile int *)ptr = 0x55555555;
1011			if (*(volatile int *)ptr != 0x55555555)
1012				page_bad = TRUE;
1013			/*
1014			 * Test for all 1's
1015			 */
1016			*(volatile int *)ptr = 0xffffffff;
1017			if (*(volatile int *)ptr != 0xffffffff)
1018				page_bad = TRUE;
1019			/*
1020			 * Test for all 0's
1021			 */
1022			*(volatile int *)ptr = 0x0;
1023			if (*(volatile int *)ptr != 0x0)
1024				page_bad = TRUE;
1025			/*
1026			 * Restore original value.
1027			 */
1028			*(int *)ptr = tmp;
1029
1030			/*
1031			 * Adjust array of valid/good pages.
1032			 */
1033			if (page_bad == TRUE)
1034				continue;
1035			/*
1036			 * If this good page is a continuation of the
1037			 * previous set of good pages, then just increase
1038			 * the end pointer. Otherwise start a new chunk.
1039			 * Note that "end" points one higher than end,
1040			 * making the range >= start and < end.
1041			 * If we're also doing a speculative memory
1042			 * test and we at or past the end, bump up Maxmem
1043			 * so that we keep going. The first bad page
1044			 * will terminate the loop.
1045			 */
1046			if (phys_avail[pa_indx] == pa) {
1047				phys_avail[pa_indx] += PAGE_SIZE;
1048			} else {
1049				pa_indx++;
1050				if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1051					printf(
1052		"Too many holes in the physical address space, giving up\n");
1053					pa_indx--;
1054					full = TRUE;
1055					goto do_dump_avail;
1056				}
1057				phys_avail[pa_indx++] = pa;	/* start */
1058				phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
1059			}
1060			physmem++;
1061do_dump_avail:
1062			if (dump_avail[da_indx] == pa) {
1063				dump_avail[da_indx] += PAGE_SIZE;
1064			} else {
1065				da_indx++;
1066				if (da_indx == DUMP_AVAIL_ARRAY_END) {
1067					da_indx--;
1068					goto do_next;
1069				}
1070				dump_avail[da_indx++] = pa; /* start */
1071				dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
1072			}
1073do_next:
1074			if (full)
1075				break;
1076		}
1077	}
1078	*pte = 0;
1079	invltlb();
1080
1081	/*
1082	 * XXX
1083	 * The last chunk must contain at least one page plus the message
1084	 * buffer to avoid complicating other code (message buffer address
1085	 * calculation, etc.).
1086	 */
1087	while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1088	    round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
1089		physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1090		phys_avail[pa_indx--] = 0;
1091		phys_avail[pa_indx--] = 0;
1092	}
1093
1094	Maxmem = atop(phys_avail[pa_indx]);
1095
1096	/* Trim off space for the message buffer. */
1097	phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
1098
1099	avail_end = phys_avail[pa_indx];
1100}
1101
1102u_int64_t
1103hammer_time(u_int64_t modulep, u_int64_t physfree)
1104{
1105	caddr_t kmdp;
1106	int gsel_tss, off, x;
1107	struct pcpu *pc;
1108	u_int64_t msr;
1109	char *env;
1110
1111	thread0.td_kstack = physfree + KERNBASE;
1112	bzero((void *)thread0.td_kstack, KSTACK_PAGES * PAGE_SIZE);
1113	physfree += KSTACK_PAGES * PAGE_SIZE;
1114	thread0.td_pcb = (struct pcb *)
1115	   (thread0.td_kstack + KSTACK_PAGES * PAGE_SIZE) - 1;
1116
1117	/*
1118 	 * This may be done better later if it gets more high level
1119 	 * components in it. If so just link td->td_proc here.
1120	 */
1121#ifdef KSE
1122	proc_linkup(&proc0, &ksegrp0, &thread0);
1123#else
1124	proc_linkup(&proc0, &thread0);
1125#endif
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(tssp, &common_tss[0]);
1168
1169	/*
1170	 * Initialize mutexes.
1171	 *
1172	 * icu_lock: in order to allow an interrupt to occur in a critical
1173	 * 	     section, to set pcpu->ipending (etc...) properly, we
1174	 *	     must be able to get the icu lock, so it can't be
1175	 *	     under witness.
1176	 */
1177	mutex_init();
1178	mtx_init(&clock_lock, "clk", NULL, MTX_SPIN);
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, 0);
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 console before we print anything out.
1210	 */
1211	cninit();
1212
1213#ifdef DEV_ISA
1214#ifdef DEV_ATPIC
1215	elcr_probe();
1216	atpic_startup();
1217#else
1218	/* Reset and mask the atpics and leave them shut down. */
1219	atpic_reset();
1220
1221	/*
1222	 * Point the ICU spurious interrupt vectors at the APIC spurious
1223	 * interrupt handler.
1224	 */
1225	setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1226	setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1227#endif
1228#else
1229#error "have you forgotten the isa device?";
1230#endif
1231
1232	kdb_init();
1233
1234#ifdef KDB
1235	if (boothowto & RB_KDB)
1236		kdb_enter("Boot flags requested debugger");
1237#endif
1238
1239	identify_cpu();		/* Final stage of CPU initialization */
1240	initializecpu();	/* Initialize CPU registers */
1241
1242	/* make an initial tss so cpu can get interrupt stack on syscall! */
1243	common_tss[0].tss_rsp0 = thread0.td_kstack + \
1244	    KSTACK_PAGES * PAGE_SIZE - sizeof(struct pcb);
1245	/* Ensure the stack is aligned to 16 bytes */
1246	common_tss[0].tss_rsp0 &= ~0xFul;
1247	PCPU_SET(rsp0, common_tss[0].tss_rsp0);
1248
1249	/* doublefault stack space, runs on ist1 */
1250	common_tss[0].tss_ist1 = (long)&dblfault_stack[sizeof(dblfault_stack)];
1251
1252	/* Set the IO permission bitmap (empty due to tss seg limit) */
1253	common_tss[0].tss_iobase = sizeof(struct amd64tss);
1254
1255	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1256	ltr(gsel_tss);
1257
1258	/* Set up the fast syscall stuff */
1259	msr = rdmsr(MSR_EFER) | EFER_SCE;
1260	wrmsr(MSR_EFER, msr);
1261	wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
1262	wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
1263	msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
1264	      ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
1265	wrmsr(MSR_STAR, msr);
1266	wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
1267
1268	getmemsize(kmdp, physfree);
1269	init_param2(physmem);
1270
1271	/* now running on new page tables, configured,and u/iom is accessible */
1272
1273	/* Map the message buffer. */
1274	for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
1275		pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
1276
1277	msgbufinit(msgbufp, MSGBUF_SIZE);
1278	fpuinit();
1279
1280	/* transfer to user mode */
1281
1282	_ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
1283	_udatasel = GSEL(GUDATA_SEL, SEL_UPL);
1284	_ucode32sel = GSEL(GUCODE32_SEL, SEL_UPL);
1285
1286	/* setup proc 0's pcb */
1287	thread0.td_pcb->pcb_flags = 0; /* XXXKSE */
1288	thread0.td_pcb->pcb_cr3 = KPML4phys;
1289	thread0.td_frame = &proc0_tf;
1290
1291        env = getenv("kernelname");
1292	if (env != NULL)
1293		strlcpy(kernelname, env, sizeof(kernelname));
1294
1295	/* Location of kernel stack for locore */
1296	return ((u_int64_t)thread0.td_pcb);
1297}
1298
1299void
1300cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
1301{
1302
1303	pcpu->pc_acpi_id = 0xffffffff;
1304}
1305
1306void
1307spinlock_enter(void)
1308{
1309	struct thread *td;
1310
1311	td = curthread;
1312	if (td->td_md.md_spinlock_count == 0)
1313		td->td_md.md_saved_flags = intr_disable();
1314	td->td_md.md_spinlock_count++;
1315	critical_enter();
1316}
1317
1318void
1319spinlock_exit(void)
1320{
1321	struct thread *td;
1322
1323	td = curthread;
1324	critical_exit();
1325	td->td_md.md_spinlock_count--;
1326	if (td->td_md.md_spinlock_count == 0)
1327		intr_restore(td->td_md.md_saved_flags);
1328}
1329
1330/*
1331 * Construct a PCB from a trapframe. This is called from kdb_trap() where
1332 * we want to start a backtrace from the function that caused us to enter
1333 * the debugger. We have the context in the trapframe, but base the trace
1334 * on the PCB. The PCB doesn't have to be perfect, as long as it contains
1335 * enough for a backtrace.
1336 */
1337void
1338makectx(struct trapframe *tf, struct pcb *pcb)
1339{
1340
1341	pcb->pcb_r12 = tf->tf_r12;
1342	pcb->pcb_r13 = tf->tf_r13;
1343	pcb->pcb_r14 = tf->tf_r14;
1344	pcb->pcb_r15 = tf->tf_r15;
1345	pcb->pcb_rbp = tf->tf_rbp;
1346	pcb->pcb_rbx = tf->tf_rbx;
1347	pcb->pcb_rip = tf->tf_rip;
1348	pcb->pcb_rsp = (ISPL(tf->tf_cs)) ? tf->tf_rsp : (long)(tf + 1) - 8;
1349}
1350
1351int
1352ptrace_set_pc(struct thread *td, unsigned long addr)
1353{
1354	td->td_frame->tf_rip = addr;
1355	return (0);
1356}
1357
1358int
1359ptrace_single_step(struct thread *td)
1360{
1361	td->td_frame->tf_rflags |= PSL_T;
1362	return (0);
1363}
1364
1365int
1366ptrace_clear_single_step(struct thread *td)
1367{
1368	td->td_frame->tf_rflags &= ~PSL_T;
1369	return (0);
1370}
1371
1372int
1373fill_regs(struct thread *td, struct reg *regs)
1374{
1375	struct trapframe *tp;
1376
1377	tp = td->td_frame;
1378	regs->r_r15 = tp->tf_r15;
1379	regs->r_r14 = tp->tf_r14;
1380	regs->r_r13 = tp->tf_r13;
1381	regs->r_r12 = tp->tf_r12;
1382	regs->r_r11 = tp->tf_r11;
1383	regs->r_r10 = tp->tf_r10;
1384	regs->r_r9  = tp->tf_r9;
1385	regs->r_r8  = tp->tf_r8;
1386	regs->r_rdi = tp->tf_rdi;
1387	regs->r_rsi = tp->tf_rsi;
1388	regs->r_rbp = tp->tf_rbp;
1389	regs->r_rbx = tp->tf_rbx;
1390	regs->r_rdx = tp->tf_rdx;
1391	regs->r_rcx = tp->tf_rcx;
1392	regs->r_rax = tp->tf_rax;
1393	regs->r_rip = tp->tf_rip;
1394	regs->r_cs = tp->tf_cs;
1395	regs->r_rflags = tp->tf_rflags;
1396	regs->r_rsp = tp->tf_rsp;
1397	regs->r_ss = tp->tf_ss;
1398	return (0);
1399}
1400
1401int
1402set_regs(struct thread *td, struct reg *regs)
1403{
1404	struct trapframe *tp;
1405	register_t rflags;
1406
1407	tp = td->td_frame;
1408	rflags = regs->r_rflags & 0xffffffff;
1409	if (!EFL_SECURE(rflags, tp->tf_rflags) || !CS_SECURE(regs->r_cs))
1410		return (EINVAL);
1411	tp->tf_r15 = regs->r_r15;
1412	tp->tf_r14 = regs->r_r14;
1413	tp->tf_r13 = regs->r_r13;
1414	tp->tf_r12 = regs->r_r12;
1415	tp->tf_r11 = regs->r_r11;
1416	tp->tf_r10 = regs->r_r10;
1417	tp->tf_r9  = regs->r_r9;
1418	tp->tf_r8  = regs->r_r8;
1419	tp->tf_rdi = regs->r_rdi;
1420	tp->tf_rsi = regs->r_rsi;
1421	tp->tf_rbp = regs->r_rbp;
1422	tp->tf_rbx = regs->r_rbx;
1423	tp->tf_rdx = regs->r_rdx;
1424	tp->tf_rcx = regs->r_rcx;
1425	tp->tf_rax = regs->r_rax;
1426	tp->tf_rip = regs->r_rip;
1427	tp->tf_cs = regs->r_cs;
1428	tp->tf_rflags = rflags;
1429	tp->tf_rsp = regs->r_rsp;
1430	tp->tf_ss = regs->r_ss;
1431	td->td_pcb->pcb_flags |= PCB_FULLCTX;
1432	return (0);
1433}
1434
1435/* XXX check all this stuff! */
1436/* externalize from sv_xmm */
1437static void
1438fill_fpregs_xmm(struct savefpu *sv_xmm, struct fpreg *fpregs)
1439{
1440	struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
1441	struct envxmm *penv_xmm = &sv_xmm->sv_env;
1442	int i;
1443
1444	/* pcb -> fpregs */
1445	bzero(fpregs, sizeof(*fpregs));
1446
1447	/* FPU control/status */
1448	penv_fpreg->en_cw = penv_xmm->en_cw;
1449	penv_fpreg->en_sw = penv_xmm->en_sw;
1450	penv_fpreg->en_tw = penv_xmm->en_tw;
1451	penv_fpreg->en_opcode = penv_xmm->en_opcode;
1452	penv_fpreg->en_rip = penv_xmm->en_rip;
1453	penv_fpreg->en_rdp = penv_xmm->en_rdp;
1454	penv_fpreg->en_mxcsr = penv_xmm->en_mxcsr;
1455	penv_fpreg->en_mxcsr_mask = penv_xmm->en_mxcsr_mask;
1456
1457	/* FPU registers */
1458	for (i = 0; i < 8; ++i)
1459		bcopy(sv_xmm->sv_fp[i].fp_acc.fp_bytes, fpregs->fpr_acc[i], 10);
1460
1461	/* SSE registers */
1462	for (i = 0; i < 16; ++i)
1463		bcopy(sv_xmm->sv_xmm[i].xmm_bytes, fpregs->fpr_xacc[i], 16);
1464}
1465
1466/* internalize from fpregs into sv_xmm */
1467static void
1468set_fpregs_xmm(struct fpreg *fpregs, struct savefpu *sv_xmm)
1469{
1470	struct envxmm *penv_xmm = &sv_xmm->sv_env;
1471	struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
1472	int i;
1473
1474	/* fpregs -> pcb */
1475	/* FPU control/status */
1476	penv_xmm->en_cw = penv_fpreg->en_cw;
1477	penv_xmm->en_sw = penv_fpreg->en_sw;
1478	penv_xmm->en_tw = penv_fpreg->en_tw;
1479	penv_xmm->en_opcode = penv_fpreg->en_opcode;
1480	penv_xmm->en_rip = penv_fpreg->en_rip;
1481	penv_xmm->en_rdp = penv_fpreg->en_rdp;
1482	penv_xmm->en_mxcsr = penv_fpreg->en_mxcsr;
1483	penv_xmm->en_mxcsr_mask = penv_fpreg->en_mxcsr_mask & cpu_mxcsr_mask;
1484
1485	/* FPU registers */
1486	for (i = 0; i < 8; ++i)
1487		bcopy(fpregs->fpr_acc[i], sv_xmm->sv_fp[i].fp_acc.fp_bytes, 10);
1488
1489	/* SSE registers */
1490	for (i = 0; i < 16; ++i)
1491		bcopy(fpregs->fpr_xacc[i], sv_xmm->sv_xmm[i].xmm_bytes, 16);
1492}
1493
1494/* externalize from td->pcb */
1495int
1496fill_fpregs(struct thread *td, struct fpreg *fpregs)
1497{
1498
1499	fill_fpregs_xmm(&td->td_pcb->pcb_save, fpregs);
1500	return (0);
1501}
1502
1503/* internalize to td->pcb */
1504int
1505set_fpregs(struct thread *td, struct fpreg *fpregs)
1506{
1507
1508	set_fpregs_xmm(fpregs, &td->td_pcb->pcb_save);
1509	return (0);
1510}
1511
1512/*
1513 * Get machine context.
1514 */
1515int
1516get_mcontext(struct thread *td, mcontext_t *mcp, int flags)
1517{
1518	struct trapframe *tp;
1519
1520	tp = td->td_frame;
1521	PROC_LOCK(curthread->td_proc);
1522	mcp->mc_onstack = sigonstack(tp->tf_rsp);
1523	PROC_UNLOCK(curthread->td_proc);
1524	mcp->mc_r15 = tp->tf_r15;
1525	mcp->mc_r14 = tp->tf_r14;
1526	mcp->mc_r13 = tp->tf_r13;
1527	mcp->mc_r12 = tp->tf_r12;
1528	mcp->mc_r11 = tp->tf_r11;
1529	mcp->mc_r10 = tp->tf_r10;
1530	mcp->mc_r9  = tp->tf_r9;
1531	mcp->mc_r8  = tp->tf_r8;
1532	mcp->mc_rdi = tp->tf_rdi;
1533	mcp->mc_rsi = tp->tf_rsi;
1534	mcp->mc_rbp = tp->tf_rbp;
1535	mcp->mc_rbx = tp->tf_rbx;
1536	mcp->mc_rcx = tp->tf_rcx;
1537	mcp->mc_rflags = tp->tf_rflags;
1538	if (flags & GET_MC_CLEAR_RET) {
1539		mcp->mc_rax = 0;
1540		mcp->mc_rdx = 0;
1541		mcp->mc_rflags &= ~PSL_C;
1542	} else {
1543		mcp->mc_rax = tp->tf_rax;
1544		mcp->mc_rdx = tp->tf_rdx;
1545	}
1546	mcp->mc_rip = tp->tf_rip;
1547	mcp->mc_cs = tp->tf_cs;
1548	mcp->mc_rsp = tp->tf_rsp;
1549	mcp->mc_ss = tp->tf_ss;
1550	mcp->mc_len = sizeof(*mcp);
1551	get_fpcontext(td, mcp);
1552	return (0);
1553}
1554
1555/*
1556 * Set machine context.
1557 *
1558 * However, we don't set any but the user modifiable flags, and we won't
1559 * touch the cs selector.
1560 */
1561int
1562set_mcontext(struct thread *td, const mcontext_t *mcp)
1563{
1564	struct trapframe *tp;
1565	long rflags;
1566	int ret;
1567
1568	tp = td->td_frame;
1569	if (mcp->mc_len != sizeof(*mcp))
1570		return (EINVAL);
1571	rflags = (mcp->mc_rflags & PSL_USERCHANGE) |
1572	    (tp->tf_rflags & ~PSL_USERCHANGE);
1573	ret = set_fpcontext(td, mcp);
1574	if (ret != 0)
1575		return (ret);
1576	tp->tf_r15 = mcp->mc_r15;
1577	tp->tf_r14 = mcp->mc_r14;
1578	tp->tf_r13 = mcp->mc_r13;
1579	tp->tf_r12 = mcp->mc_r12;
1580	tp->tf_r11 = mcp->mc_r11;
1581	tp->tf_r10 = mcp->mc_r10;
1582	tp->tf_r9  = mcp->mc_r9;
1583	tp->tf_r8  = mcp->mc_r8;
1584	tp->tf_rdi = mcp->mc_rdi;
1585	tp->tf_rsi = mcp->mc_rsi;
1586	tp->tf_rbp = mcp->mc_rbp;
1587	tp->tf_rbx = mcp->mc_rbx;
1588	tp->tf_rdx = mcp->mc_rdx;
1589	tp->tf_rcx = mcp->mc_rcx;
1590	tp->tf_rax = mcp->mc_rax;
1591	tp->tf_rip = mcp->mc_rip;
1592	tp->tf_rflags = rflags;
1593	tp->tf_rsp = mcp->mc_rsp;
1594	tp->tf_ss = mcp->mc_ss;
1595	td->td_pcb->pcb_flags |= PCB_FULLCTX;
1596	return (0);
1597}
1598
1599static void
1600get_fpcontext(struct thread *td, mcontext_t *mcp)
1601{
1602
1603	mcp->mc_ownedfp = fpugetregs(td, (struct savefpu *)&mcp->mc_fpstate);
1604	mcp->mc_fpformat = fpuformat();
1605}
1606
1607static int
1608set_fpcontext(struct thread *td, const mcontext_t *mcp)
1609{
1610	struct savefpu *fpstate;
1611
1612	if (mcp->mc_fpformat == _MC_FPFMT_NODEV)
1613		return (0);
1614	else if (mcp->mc_fpformat != _MC_FPFMT_XMM)
1615		return (EINVAL);
1616	else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE)
1617		/* We don't care what state is left in the FPU or PCB. */
1618		fpstate_drop(td);
1619	else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU ||
1620	    mcp->mc_ownedfp == _MC_FPOWNED_PCB) {
1621		/*
1622		 * XXX we violate the dubious requirement that fpusetregs()
1623		 * be called with interrupts disabled.
1624		 * XXX obsolete on trap-16 systems?
1625		 */
1626		fpstate = (struct savefpu *)&mcp->mc_fpstate;
1627		fpstate->sv_env.en_mxcsr &= cpu_mxcsr_mask;
1628		fpusetregs(td, fpstate);
1629	} else
1630		return (EINVAL);
1631	return (0);
1632}
1633
1634void
1635fpstate_drop(struct thread *td)
1636{
1637	register_t s;
1638
1639	s = intr_disable();
1640	if (PCPU_GET(fpcurthread) == td)
1641		fpudrop();
1642	/*
1643	 * XXX force a full drop of the fpu.  The above only drops it if we
1644	 * owned it.
1645	 *
1646	 * XXX I don't much like fpugetregs()'s semantics of doing a full
1647	 * drop.  Dropping only to the pcb matches fnsave's behaviour.
1648	 * We only need to drop to !PCB_INITDONE in sendsig().  But
1649	 * sendsig() is the only caller of fpugetregs()... perhaps we just
1650	 * have too many layers.
1651	 */
1652	curthread->td_pcb->pcb_flags &= ~PCB_FPUINITDONE;
1653	intr_restore(s);
1654}
1655
1656int
1657fill_dbregs(struct thread *td, struct dbreg *dbregs)
1658{
1659	struct pcb *pcb;
1660
1661	if (td == NULL) {
1662		dbregs->dr[0] = rdr0();
1663		dbregs->dr[1] = rdr1();
1664		dbregs->dr[2] = rdr2();
1665		dbregs->dr[3] = rdr3();
1666		dbregs->dr[6] = rdr6();
1667		dbregs->dr[7] = rdr7();
1668	} else {
1669		pcb = td->td_pcb;
1670		dbregs->dr[0] = pcb->pcb_dr0;
1671		dbregs->dr[1] = pcb->pcb_dr1;
1672		dbregs->dr[2] = pcb->pcb_dr2;
1673		dbregs->dr[3] = pcb->pcb_dr3;
1674		dbregs->dr[6] = pcb->pcb_dr6;
1675		dbregs->dr[7] = pcb->pcb_dr7;
1676	}
1677	dbregs->dr[4] = 0;
1678	dbregs->dr[5] = 0;
1679	dbregs->dr[8] = 0;
1680	dbregs->dr[9] = 0;
1681	dbregs->dr[10] = 0;
1682	dbregs->dr[11] = 0;
1683	dbregs->dr[12] = 0;
1684	dbregs->dr[13] = 0;
1685	dbregs->dr[14] = 0;
1686	dbregs->dr[15] = 0;
1687	return (0);
1688}
1689
1690int
1691set_dbregs(struct thread *td, struct dbreg *dbregs)
1692{
1693	struct pcb *pcb;
1694	int i;
1695	u_int64_t mask1, mask2;
1696
1697	if (td == NULL) {
1698		load_dr0(dbregs->dr[0]);
1699		load_dr1(dbregs->dr[1]);
1700		load_dr2(dbregs->dr[2]);
1701		load_dr3(dbregs->dr[3]);
1702		load_dr6(dbregs->dr[6]);
1703		load_dr7(dbregs->dr[7]);
1704	} else {
1705		/*
1706		 * Don't let an illegal value for dr7 get set.  Specifically,
1707		 * check for undefined settings.  Setting these bit patterns
1708		 * result in undefined behaviour and can lead to an unexpected
1709		 * TRCTRAP or a general protection fault right here.
1710		 * Upper bits of dr6 and dr7 must not be set
1711		 */
1712		for (i = 0, mask1 = 0x3<<16, mask2 = 0x2<<16; i < 8;
1713		     i++, mask1 <<= 2, mask2 <<= 2)
1714			if ((dbregs->dr[7] & mask1) == mask2)
1715				return (EINVAL);
1716		if ((dbregs->dr[6] & 0xffffffff00000000ul) != 0 ||
1717		    (dbregs->dr[7] & 0xffffffff00000000ul) != 0)
1718			return (EINVAL);
1719
1720		pcb = td->td_pcb;
1721
1722		/*
1723		 * Don't let a process set a breakpoint that is not within the
1724		 * process's address space.  If a process could do this, it
1725		 * could halt the system by setting a breakpoint in the kernel
1726		 * (if ddb was enabled).  Thus, we need to check to make sure
1727		 * that no breakpoints are being enabled for addresses outside
1728		 * process's address space.
1729		 *
1730		 * XXX - what about when the watched area of the user's
1731		 * address space is written into from within the kernel
1732		 * ... wouldn't that still cause a breakpoint to be generated
1733		 * from within kernel mode?
1734		 */
1735
1736		if (dbregs->dr[7] & 0x3) {
1737			/* dr0 is enabled */
1738			if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS)
1739				return (EINVAL);
1740		}
1741		if (dbregs->dr[7] & 0x3<<2) {
1742			/* dr1 is enabled */
1743			if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS)
1744				return (EINVAL);
1745		}
1746		if (dbregs->dr[7] & 0x3<<4) {
1747			/* dr2 is enabled */
1748			if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS)
1749				return (EINVAL);
1750		}
1751		if (dbregs->dr[7] & 0x3<<6) {
1752			/* dr3 is enabled */
1753			if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS)
1754				return (EINVAL);
1755		}
1756
1757		pcb->pcb_dr0 = dbregs->dr[0];
1758		pcb->pcb_dr1 = dbregs->dr[1];
1759		pcb->pcb_dr2 = dbregs->dr[2];
1760		pcb->pcb_dr3 = dbregs->dr[3];
1761		pcb->pcb_dr6 = dbregs->dr[6];
1762		pcb->pcb_dr7 = dbregs->dr[7];
1763
1764		pcb->pcb_flags |= PCB_DBREGS;
1765	}
1766
1767	return (0);
1768}
1769
1770void
1771reset_dbregs(void)
1772{
1773
1774	load_dr7(0);	/* Turn off the control bits first */
1775	load_dr0(0);
1776	load_dr1(0);
1777	load_dr2(0);
1778	load_dr3(0);
1779	load_dr6(0);
1780}
1781
1782/*
1783 * Return > 0 if a hardware breakpoint has been hit, and the
1784 * breakpoint was in user space.  Return 0, otherwise.
1785 */
1786int
1787user_dbreg_trap(void)
1788{
1789        u_int64_t dr7, dr6; /* debug registers dr6 and dr7 */
1790        u_int64_t bp;       /* breakpoint bits extracted from dr6 */
1791        int nbp;            /* number of breakpoints that triggered */
1792        caddr_t addr[4];    /* breakpoint addresses */
1793        int i;
1794
1795        dr7 = rdr7();
1796        if ((dr7 & 0x000000ff) == 0) {
1797                /*
1798                 * all GE and LE bits in the dr7 register are zero,
1799                 * thus the trap couldn't have been caused by the
1800                 * hardware debug registers
1801                 */
1802                return 0;
1803        }
1804
1805        nbp = 0;
1806        dr6 = rdr6();
1807        bp = dr6 & 0x0000000f;
1808
1809        if (!bp) {
1810                /*
1811                 * None of the breakpoint bits are set meaning this
1812                 * trap was not caused by any of the debug registers
1813                 */
1814                return 0;
1815        }
1816
1817        /*
1818         * at least one of the breakpoints were hit, check to see
1819         * which ones and if any of them are user space addresses
1820         */
1821
1822        if (bp & 0x01) {
1823                addr[nbp++] = (caddr_t)rdr0();
1824        }
1825        if (bp & 0x02) {
1826                addr[nbp++] = (caddr_t)rdr1();
1827        }
1828        if (bp & 0x04) {
1829                addr[nbp++] = (caddr_t)rdr2();
1830        }
1831        if (bp & 0x08) {
1832                addr[nbp++] = (caddr_t)rdr3();
1833        }
1834
1835        for (i = 0; i < nbp; i++) {
1836                if (addr[i] < (caddr_t)VM_MAXUSER_ADDRESS) {
1837                        /*
1838                         * addr[i] is in user space
1839                         */
1840                        return nbp;
1841                }
1842        }
1843
1844        /*
1845         * None of the breakpoints are in user space.
1846         */
1847        return 0;
1848}
1849
1850#ifdef KDB
1851
1852/*
1853 * Provide inb() and outb() as functions.  They are normally only
1854 * available as macros calling inlined functions, thus cannot be
1855 * called from the debugger.
1856 *
1857 * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
1858 */
1859
1860#undef inb
1861#undef outb
1862
1863/* silence compiler warnings */
1864u_char inb(u_int);
1865void outb(u_int, u_char);
1866
1867u_char
1868inb(u_int port)
1869{
1870	u_char	data;
1871	/*
1872	 * We use %%dx and not %1 here because i/o is done at %dx and not at
1873	 * %edx, while gcc generates inferior code (movw instead of movl)
1874	 * if we tell it to load (u_short) port.
1875	 */
1876	__asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
1877	return (data);
1878}
1879
1880void
1881outb(u_int port, u_char data)
1882{
1883	u_char	al;
1884	/*
1885	 * Use an unnecessary assignment to help gcc's register allocator.
1886	 * This make a large difference for gcc-1.40 and a tiny difference
1887	 * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
1888	 * best results.  gcc-2.6.0 can't handle this.
1889	 */
1890	al = data;
1891	__asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
1892}
1893
1894#endif /* KDB */
1895