machdep.c revision 93461
1/*-
2 * Copyright (c) 1992 Terrence R. Lambert.
3 * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
4 * All rights reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * William Jolitz.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 *    must display the following acknowledgement:
19 *	This product includes software developed by the University of
20 *	California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 *    may be used to endorse or promote products derived from this software
23 *    without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 *
37 *	from: @(#)machdep.c	7.4 (Berkeley) 6/3/91
38 * $FreeBSD: head/sys/amd64/amd64/machdep.c 93461 2002-03-31 01:13:21Z alc $
39 */
40
41#include "opt_atalk.h"
42#include "opt_compat.h"
43#include "opt_cpu.h"
44#include "opt_ddb.h"
45#include "opt_inet.h"
46#include "opt_ipx.h"
47#include "opt_isa.h"
48#include "opt_maxmem.h"
49#include "opt_msgbuf.h"
50#include "opt_npx.h"
51#include "opt_perfmon.h"
52#include "opt_kstack_pages.h"
53/* #include "opt_userconfig.h" */
54
55#include <sys/param.h>
56#include <sys/systm.h>
57#include <sys/sysproto.h>
58#include <sys/signalvar.h>
59#include <sys/kernel.h>
60#include <sys/ktr.h>
61#include <sys/linker.h>
62#include <sys/lock.h>
63#include <sys/malloc.h>
64#include <sys/mutex.h>
65#include <sys/pcpu.h>
66#include <sys/proc.h>
67#include <sys/bio.h>
68#include <sys/buf.h>
69#include <sys/reboot.h>
70#include <sys/callout.h>
71#include <sys/msgbuf.h>
72#include <sys/sysent.h>
73#include <sys/sysctl.h>
74#include <sys/ucontext.h>
75#include <sys/vmmeter.h>
76#include <sys/bus.h>
77#include <sys/eventhandler.h>
78
79#include <vm/vm.h>
80#include <vm/vm_param.h>
81#include <sys/lock.h>
82#include <vm/vm_kern.h>
83#include <vm/vm_object.h>
84#include <vm/vm_page.h>
85#include <vm/vm_map.h>
86#include <vm/vm_pager.h>
87#include <vm/vm_extern.h>
88
89#include <sys/user.h>
90#include <sys/exec.h>
91#include <sys/cons.h>
92
93#include <ddb/ddb.h>
94
95#include <net/netisr.h>
96
97#include <machine/cpu.h>
98#include <machine/cputypes.h>
99#include <machine/reg.h>
100#include <machine/clock.h>
101#include <machine/specialreg.h>
102#include <machine/bootinfo.h>
103#include <machine/md_var.h>
104#include <machine/pc/bios.h>
105#include <machine/pcb_ext.h>		/* pcb.h included via sys/user.h */
106#include <machine/proc.h>
107#ifdef PERFMON
108#include <machine/perfmon.h>
109#endif
110#ifdef SMP
111#include <machine/privatespace.h>
112#include <machine/smp.h>
113#endif
114
115#include <i386/isa/icu.h>
116#include <i386/isa/intr_machdep.h>
117#include <isa/rtc.h>
118#include <machine/vm86.h>
119#include <sys/ptrace.h>
120#include <machine/sigframe.h>
121
122extern void init386(int first);
123extern void dblfault_handler(void);
124
125extern void printcpuinfo(void);	/* XXX header file */
126extern void earlysetcpuclass(void);	/* same header file */
127extern void finishidentcpu(void);
128extern void panicifcpuunsupported(void);
129extern void initializecpu(void);
130
131#define	CS_SECURE(cs)		(ISPL(cs) == SEL_UPL)
132#define	EFL_SECURE(ef, oef)	((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
133
134static void cpu_startup(void *);
135#ifdef CPU_ENABLE_SSE
136static void set_fpregs_xmm(struct save87 *, struct savexmm *);
137static void fill_fpregs_xmm(struct savexmm *, struct save87 *);
138#endif /* CPU_ENABLE_SSE */
139SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL)
140
141int	_udatasel, _ucodesel;
142u_int	atdevbase;
143
144#if defined(SWTCH_OPTIM_STATS)
145extern int swtch_optim_stats;
146SYSCTL_INT(_debug, OID_AUTO, swtch_optim_stats,
147	CTLFLAG_RD, &swtch_optim_stats, 0, "");
148SYSCTL_INT(_debug, OID_AUTO, tlb_flush_count,
149	CTLFLAG_RD, &tlb_flush_count, 0, "");
150#endif
151
152#ifdef PC98
153static int	ispc98 = 1;
154#else
155static int	ispc98 = 0;
156#endif
157SYSCTL_INT(_machdep, OID_AUTO, ispc98, CTLFLAG_RD, &ispc98, 0, "");
158
159int physmem = 0;
160int cold = 1;
161
162#ifdef COMPAT_43
163static void osendsig(sig_t catcher, int sig, sigset_t *mask, u_long code);
164#endif
165
166static int
167sysctl_hw_physmem(SYSCTL_HANDLER_ARGS)
168{
169	int error = sysctl_handle_int(oidp, 0, ctob(physmem), req);
170	return (error);
171}
172
173SYSCTL_PROC(_hw, HW_PHYSMEM, physmem, CTLTYPE_INT|CTLFLAG_RD,
174	0, 0, sysctl_hw_physmem, "IU", "");
175
176static int
177sysctl_hw_usermem(SYSCTL_HANDLER_ARGS)
178{
179	int error = sysctl_handle_int(oidp, 0,
180		ctob(physmem - cnt.v_wire_count), req);
181	return (error);
182}
183
184SYSCTL_PROC(_hw, HW_USERMEM, usermem, CTLTYPE_INT|CTLFLAG_RD,
185	0, 0, sysctl_hw_usermem, "IU", "");
186
187static int
188sysctl_hw_availpages(SYSCTL_HANDLER_ARGS)
189{
190	int error = sysctl_handle_int(oidp, 0,
191		i386_btop(avail_end - avail_start), req);
192	return (error);
193}
194
195SYSCTL_PROC(_hw, OID_AUTO, availpages, CTLTYPE_INT|CTLFLAG_RD,
196	0, 0, sysctl_hw_availpages, "I", "");
197
198int Maxmem = 0;
199long dumplo;
200
201vm_offset_t phys_avail[10];
202
203/* must be 2 less so 0 0 can signal end of chunks */
204#define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(vm_offset_t)) - 2)
205
206struct kva_md_info kmi;
207
208static struct trapframe proc0_tf;
209#ifndef SMP
210static struct pcpu __pcpu;
211#endif
212
213struct mtx sched_lock;
214struct mtx Giant;
215struct mtx icu_lock;
216
217static void
218cpu_startup(dummy)
219	void *dummy;
220{
221	/*
222	 * Good {morning,afternoon,evening,night}.
223	 */
224	earlysetcpuclass();
225	startrtclock();
226	printcpuinfo();
227	panicifcpuunsupported();
228#ifdef PERFMON
229	perfmon_init();
230#endif
231	printf("real memory  = %u (%uK bytes)\n", ptoa(Maxmem),
232	    ptoa(Maxmem) / 1024);
233	/*
234	 * Display any holes after the first chunk of extended memory.
235	 */
236	if (bootverbose) {
237		int indx;
238
239		printf("Physical memory chunk(s):\n");
240		for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
241			unsigned int size1;
242
243			size1 = phys_avail[indx + 1] - phys_avail[indx];
244			printf("0x%08x - 0x%08x, %u bytes (%u pages)\n",
245			    phys_avail[indx], phys_avail[indx + 1] - 1, size1,
246			    size1 / PAGE_SIZE);
247		}
248	}
249
250	vm_ksubmap_init(&kmi);
251
252#if defined(USERCONFIG)
253	userconfig();
254	cninit();		/* the preferred console may have changed */
255#endif
256
257	printf("avail memory = %u (%uK bytes)\n", ptoa(cnt.v_free_count),
258	    ptoa(cnt.v_free_count) / 1024);
259
260	/*
261	 * Set up buffers, so they can be used to read disk labels.
262	 */
263	bufinit();
264	vm_pager_bufferinit();
265
266#ifndef SMP
267	/* For SMP, we delay the cpu_setregs() until after SMP startup. */
268	cpu_setregs();
269#endif
270}
271
272/*
273 * Send an interrupt to process.
274 *
275 * Stack is set up to allow sigcode stored
276 * at top to call routine, followed by kcall
277 * to sigreturn routine below.  After sigreturn
278 * resets the signal mask, the stack, and the
279 * frame pointer, it returns to the user
280 * specified pc, psl.
281 */
282#ifdef COMPAT_43
283static void
284osendsig(catcher, sig, mask, code)
285	sig_t catcher;
286	int sig;
287	sigset_t *mask;
288	u_long code;
289{
290	struct osigframe sf;
291	struct osigframe *fp;
292	struct proc *p;
293	struct thread *td;
294	struct sigacts *psp;
295	struct trapframe *regs;
296	int oonstack;
297
298	td = curthread;
299	p = td->td_proc;
300	PROC_LOCK_ASSERT(p, MA_OWNED);
301	psp = p->p_sigacts;
302	regs = td->td_frame;
303	oonstack = sigonstack(regs->tf_esp);
304
305	/* Allocate space for the signal handler context. */
306	if ((p->p_flag & P_ALTSTACK) && !oonstack &&
307	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
308		fp = (struct osigframe *)(p->p_sigstk.ss_sp +
309		    p->p_sigstk.ss_size - sizeof(struct osigframe));
310#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
311		p->p_sigstk.ss_flags |= SS_ONSTACK;
312#endif
313	} else
314		fp = (struct osigframe *)regs->tf_esp - 1;
315	PROC_UNLOCK(p);
316
317	/* Translate the signal if appropriate. */
318	if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
319		sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
320
321	/* Build the argument list for the signal handler. */
322	sf.sf_signum = sig;
323	sf.sf_scp = (register_t)&fp->sf_siginfo.si_sc;
324	PROC_LOCK(p);
325	if (SIGISMEMBER(p->p_sigacts->ps_siginfo, sig)) {
326		/* Signal handler installed with SA_SIGINFO. */
327		sf.sf_arg2 = (register_t)&fp->sf_siginfo;
328		sf.sf_siginfo.si_signo = sig;
329		sf.sf_siginfo.si_code = code;
330		sf.sf_ahu.sf_action = (__osiginfohandler_t *)catcher;
331	} else {
332		/* Old FreeBSD-style arguments. */
333		sf.sf_arg2 = code;
334		sf.sf_addr = regs->tf_err;
335		sf.sf_ahu.sf_handler = catcher;
336	}
337	PROC_UNLOCK(p);
338
339	/* Save most if not all of trap frame. */
340	sf.sf_siginfo.si_sc.sc_eax = regs->tf_eax;
341	sf.sf_siginfo.si_sc.sc_ebx = regs->tf_ebx;
342	sf.sf_siginfo.si_sc.sc_ecx = regs->tf_ecx;
343	sf.sf_siginfo.si_sc.sc_edx = regs->tf_edx;
344	sf.sf_siginfo.si_sc.sc_esi = regs->tf_esi;
345	sf.sf_siginfo.si_sc.sc_edi = regs->tf_edi;
346	sf.sf_siginfo.si_sc.sc_cs = regs->tf_cs;
347	sf.sf_siginfo.si_sc.sc_ds = regs->tf_ds;
348	sf.sf_siginfo.si_sc.sc_ss = regs->tf_ss;
349	sf.sf_siginfo.si_sc.sc_es = regs->tf_es;
350	sf.sf_siginfo.si_sc.sc_fs = regs->tf_fs;
351	sf.sf_siginfo.si_sc.sc_gs = rgs();
352	sf.sf_siginfo.si_sc.sc_isp = regs->tf_isp;
353
354	/* Build the signal context to be used by osigreturn(). */
355	sf.sf_siginfo.si_sc.sc_onstack = (oonstack) ? 1 : 0;
356	SIG2OSIG(*mask, sf.sf_siginfo.si_sc.sc_mask);
357	sf.sf_siginfo.si_sc.sc_sp = regs->tf_esp;
358	sf.sf_siginfo.si_sc.sc_fp = regs->tf_ebp;
359	sf.sf_siginfo.si_sc.sc_pc = regs->tf_eip;
360	sf.sf_siginfo.si_sc.sc_ps = regs->tf_eflags;
361	sf.sf_siginfo.si_sc.sc_trapno = regs->tf_trapno;
362	sf.sf_siginfo.si_sc.sc_err = regs->tf_err;
363
364	/*
365	 * If we're a vm86 process, we want to save the segment registers.
366	 * We also change eflags to be our emulated eflags, not the actual
367	 * eflags.
368	 */
369	if (regs->tf_eflags & PSL_VM) {
370		/* XXX confusing names: `tf' isn't a trapframe; `regs' is. */
371		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
372		struct vm86_kernel *vm86 = &td->td_pcb->pcb_ext->ext_vm86;
373
374		sf.sf_siginfo.si_sc.sc_gs = tf->tf_vm86_gs;
375		sf.sf_siginfo.si_sc.sc_fs = tf->tf_vm86_fs;
376		sf.sf_siginfo.si_sc.sc_es = tf->tf_vm86_es;
377		sf.sf_siginfo.si_sc.sc_ds = tf->tf_vm86_ds;
378
379		if (vm86->vm86_has_vme == 0)
380			sf.sf_siginfo.si_sc.sc_ps =
381			    (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
382			    (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
383
384		/* See sendsig() for comments. */
385		tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
386	}
387
388	/*
389	 * Copy the sigframe out to the user's stack.
390	 */
391	if (copyout(&sf, fp, sizeof(*fp)) != 0) {
392#ifdef DEBUG
393		printf("process %ld has trashed its stack\n", (long)p->p_pid);
394#endif
395		PROC_LOCK(p);
396		sigexit(td, SIGILL);
397	}
398
399	regs->tf_esp = (int)fp;
400	regs->tf_eip = PS_STRINGS - szosigcode;
401	regs->tf_eflags &= ~PSL_T;
402	regs->tf_cs = _ucodesel;
403	regs->tf_ds = _udatasel;
404	regs->tf_es = _udatasel;
405	regs->tf_fs = _udatasel;
406	load_gs(_udatasel);
407	regs->tf_ss = _udatasel;
408	PROC_LOCK(p);
409}
410#endif /* COMPAT_43 */
411
412void
413sendsig(catcher, sig, mask, code)
414	sig_t catcher;
415	int sig;
416	sigset_t *mask;
417	u_long code;
418{
419	struct sigframe sf;
420	struct proc *p;
421	struct thread *td;
422	struct sigacts *psp;
423	struct trapframe *regs;
424	struct sigframe *sfp;
425	int oonstack;
426
427	td = curthread;
428	p = td->td_proc;
429	PROC_LOCK_ASSERT(p, MA_OWNED);
430	psp = p->p_sigacts;
431#ifdef COMPAT_43
432	if (SIGISMEMBER(psp->ps_osigset, sig)) {
433		osendsig(catcher, sig, mask, code);
434		return;
435	}
436#endif
437	regs = td->td_frame;
438	oonstack = sigonstack(regs->tf_esp);
439
440	/* Save user context. */
441	bzero(&sf, sizeof(sf));
442	sf.sf_uc.uc_sigmask = *mask;
443	sf.sf_uc.uc_stack = p->p_sigstk;
444	sf.sf_uc.uc_stack.ss_flags = (p->p_flag & P_ALTSTACK)
445	    ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
446	sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
447	sf.sf_uc.uc_mcontext.mc_gs = rgs();
448	sf.sf_uc.uc_mcontext.mc_flags = __UC_MC_VALID;	/* no FP regs */
449	bcopy(regs, &sf.sf_uc.uc_mcontext.mc_fs, sizeof(*regs));
450
451	/* Allocate space for the signal handler context. */
452	if ((p->p_flag & P_ALTSTACK) != 0 && !oonstack &&
453	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
454		sfp = (struct sigframe *)(p->p_sigstk.ss_sp +
455		    p->p_sigstk.ss_size - sizeof(struct sigframe));
456#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
457		p->p_sigstk.ss_flags |= SS_ONSTACK;
458#endif
459	} else
460		sfp = (struct sigframe *)regs->tf_esp - 1;
461	PROC_UNLOCK(p);
462
463	/* Translate the signal if appropriate. */
464	if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
465		sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
466
467	/* Build the argument list for the signal handler. */
468	sf.sf_signum = sig;
469	sf.sf_ucontext = (register_t)&sfp->sf_uc;
470	PROC_LOCK(p);
471	if (SIGISMEMBER(p->p_sigacts->ps_siginfo, sig)) {
472		/* Signal handler installed with SA_SIGINFO. */
473		sf.sf_siginfo = (register_t)&sfp->sf_si;
474		sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
475
476		/* Fill siginfo structure. */
477		sf.sf_si.si_signo = sig;
478		sf.sf_si.si_code = code;
479		sf.sf_si.si_addr = (void *)regs->tf_err;
480	} else {
481		/* Old FreeBSD-style arguments. */
482		sf.sf_siginfo = code;
483		sf.sf_addr = regs->tf_err;
484		sf.sf_ahu.sf_handler = catcher;
485	}
486	PROC_UNLOCK(p);
487
488	/*
489	 * If we're a vm86 process, we want to save the segment registers.
490	 * We also change eflags to be our emulated eflags, not the actual
491	 * eflags.
492	 */
493	if (regs->tf_eflags & PSL_VM) {
494		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
495		struct vm86_kernel *vm86 = &td->td_pcb->pcb_ext->ext_vm86;
496
497		sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
498		sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
499		sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
500		sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
501
502		if (vm86->vm86_has_vme == 0)
503			sf.sf_uc.uc_mcontext.mc_eflags =
504			    (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
505			    (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
506
507		/*
508		 * Clear PSL_NT to inhibit T_TSSFLT faults on return from
509		 * syscalls made by the signal handler.  This just avoids
510		 * wasting time for our lazy fixup of such faults.  PSL_NT
511		 * does nothing in vm86 mode, but vm86 programs can set it
512		 * almost legitimately in probes for old cpu types.
513		 */
514		tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
515	}
516
517	/*
518	 * Copy the sigframe out to the user's stack.
519	 */
520	if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
521#ifdef DEBUG
522		printf("process %ld has trashed its stack\n", (long)p->p_pid);
523#endif
524		PROC_LOCK(p);
525		sigexit(td, SIGILL);
526	}
527
528	regs->tf_esp = (int)sfp;
529	regs->tf_eip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
530	regs->tf_eflags &= ~PSL_T;
531	regs->tf_cs = _ucodesel;
532	regs->tf_ds = _udatasel;
533	regs->tf_es = _udatasel;
534	regs->tf_fs = _udatasel;
535	regs->tf_ss = _udatasel;
536	PROC_LOCK(p);
537}
538
539/*
540 * System call to cleanup state after a signal
541 * has been taken.  Reset signal mask and
542 * stack state from context left by sendsig (above).
543 * Return to previous pc and psl as specified by
544 * context left by sendsig. Check carefully to
545 * make sure that the user has not modified the
546 * state to gain improper privileges.
547 */
548int
549osigreturn(td, uap)
550	struct thread *td;
551	struct osigreturn_args /* {
552		struct osigcontext *sigcntxp;
553	} */ *uap;
554{
555#ifdef COMPAT_43
556	struct osigcontext sc;
557	struct trapframe *regs;
558	struct osigcontext *scp;
559	struct proc *p = td->td_proc;
560	int eflags, error;
561
562	regs = td->td_frame;
563	error = copyin(uap->sigcntxp, &sc, sizeof(sc));
564	if (error != 0)
565		return (error);
566	scp = &sc;
567	eflags = scp->sc_ps;
568	if (eflags & PSL_VM) {
569		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
570		struct vm86_kernel *vm86;
571
572		/*
573		 * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
574		 * set up the vm86 area, and we can't enter vm86 mode.
575		 */
576		if (td->td_pcb->pcb_ext == 0)
577			return (EINVAL);
578		vm86 = &td->td_pcb->pcb_ext->ext_vm86;
579		if (vm86->vm86_inited == 0)
580			return (EINVAL);
581
582		/* Go back to user mode if both flags are set. */
583		if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
584			trapsignal(p, SIGBUS, 0);
585
586		if (vm86->vm86_has_vme) {
587			eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
588			    (eflags & VME_USERCHANGE) | PSL_VM;
589		} else {
590			vm86->vm86_eflags = eflags;	/* save VIF, VIP */
591			eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
592			    (eflags & VM_USERCHANGE) | PSL_VM;
593		}
594		tf->tf_vm86_ds = scp->sc_ds;
595		tf->tf_vm86_es = scp->sc_es;
596		tf->tf_vm86_fs = scp->sc_fs;
597		tf->tf_vm86_gs = scp->sc_gs;
598		tf->tf_ds = _udatasel;
599		tf->tf_es = _udatasel;
600		tf->tf_fs = _udatasel;
601	} else {
602		/*
603		 * Don't allow users to change privileged or reserved flags.
604		 */
605		/*
606		 * XXX do allow users to change the privileged flag PSL_RF.
607		 * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
608		 * should sometimes set it there too.  tf_eflags is kept in
609		 * the signal context during signal handling and there is no
610		 * other place to remember it, so the PSL_RF bit may be
611		 * corrupted by the signal handler without us knowing.
612		 * Corruption of the PSL_RF bit at worst causes one more or
613		 * one less debugger trap, so allowing it is fairly harmless.
614		 */
615		if (!EFL_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
616	    		return (EINVAL);
617		}
618
619		/*
620		 * Don't allow users to load a valid privileged %cs.  Let the
621		 * hardware check for invalid selectors, excess privilege in
622		 * other selectors, invalid %eip's and invalid %esp's.
623		 */
624		if (!CS_SECURE(scp->sc_cs)) {
625			trapsignal(p, SIGBUS, T_PROTFLT);
626			return (EINVAL);
627		}
628		regs->tf_ds = scp->sc_ds;
629		regs->tf_es = scp->sc_es;
630		regs->tf_fs = scp->sc_fs;
631	}
632
633	/* Restore remaining registers. */
634	regs->tf_eax = scp->sc_eax;
635	regs->tf_ebx = scp->sc_ebx;
636	regs->tf_ecx = scp->sc_ecx;
637	regs->tf_edx = scp->sc_edx;
638	regs->tf_esi = scp->sc_esi;
639	regs->tf_edi = scp->sc_edi;
640	regs->tf_cs = scp->sc_cs;
641	regs->tf_ss = scp->sc_ss;
642	regs->tf_isp = scp->sc_isp;
643
644	PROC_LOCK(p);
645#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
646	if (scp->sc_onstack & 1)
647		p->p_sigstk.ss_flags |= SS_ONSTACK;
648	else
649		p->p_sigstk.ss_flags &= ~SS_ONSTACK;
650#endif
651
652	SIGSETOLD(p->p_sigmask, scp->sc_mask);
653	SIG_CANTMASK(p->p_sigmask);
654	PROC_UNLOCK(p);
655	regs->tf_ebp = scp->sc_fp;
656	regs->tf_esp = scp->sc_sp;
657	regs->tf_eip = scp->sc_pc;
658	regs->tf_eflags = eflags;
659	return (EJUSTRETURN);
660#else /* !COMPAT_43 */
661	return (ENOSYS);
662#endif /* COMPAT_43 */
663}
664
665int
666sigreturn(td, uap)
667	struct thread *td;
668	struct sigreturn_args /* {
669		const __ucontext *sigcntxp;
670	} */ *uap;
671{
672	ucontext_t uc;
673	struct proc *p = td->td_proc;
674	struct trapframe *regs;
675	const ucontext_t *ucp;
676	int cs, eflags, error;
677
678	error = copyin(uap->sigcntxp, &uc, sizeof(uc));
679	if (error != 0)
680		return (error);
681	ucp = &uc;
682	regs = td->td_frame;
683	eflags = ucp->uc_mcontext.mc_eflags;
684	if (eflags & PSL_VM) {
685		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
686		struct vm86_kernel *vm86;
687
688		/*
689		 * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
690		 * set up the vm86 area, and we can't enter vm86 mode.
691		 */
692		if (td->td_pcb->pcb_ext == 0)
693			return (EINVAL);
694		vm86 = &td->td_pcb->pcb_ext->ext_vm86;
695		if (vm86->vm86_inited == 0)
696			return (EINVAL);
697
698		/* Go back to user mode if both flags are set. */
699		if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
700			trapsignal(p, SIGBUS, 0);
701
702		if (vm86->vm86_has_vme) {
703			eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
704			    (eflags & VME_USERCHANGE) | PSL_VM;
705		} else {
706			vm86->vm86_eflags = eflags;	/* save VIF, VIP */
707			eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
708			    (eflags & VM_USERCHANGE) | PSL_VM;
709		}
710		bcopy(&ucp->uc_mcontext.mc_fs, tf, sizeof(struct trapframe));
711		tf->tf_eflags = eflags;
712		tf->tf_vm86_ds = tf->tf_ds;
713		tf->tf_vm86_es = tf->tf_es;
714		tf->tf_vm86_fs = tf->tf_fs;
715		tf->tf_vm86_gs = ucp->uc_mcontext.mc_gs;
716		tf->tf_ds = _udatasel;
717		tf->tf_es = _udatasel;
718		tf->tf_fs = _udatasel;
719	} else {
720		/*
721		 * Don't allow users to change privileged or reserved flags.
722		 */
723		/*
724		 * XXX do allow users to change the privileged flag PSL_RF.
725		 * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
726		 * should sometimes set it there too.  tf_eflags is kept in
727		 * the signal context during signal handling and there is no
728		 * other place to remember it, so the PSL_RF bit may be
729		 * corrupted by the signal handler without us knowing.
730		 * Corruption of the PSL_RF bit at worst causes one more or
731		 * one less debugger trap, so allowing it is fairly harmless.
732		 */
733		if (!EFL_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
734			printf("sigreturn: eflags = 0x%x\n", eflags);
735	    		return (EINVAL);
736		}
737
738		/*
739		 * Don't allow users to load a valid privileged %cs.  Let the
740		 * hardware check for invalid selectors, excess privilege in
741		 * other selectors, invalid %eip's and invalid %esp's.
742		 */
743		cs = ucp->uc_mcontext.mc_cs;
744		if (!CS_SECURE(cs)) {
745			printf("sigreturn: cs = 0x%x\n", cs);
746			trapsignal(p, SIGBUS, T_PROTFLT);
747			return (EINVAL);
748		}
749
750		bcopy(&ucp->uc_mcontext.mc_fs, regs, sizeof(*regs));
751	}
752
753	PROC_LOCK(p);
754#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
755	if (ucp->uc_mcontext.mc_onstack & 1)
756		p->p_sigstk.ss_flags |= SS_ONSTACK;
757	else
758		p->p_sigstk.ss_flags &= ~SS_ONSTACK;
759#endif
760
761	p->p_sigmask = ucp->uc_sigmask;
762	SIG_CANTMASK(p->p_sigmask);
763	PROC_UNLOCK(p);
764	return (EJUSTRETURN);
765}
766
767/*
768 * Machine dependent boot() routine
769 *
770 * I haven't seen anything to put here yet
771 * Possibly some stuff might be grafted back here from boot()
772 */
773void
774cpu_boot(int howto)
775{
776}
777
778/*
779 * Shutdown the CPU as much as possible
780 */
781void
782cpu_halt(void)
783{
784	for (;;)
785		__asm__ ("hlt");
786}
787
788/*
789 * Hook to idle the CPU when possible.  This currently only works in
790 * the !SMP case, as there is no clean way to ensure that a CPU will be
791 * woken when there is work available for it.
792 */
793static int	cpu_idle_hlt = 1;
794SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hlt, CTLFLAG_RW,
795    &cpu_idle_hlt, 0, "Idle loop HLT enable");
796
797/*
798 * Note that we have to be careful here to avoid a race between checking
799 * procrunnable() and actually halting.  If we don't do this, we may waste
800 * the time between calling hlt and the next interrupt even though there
801 * is a runnable process.
802 */
803void
804cpu_idle(void)
805{
806#ifndef SMP
807	if (cpu_idle_hlt) {
808		disable_intr();
809		if (procrunnable()) {
810			enable_intr();
811		} else {
812			/*
813			 * we must absolutely guarentee that hlt is the
814			 * absolute next instruction after sti or we
815			 * introduce a timing window.
816			 */
817			__asm __volatile("sti; hlt");
818		}
819	}
820#endif
821}
822
823/*
824 * Clear registers on exec
825 */
826void
827setregs(td, entry, stack, ps_strings)
828	struct thread *td;
829	u_long entry;
830	u_long stack;
831	u_long ps_strings;
832{
833	struct trapframe *regs = td->td_frame;
834	struct pcb *pcb = td->td_pcb;
835
836	if (td->td_proc->p_md.md_ldt)
837		user_ldt_free(td);
838
839	bzero((char *)regs, sizeof(struct trapframe));
840	regs->tf_eip = entry;
841	regs->tf_esp = stack;
842	regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
843	regs->tf_ss = _udatasel;
844	regs->tf_ds = _udatasel;
845	regs->tf_es = _udatasel;
846	regs->tf_fs = _udatasel;
847	regs->tf_cs = _ucodesel;
848
849	/* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
850	regs->tf_ebx = ps_strings;
851
852	/* reset %gs as well */
853	if (pcb == PCPU_GET(curpcb))
854		load_gs(_udatasel);
855	else
856		pcb->pcb_gs = _udatasel;
857
858        /*
859         * Reset the hardware debug registers if they were in use.
860         * They won't have any meaning for the newly exec'd process.
861         */
862        if (pcb->pcb_flags & PCB_DBREGS) {
863                pcb->pcb_dr0 = 0;
864                pcb->pcb_dr1 = 0;
865                pcb->pcb_dr2 = 0;
866                pcb->pcb_dr3 = 0;
867                pcb->pcb_dr6 = 0;
868                pcb->pcb_dr7 = 0;
869                if (pcb == PCPU_GET(curpcb)) {
870		        /*
871			 * Clear the debug registers on the running
872			 * CPU, otherwise they will end up affecting
873			 * the next process we switch to.
874			 */
875		        reset_dbregs();
876                }
877                pcb->pcb_flags &= ~PCB_DBREGS;
878        }
879
880	/*
881	 * Initialize the math emulator (if any) for the current process.
882	 * Actually, just clear the bit that says that the emulator has
883	 * been initialized.  Initialization is delayed until the process
884	 * traps to the emulator (if it is done at all) mainly because
885	 * emulators don't provide an entry point for initialization.
886	 */
887	td->td_pcb->pcb_flags &= ~FP_SOFTFP;
888
889	/*
890	 * Arrange to trap the next npx or `fwait' instruction (see npx.c
891	 * for why fwait must be trapped at least if there is an npx or an
892	 * emulator).  This is mainly to handle the case where npx0 is not
893	 * configured, since the npx routines normally set up the trap
894	 * otherwise.  It should be done only at boot time, but doing it
895	 * here allows modifying `npx_exists' for testing the emulator on
896	 * systems with an npx.
897	 */
898	load_cr0(rcr0() | CR0_MP | CR0_TS);
899
900#ifdef DEV_NPX
901	/* Initialize the npx (if any) for the current process. */
902	npxinit(__INITIAL_NPXCW__);
903#endif
904
905	/*
906	 * XXX - Linux emulator
907	 * Make sure sure edx is 0x0 on entry. Linux binaries depend
908	 * on it.
909	 */
910	td->td_retval[1] = 0;
911}
912
913void
914cpu_setregs(void)
915{
916	unsigned int cr0;
917
918	cr0 = rcr0();
919#ifdef SMP
920	cr0 |= CR0_NE;			/* Done by npxinit() */
921#endif
922	cr0 |= CR0_MP | CR0_TS;		/* Done at every execve() too. */
923#ifndef I386_CPU
924	cr0 |= CR0_WP | CR0_AM;
925#endif
926	load_cr0(cr0);
927	load_gs(_udatasel);
928}
929
930static int
931sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
932{
933	int error;
934	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
935		req);
936	if (!error && req->newptr)
937		resettodr();
938	return (error);
939}
940
941SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
942	&adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
943
944SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
945	CTLFLAG_RW, &disable_rtc_set, 0, "");
946
947SYSCTL_STRUCT(_machdep, CPU_BOOTINFO, bootinfo,
948	CTLFLAG_RD, &bootinfo, bootinfo, "");
949
950SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
951	CTLFLAG_RW, &wall_cmos_clock, 0, "");
952
953u_long bootdev;		/* not a dev_t - encoding is different */
954SYSCTL_ULONG(_machdep, OID_AUTO, guessed_bootdev,
955	CTLFLAG_RD, &bootdev, 0, "Maybe the Boot device (not in dev_t format)");
956
957/*
958 * Initialize 386 and configure to run kernel
959 */
960
961/*
962 * Initialize segments & interrupt table
963 */
964
965int _default_ldt;
966union descriptor gdt[NGDT * MAXCPU];	/* global descriptor table */
967static struct gate_descriptor idt0[NIDT];
968struct gate_descriptor *idt = &idt0[0];	/* interrupt descriptor table */
969union descriptor ldt[NLDT];		/* local descriptor table */
970#ifdef SMP
971/* table descriptors - used to load tables by microp */
972struct region_descriptor r_gdt, r_idt;
973#endif
974
975int private_tss;			/* flag indicating private tss */
976
977#if defined(I586_CPU) && !defined(NO_F00F_HACK)
978extern int has_f00f_bug;
979#endif
980
981static struct i386tss dblfault_tss;
982static char dblfault_stack[PAGE_SIZE];
983
984extern  struct user	*proc0uarea;
985extern  vm_offset_t	proc0kstack;
986
987
988/* software prototypes -- in more palatable form */
989struct soft_segment_descriptor gdt_segs[] = {
990/* GNULL_SEL	0 Null Descriptor */
991{	0x0,			/* segment base address  */
992	0x0,			/* length */
993	0,			/* segment type */
994	0,			/* segment descriptor priority level */
995	0,			/* segment descriptor present */
996	0, 0,
997	0,			/* default 32 vs 16 bit size */
998	0  			/* limit granularity (byte/page units)*/ },
999/* GCODE_SEL	1 Code Descriptor for kernel */
1000{	0x0,			/* segment base address  */
1001	0xfffff,		/* length - all address space */
1002	SDT_MEMERA,		/* segment type */
1003	0,			/* segment descriptor priority level */
1004	1,			/* segment descriptor present */
1005	0, 0,
1006	1,			/* default 32 vs 16 bit size */
1007	1  			/* limit granularity (byte/page units)*/ },
1008/* GDATA_SEL	2 Data Descriptor for kernel */
1009{	0x0,			/* segment base address  */
1010	0xfffff,		/* length - all address space */
1011	SDT_MEMRWA,		/* segment type */
1012	0,			/* segment descriptor priority level */
1013	1,			/* segment descriptor present */
1014	0, 0,
1015	1,			/* default 32 vs 16 bit size */
1016	1  			/* limit granularity (byte/page units)*/ },
1017/* GPRIV_SEL	3 SMP Per-Processor Private Data Descriptor */
1018{	0x0,			/* segment base address  */
1019	0xfffff,		/* length - all address space */
1020	SDT_MEMRWA,		/* segment type */
1021	0,			/* segment descriptor priority level */
1022	1,			/* segment descriptor present */
1023	0, 0,
1024	1,			/* default 32 vs 16 bit size */
1025	1  			/* limit granularity (byte/page units)*/ },
1026/* GPROC0_SEL	4 Proc 0 Tss Descriptor */
1027{
1028	0x0,			/* segment base address */
1029	sizeof(struct i386tss)-1,/* length - all address space */
1030	SDT_SYS386TSS,		/* segment type */
1031	0,			/* segment descriptor priority level */
1032	1,			/* segment descriptor present */
1033	0, 0,
1034	0,			/* unused - default 32 vs 16 bit size */
1035	0  			/* limit granularity (byte/page units)*/ },
1036/* GLDT_SEL	5 LDT Descriptor */
1037{	(int) ldt,		/* segment base address  */
1038	sizeof(ldt)-1,		/* length - all address space */
1039	SDT_SYSLDT,		/* segment type */
1040	SEL_UPL,		/* segment descriptor priority level */
1041	1,			/* segment descriptor present */
1042	0, 0,
1043	0,			/* unused - default 32 vs 16 bit size */
1044	0  			/* limit granularity (byte/page units)*/ },
1045/* GUSERLDT_SEL	6 User LDT Descriptor per process */
1046{	(int) ldt,		/* segment base address  */
1047	(512 * sizeof(union descriptor)-1),		/* length */
1048	SDT_SYSLDT,		/* segment type */
1049	0,			/* segment descriptor priority level */
1050	1,			/* segment descriptor present */
1051	0, 0,
1052	0,			/* unused - default 32 vs 16 bit size */
1053	0  			/* limit granularity (byte/page units)*/ },
1054/* GTGATE_SEL	7 Null Descriptor - Placeholder */
1055{	0x0,			/* segment base address  */
1056	0x0,			/* length - all address space */
1057	0,			/* segment type */
1058	0,			/* segment descriptor priority level */
1059	0,			/* segment descriptor present */
1060	0, 0,
1061	0,			/* default 32 vs 16 bit size */
1062	0  			/* limit granularity (byte/page units)*/ },
1063/* GBIOSLOWMEM_SEL 8 BIOS access to realmode segment 0x40, must be #8 in GDT */
1064{	0x400,			/* segment base address */
1065	0xfffff,		/* length */
1066	SDT_MEMRWA,		/* segment type */
1067	0,			/* segment descriptor priority level */
1068	1,			/* segment descriptor present */
1069	0, 0,
1070	1,			/* default 32 vs 16 bit size */
1071	1  			/* limit granularity (byte/page units)*/ },
1072/* GPANIC_SEL	9 Panic Tss Descriptor */
1073{	(int) &dblfault_tss,	/* segment base address  */
1074	sizeof(struct i386tss)-1,/* length - all address space */
1075	SDT_SYS386TSS,		/* segment type */
1076	0,			/* segment descriptor priority level */
1077	1,			/* segment descriptor present */
1078	0, 0,
1079	0,			/* unused - default 32 vs 16 bit size */
1080	0  			/* limit granularity (byte/page units)*/ },
1081/* GBIOSCODE32_SEL 10 BIOS 32-bit interface (32bit Code) */
1082{	0,			/* segment base address (overwritten)  */
1083	0xfffff,		/* length */
1084	SDT_MEMERA,		/* segment type */
1085	0,			/* segment descriptor priority level */
1086	1,			/* segment descriptor present */
1087	0, 0,
1088	0,			/* default 32 vs 16 bit size */
1089	1  			/* limit granularity (byte/page units)*/ },
1090/* GBIOSCODE16_SEL 11 BIOS 32-bit interface (16bit Code) */
1091{	0,			/* segment base address (overwritten)  */
1092	0xfffff,		/* length */
1093	SDT_MEMERA,		/* segment type */
1094	0,			/* segment descriptor priority level */
1095	1,			/* segment descriptor present */
1096	0, 0,
1097	0,			/* default 32 vs 16 bit size */
1098	1  			/* limit granularity (byte/page units)*/ },
1099/* GBIOSDATA_SEL 12 BIOS 32-bit interface (Data) */
1100{	0,			/* segment base address (overwritten) */
1101	0xfffff,		/* length */
1102	SDT_MEMRWA,		/* segment type */
1103	0,			/* segment descriptor priority level */
1104	1,			/* segment descriptor present */
1105	0, 0,
1106	1,			/* default 32 vs 16 bit size */
1107	1  			/* limit granularity (byte/page units)*/ },
1108/* GBIOSUTIL_SEL 13 BIOS 16-bit interface (Utility) */
1109{	0,			/* segment base address (overwritten) */
1110	0xfffff,		/* length */
1111	SDT_MEMRWA,		/* segment type */
1112	0,			/* segment descriptor priority level */
1113	1,			/* segment descriptor present */
1114	0, 0,
1115	0,			/* default 32 vs 16 bit size */
1116	1  			/* limit granularity (byte/page units)*/ },
1117/* GBIOSARGS_SEL 14 BIOS 16-bit interface (Arguments) */
1118{	0,			/* segment base address (overwritten) */
1119	0xfffff,		/* length */
1120	SDT_MEMRWA,		/* segment type */
1121	0,			/* segment descriptor priority level */
1122	1,			/* segment descriptor present */
1123	0, 0,
1124	0,			/* default 32 vs 16 bit size */
1125	1  			/* limit granularity (byte/page units)*/ },
1126};
1127
1128static struct soft_segment_descriptor ldt_segs[] = {
1129	/* Null Descriptor - overwritten by call gate */
1130{	0x0,			/* segment base address  */
1131	0x0,			/* length - all address space */
1132	0,			/* segment type */
1133	0,			/* segment descriptor priority level */
1134	0,			/* segment descriptor present */
1135	0, 0,
1136	0,			/* default 32 vs 16 bit size */
1137	0  			/* limit granularity (byte/page units)*/ },
1138	/* Null Descriptor - overwritten by call gate */
1139{	0x0,			/* segment base address  */
1140	0x0,			/* length - all address space */
1141	0,			/* segment type */
1142	0,			/* segment descriptor priority level */
1143	0,			/* segment descriptor present */
1144	0, 0,
1145	0,			/* default 32 vs 16 bit size */
1146	0  			/* limit granularity (byte/page units)*/ },
1147	/* Null Descriptor - overwritten by call gate */
1148{	0x0,			/* segment base address  */
1149	0x0,			/* length - all address space */
1150	0,			/* segment type */
1151	0,			/* segment descriptor priority level */
1152	0,			/* segment descriptor present */
1153	0, 0,
1154	0,			/* default 32 vs 16 bit size */
1155	0  			/* limit granularity (byte/page units)*/ },
1156	/* Code Descriptor for user */
1157{	0x0,			/* segment base address  */
1158	0xfffff,		/* length - all address space */
1159	SDT_MEMERA,		/* segment type */
1160	SEL_UPL,		/* segment descriptor priority level */
1161	1,			/* segment descriptor present */
1162	0, 0,
1163	1,			/* default 32 vs 16 bit size */
1164	1  			/* limit granularity (byte/page units)*/ },
1165	/* Null Descriptor - overwritten by call gate */
1166{	0x0,			/* segment base address  */
1167	0x0,			/* length - all address space */
1168	0,			/* segment type */
1169	0,			/* segment descriptor priority level */
1170	0,			/* segment descriptor present */
1171	0, 0,
1172	0,			/* default 32 vs 16 bit size */
1173	0  			/* limit granularity (byte/page units)*/ },
1174	/* Data Descriptor for user */
1175{	0x0,			/* segment base address  */
1176	0xfffff,		/* length - all address space */
1177	SDT_MEMRWA,		/* segment type */
1178	SEL_UPL,		/* segment descriptor priority level */
1179	1,			/* segment descriptor present */
1180	0, 0,
1181	1,			/* default 32 vs 16 bit size */
1182	1  			/* limit granularity (byte/page units)*/ },
1183};
1184
1185void
1186setidt(idx, func, typ, dpl, selec)
1187	int idx;
1188	inthand_t *func;
1189	int typ;
1190	int dpl;
1191	int selec;
1192{
1193	struct gate_descriptor *ip;
1194
1195	ip = idt + idx;
1196	ip->gd_looffset = (int)func;
1197	ip->gd_selector = selec;
1198	ip->gd_stkcpy = 0;
1199	ip->gd_xx = 0;
1200	ip->gd_type = typ;
1201	ip->gd_dpl = dpl;
1202	ip->gd_p = 1;
1203	ip->gd_hioffset = ((int)func)>>16 ;
1204}
1205
1206#define	IDTVEC(name)	__CONCAT(X,name)
1207
1208extern inthand_t
1209	IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1210	IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1211	IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1212	IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1213	IDTVEC(xmm), IDTVEC(lcall_syscall), IDTVEC(int0x80_syscall);
1214
1215void
1216sdtossd(sd, ssd)
1217	struct segment_descriptor *sd;
1218	struct soft_segment_descriptor *ssd;
1219{
1220	ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1221	ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1222	ssd->ssd_type  = sd->sd_type;
1223	ssd->ssd_dpl   = sd->sd_dpl;
1224	ssd->ssd_p     = sd->sd_p;
1225	ssd->ssd_def32 = sd->sd_def32;
1226	ssd->ssd_gran  = sd->sd_gran;
1227}
1228
1229#define PHYSMAP_SIZE	(2 * 8)
1230
1231/*
1232 * Populate the (physmap) array with base/bound pairs describing the
1233 * available physical memory in the system, then test this memory and
1234 * build the phys_avail array describing the actually-available memory.
1235 *
1236 * If we cannot accurately determine the physical memory map, then use
1237 * value from the 0xE801 call, and failing that, the RTC.
1238 *
1239 * Total memory size may be set by the kernel environment variable
1240 * hw.physmem or the compile-time define MAXMEM.
1241 */
1242static void
1243getmemsize(int first)
1244{
1245	int i, physmap_idx, pa_indx;
1246	u_int basemem, extmem;
1247	struct vm86frame vmf;
1248	struct vm86context vmc;
1249	vm_offset_t pa, physmap[PHYSMAP_SIZE];
1250	pt_entry_t *pte;
1251	const char *cp;
1252	struct bios_smap *smap;
1253
1254	bzero(&vmf, sizeof(struct vm86frame));
1255	bzero(physmap, sizeof(physmap));
1256
1257	/*
1258	 * Perform "base memory" related probes & setup
1259	 */
1260	vm86_intcall(0x12, &vmf);
1261	basemem = vmf.vmf_ax;
1262	if (basemem > 640) {
1263		printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
1264			basemem);
1265		basemem = 640;
1266	}
1267
1268	/*
1269	 * XXX if biosbasemem is now < 640, there is a `hole'
1270	 * between the end of base memory and the start of
1271	 * ISA memory.  The hole may be empty or it may
1272	 * contain BIOS code or data.  Map it read/write so
1273	 * that the BIOS can write to it.  (Memory from 0 to
1274	 * the physical end of the kernel is mapped read-only
1275	 * to begin with and then parts of it are remapped.
1276	 * The parts that aren't remapped form holes that
1277	 * remain read-only and are unused by the kernel.
1278	 * The base memory area is below the physical end of
1279	 * the kernel and right now forms a read-only hole.
1280	 * The part of it from PAGE_SIZE to
1281	 * (trunc_page(biosbasemem * 1024) - 1) will be
1282	 * remapped and used by the kernel later.)
1283	 *
1284	 * This code is similar to the code used in
1285	 * pmap_mapdev, but since no memory needs to be
1286	 * allocated we simply change the mapping.
1287	 */
1288	for (pa = trunc_page(basemem * 1024);
1289	     pa < ISA_HOLE_START; pa += PAGE_SIZE) {
1290		pte = vtopte(pa + KERNBASE);
1291		*pte = pa | PG_RW | PG_V;
1292	}
1293
1294	/*
1295	 * if basemem != 640, map pages r/w into vm86 page table so
1296	 * that the bios can scribble on it.
1297	 */
1298	pte = (pt_entry_t *)vm86paddr;
1299	for (i = basemem / 4; i < 160; i++)
1300		pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
1301
1302	/*
1303	 * map page 1 R/W into the kernel page table so we can use it
1304	 * as a buffer.  The kernel will unmap this page later.
1305	 */
1306	pte = vtopte(KERNBASE + (1 << PAGE_SHIFT));
1307	*pte = (1 << PAGE_SHIFT) | PG_RW | PG_V;
1308
1309	/*
1310	 * get memory map with INT 15:E820
1311	 */
1312	vmc.npages = 0;
1313	smap = (void *)vm86_addpage(&vmc, 1, KERNBASE + (1 << PAGE_SHIFT));
1314	vm86_getptr(&vmc, (vm_offset_t)smap, &vmf.vmf_es, &vmf.vmf_di);
1315
1316	physmap_idx = 0;
1317	vmf.vmf_ebx = 0;
1318	do {
1319		vmf.vmf_eax = 0xE820;
1320		vmf.vmf_edx = SMAP_SIG;
1321		vmf.vmf_ecx = sizeof(struct bios_smap);
1322		i = vm86_datacall(0x15, &vmf, &vmc);
1323		if (i || vmf.vmf_eax != SMAP_SIG)
1324			break;
1325		if (boothowto & RB_VERBOSE)
1326			printf("SMAP type=%02x base=%08x %08x len=%08x %08x\n",
1327				smap->type,
1328				*(u_int32_t *)((char *)&smap->base + 4),
1329				(u_int32_t)smap->base,
1330				*(u_int32_t *)((char *)&smap->length + 4),
1331				(u_int32_t)smap->length);
1332
1333		if (smap->type != 0x01)
1334			goto next_run;
1335
1336		if (smap->length == 0)
1337			goto next_run;
1338
1339		if (smap->base >= 0xffffffff) {
1340			printf("%uK of memory above 4GB ignored\n",
1341			    (u_int)(smap->length / 1024));
1342			goto next_run;
1343		}
1344
1345		for (i = 0; i <= physmap_idx; i += 2) {
1346			if (smap->base < physmap[i + 1]) {
1347				if (boothowto & RB_VERBOSE)
1348					printf(
1349	"Overlapping or non-montonic memory region, ignoring second region\n");
1350				goto next_run;
1351			}
1352		}
1353
1354		if (smap->base == physmap[physmap_idx + 1]) {
1355			physmap[physmap_idx + 1] += smap->length;
1356			goto next_run;
1357		}
1358
1359		physmap_idx += 2;
1360		if (physmap_idx == PHYSMAP_SIZE) {
1361			printf(
1362		"Too many segments in the physical address map, giving up\n");
1363			break;
1364		}
1365		physmap[physmap_idx] = smap->base;
1366		physmap[physmap_idx + 1] = smap->base + smap->length;
1367next_run:
1368	} while (vmf.vmf_ebx != 0);
1369
1370	if (physmap[1] != 0)
1371		goto physmap_done;
1372
1373	/*
1374	 * If we failed above, try memory map with INT 15:E801
1375	 */
1376	vmf.vmf_ax = 0xE801;
1377	if (vm86_intcall(0x15, &vmf) == 0) {
1378		extmem = vmf.vmf_cx + vmf.vmf_dx * 64;
1379	} else {
1380#if 0
1381		vmf.vmf_ah = 0x88;
1382		vm86_intcall(0x15, &vmf);
1383		extmem = vmf.vmf_ax;
1384#else
1385		/*
1386		 * Prefer the RTC value for extended memory.
1387		 */
1388		extmem = rtcin(RTC_EXTLO) + (rtcin(RTC_EXTHI) << 8);
1389#endif
1390	}
1391
1392	/*
1393	 * Special hack for chipsets that still remap the 384k hole when
1394	 * there's 16MB of memory - this really confuses people that
1395	 * are trying to use bus mastering ISA controllers with the
1396	 * "16MB limit"; they only have 16MB, but the remapping puts
1397	 * them beyond the limit.
1398	 *
1399	 * If extended memory is between 15-16MB (16-17MB phys address range),
1400	 *	chop it to 15MB.
1401	 */
1402	if ((extmem > 15 * 1024) && (extmem < 16 * 1024))
1403		extmem = 15 * 1024;
1404
1405	physmap[0] = 0;
1406	physmap[1] = basemem * 1024;
1407	physmap_idx = 2;
1408	physmap[physmap_idx] = 0x100000;
1409	physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
1410
1411physmap_done:
1412	/*
1413	 * Now, physmap contains a map of physical memory.
1414	 */
1415
1416#ifdef SMP
1417	/* make hole for AP bootstrap code */
1418	physmap[1] = mp_bootaddress(physmap[1] / 1024);
1419
1420	/* look for the MP hardware - needed for apic addresses */
1421	i386_mp_probe();
1422#endif
1423
1424	/*
1425	 * Maxmem isn't the "maximum memory", it's one larger than the
1426	 * highest page of the physical address space.  It should be
1427	 * called something like "Maxphyspage".  We may adjust this
1428	 * based on ``hw.physmem'' and the results of the memory test.
1429	 */
1430	Maxmem = atop(physmap[physmap_idx + 1]);
1431
1432#ifdef MAXMEM
1433	Maxmem = MAXMEM / 4;
1434#endif
1435
1436	/*
1437	 * hw.physmem is a size in bytes; we also allow k, m, and g suffixes
1438	 * for the appropriate modifiers.  This overrides MAXMEM.
1439	 */
1440	if ((cp = getenv("hw.physmem")) != NULL) {
1441		u_int64_t AllowMem, sanity;
1442		char *ep;
1443
1444		sanity = AllowMem = strtouq(cp, &ep, 0);
1445		if ((ep != cp) && (*ep != 0)) {
1446			switch(*ep) {
1447			case 'g':
1448			case 'G':
1449				AllowMem <<= 10;
1450			case 'm':
1451			case 'M':
1452				AllowMem <<= 10;
1453			case 'k':
1454			case 'K':
1455				AllowMem <<= 10;
1456				break;
1457			default:
1458				AllowMem = sanity = 0;
1459			}
1460			if (AllowMem < sanity)
1461				AllowMem = 0;
1462		}
1463		if (AllowMem == 0)
1464			printf("Ignoring invalid memory size of '%s'\n", cp);
1465		else
1466			Maxmem = atop(AllowMem);
1467	}
1468
1469	if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1470	    (boothowto & RB_VERBOSE))
1471		printf("Physical memory use set to %uK\n", Maxmem * 4);
1472
1473	/*
1474	 * If Maxmem has been increased beyond what the system has detected,
1475	 * extend the last memory segment to the new limit.
1476	 */
1477	if (atop(physmap[physmap_idx + 1]) < Maxmem)
1478		physmap[physmap_idx + 1] = ptoa(Maxmem);
1479
1480	/* call pmap initialization to make new kernel address space */
1481	pmap_bootstrap(first, 0);
1482
1483	/*
1484	 * Size up each available chunk of physical memory.
1485	 */
1486	physmap[0] = PAGE_SIZE;		/* mask off page 0 */
1487	pa_indx = 0;
1488	phys_avail[pa_indx++] = physmap[0];
1489	phys_avail[pa_indx] = physmap[0];
1490#if 0
1491	pte = vtopte(KERNBASE);
1492#else
1493	pte = CMAP1;
1494#endif
1495
1496	/*
1497	 * physmap is in bytes, so when converting to page boundaries,
1498	 * round up the start address and round down the end address.
1499	 */
1500	for (i = 0; i <= physmap_idx; i += 2) {
1501		vm_offset_t end;
1502
1503		end = ptoa(Maxmem);
1504		if (physmap[i + 1] < end)
1505			end = trunc_page(physmap[i + 1]);
1506		for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1507			int tmp, page_bad;
1508#if 0
1509			int *ptr = 0;
1510#else
1511			int *ptr = (int *)CADDR1;
1512#endif
1513
1514			/*
1515			 * block out kernel memory as not available.
1516			 */
1517			if (pa >= 0x100000 && pa < first)
1518				continue;
1519
1520			page_bad = FALSE;
1521
1522			/*
1523			 * map page into kernel: valid, read/write,non-cacheable
1524			 */
1525			*pte = pa | PG_V | PG_RW | PG_N;
1526			invltlb();
1527
1528			tmp = *(int *)ptr;
1529			/*
1530			 * Test for alternating 1's and 0's
1531			 */
1532			*(volatile int *)ptr = 0xaaaaaaaa;
1533			if (*(volatile int *)ptr != 0xaaaaaaaa) {
1534				page_bad = TRUE;
1535			}
1536			/*
1537			 * Test for alternating 0's and 1's
1538			 */
1539			*(volatile int *)ptr = 0x55555555;
1540			if (*(volatile int *)ptr != 0x55555555) {
1541			page_bad = TRUE;
1542			}
1543			/*
1544			 * Test for all 1's
1545			 */
1546			*(volatile int *)ptr = 0xffffffff;
1547			if (*(volatile int *)ptr != 0xffffffff) {
1548				page_bad = TRUE;
1549			}
1550			/*
1551			 * Test for all 0's
1552			 */
1553			*(volatile int *)ptr = 0x0;
1554			if (*(volatile int *)ptr != 0x0) {
1555				page_bad = TRUE;
1556			}
1557			/*
1558			 * Restore original value.
1559			 */
1560			*(int *)ptr = tmp;
1561
1562			/*
1563			 * Adjust array of valid/good pages.
1564			 */
1565			if (page_bad == TRUE) {
1566				continue;
1567			}
1568			/*
1569			 * If this good page is a continuation of the
1570			 * previous set of good pages, then just increase
1571			 * the end pointer. Otherwise start a new chunk.
1572			 * Note that "end" points one higher than end,
1573			 * making the range >= start and < end.
1574			 * If we're also doing a speculative memory
1575			 * test and we at or past the end, bump up Maxmem
1576			 * so that we keep going. The first bad page
1577			 * will terminate the loop.
1578			 */
1579			if (phys_avail[pa_indx] == pa) {
1580				phys_avail[pa_indx] += PAGE_SIZE;
1581			} else {
1582				pa_indx++;
1583				if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1584					printf(
1585		"Too many holes in the physical address space, giving up\n");
1586					pa_indx--;
1587					break;
1588				}
1589				phys_avail[pa_indx++] = pa;	/* start */
1590				phys_avail[pa_indx] = pa + PAGE_SIZE;	/* end */
1591			}
1592			physmem++;
1593		}
1594	}
1595	*pte = 0;
1596	invltlb();
1597
1598	/*
1599	 * XXX
1600	 * The last chunk must contain at least one page plus the message
1601	 * buffer to avoid complicating other code (message buffer address
1602	 * calculation, etc.).
1603	 */
1604	while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1605	    round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
1606		physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1607		phys_avail[pa_indx--] = 0;
1608		phys_avail[pa_indx--] = 0;
1609	}
1610
1611	Maxmem = atop(phys_avail[pa_indx]);
1612
1613	/* Trim off space for the message buffer. */
1614	phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
1615
1616	avail_end = phys_avail[pa_indx];
1617}
1618
1619void
1620init386(first)
1621	int first;
1622{
1623	struct gate_descriptor *gdp;
1624	int gsel_tss, metadata_missing, off, x;
1625#ifndef SMP
1626	/* table descriptors - used to load tables by microp */
1627	struct region_descriptor r_gdt, r_idt;
1628#endif
1629	struct pcpu *pc;
1630
1631	proc0.p_uarea = proc0uarea;
1632	thread0.td_kstack = proc0kstack;
1633	thread0.td_pcb = (struct pcb *)
1634	   (thread0.td_kstack + KSTACK_PAGES * PAGE_SIZE) - 1;
1635	atdevbase = ISA_HOLE_START + KERNBASE;
1636
1637	/*
1638 	 * This may be done better later if it gets more high level
1639 	 * components in it. If so just link td->td_proc here.
1640	 */
1641	proc_linkup(&proc0, &proc0.p_ksegrp, &proc0.p_kse, &thread0);
1642
1643	metadata_missing = 0;
1644	if (bootinfo.bi_modulep) {
1645		preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
1646		preload_bootstrap_relocate(KERNBASE);
1647	} else {
1648		metadata_missing = 1;
1649	}
1650	if (envmode == 1)
1651		kern_envp = static_env;
1652	else if (bootinfo.bi_envp)
1653		kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
1654
1655	/* Init basic tunables, hz etc */
1656	init_param1();
1657
1658	/*
1659	 * make gdt memory segments, the code segment goes up to end of the
1660	 * page with etext in it, the data segment goes to the end of
1661	 * the address space
1662	 */
1663	/*
1664	 * XXX text protection is temporarily (?) disabled.  The limit was
1665	 * i386_btop(round_page(etext)) - 1.
1666	 */
1667	gdt_segs[GCODE_SEL].ssd_limit = atop(0 - 1);
1668	gdt_segs[GDATA_SEL].ssd_limit = atop(0 - 1);
1669#ifdef SMP
1670	pc = &SMP_prvspace[0].pcpu;
1671	gdt_segs[GPRIV_SEL].ssd_limit =
1672		atop(sizeof(struct privatespace) - 1);
1673#else
1674	pc = &__pcpu;
1675	gdt_segs[GPRIV_SEL].ssd_limit =
1676		atop(sizeof(struct pcpu) - 1);
1677#endif
1678	gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
1679	gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
1680
1681	for (x = 0; x < NGDT; x++) {
1682#ifdef BDE_DEBUGGER
1683		/* avoid overwriting db entries with APM ones */
1684		if (x >= GAPMCODE32_SEL && x <= GAPMDATA_SEL)
1685			continue;
1686#endif
1687		ssdtosd(&gdt_segs[x], &gdt[x].sd);
1688	}
1689
1690	r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1691	r_gdt.rd_base =  (int) gdt;
1692	lgdt(&r_gdt);
1693
1694	pcpu_init(pc, 0, sizeof(struct pcpu));
1695	PCPU_SET(prvspace, pc);
1696
1697	/* setup curproc so that mutexes work */
1698	PCPU_SET(curthread, &thread0);
1699
1700	LIST_INIT(&thread0.td_contested);
1701
1702	/*
1703	 * Initialize mutexes.
1704	 *
1705	 * icu_lock: in order to allow an interrupt to occur in a critical
1706	 * 	     section, to set pcpu->ipending (etc...) properly, we
1707	 *	     must be able to get the icu lock, so it can't be
1708	 *	     under witness.
1709	 */
1710	mtx_init(&Giant, "Giant", MTX_DEF | MTX_RECURSE);
1711	mtx_init(&sched_lock, "sched lock", MTX_SPIN | MTX_RECURSE);
1712	mtx_init(&proc0.p_mtx, "process lock", MTX_DEF|MTX_DUPOK);
1713	mtx_init(&clock_lock, "clk", MTX_SPIN | MTX_RECURSE);
1714	mtx_init(&icu_lock, "icu", MTX_SPIN | MTX_NOWITNESS);
1715	mtx_lock(&Giant);
1716
1717	/* make ldt memory segments */
1718	/*
1719	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  And it
1720	 * should be spelled ...MAX_USER...
1721	 */
1722	ldt_segs[LUCODE_SEL].ssd_limit = atop(VM_MAXUSER_ADDRESS - 1);
1723	ldt_segs[LUDATA_SEL].ssd_limit = atop(VM_MAXUSER_ADDRESS - 1);
1724	for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
1725		ssdtosd(&ldt_segs[x], &ldt[x].sd);
1726
1727	_default_ldt = GSEL(GLDT_SEL, SEL_KPL);
1728	lldt(_default_ldt);
1729	PCPU_SET(currentldt, _default_ldt);
1730
1731	/* exceptions */
1732	for (x = 0; x < NIDT; x++)
1733		setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL,
1734		    GSEL(GCODE_SEL, SEL_KPL));
1735	setidt(0, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL,
1736	    GSEL(GCODE_SEL, SEL_KPL));
1737	setidt(1, &IDTVEC(dbg),  SDT_SYS386IGT, SEL_KPL,
1738	    GSEL(GCODE_SEL, SEL_KPL));
1739	setidt(2, &IDTVEC(nmi),  SDT_SYS386TGT, SEL_KPL,
1740	    GSEL(GCODE_SEL, SEL_KPL));
1741 	setidt(3, &IDTVEC(bpt),  SDT_SYS386IGT, SEL_UPL,
1742	    GSEL(GCODE_SEL, SEL_KPL));
1743	setidt(4, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL,
1744	    GSEL(GCODE_SEL, SEL_KPL));
1745	setidt(5, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL,
1746	    GSEL(GCODE_SEL, SEL_KPL));
1747	setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL,
1748	    GSEL(GCODE_SEL, SEL_KPL));
1749	setidt(7, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL
1750	    , GSEL(GCODE_SEL, SEL_KPL));
1751	setidt(8, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
1752	setidt(9, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL,
1753	    GSEL(GCODE_SEL, SEL_KPL));
1754	setidt(10, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL,
1755	    GSEL(GCODE_SEL, SEL_KPL));
1756	setidt(11, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL,
1757	    GSEL(GCODE_SEL, SEL_KPL));
1758	setidt(12, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL,
1759	    GSEL(GCODE_SEL, SEL_KPL));
1760	setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL,
1761	    GSEL(GCODE_SEL, SEL_KPL));
1762	setidt(14, &IDTVEC(page),  SDT_SYS386IGT, SEL_KPL,
1763	    GSEL(GCODE_SEL, SEL_KPL));
1764	setidt(15, &IDTVEC(rsvd),  SDT_SYS386TGT, SEL_KPL,
1765	    GSEL(GCODE_SEL, SEL_KPL));
1766	setidt(16, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL,
1767	    GSEL(GCODE_SEL, SEL_KPL));
1768	setidt(17, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL,
1769	    GSEL(GCODE_SEL, SEL_KPL));
1770	setidt(18, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL,
1771	    GSEL(GCODE_SEL, SEL_KPL));
1772	setidt(19, &IDTVEC(xmm), SDT_SYS386TGT, SEL_KPL,
1773	    GSEL(GCODE_SEL, SEL_KPL));
1774 	setidt(0x80, &IDTVEC(int0x80_syscall), SDT_SYS386TGT, SEL_UPL,
1775	    GSEL(GCODE_SEL, SEL_KPL));
1776
1777	r_idt.rd_limit = sizeof(idt0) - 1;
1778	r_idt.rd_base = (int) idt;
1779	lidt(&r_idt);
1780
1781	/*
1782	 * Initialize the console before we print anything out.
1783	 */
1784	cninit();
1785
1786	if (metadata_missing)
1787		printf("WARNING: loader(8) metadata is missing!\n");
1788
1789#ifdef DEV_ISA
1790	isa_defaultirq();
1791#endif
1792
1793#ifdef DDB
1794	kdb_init();
1795	if (boothowto & RB_KDB)
1796		Debugger("Boot flags requested debugger");
1797#endif
1798
1799	finishidentcpu();	/* Final stage of CPU initialization */
1800	setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL,
1801	    GSEL(GCODE_SEL, SEL_KPL));
1802	setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL,
1803	    GSEL(GCODE_SEL, SEL_KPL));
1804	initializecpu();	/* Initialize CPU registers */
1805
1806	/* make an initial tss so cpu can get interrupt stack on syscall! */
1807	/* Note: -16 is so we can grow the trapframe if we came from vm86 */
1808	PCPU_SET(common_tss.tss_esp0, thread0.td_kstack +
1809	    KSTACK_PAGES * PAGE_SIZE - sizeof(struct pcb) - 16);
1810	PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
1811	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1812	private_tss = 0;
1813	PCPU_SET(tss_gdt, &gdt[GPROC0_SEL].sd);
1814	PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
1815	PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
1816	ltr(gsel_tss);
1817
1818	dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
1819	    dblfault_tss.tss_esp2 = (int)&dblfault_stack[sizeof(dblfault_stack)];
1820	dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
1821	    dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
1822	dblfault_tss.tss_cr3 = (int)IdlePTD;
1823	dblfault_tss.tss_eip = (int)dblfault_handler;
1824	dblfault_tss.tss_eflags = PSL_KERNEL;
1825	dblfault_tss.tss_ds = dblfault_tss.tss_es =
1826	    dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
1827	dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
1828	dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
1829	dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
1830
1831	vm86_initialize();
1832	getmemsize(first);
1833	init_param2(physmem);
1834
1835	/* now running on new page tables, configured,and u/iom is accessible */
1836
1837	/* Map the message buffer. */
1838	for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
1839		pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
1840
1841	msgbufinit(msgbufp, MSGBUF_SIZE);
1842
1843	/* make a call gate to reenter kernel with */
1844	gdp = &ldt[LSYS5CALLS_SEL].gd;
1845
1846	x = (int) &IDTVEC(lcall_syscall);
1847	gdp->gd_looffset = x;
1848	gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
1849	gdp->gd_stkcpy = 1;
1850	gdp->gd_type = SDT_SYS386CGT;
1851	gdp->gd_dpl = SEL_UPL;
1852	gdp->gd_p = 1;
1853	gdp->gd_hioffset = x >> 16;
1854
1855	/* XXX does this work? */
1856	ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
1857	ldt[LSOL26CALLS_SEL] = ldt[LSYS5CALLS_SEL];
1858
1859	/* transfer to user mode */
1860
1861	_ucodesel = LSEL(LUCODE_SEL, SEL_UPL);
1862	_udatasel = LSEL(LUDATA_SEL, SEL_UPL);
1863
1864	/* setup proc 0's pcb */
1865	thread0.td_pcb->pcb_flags = 0; /* XXXKSE */
1866	thread0.td_pcb->pcb_cr3 = (int)IdlePTD;
1867	thread0.td_pcb->pcb_ext = 0;
1868	thread0.td_frame = &proc0_tf;
1869}
1870
1871void
1872cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
1873{
1874}
1875
1876#if defined(I586_CPU) && !defined(NO_F00F_HACK)
1877static void f00f_hack(void *unused);
1878SYSINIT(f00f_hack, SI_SUB_INTRINSIC, SI_ORDER_FIRST, f00f_hack, NULL);
1879
1880static void
1881f00f_hack(void *unused) {
1882	struct gate_descriptor *new_idt;
1883#ifndef SMP
1884	struct region_descriptor r_idt;
1885#endif
1886	vm_offset_t tmp;
1887
1888	if (!has_f00f_bug)
1889		return;
1890
1891	GIANT_REQUIRED;
1892
1893	printf("Intel Pentium detected, installing workaround for F00F bug\n");
1894
1895	r_idt.rd_limit = sizeof(idt0) - 1;
1896
1897	tmp = kmem_alloc(kernel_map, PAGE_SIZE * 2);
1898	if (tmp == 0)
1899		panic("kmem_alloc returned 0");
1900	if (((unsigned int)tmp & (PAGE_SIZE-1)) != 0)
1901		panic("kmem_alloc returned non-page-aligned memory");
1902	/* Put the first seven entries in the lower page */
1903	new_idt = (struct gate_descriptor*)(tmp + PAGE_SIZE - (7*8));
1904	bcopy(idt, new_idt, sizeof(idt0));
1905	r_idt.rd_base = (int)new_idt;
1906	lidt(&r_idt);
1907	idt = new_idt;
1908	if (vm_map_protect(kernel_map, tmp, tmp + PAGE_SIZE,
1909			   VM_PROT_READ, FALSE) != KERN_SUCCESS)
1910		panic("vm_map_protect failed");
1911	return;
1912}
1913#endif /* defined(I586_CPU) && !NO_F00F_HACK */
1914
1915int
1916ptrace_set_pc(struct thread *td, unsigned long addr)
1917{
1918	td->td_frame->tf_eip = addr;
1919	return (0);
1920}
1921
1922int
1923ptrace_single_step(struct thread *td)
1924{
1925	td->td_frame->tf_eflags |= PSL_T;
1926	return (0);
1927}
1928
1929int
1930fill_regs(struct thread *td, struct reg *regs)
1931{
1932	struct pcb *pcb;
1933	struct trapframe *tp;
1934
1935	tp = td->td_frame;
1936	regs->r_fs = tp->tf_fs;
1937	regs->r_es = tp->tf_es;
1938	regs->r_ds = tp->tf_ds;
1939	regs->r_edi = tp->tf_edi;
1940	regs->r_esi = tp->tf_esi;
1941	regs->r_ebp = tp->tf_ebp;
1942	regs->r_ebx = tp->tf_ebx;
1943	regs->r_edx = tp->tf_edx;
1944	regs->r_ecx = tp->tf_ecx;
1945	regs->r_eax = tp->tf_eax;
1946	regs->r_eip = tp->tf_eip;
1947	regs->r_cs = tp->tf_cs;
1948	regs->r_eflags = tp->tf_eflags;
1949	regs->r_esp = tp->tf_esp;
1950	regs->r_ss = tp->tf_ss;
1951	pcb = td->td_pcb;
1952	regs->r_gs = pcb->pcb_gs;
1953	return (0);
1954}
1955
1956int
1957set_regs(struct thread *td, struct reg *regs)
1958{
1959	struct pcb *pcb;
1960	struct trapframe *tp;
1961
1962	tp = td->td_frame;
1963	if (!EFL_SECURE(regs->r_eflags, tp->tf_eflags) ||
1964	    !CS_SECURE(regs->r_cs))
1965		return (EINVAL);
1966	tp->tf_fs = regs->r_fs;
1967	tp->tf_es = regs->r_es;
1968	tp->tf_ds = regs->r_ds;
1969	tp->tf_edi = regs->r_edi;
1970	tp->tf_esi = regs->r_esi;
1971	tp->tf_ebp = regs->r_ebp;
1972	tp->tf_ebx = regs->r_ebx;
1973	tp->tf_edx = regs->r_edx;
1974	tp->tf_ecx = regs->r_ecx;
1975	tp->tf_eax = regs->r_eax;
1976	tp->tf_eip = regs->r_eip;
1977	tp->tf_cs = regs->r_cs;
1978	tp->tf_eflags = regs->r_eflags;
1979	tp->tf_esp = regs->r_esp;
1980	tp->tf_ss = regs->r_ss;
1981	pcb = td->td_pcb;
1982	pcb->pcb_gs = regs->r_gs;
1983	return (0);
1984}
1985
1986#ifdef CPU_ENABLE_SSE
1987static void
1988fill_fpregs_xmm(sv_xmm, sv_87)
1989	struct savexmm *sv_xmm;
1990	struct save87 *sv_87;
1991{
1992	register struct env87 *penv_87 = &sv_87->sv_env;
1993	register struct envxmm *penv_xmm = &sv_xmm->sv_env;
1994	int i;
1995
1996	bzero(sv_87, sizeof(*sv_87));
1997
1998	/* FPU control/status */
1999	penv_87->en_cw = penv_xmm->en_cw;
2000	penv_87->en_sw = penv_xmm->en_sw;
2001	penv_87->en_tw = penv_xmm->en_tw;
2002	penv_87->en_fip = penv_xmm->en_fip;
2003	penv_87->en_fcs = penv_xmm->en_fcs;
2004	penv_87->en_opcode = penv_xmm->en_opcode;
2005	penv_87->en_foo = penv_xmm->en_foo;
2006	penv_87->en_fos = penv_xmm->en_fos;
2007
2008	/* FPU registers */
2009	for (i = 0; i < 8; ++i)
2010		sv_87->sv_ac[i] = sv_xmm->sv_fp[i].fp_acc;
2011
2012	sv_87->sv_ex_sw = sv_xmm->sv_ex_sw;
2013}
2014
2015static void
2016set_fpregs_xmm(sv_87, sv_xmm)
2017	struct save87 *sv_87;
2018	struct savexmm *sv_xmm;
2019{
2020	register struct env87 *penv_87 = &sv_87->sv_env;
2021	register struct envxmm *penv_xmm = &sv_xmm->sv_env;
2022	int i;
2023
2024	/* FPU control/status */
2025	penv_xmm->en_cw = penv_87->en_cw;
2026	penv_xmm->en_sw = penv_87->en_sw;
2027	penv_xmm->en_tw = penv_87->en_tw;
2028	penv_xmm->en_fip = penv_87->en_fip;
2029	penv_xmm->en_fcs = penv_87->en_fcs;
2030	penv_xmm->en_opcode = penv_87->en_opcode;
2031	penv_xmm->en_foo = penv_87->en_foo;
2032	penv_xmm->en_fos = penv_87->en_fos;
2033
2034	/* FPU registers */
2035	for (i = 0; i < 8; ++i)
2036		sv_xmm->sv_fp[i].fp_acc = sv_87->sv_ac[i];
2037
2038	sv_xmm->sv_ex_sw = sv_87->sv_ex_sw;
2039}
2040#endif /* CPU_ENABLE_SSE */
2041
2042int
2043fill_fpregs(struct thread *td, struct fpreg *fpregs)
2044{
2045#ifdef CPU_ENABLE_SSE
2046	if (cpu_fxsr) {
2047		fill_fpregs_xmm(&td->td_pcb->pcb_save.sv_xmm,
2048						(struct save87 *)fpregs);
2049		return (0);
2050	}
2051#endif /* CPU_ENABLE_SSE */
2052	bcopy(&td->td_pcb->pcb_save.sv_87, fpregs, sizeof *fpregs);
2053	return (0);
2054}
2055
2056int
2057set_fpregs(struct thread *td, struct fpreg *fpregs)
2058{
2059#ifdef CPU_ENABLE_SSE
2060	if (cpu_fxsr) {
2061		set_fpregs_xmm((struct save87 *)fpregs,
2062					   &td->td_pcb->pcb_save.sv_xmm);
2063		return (0);
2064	}
2065#endif /* CPU_ENABLE_SSE */
2066	bcopy(fpregs, &td->td_pcb->pcb_save.sv_87, sizeof *fpregs);
2067	return (0);
2068}
2069
2070int
2071fill_dbregs(struct thread *td, struct dbreg *dbregs)
2072{
2073	struct pcb *pcb;
2074
2075	if (td == NULL) {
2076		dbregs->dr0 = rdr0();
2077		dbregs->dr1 = rdr1();
2078		dbregs->dr2 = rdr2();
2079		dbregs->dr3 = rdr3();
2080		dbregs->dr4 = rdr4();
2081		dbregs->dr5 = rdr5();
2082		dbregs->dr6 = rdr6();
2083		dbregs->dr7 = rdr7();
2084	} else {
2085		pcb = td->td_pcb;
2086		dbregs->dr0 = pcb->pcb_dr0;
2087		dbregs->dr1 = pcb->pcb_dr1;
2088		dbregs->dr2 = pcb->pcb_dr2;
2089		dbregs->dr3 = pcb->pcb_dr3;
2090		dbregs->dr4 = 0;
2091		dbregs->dr5 = 0;
2092		dbregs->dr6 = pcb->pcb_dr6;
2093		dbregs->dr7 = pcb->pcb_dr7;
2094	}
2095	return (0);
2096}
2097
2098int
2099set_dbregs(struct thread *td, struct dbreg *dbregs)
2100{
2101	struct pcb *pcb;
2102	int i;
2103	u_int32_t mask1, mask2;
2104
2105	if (td == NULL) {
2106		load_dr0(dbregs->dr0);
2107		load_dr1(dbregs->dr1);
2108		load_dr2(dbregs->dr2);
2109		load_dr3(dbregs->dr3);
2110		load_dr4(dbregs->dr4);
2111		load_dr5(dbregs->dr5);
2112		load_dr6(dbregs->dr6);
2113		load_dr7(dbregs->dr7);
2114	} else {
2115		/*
2116		 * Don't let an illegal value for dr7 get set.	Specifically,
2117		 * check for undefined settings.  Setting these bit patterns
2118		 * result in undefined behaviour and can lead to an unexpected
2119		 * TRCTRAP.
2120		 */
2121		for (i = 0, mask1 = 0x3<<16, mask2 = 0x2<<16; i < 8;
2122		     i++, mask1 <<= 2, mask2 <<= 2)
2123			if ((dbregs->dr7 & mask1) == mask2)
2124				return (EINVAL);
2125
2126		pcb = td->td_pcb;
2127
2128		/*
2129		 * Don't let a process set a breakpoint that is not within the
2130		 * process's address space.  If a process could do this, it
2131		 * could halt the system by setting a breakpoint in the kernel
2132		 * (if ddb was enabled).  Thus, we need to check to make sure
2133		 * that no breakpoints are being enabled for addresses outside
2134		 * process's address space, unless, perhaps, we were called by
2135		 * uid 0.
2136		 *
2137		 * XXX - what about when the watched area of the user's
2138		 * address space is written into from within the kernel
2139		 * ... wouldn't that still cause a breakpoint to be generated
2140		 * from within kernel mode?
2141		 */
2142
2143		if (suser_td(td) != 0) {
2144			if (dbregs->dr7 & 0x3) {
2145				/* dr0 is enabled */
2146				if (dbregs->dr0 >= VM_MAXUSER_ADDRESS)
2147					return (EINVAL);
2148			}
2149
2150			if (dbregs->dr7 & (0x3<<2)) {
2151				/* dr1 is enabled */
2152				if (dbregs->dr1 >= VM_MAXUSER_ADDRESS)
2153					return (EINVAL);
2154			}
2155
2156			if (dbregs->dr7 & (0x3<<4)) {
2157				/* dr2 is enabled */
2158				if (dbregs->dr2 >= VM_MAXUSER_ADDRESS)
2159					return (EINVAL);
2160			}
2161
2162			if (dbregs->dr7 & (0x3<<6)) {
2163				/* dr3 is enabled */
2164				if (dbregs->dr3 >= VM_MAXUSER_ADDRESS)
2165					return (EINVAL);
2166			}
2167		}
2168
2169		pcb->pcb_dr0 = dbregs->dr0;
2170		pcb->pcb_dr1 = dbregs->dr1;
2171		pcb->pcb_dr2 = dbregs->dr2;
2172		pcb->pcb_dr3 = dbregs->dr3;
2173		pcb->pcb_dr6 = dbregs->dr6;
2174		pcb->pcb_dr7 = dbregs->dr7;
2175
2176		pcb->pcb_flags |= PCB_DBREGS;
2177	}
2178
2179	return (0);
2180}
2181
2182/*
2183 * Return > 0 if a hardware breakpoint has been hit, and the
2184 * breakpoint was in user space.  Return 0, otherwise.
2185 */
2186int
2187user_dbreg_trap(void)
2188{
2189        u_int32_t dr7, dr6; /* debug registers dr6 and dr7 */
2190        u_int32_t bp;       /* breakpoint bits extracted from dr6 */
2191        int nbp;            /* number of breakpoints that triggered */
2192        caddr_t addr[4];    /* breakpoint addresses */
2193        int i;
2194
2195        dr7 = rdr7();
2196        if ((dr7 & 0x000000ff) == 0) {
2197                /*
2198                 * all GE and LE bits in the dr7 register are zero,
2199                 * thus the trap couldn't have been caused by the
2200                 * hardware debug registers
2201                 */
2202                return 0;
2203        }
2204
2205        nbp = 0;
2206        dr6 = rdr6();
2207        bp = dr6 & 0x0000000f;
2208
2209        if (!bp) {
2210                /*
2211                 * None of the breakpoint bits are set meaning this
2212                 * trap was not caused by any of the debug registers
2213                 */
2214                return 0;
2215        }
2216
2217        /*
2218         * at least one of the breakpoints were hit, check to see
2219         * which ones and if any of them are user space addresses
2220         */
2221
2222        if (bp & 0x01) {
2223                addr[nbp++] = (caddr_t)rdr0();
2224        }
2225        if (bp & 0x02) {
2226                addr[nbp++] = (caddr_t)rdr1();
2227        }
2228        if (bp & 0x04) {
2229                addr[nbp++] = (caddr_t)rdr2();
2230        }
2231        if (bp & 0x08) {
2232                addr[nbp++] = (caddr_t)rdr3();
2233        }
2234
2235        for (i=0; i<nbp; i++) {
2236                if (addr[i] <
2237                    (caddr_t)VM_MAXUSER_ADDRESS) {
2238                        /*
2239                         * addr[i] is in user space
2240                         */
2241                        return nbp;
2242                }
2243        }
2244
2245        /*
2246         * None of the breakpoints are in user space.
2247         */
2248        return 0;
2249}
2250
2251
2252#ifndef DDB
2253void
2254Debugger(const char *msg)
2255{
2256	printf("Debugger(\"%s\") called.\n", msg);
2257}
2258#endif /* no DDB */
2259
2260#include <sys/disklabel.h>
2261
2262/*
2263 * Determine the size of the transfer, and make sure it is
2264 * within the boundaries of the partition. Adjust transfer
2265 * if needed, and signal errors or early completion.
2266 */
2267int
2268bounds_check_with_label(struct bio *bp, struct disklabel *lp, int wlabel)
2269{
2270        struct partition *p = lp->d_partitions + dkpart(bp->bio_dev);
2271        int labelsect = lp->d_partitions[0].p_offset;
2272        int maxsz = p->p_size,
2273                sz = (bp->bio_bcount + DEV_BSIZE - 1) >> DEV_BSHIFT;
2274
2275        /* overwriting disk label ? */
2276        /* XXX should also protect bootstrap in first 8K */
2277        if (bp->bio_blkno + p->p_offset <= LABELSECTOR + labelsect &&
2278#if LABELSECTOR != 0
2279            bp->bio_blkno + p->p_offset + sz > LABELSECTOR + labelsect &&
2280#endif
2281            (bp->bio_cmd == BIO_WRITE) && wlabel == 0) {
2282                bp->bio_error = EROFS;
2283                goto bad;
2284        }
2285
2286#if     defined(DOSBBSECTOR) && defined(notyet)
2287        /* overwriting master boot record? */
2288        if (bp->bio_blkno + p->p_offset <= DOSBBSECTOR &&
2289            (bp->bio_cmd == BIO_WRITE) && wlabel == 0) {
2290                bp->bio_error = EROFS;
2291                goto bad;
2292        }
2293#endif
2294
2295        /* beyond partition? */
2296        if (bp->bio_blkno < 0 || bp->bio_blkno + sz > maxsz) {
2297                /* if exactly at end of disk, return an EOF */
2298                if (bp->bio_blkno == maxsz) {
2299                        bp->bio_resid = bp->bio_bcount;
2300                        return(0);
2301                }
2302                /* or truncate if part of it fits */
2303                sz = maxsz - bp->bio_blkno;
2304                if (sz <= 0) {
2305                        bp->bio_error = EINVAL;
2306                        goto bad;
2307                }
2308                bp->bio_bcount = sz << DEV_BSHIFT;
2309        }
2310
2311        bp->bio_pblkno = bp->bio_blkno + p->p_offset;
2312        return(1);
2313
2314bad:
2315        bp->bio_flags |= BIO_ERROR;
2316        return(-1);
2317}
2318
2319#ifdef DDB
2320
2321/*
2322 * Provide inb() and outb() as functions.  They are normally only
2323 * available as macros calling inlined functions, thus cannot be
2324 * called inside DDB.
2325 *
2326 * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
2327 */
2328
2329#undef inb
2330#undef outb
2331
2332/* silence compiler warnings */
2333u_char inb(u_int);
2334void outb(u_int, u_char);
2335
2336u_char
2337inb(u_int port)
2338{
2339	u_char	data;
2340	/*
2341	 * We use %%dx and not %1 here because i/o is done at %dx and not at
2342	 * %edx, while gcc generates inferior code (movw instead of movl)
2343	 * if we tell it to load (u_short) port.
2344	 */
2345	__asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
2346	return (data);
2347}
2348
2349void
2350outb(u_int port, u_char data)
2351{
2352	u_char	al;
2353	/*
2354	 * Use an unnecessary assignment to help gcc's register allocator.
2355	 * This make a large difference for gcc-1.40 and a tiny difference
2356	 * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
2357	 * best results.  gcc-2.6.0 can't handle this.
2358	 */
2359	al = data;
2360	__asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
2361}
2362
2363#endif /* DDB */
2364