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