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