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