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