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