machdep.c revision 45270
1260684Skaiw/*-
2260684Skaiw * Copyright (c) 1992 Terrence R. Lambert.
3260684Skaiw * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
4260684Skaiw * All rights reserved.
5260684Skaiw *
6260684Skaiw * This code is derived from software contributed to Berkeley by
7260684Skaiw * William Jolitz.
8260684Skaiw *
9260684Skaiw * Redistribution and use in source and binary forms, with or without
10260684Skaiw * modification, are permitted provided that the following conditions
11260684Skaiw * are met:
12260684Skaiw * 1. Redistributions of source code must retain the above copyright
13260684Skaiw *    notice, this list of conditions and the following disclaimer.
14260684Skaiw * 2. Redistributions in binary form must reproduce the above copyright
15260684Skaiw *    notice, this list of conditions and the following disclaimer in the
16260684Skaiw *    documentation and/or other materials provided with the distribution.
17260684Skaiw * 3. All advertising materials mentioning features or use of this software
18260684Skaiw *    must display the following acknowledgement:
19260684Skaiw *	This product includes software developed by the University of
20260684Skaiw *	California, Berkeley and its contributors.
21260684Skaiw * 4. Neither the name of the University nor the names of its contributors
22260684Skaiw *    may be used to endorse or promote products derived from this software
23260684Skaiw *    without specific prior written permission.
24260684Skaiw *
25260684Skaiw * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26260684Skaiw * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27260684Skaiw * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28260684Skaiw * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29295577Semaste * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30260684Skaiw * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31260684Skaiw * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32260684Skaiw * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33260684Skaiw * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34260684Skaiw * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35260684Skaiw * SUCH DAMAGE.
36260684Skaiw *
37295577Semaste *	from: @(#)machdep.c	7.4 (Berkeley) 6/3/91
38260684Skaiw *	$Id: machdep.c,v 1.327 1999/03/06 04:46:18 wollman Exp $
39260684Skaiw */
40260684Skaiw
41260684Skaiw#include "apm.h"
42260684Skaiw#include "ether.h"
43260684Skaiw#include "npx.h"
44260684Skaiw#include "opt_atalk.h"
45260684Skaiw#include "opt_cpu.h"
46260684Skaiw#include "opt_ddb.h"
47260684Skaiw#include "opt_inet.h"
48295577Semaste#include "opt_ipx.h"
49260684Skaiw#include "opt_maxmem.h"
50260684Skaiw#include "opt_msgbuf.h"
51260684Skaiw#include "opt_perfmon.h"
52260684Skaiw#include "opt_smp.h"
53295577Semaste#include "opt_sysvipc.h"
54260684Skaiw#include "opt_user_ldt.h"
55260684Skaiw#include "opt_userconfig.h"
56260684Skaiw#include "opt_vm86.h"
57260684Skaiw
58260684Skaiw#include <sys/param.h>
59260684Skaiw#include <sys/systm.h>
60260684Skaiw#include <sys/sysproto.h>
61260684Skaiw#include <sys/signalvar.h>
62260684Skaiw#include <sys/kernel.h>
63#include <sys/linker.h>
64#include <sys/proc.h>
65#include <sys/buf.h>
66#include <sys/reboot.h>
67#include <sys/callout.h>
68#include <sys/malloc.h>
69#include <sys/mbuf.h>
70#include <sys/msgbuf.h>
71#include <sys/sysent.h>
72#include <sys/sysctl.h>
73#include <sys/vmmeter.h>
74
75#ifdef SYSVSHM
76#include <sys/shm.h>
77#endif
78
79#ifdef SYSVMSG
80#include <sys/msg.h>
81#endif
82
83#ifdef SYSVSEM
84#include <sys/sem.h>
85#endif
86
87#include <vm/vm.h>
88#include <vm/vm_param.h>
89#include <vm/vm_prot.h>
90#include <sys/lock.h>
91#include <vm/vm_kern.h>
92#include <vm/vm_object.h>
93#include <vm/vm_page.h>
94#include <vm/vm_map.h>
95#include <vm/vm_pager.h>
96#include <vm/vm_extern.h>
97
98#include <sys/user.h>
99#include <sys/exec.h>
100
101#include <ddb/ddb.h>
102
103#if defined(INET) || defined(IPX) || defined(NATM) || defined(NETATALK) \
104    || NETHER > 0 || defined(NS)
105#define NETISR
106#endif
107
108#ifdef NETISR
109#include <net/netisr.h>
110#endif
111
112#include <machine/cpu.h>
113#include <machine/reg.h>
114#include <machine/clock.h>
115#include <machine/specialreg.h>
116#include <machine/cons.h>
117#include <machine/bootinfo.h>
118#include <machine/ipl.h>
119#include <machine/md_var.h>
120#include <machine/pcb_ext.h>		/* pcb.h included via sys/user.h */
121#ifdef SMP
122#include <machine/smp.h>
123#endif
124#ifdef PERFMON
125#include <machine/perfmon.h>
126#endif
127
128#include <i386/isa/isa_device.h>
129#include <i386/isa/intr_machdep.h>
130#ifndef VM86
131#include <i386/isa/rtc.h>
132#endif
133#include <machine/random.h>
134#include <sys/ptrace.h>
135
136extern void init386 __P((int first));
137extern void dblfault_handler __P((void));
138
139extern void printcpuinfo(void);	/* XXX header file */
140extern void earlysetcpuclass(void);	/* same header file */
141extern void finishidentcpu(void);
142extern void panicifcpuunsupported(void);
143extern void initializecpu(void);
144
145static void cpu_startup __P((void *));
146SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL)
147
148static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
149
150int	_udatasel, _ucodesel;
151u_int	atdevbase;
152
153#if defined(SWTCH_OPTIM_STATS)
154extern int swtch_optim_stats;
155SYSCTL_INT(_debug, OID_AUTO, swtch_optim_stats,
156	CTLFLAG_RD, &swtch_optim_stats, 0, "");
157SYSCTL_INT(_debug, OID_AUTO, tlb_flush_count,
158	CTLFLAG_RD, &tlb_flush_count, 0, "");
159#endif
160
161#ifdef PC98
162static int	ispc98 = 1;
163#else
164static int	ispc98 = 0;
165#endif
166SYSCTL_INT(_machdep, OID_AUTO, ispc98, CTLFLAG_RD, &ispc98, 0, "");
167
168int physmem = 0;
169int cold = 1;
170
171static int
172sysctl_hw_physmem SYSCTL_HANDLER_ARGS
173{
174	int error = sysctl_handle_int(oidp, 0, ctob(physmem), req);
175	return (error);
176}
177
178SYSCTL_PROC(_hw, HW_PHYSMEM, physmem, CTLTYPE_INT|CTLFLAG_RD,
179	0, 0, sysctl_hw_physmem, "I", "");
180
181static int
182sysctl_hw_usermem SYSCTL_HANDLER_ARGS
183{
184	int error = sysctl_handle_int(oidp, 0,
185		ctob(physmem - cnt.v_wire_count), req);
186	return (error);
187}
188
189SYSCTL_PROC(_hw, HW_USERMEM, usermem, CTLTYPE_INT|CTLFLAG_RD,
190	0, 0, sysctl_hw_usermem, "I", "");
191
192static int
193sysctl_hw_availpages SYSCTL_HANDLER_ARGS
194{
195	int error = sysctl_handle_int(oidp, 0,
196		i386_btop(avail_end - avail_start), req);
197	return (error);
198}
199
200SYSCTL_PROC(_hw, OID_AUTO, availpages, CTLTYPE_INT|CTLFLAG_RD,
201	0, 0, sysctl_hw_availpages, "I", "");
202
203static int
204sysctl_machdep_msgbuf SYSCTL_HANDLER_ARGS
205{
206	int error;
207
208	/* Unwind the buffer, so that it's linear (possibly starting with
209	 * some initial nulls).
210	 */
211	error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr+msgbufp->msg_bufr,
212		msgbufp->msg_size-msgbufp->msg_bufr,req);
213	if(error) return(error);
214	if(msgbufp->msg_bufr>0) {
215		error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr,
216			msgbufp->msg_bufr,req);
217	}
218	return(error);
219}
220
221SYSCTL_PROC(_machdep, OID_AUTO, msgbuf, CTLTYPE_STRING|CTLFLAG_RD,
222	0, 0, sysctl_machdep_msgbuf, "A","Contents of kernel message buffer");
223
224static int msgbuf_clear;
225
226static int
227sysctl_machdep_msgbuf_clear SYSCTL_HANDLER_ARGS
228{
229	int error;
230	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
231		req);
232	if (!error && req->newptr) {
233		/* Clear the buffer and reset write pointer */
234		bzero(msgbufp->msg_ptr,msgbufp->msg_size);
235		msgbufp->msg_bufr=msgbufp->msg_bufx=0;
236		msgbuf_clear=0;
237	}
238	return (error);
239}
240
241SYSCTL_PROC(_machdep, OID_AUTO, msgbuf_clear, CTLTYPE_INT|CTLFLAG_RW,
242	&msgbuf_clear, 0, sysctl_machdep_msgbuf_clear, "I",
243	"Clear kernel message buffer");
244
245int bootverbose = 0, Maxmem = 0;
246long dumplo;
247
248vm_offset_t phys_avail[10];
249
250/* must be 2 less so 0 0 can signal end of chunks */
251#define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(vm_offset_t)) - 2)
252
253#ifdef NETISR
254static void setup_netisrs __P((struct linker_set *));
255#endif
256
257static vm_offset_t buffer_sva, buffer_eva;
258vm_offset_t clean_sva, clean_eva;
259static vm_offset_t pager_sva, pager_eva;
260#ifdef NETISR
261extern struct linker_set netisr_set;
262#endif
263#if NNPX > 0
264extern struct isa_driver npxdriver;
265#endif
266
267#define offsetof(type, member)	((size_t)(&((type *)0)->member))
268
269static void
270cpu_startup(dummy)
271	void *dummy;
272{
273	register unsigned i;
274	register caddr_t v;
275	vm_offset_t maxaddr;
276	vm_size_t size = 0;
277	int firstaddr;
278	vm_offset_t minaddr;
279
280	if (boothowto & RB_VERBOSE)
281		bootverbose++;
282
283	/*
284	 * Good {morning,afternoon,evening,night}.
285	 */
286	printf(version);
287	earlysetcpuclass();
288	startrtclock();
289	printcpuinfo();
290	panicifcpuunsupported();
291#ifdef PERFMON
292	perfmon_init();
293#endif
294	printf("real memory  = %u (%uK bytes)\n", ptoa(Maxmem), ptoa(Maxmem) / 1024);
295	/*
296	 * Display any holes after the first chunk of extended memory.
297	 */
298	if (bootverbose) {
299		int indx;
300
301		printf("Physical memory chunk(s):\n");
302		for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
303			int size1 = phys_avail[indx + 1] - phys_avail[indx];
304
305			printf("0x%08x - 0x%08x, %u bytes (%u pages)\n",
306			    phys_avail[indx], phys_avail[indx + 1] - 1, size1,
307			    size1 / PAGE_SIZE);
308		}
309	}
310
311#ifdef NETISR
312	/*
313	 * Quickly wire in netisrs.
314	 */
315	setup_netisrs(&netisr_set);
316#endif
317
318	/*
319	 * Calculate callout wheel size
320	 */
321	for (callwheelsize = 1, callwheelbits = 0;
322	     callwheelsize < ncallout;
323	     callwheelsize <<= 1, ++callwheelbits)
324		;
325	callwheelmask = callwheelsize - 1;
326
327	/*
328	 * Allocate space for system data structures.
329	 * The first available kernel virtual address is in "v".
330	 * As pages of kernel virtual memory are allocated, "v" is incremented.
331	 * As pages of memory are allocated and cleared,
332	 * "firstaddr" is incremented.
333	 * An index into the kernel page table corresponding to the
334	 * virtual memory address maintained in "v" is kept in "mapaddr".
335	 */
336
337	/*
338	 * Make two passes.  The first pass calculates how much memory is
339	 * needed and allocates it.  The second pass assigns virtual
340	 * addresses to the various data structures.
341	 */
342	firstaddr = 0;
343again:
344	v = (caddr_t)firstaddr;
345
346#define	valloc(name, type, num) \
347	    (name) = (type *)v; v = (caddr_t)((name)+(num))
348#define	valloclim(name, type, num, lim) \
349	    (name) = (type *)v; v = (caddr_t)((lim) = ((name)+(num)))
350
351	valloc(callout, struct callout, ncallout);
352	valloc(callwheel, struct callout_tailq, callwheelsize);
353#ifdef SYSVSHM
354	valloc(shmsegs, struct shmid_ds, shminfo.shmmni);
355#endif
356#ifdef SYSVSEM
357	valloc(sema, struct semid_ds, seminfo.semmni);
358	valloc(sem, struct sem, seminfo.semmns);
359	/* This is pretty disgusting! */
360	valloc(semu, int, (seminfo.semmnu * seminfo.semusz) / sizeof(int));
361#endif
362#ifdef SYSVMSG
363	valloc(msgpool, char, msginfo.msgmax);
364	valloc(msgmaps, struct msgmap, msginfo.msgseg);
365	valloc(msghdrs, struct msg, msginfo.msgtql);
366	valloc(msqids, struct msqid_ds, msginfo.msgmni);
367#endif
368
369	if (nbuf == 0) {
370		nbuf = 30;
371		if( physmem > 1024)
372			nbuf += min((physmem - 1024) / 8, 2048);
373	}
374	nswbuf = max(min(nbuf/4, 64), 16);
375
376	valloc(swbuf, struct buf, nswbuf);
377	valloc(buf, struct buf, nbuf);
378
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	pager_map = kmem_suballoc(clean_map, &pager_sva, &pager_eva,
402				(nswbuf*MAXPHYS) + pager_map_size);
403	pager_map->system_map = 1;
404	exec_map = kmem_suballoc(kernel_map, &minaddr, &maxaddr,
405				(16*(ARG_MAX+(PAGE_SIZE*3))));
406
407	/*
408	 * Finally, allocate mbuf pool.  Since mclrefcnt is an off-size
409	 * we use the more space efficient malloc in place of kmem_alloc.
410	 */
411	{
412		vm_offset_t mb_map_size;
413		int xclusters;
414
415		/* Allow override of NMBCLUSTERS from the kernel environment */
416		if (getenv_int("kern.ipc.nmbclusters", &xclusters) &&
417		    xclusters > nmbclusters)
418		    nmbclusters = xclusters;
419
420		mb_map_size = nmbufs * MSIZE + nmbclusters * MCLBYTES;
421		mb_map_size = roundup2(mb_map_size, max(MCLBYTES, PAGE_SIZE));
422		mclrefcnt = malloc(mb_map_size / MCLBYTES, M_MBUF, M_NOWAIT);
423		bzero(mclrefcnt, mb_map_size / MCLBYTES);
424		mb_map = kmem_suballoc(kmem_map, (vm_offset_t *)&mbutl, &maxaddr,
425			mb_map_size);
426		mb_map->system_map = 1;
427	}
428
429	/*
430	 * Initialize callouts
431	 */
432	SLIST_INIT(&callfree);
433	for (i = 0; i < ncallout; i++) {
434		callout_init(&callout[i]);
435		callout[i].c_flags = CALLOUT_LOCAL_ALLOC;
436		SLIST_INSERT_HEAD(&callfree, &callout[i], c_links.sle);
437	}
438
439	for (i = 0; i < callwheelsize; i++) {
440		TAILQ_INIT(&callwheel[i]);
441	}
442
443#if defined(USERCONFIG)
444	userconfig();
445	cninit();		/* the preferred console may have changed */
446#endif
447
448	printf("avail memory = %u (%uK bytes)\n", ptoa(cnt.v_free_count),
449	    ptoa(cnt.v_free_count) / 1024);
450
451	/*
452	 * Set up buffers, so they can be used to read disk labels.
453	 */
454	bufinit();
455	vm_pager_bufferinit();
456
457#ifdef SMP
458	/*
459	 * OK, enough kmem_alloc/malloc state should be up, lets get on with it!
460	 */
461	mp_start();			/* fire up the APs and APICs */
462	mp_announce();
463#endif  /* SMP */
464}
465
466#ifdef NETISR
467int
468register_netisr(num, handler)
469	int num;
470	netisr_t *handler;
471{
472
473	if (num < 0 || num >= (sizeof(netisrs)/sizeof(*netisrs)) ) {
474		printf("register_netisr: bad isr number: %d\n", num);
475		return (EINVAL);
476	}
477	netisrs[num] = handler;
478	return (0);
479}
480
481static void
482setup_netisrs(ls)
483	struct linker_set *ls;
484{
485	int i;
486	const struct netisrtab *nit;
487
488	for(i = 0; ls->ls_items[i]; i++) {
489		nit = (const struct netisrtab *)ls->ls_items[i];
490		register_netisr(nit->nit_num, nit->nit_isr);
491	}
492}
493#endif /* NETISR */
494
495/*
496 * Send an interrupt to process.
497 *
498 * Stack is set up to allow sigcode stored
499 * at top to call routine, followed by kcall
500 * to sigreturn routine below.  After sigreturn
501 * resets the signal mask, the stack, and the
502 * frame pointer, it returns to the user
503 * specified pc, psl.
504 */
505void
506sendsig(catcher, sig, mask, code)
507	sig_t catcher;
508	int sig, mask;
509	u_long code;
510{
511	register struct proc *p = curproc;
512	register struct trapframe *regs;
513	register struct sigframe *fp;
514	struct sigframe sf;
515	struct sigacts *psp = p->p_sigacts;
516	int oonstack;
517
518	regs = p->p_md.md_regs;
519        oonstack = psp->ps_sigstk.ss_flags & SS_ONSTACK;
520	/*
521	 * Allocate and validate space for the signal handler context.
522	 */
523        if ((psp->ps_flags & SAS_ALTSTACK) && !oonstack &&
524	    (psp->ps_sigonstack & sigmask(sig))) {
525		fp = (struct sigframe *)(psp->ps_sigstk.ss_sp +
526		    psp->ps_sigstk.ss_size - sizeof(struct sigframe));
527		psp->ps_sigstk.ss_flags |= SS_ONSTACK;
528	} else {
529		fp = (struct sigframe *)regs->tf_esp - 1;
530	}
531
532	/*
533	 * grow() will return FALSE if the fp will not fit inside the stack
534	 *	and the stack can not be grown. useracc will return FALSE
535	 *	if access is denied.
536	 */
537#ifdef VM_STACK
538	if ((grow_stack (p, (int)fp) == FALSE) ||
539#else
540	if ((grow(p, (int)fp) == FALSE) ||
541#endif
542	    (useracc((caddr_t)fp, sizeof(struct sigframe), B_WRITE) == FALSE)) {
543		/*
544		 * Process has trashed its stack; give it an illegal
545		 * instruction to halt it in its tracks.
546		 */
547		SIGACTION(p, SIGILL) = SIG_DFL;
548		sig = sigmask(SIGILL);
549		p->p_sigignore &= ~sig;
550		p->p_sigcatch &= ~sig;
551		p->p_sigmask &= ~sig;
552		psignal(p, SIGILL);
553		return;
554	}
555
556	/*
557	 * Build the argument list for the signal handler.
558	 */
559	if (p->p_sysent->sv_sigtbl) {
560		if (sig < p->p_sysent->sv_sigsize)
561			sig = p->p_sysent->sv_sigtbl[sig];
562		else
563			sig = p->p_sysent->sv_sigsize + 1;
564	}
565	sf.sf_signum = sig;
566	sf.sf_code = code;
567	sf.sf_scp = &fp->sf_sc;
568	sf.sf_addr = (char *) regs->tf_err;
569	sf.sf_handler = catcher;
570
571	/* save scratch registers */
572	sf.sf_sc.sc_eax = regs->tf_eax;
573	sf.sf_sc.sc_ebx = regs->tf_ebx;
574	sf.sf_sc.sc_ecx = regs->tf_ecx;
575	sf.sf_sc.sc_edx = regs->tf_edx;
576	sf.sf_sc.sc_esi = regs->tf_esi;
577	sf.sf_sc.sc_edi = regs->tf_edi;
578	sf.sf_sc.sc_cs = regs->tf_cs;
579	sf.sf_sc.sc_ds = regs->tf_ds;
580	sf.sf_sc.sc_ss = regs->tf_ss;
581	sf.sf_sc.sc_es = regs->tf_es;
582	sf.sf_sc.sc_isp = regs->tf_isp;
583
584	/*
585	 * Build the signal context to be used by sigreturn.
586	 */
587	sf.sf_sc.sc_onstack = oonstack;
588	sf.sf_sc.sc_mask = mask;
589	sf.sf_sc.sc_sp = regs->tf_esp;
590	sf.sf_sc.sc_fp = regs->tf_ebp;
591	sf.sf_sc.sc_pc = regs->tf_eip;
592	sf.sf_sc.sc_ps = regs->tf_eflags;
593	sf.sf_sc.sc_trapno = regs->tf_trapno;
594	sf.sf_sc.sc_err = regs->tf_err;
595
596#ifdef VM86
597	/*
598	 * If we're a vm86 process, we want to save the segment registers.
599	 * We also change eflags to be our emulated eflags, not the actual
600	 * eflags.
601	 */
602	if (regs->tf_eflags & PSL_VM) {
603		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
604		struct vm86_kernel *vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
605
606		sf.sf_sc.sc_gs = tf->tf_vm86_gs;
607		sf.sf_sc.sc_fs = tf->tf_vm86_fs;
608		sf.sf_sc.sc_es = tf->tf_vm86_es;
609		sf.sf_sc.sc_ds = tf->tf_vm86_ds;
610
611		if (vm86->vm86_has_vme == 0)
612			sf.sf_sc.sc_ps = (tf->tf_eflags & ~(PSL_VIF | PSL_VIP))
613			    | (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
614
615		/*
616		 * We should never have PSL_T set when returning from vm86
617		 * mode.  It may be set here if we deliver a signal before
618		 * getting to vm86 mode, so turn it off.
619		 *
620		 * Clear PSL_NT to inhibit T_TSSFLT faults on return from
621		 * syscalls made by the signal handler.  This just avoids
622		 * wasting time for our lazy fixup of such faults.  PSL_NT
623		 * does nothing in vm86 mode, but vm86 programs can set it
624		 * almost legitimately in probes for old cpu types.
625		 */
626		tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_T | PSL_VIF | PSL_VIP);
627	}
628#endif /* VM86 */
629
630	/*
631	 * Copy the sigframe out to the user's stack.
632	 */
633	if (copyout(&sf, fp, sizeof(struct sigframe)) != 0) {
634		/*
635		 * Something is wrong with the stack pointer.
636		 * ...Kill the process.
637		 */
638		sigexit(p, SIGILL);
639	}
640
641	regs->tf_esp = (int)fp;
642	regs->tf_eip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
643	regs->tf_cs = _ucodesel;
644	regs->tf_ds = _udatasel;
645	regs->tf_es = _udatasel;
646	regs->tf_ss = _udatasel;
647}
648
649/*
650 * System call to cleanup state after a signal
651 * has been taken.  Reset signal mask and
652 * stack state from context left by sendsig (above).
653 * Return to previous pc and psl as specified by
654 * context left by sendsig. Check carefully to
655 * make sure that the user has not modified the
656 * state to gain improper privileges.
657 */
658int
659sigreturn(p, uap)
660	struct proc *p;
661	struct sigreturn_args /* {
662		struct sigcontext *sigcntxp;
663	} */ *uap;
664{
665	register struct sigcontext *scp;
666	register struct sigframe *fp;
667	register struct trapframe *regs = p->p_md.md_regs;
668	int eflags;
669
670	/*
671	 * (XXX old comment) regs->tf_esp points to the return address.
672	 * The user scp pointer is above that.
673	 * The return address is faked in the signal trampoline code
674	 * for consistency.
675	 */
676	scp = uap->sigcntxp;
677	fp = (struct sigframe *)
678	     ((caddr_t)scp - offsetof(struct sigframe, sf_sc));
679
680	if (useracc((caddr_t)fp, sizeof (*fp), B_WRITE) == 0)
681		return(EFAULT);
682
683	eflags = scp->sc_ps;
684#ifdef VM86
685	if (eflags & PSL_VM) {
686		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
687		struct vm86_kernel *vm86;
688
689		/*
690		 * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
691		 * set up the vm86 area, and we can't enter vm86 mode.
692		 */
693		if (p->p_addr->u_pcb.pcb_ext == 0)
694			return (EINVAL);
695		vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
696		if (vm86->vm86_inited == 0)
697			return (EINVAL);
698
699		/* go back to user mode if both flags are set */
700		if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
701			trapsignal(p, SIGBUS, 0);
702
703		if (vm86->vm86_has_vme) {
704			eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
705			    (eflags & VME_USERCHANGE) | PSL_VM;
706		} else {
707			vm86->vm86_eflags = eflags;	/* save VIF, VIP */
708			eflags = (tf->tf_eflags & ~VM_USERCHANGE) |					    (eflags & VM_USERCHANGE) | PSL_VM;
709		}
710		tf->tf_vm86_ds = scp->sc_ds;
711		tf->tf_vm86_es = scp->sc_es;
712		tf->tf_vm86_fs = scp->sc_fs;
713		tf->tf_vm86_gs = scp->sc_gs;
714		tf->tf_ds = _udatasel;
715		tf->tf_es = _udatasel;
716	} else {
717#endif /* VM86 */
718		/*
719		 * Don't allow users to change privileged or reserved flags.
720		 */
721#define	EFLAGS_SECURE(ef, oef)	((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
722		/*
723		 * XXX do allow users to change the privileged flag PSL_RF.
724		 * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
725		 * should sometimes set it there too.  tf_eflags is kept in
726		 * the signal context during signal handling and there is no
727		 * other place to remember it, so the PSL_RF bit may be
728		 * corrupted by the signal handler without us knowing.
729		 * Corruption of the PSL_RF bit at worst causes one more or
730		 * one less debugger trap, so allowing it is fairly harmless.
731		 */
732		if (!EFLAGS_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
733#ifdef DEBUG
734	    		printf("sigreturn: eflags = 0x%x\n", eflags);
735#endif
736	    		return(EINVAL);
737		}
738
739		/*
740		 * Don't allow users to load a valid privileged %cs.  Let the
741		 * hardware check for invalid selectors, excess privilege in
742		 * other selectors, invalid %eip's and invalid %esp's.
743		 */
744#define	CS_SECURE(cs)	(ISPL(cs) == SEL_UPL)
745		if (!CS_SECURE(scp->sc_cs)) {
746#ifdef DEBUG
747    			printf("sigreturn: cs = 0x%x\n", scp->sc_cs);
748#endif
749			trapsignal(p, SIGBUS, T_PROTFLT);
750			return(EINVAL);
751		}
752		regs->tf_ds = scp->sc_ds;
753		regs->tf_es = scp->sc_es;
754#ifdef VM86
755	}
756#endif
757
758	/* restore scratch registers */
759	regs->tf_eax = scp->sc_eax;
760	regs->tf_ebx = scp->sc_ebx;
761	regs->tf_ecx = scp->sc_ecx;
762	regs->tf_edx = scp->sc_edx;
763	regs->tf_esi = scp->sc_esi;
764	regs->tf_edi = scp->sc_edi;
765	regs->tf_cs = scp->sc_cs;
766	regs->tf_ss = scp->sc_ss;
767	regs->tf_isp = scp->sc_isp;
768
769	if (useracc((caddr_t)scp, sizeof (*scp), B_WRITE) == 0)
770		return(EINVAL);
771
772	if (scp->sc_onstack & 01)
773		p->p_sigacts->ps_sigstk.ss_flags |= SS_ONSTACK;
774	else
775		p->p_sigacts->ps_sigstk.ss_flags &= ~SS_ONSTACK;
776	p->p_sigmask = scp->sc_mask & ~sigcantmask;
777	regs->tf_ebp = scp->sc_fp;
778	regs->tf_esp = scp->sc_sp;
779	regs->tf_eip = scp->sc_pc;
780	regs->tf_eflags = eflags;
781	return(EJUSTRETURN);
782}
783
784/*
785 * Machine dependent boot() routine
786 *
787 * I haven't seen anything to put here yet
788 * Possibly some stuff might be grafted back here from boot()
789 */
790void
791cpu_boot(int howto)
792{
793}
794
795/*
796 * Shutdown the CPU as much as possible
797 */
798void
799cpu_halt(void)
800{
801	for (;;)
802		__asm__ ("hlt");
803}
804
805/*
806 * Clear registers on exec
807 */
808void
809setregs(p, entry, stack, ps_strings)
810	struct proc *p;
811	u_long entry;
812	u_long stack;
813	u_long ps_strings;
814{
815	struct trapframe *regs = p->p_md.md_regs;
816	struct pcb *pcb = &p->p_addr->u_pcb;
817
818#ifdef USER_LDT
819	/* was i386_user_cleanup() in NetBSD */
820	if (pcb->pcb_ldt) {
821		if (pcb == curpcb) {
822			lldt(_default_ldt);
823			currentldt = _default_ldt;
824		}
825		kmem_free(kernel_map, (vm_offset_t)pcb->pcb_ldt,
826			pcb->pcb_ldt_len * sizeof(union descriptor));
827		pcb->pcb_ldt_len = (int)pcb->pcb_ldt = 0;
828 	}
829#endif
830
831	bzero((char *)regs, sizeof(struct trapframe));
832	regs->tf_eip = entry;
833	regs->tf_esp = stack;
834	regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
835	regs->tf_ss = _udatasel;
836	regs->tf_ds = _udatasel;
837	regs->tf_es = _udatasel;
838	regs->tf_cs = _ucodesel;
839
840	/* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
841	regs->tf_ebx = ps_strings;
842
843	/* reset %fs and %gs as well */
844	pcb->pcb_fs = _udatasel;
845	pcb->pcb_gs = _udatasel;
846	if (pcb == curpcb) {
847		__asm("movw %w0,%%fs" : : "r" (_udatasel));
848		__asm("movw %w0,%%gs" : : "r" (_udatasel));
849	}
850
851	/*
852	 * Initialize the math emulator (if any) for the current process.
853	 * Actually, just clear the bit that says that the emulator has
854	 * been initialized.  Initialization is delayed until the process
855	 * traps to the emulator (if it is done at all) mainly because
856	 * emulators don't provide an entry point for initialization.
857	 */
858	p->p_addr->u_pcb.pcb_flags &= ~FP_SOFTFP;
859
860	/*
861	 * Arrange to trap the next npx or `fwait' instruction (see npx.c
862	 * for why fwait must be trapped at least if there is an npx or an
863	 * emulator).  This is mainly to handle the case where npx0 is not
864	 * configured, since the npx routines normally set up the trap
865	 * otherwise.  It should be done only at boot time, but doing it
866	 * here allows modifying `npx_exists' for testing the emulator on
867	 * systems with an npx.
868	 */
869	load_cr0(rcr0() | CR0_MP | CR0_TS);
870
871#if NNPX > 0
872	/* Initialize the npx (if any) for the current process. */
873	npxinit(__INITIAL_NPXCW__);
874#endif
875
876      /*
877       * XXX - Linux emulator
878       * Make sure sure edx is 0x0 on entry. Linux binaries depend
879       * on it.
880       */
881      p->p_retval[1] = 0;
882}
883
884static int
885sysctl_machdep_adjkerntz SYSCTL_HANDLER_ARGS
886{
887	int error;
888	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
889		req);
890	if (!error && req->newptr)
891		resettodr();
892	return (error);
893}
894
895SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
896	&adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
897
898SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
899	CTLFLAG_RW, &disable_rtc_set, 0, "");
900
901SYSCTL_STRUCT(_machdep, CPU_BOOTINFO, bootinfo,
902	CTLFLAG_RD, &bootinfo, bootinfo, "");
903
904SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
905	CTLFLAG_RW, &wall_cmos_clock, 0, "");
906
907/*
908 * Initialize 386 and configure to run kernel
909 */
910
911/*
912 * Initialize segments & interrupt table
913 */
914
915int _default_ldt;
916#ifdef SMP
917union descriptor gdt[NGDT + NCPU];	/* global descriptor table */
918#else
919union descriptor gdt[NGDT];		/* global descriptor table */
920#endif
921struct gate_descriptor idt[NIDT];	/* interrupt descriptor table */
922union descriptor ldt[NLDT];		/* local descriptor table */
923#ifdef SMP
924/* table descriptors - used to load tables by microp */
925struct region_descriptor r_gdt, r_idt;
926#endif
927
928extern struct i386tss common_tss;	/* One tss per cpu */
929#ifdef VM86
930extern struct segment_descriptor common_tssd;
931extern int private_tss;			/* flag indicating private tss */
932extern u_int my_tr;			/* which task register setting */
933#endif /* VM86 */
934
935#if defined(I586_CPU) && !defined(NO_F00F_HACK)
936struct gate_descriptor *t_idt;
937extern int has_f00f_bug;
938#endif
939
940static struct i386tss dblfault_tss;
941static char dblfault_stack[PAGE_SIZE];
942
943extern  struct user *proc0paddr;
944
945
946/* software prototypes -- in more palatable form */
947struct soft_segment_descriptor gdt_segs[
948#ifdef SMP
949					NGDT + NCPU
950#endif
951						   ] = {
952/* GNULL_SEL	0 Null Descriptor */
953{	0x0,			/* segment base address  */
954	0x0,			/* length */
955	0,			/* segment type */
956	0,			/* segment descriptor priority level */
957	0,			/* segment descriptor present */
958	0, 0,
959	0,			/* default 32 vs 16 bit size */
960	0  			/* limit granularity (byte/page units)*/ },
961/* GCODE_SEL	1 Code Descriptor for kernel */
962{	0x0,			/* segment base address  */
963	0xfffff,		/* length - all address space */
964	SDT_MEMERA,		/* segment type */
965	0,			/* segment descriptor priority level */
966	1,			/* segment descriptor present */
967	0, 0,
968	1,			/* default 32 vs 16 bit size */
969	1  			/* limit granularity (byte/page units)*/ },
970/* GDATA_SEL	2 Data Descriptor for kernel */
971{	0x0,			/* segment base address  */
972	0xfffff,		/* length - all address space */
973	SDT_MEMRWA,		/* segment type */
974	0,			/* segment descriptor priority level */
975	1,			/* segment descriptor present */
976	0, 0,
977	1,			/* default 32 vs 16 bit size */
978	1  			/* limit granularity (byte/page units)*/ },
979/* GLDT_SEL	3 LDT Descriptor */
980{	(int) ldt,		/* segment base address  */
981	sizeof(ldt)-1,		/* length - all address space */
982	SDT_SYSLDT,		/* segment type */
983	SEL_UPL,		/* segment descriptor priority level */
984	1,			/* segment descriptor present */
985	0, 0,
986	0,			/* unused - default 32 vs 16 bit size */
987	0  			/* limit granularity (byte/page units)*/ },
988/* GTGATE_SEL	4 Null Descriptor - Placeholder */
989{	0x0,			/* segment base address  */
990	0x0,			/* length - all address space */
991	0,			/* segment type */
992	0,			/* segment descriptor priority level */
993	0,			/* segment descriptor present */
994	0, 0,
995	0,			/* default 32 vs 16 bit size */
996	0  			/* limit granularity (byte/page units)*/ },
997/* GPANIC_SEL	5 Panic Tss Descriptor */
998{	(int) &dblfault_tss,	/* segment base address  */
999	sizeof(struct i386tss)-1,/* length - all address space */
1000	SDT_SYS386TSS,		/* segment type */
1001	0,			/* segment descriptor priority level */
1002	1,			/* segment descriptor present */
1003	0, 0,
1004	0,			/* unused - default 32 vs 16 bit size */
1005	0  			/* limit granularity (byte/page units)*/ },
1006/* GPROC0_SEL	6 Proc 0 Tss Descriptor */
1007{
1008	(int) &common_tss,	/* segment base address */
1009	sizeof(struct i386tss)-1,/* length - all address space */
1010	SDT_SYS386TSS,		/* segment type */
1011	0,			/* segment descriptor priority level */
1012	1,			/* segment descriptor present */
1013	0, 0,
1014	0,			/* unused - default 32 vs 16 bit size */
1015	0  			/* limit granularity (byte/page units)*/ },
1016/* GUSERLDT_SEL	7 User LDT Descriptor per process */
1017{	(int) ldt,		/* segment base address  */
1018	(512 * sizeof(union descriptor)-1),		/* length */
1019	SDT_SYSLDT,		/* segment type */
1020	0,			/* segment descriptor priority level */
1021	1,			/* segment descriptor present */
1022	0, 0,
1023	0,			/* unused - default 32 vs 16 bit size */
1024	0  			/* limit granularity (byte/page units)*/ },
1025/* GAPMCODE32_SEL 8 APM BIOS 32-bit interface (32bit Code) */
1026{	0,			/* segment base address (overwritten by APM)  */
1027	0xfffff,		/* length */
1028	SDT_MEMERA,		/* segment type */
1029	0,			/* segment descriptor priority level */
1030	1,			/* segment descriptor present */
1031	0, 0,
1032	1,			/* default 32 vs 16 bit size */
1033	1  			/* limit granularity (byte/page units)*/ },
1034/* GAPMCODE16_SEL 9 APM BIOS 32-bit interface (16bit Code) */
1035{	0,			/* segment base address (overwritten by APM)  */
1036	0xfffff,		/* length */
1037	SDT_MEMERA,		/* segment type */
1038	0,			/* segment descriptor priority level */
1039	1,			/* segment descriptor present */
1040	0, 0,
1041	0,			/* default 32 vs 16 bit size */
1042	1  			/* limit granularity (byte/page units)*/ },
1043/* GAPMDATA_SEL	10 APM BIOS 32-bit interface (Data) */
1044{	0,			/* segment base address (overwritten by APM) */
1045	0xfffff,		/* length */
1046	SDT_MEMRWA,		/* segment type */
1047	0,			/* segment descriptor priority level */
1048	1,			/* segment descriptor present */
1049	0, 0,
1050	1,			/* default 32 vs 16 bit size */
1051	1  			/* limit granularity (byte/page units)*/ },
1052};
1053
1054static struct soft_segment_descriptor ldt_segs[] = {
1055	/* Null Descriptor - overwritten by call gate */
1056{	0x0,			/* segment base address  */
1057	0x0,			/* length - all address space */
1058	0,			/* segment type */
1059	0,			/* segment descriptor priority level */
1060	0,			/* segment descriptor present */
1061	0, 0,
1062	0,			/* default 32 vs 16 bit size */
1063	0  			/* limit granularity (byte/page units)*/ },
1064	/* Null Descriptor - overwritten by call gate */
1065{	0x0,			/* segment base address  */
1066	0x0,			/* length - all address space */
1067	0,			/* segment type */
1068	0,			/* segment descriptor priority level */
1069	0,			/* segment descriptor present */
1070	0, 0,
1071	0,			/* default 32 vs 16 bit size */
1072	0  			/* limit granularity (byte/page units)*/ },
1073	/* Null Descriptor - overwritten by call gate */
1074{	0x0,			/* segment base address  */
1075	0x0,			/* length - all address space */
1076	0,			/* segment type */
1077	0,			/* segment descriptor priority level */
1078	0,			/* segment descriptor present */
1079	0, 0,
1080	0,			/* default 32 vs 16 bit size */
1081	0  			/* limit granularity (byte/page units)*/ },
1082	/* Code Descriptor for user */
1083{	0x0,			/* segment base address  */
1084	0xfffff,		/* length - all address space */
1085	SDT_MEMERA,		/* segment type */
1086	SEL_UPL,		/* segment descriptor priority level */
1087	1,			/* segment descriptor present */
1088	0, 0,
1089	1,			/* default 32 vs 16 bit size */
1090	1  			/* limit granularity (byte/page units)*/ },
1091	/* Null Descriptor - overwritten by call gate */
1092{	0x0,			/* segment base address  */
1093	0x0,			/* length - all address space */
1094	0,			/* segment type */
1095	0,			/* segment descriptor priority level */
1096	0,			/* segment descriptor present */
1097	0, 0,
1098	0,			/* default 32 vs 16 bit size */
1099	0  			/* limit granularity (byte/page units)*/ },
1100	/* Data Descriptor for user */
1101{	0x0,			/* segment base address  */
1102	0xfffff,		/* length - all address space */
1103	SDT_MEMRWA,		/* segment type */
1104	SEL_UPL,		/* segment descriptor priority level */
1105	1,			/* segment descriptor present */
1106	0, 0,
1107	1,			/* default 32 vs 16 bit size */
1108	1  			/* limit granularity (byte/page units)*/ },
1109};
1110
1111void
1112setidt(idx, func, typ, dpl, selec)
1113	int idx;
1114	inthand_t *func;
1115	int typ;
1116	int dpl;
1117	int selec;
1118{
1119	struct gate_descriptor *ip;
1120
1121#if defined(I586_CPU) && !defined(NO_F00F_HACK)
1122	ip = (t_idt != NULL ? t_idt : idt) + idx;
1123#else
1124	ip = idt + idx;
1125#endif
1126	ip->gd_looffset = (int)func;
1127	ip->gd_selector = selec;
1128	ip->gd_stkcpy = 0;
1129	ip->gd_xx = 0;
1130	ip->gd_type = typ;
1131	ip->gd_dpl = dpl;
1132	ip->gd_p = 1;
1133	ip->gd_hioffset = ((int)func)>>16 ;
1134}
1135
1136#define	IDTVEC(name)	__CONCAT(X,name)
1137
1138extern inthand_t
1139	IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1140	IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1141	IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1142	IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1143	IDTVEC(syscall), IDTVEC(int0x80_syscall);
1144
1145void
1146sdtossd(sd, ssd)
1147	struct segment_descriptor *sd;
1148	struct soft_segment_descriptor *ssd;
1149{
1150	ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1151	ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1152	ssd->ssd_type  = sd->sd_type;
1153	ssd->ssd_dpl   = sd->sd_dpl;
1154	ssd->ssd_p     = sd->sd_p;
1155	ssd->ssd_def32 = sd->sd_def32;
1156	ssd->ssd_gran  = sd->sd_gran;
1157}
1158
1159void
1160init386(first)
1161	int first;
1162{
1163	int x;
1164	unsigned biosbasemem, biosextmem;
1165	struct gate_descriptor *gdp;
1166	int gsel_tss;
1167
1168	struct isa_device *idp;
1169#ifndef SMP
1170	/* table descriptors - used to load tables by microp */
1171	struct region_descriptor r_gdt, r_idt;
1172#endif
1173	int pagesinbase, pagesinext;
1174	vm_offset_t target_page;
1175	int pa_indx, off;
1176	int speculative_mprobe;
1177
1178	/*
1179	 * Prevent lowering of the ipl if we call tsleep() early.
1180	 */
1181	safepri = cpl;
1182
1183	proc0.p_addr = proc0paddr;
1184
1185	atdevbase = ISA_HOLE_START + KERNBASE;
1186
1187	/*
1188	 * Initialize the console before we print anything out.
1189	 */
1190	cninit();
1191
1192	/*
1193	 * make gdt memory segments, the code segment goes up to end of the
1194	 * page with etext in it, the data segment goes to the end of
1195	 * the address space
1196	 */
1197	/*
1198	 * XXX text protection is temporarily (?) disabled.  The limit was
1199	 * i386_btop(round_page(etext)) - 1.
1200	 */
1201	gdt_segs[GCODE_SEL].ssd_limit = i386_btop(0) - 1;
1202	gdt_segs[GDATA_SEL].ssd_limit = i386_btop(0) - 1;
1203#ifdef BDE_DEBUGGER
1204#define	NGDT1	8		/* avoid overwriting db entries with APM ones */
1205#else
1206#define	NGDT1	(sizeof gdt_segs / sizeof gdt_segs[0])
1207#endif
1208	for (x = 0; x < NGDT1; x++)
1209		ssdtosd(&gdt_segs[x], &gdt[x].sd);
1210#ifdef VM86
1211	common_tssd = gdt[GPROC0_SEL].sd;
1212#endif /* VM86 */
1213
1214#ifdef SMP
1215	/*
1216	 * Spin these up now.  init_secondary() grabs them.  We could use
1217	 * #for(x,y,z) / #endfor cpp directives if they existed.
1218	 */
1219	for (x = 0; x < NCPU; x++) {
1220		gdt_segs[NGDT + x] = gdt_segs[GPROC0_SEL];
1221		ssdtosd(&gdt_segs[NGDT + x], &gdt[NGDT + x].sd);
1222	}
1223#endif
1224
1225	/* make ldt memory segments */
1226	/*
1227	 * The data segment limit must not cover the user area because we
1228	 * don't want the user area to be writable in copyout() etc. (page
1229	 * level protection is lost in kernel mode on 386's).  Also, we
1230	 * don't want the user area to be writable directly (page level
1231	 * protection of the user area is not available on 486's with
1232	 * CR0_WP set, because there is no user-read/kernel-write mode).
1233	 *
1234	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  And it
1235	 * should be spelled ...MAX_USER...
1236	 */
1237#define VM_END_USER_RW_ADDRESS	VM_MAXUSER_ADDRESS
1238	/*
1239	 * The code segment limit has to cover the user area until we move
1240	 * the signal trampoline out of the user area.  This is safe because
1241	 * the code segment cannot be written to directly.
1242	 */
1243#define VM_END_USER_R_ADDRESS	(VM_END_USER_RW_ADDRESS + UPAGES * PAGE_SIZE)
1244	ldt_segs[LUCODE_SEL].ssd_limit = i386_btop(VM_END_USER_R_ADDRESS) - 1;
1245	ldt_segs[LUDATA_SEL].ssd_limit = i386_btop(VM_END_USER_RW_ADDRESS) - 1;
1246	for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
1247		ssdtosd(&ldt_segs[x], &ldt[x].sd);
1248
1249	/* exceptions */
1250	for (x = 0; x < NIDT; x++)
1251		setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1252	setidt(0, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1253	setidt(1, &IDTVEC(dbg),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1254	setidt(2, &IDTVEC(nmi),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1255 	setidt(3, &IDTVEC(bpt),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1256	setidt(4, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1257	setidt(5, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1258	setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1259	setidt(7, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1260	setidt(8, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
1261	setidt(9, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1262	setidt(10, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1263	setidt(11, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1264	setidt(12, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1265	setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1266	setidt(14, &IDTVEC(page),  SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1267	setidt(15, &IDTVEC(rsvd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1268	setidt(16, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1269	setidt(17, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1270	setidt(18, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1271 	setidt(0x80, &IDTVEC(int0x80_syscall),
1272			SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1273
1274#include	"isa.h"
1275#if	NISA >0
1276	isa_defaultirq();
1277#endif
1278	rand_initialize();
1279
1280	r_gdt.rd_limit = sizeof(gdt) - 1;
1281	r_gdt.rd_base =  (int) gdt;
1282	lgdt(&r_gdt);
1283
1284	r_idt.rd_limit = sizeof(idt) - 1;
1285	r_idt.rd_base = (int) idt;
1286	lidt(&r_idt);
1287
1288	_default_ldt = GSEL(GLDT_SEL, SEL_KPL);
1289	lldt(_default_ldt);
1290#ifdef USER_LDT
1291	currentldt = _default_ldt;
1292#endif
1293
1294#ifdef DDB
1295	kdb_init();
1296	if (boothowto & RB_KDB)
1297		Debugger("Boot flags requested debugger");
1298#endif
1299
1300	finishidentcpu();	/* Final stage of CPU initialization */
1301	setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1302	setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1303	initializecpu();	/* Initialize CPU registers */
1304
1305	/* make an initial tss so cpu can get interrupt stack on syscall! */
1306#ifdef VM86
1307	common_tss.tss_esp0 = (int) proc0.p_addr + UPAGES*PAGE_SIZE - 16;
1308#else
1309	common_tss.tss_esp0 = (int) proc0.p_addr + UPAGES*PAGE_SIZE;
1310#endif /* VM86 */
1311	common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL) ;
1312	common_tss.tss_ioopt = (sizeof common_tss) << 16;
1313	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1314	ltr(gsel_tss);
1315#ifdef VM86
1316	private_tss = 0;
1317	my_tr = GPROC0_SEL;
1318#endif
1319
1320	dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
1321	    dblfault_tss.tss_esp2 = (int) &dblfault_stack[sizeof(dblfault_stack)];
1322	dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
1323	    dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
1324	dblfault_tss.tss_cr3 = (int)IdlePTD;
1325	dblfault_tss.tss_eip = (int) dblfault_handler;
1326	dblfault_tss.tss_eflags = PSL_KERNEL;
1327	dblfault_tss.tss_ds = dblfault_tss.tss_es = dblfault_tss.tss_fs =
1328	    dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
1329	dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
1330	dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
1331
1332#ifdef VM86
1333	initial_bioscalls(&biosbasemem, &biosextmem);
1334#else
1335
1336	/* Use BIOS values stored in RTC CMOS RAM, since probing
1337	 * breaks certain 386 AT relics.
1338	 */
1339	biosbasemem = rtcin(RTC_BASELO)+ (rtcin(RTC_BASEHI)<<8);
1340	biosextmem = rtcin(RTC_EXTLO)+ (rtcin(RTC_EXTHI)<<8);
1341#endif
1342
1343	/*
1344	 * If BIOS tells us that it has more than 640k in the basemem,
1345	 *	don't believe it - set it to 640k.
1346	 */
1347	if (biosbasemem > 640) {
1348		printf("Preposterous RTC basemem of %uK, truncating to 640K\n",
1349		       biosbasemem);
1350		biosbasemem = 640;
1351	}
1352	if (bootinfo.bi_memsizes_valid && bootinfo.bi_basemem > 640) {
1353		printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
1354		       bootinfo.bi_basemem);
1355		bootinfo.bi_basemem = 640;
1356	}
1357
1358	/*
1359	 * Warn if the official BIOS interface disagrees with the RTC
1360	 * interface used above about the amount of base memory or the
1361	 * amount of extended memory.  Prefer the BIOS value for the base
1362	 * memory.  This is necessary for machines that `steal' base
1363	 * memory for use as BIOS memory, at least if we are going to use
1364	 * the BIOS for apm.  Prefer the RTC value for extended memory.
1365	 * Eventually the hackish interface shouldn't even be looked at.
1366	 */
1367	if (bootinfo.bi_memsizes_valid) {
1368		if (bootinfo.bi_basemem != biosbasemem) {
1369			vm_offset_t pa;
1370
1371			printf(
1372	"BIOS basemem (%uK) != RTC basemem (%uK), setting to BIOS value\n",
1373			       bootinfo.bi_basemem, biosbasemem);
1374			biosbasemem = bootinfo.bi_basemem;
1375
1376			/*
1377			 * XXX if biosbasemem is now < 640, there is `hole'
1378			 * between the end of base memory and the start of
1379			 * ISA memory.  The hole may be empty or it may
1380			 * contain BIOS code or data.  Map it read/write so
1381			 * that the BIOS can write to it.  (Memory from 0 to
1382			 * the physical end of the kernel is mapped read-only
1383			 * to begin with and then parts of it are remapped.
1384			 * The parts that aren't remapped form holes that
1385			 * remain read-only and are unused by the kernel.
1386			 * The base memory area is below the physical end of
1387			 * the kernel and right now forms a read-only hole.
1388			 * The part of it from PAGE_SIZE to
1389			 * (trunc_page(biosbasemem * 1024) - 1) will be
1390			 * remapped and used by the kernel later.)
1391			 *
1392			 * This code is similar to the code used in
1393			 * pmap_mapdev, but since no memory needs to be
1394			 * allocated we simply change the mapping.
1395			 */
1396			for (pa = trunc_page(biosbasemem * 1024);
1397			     pa < ISA_HOLE_START; pa += PAGE_SIZE) {
1398				unsigned *pte;
1399
1400				pte = (unsigned *)vtopte(pa + KERNBASE);
1401				*pte = pa | PG_RW | PG_V;
1402			}
1403		}
1404		if (bootinfo.bi_extmem != biosextmem)
1405			printf("BIOS extmem (%uK) != RTC extmem (%uK)\n",
1406			       bootinfo.bi_extmem, biosextmem);
1407	}
1408
1409#ifdef SMP
1410	/* make hole for AP bootstrap code */
1411	pagesinbase = mp_bootaddress(biosbasemem) / PAGE_SIZE;
1412#else
1413	pagesinbase = biosbasemem * 1024 / PAGE_SIZE;
1414#endif
1415
1416	pagesinext = biosextmem * 1024 / PAGE_SIZE;
1417
1418	/*
1419	 * Special hack for chipsets that still remap the 384k hole when
1420	 *	there's 16MB of memory - this really confuses people that
1421	 *	are trying to use bus mastering ISA controllers with the
1422	 *	"16MB limit"; they only have 16MB, but the remapping puts
1423	 *	them beyond the limit.
1424	 */
1425	/*
1426	 * If extended memory is between 15-16MB (16-17MB phys address range),
1427	 *	chop it to 15MB.
1428	 */
1429	if ((pagesinext > 3840) && (pagesinext < 4096))
1430		pagesinext = 3840;
1431
1432	/*
1433	 * Maxmem isn't the "maximum memory", it's one larger than the
1434	 * highest page of the physical address space.  It should be
1435	 * called something like "Maxphyspage".
1436	 */
1437	Maxmem = pagesinext + 0x100000/PAGE_SIZE;
1438	/*
1439	 * Indicate that we wish to do a speculative search for memory beyond
1440	 * the end of the reported size if the indicated amount is 64MB (0x4000
1441	 * pages) - which is the largest amount that the BIOS/bootblocks can
1442	 * currently report. If a specific amount of memory is indicated via
1443	 * the MAXMEM option or the npx0 "msize", then don't do the speculative
1444	 * memory probe.
1445	 */
1446	if (Maxmem >= 0x4000)
1447		speculative_mprobe = TRUE;
1448	else
1449		speculative_mprobe = FALSE;
1450
1451#ifdef MAXMEM
1452	Maxmem = MAXMEM/4;
1453	speculative_mprobe = FALSE;
1454#endif
1455
1456#if NNPX > 0
1457	idp = find_isadev(isa_devtab_null, &npxdriver, 0);
1458	if (idp != NULL && idp->id_msize != 0) {
1459		Maxmem = idp->id_msize / 4;
1460		speculative_mprobe = FALSE;
1461	}
1462#endif
1463
1464#ifdef SMP
1465	/* look for the MP hardware - needed for apic addresses */
1466	mp_probe();
1467#endif
1468
1469	/* call pmap initialization to make new kernel address space */
1470	pmap_bootstrap (first, 0);
1471
1472	/*
1473	 * Size up each available chunk of physical memory.
1474	 */
1475
1476	/*
1477	 * We currently don't bother testing base memory.
1478	 * XXX  ...but we probably should.
1479	 */
1480	pa_indx = 0;
1481	if (pagesinbase > 1) {
1482		phys_avail[pa_indx++] = PAGE_SIZE;	/* skip first page of memory */
1483		phys_avail[pa_indx] = ptoa(pagesinbase);/* memory up to the ISA hole */
1484		physmem = pagesinbase - 1;
1485	} else {
1486		/* point at first chunk end */
1487		pa_indx++;
1488	}
1489
1490	for (target_page = avail_start; target_page < ptoa(Maxmem); target_page += PAGE_SIZE) {
1491		int tmp, page_bad;
1492
1493		page_bad = FALSE;
1494
1495		/*
1496		 * map page into kernel: valid, read/write, non-cacheable
1497		 */
1498		*(int *)CMAP1 = PG_V | PG_RW | PG_N | target_page;
1499		invltlb();
1500
1501		tmp = *(int *)CADDR1;
1502		/*
1503		 * Test for alternating 1's and 0's
1504		 */
1505		*(volatile int *)CADDR1 = 0xaaaaaaaa;
1506		if (*(volatile int *)CADDR1 != 0xaaaaaaaa) {
1507			page_bad = TRUE;
1508		}
1509		/*
1510		 * Test for alternating 0's and 1's
1511		 */
1512		*(volatile int *)CADDR1 = 0x55555555;
1513		if (*(volatile int *)CADDR1 != 0x55555555) {
1514			page_bad = TRUE;
1515		}
1516		/*
1517		 * Test for all 1's
1518		 */
1519		*(volatile int *)CADDR1 = 0xffffffff;
1520		if (*(volatile int *)CADDR1 != 0xffffffff) {
1521			page_bad = TRUE;
1522		}
1523		/*
1524		 * Test for all 0's
1525		 */
1526		*(volatile int *)CADDR1 = 0x0;
1527		if (*(volatile int *)CADDR1 != 0x0) {
1528			/*
1529			 * test of page failed
1530			 */
1531			page_bad = TRUE;
1532		}
1533		/*
1534		 * Restore original value.
1535		 */
1536		*(int *)CADDR1 = tmp;
1537
1538		/*
1539		 * Adjust array of valid/good pages.
1540		 */
1541		if (page_bad == FALSE) {
1542			/*
1543			 * If this good page is a continuation of the
1544			 * previous set of good pages, then just increase
1545			 * the end pointer. Otherwise start a new chunk.
1546			 * Note that "end" points one higher than end,
1547			 * making the range >= start and < end.
1548			 * If we're also doing a speculative memory
1549			 * test and we at or past the end, bump up Maxmem
1550			 * so that we keep going. The first bad page
1551			 * will terminate the loop.
1552			 */
1553			if (phys_avail[pa_indx] == target_page) {
1554				phys_avail[pa_indx] += PAGE_SIZE;
1555				if (speculative_mprobe == TRUE &&
1556				    phys_avail[pa_indx] >= (64*1024*1024))
1557					Maxmem++;
1558			} else {
1559				pa_indx++;
1560				if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1561					printf("Too many holes in the physical address space, giving up\n");
1562					pa_indx--;
1563					break;
1564				}
1565				phys_avail[pa_indx++] = target_page;	/* start */
1566				phys_avail[pa_indx] = target_page + PAGE_SIZE;	/* end */
1567			}
1568			physmem++;
1569		}
1570	}
1571
1572	*(int *)CMAP1 = 0;
1573	invltlb();
1574
1575	/*
1576	 * XXX
1577	 * The last chunk must contain at least one page plus the message
1578	 * buffer to avoid complicating other code (message buffer address
1579	 * calculation, etc.).
1580	 */
1581	while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1582	    round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
1583		physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1584		phys_avail[pa_indx--] = 0;
1585		phys_avail[pa_indx--] = 0;
1586	}
1587
1588	Maxmem = atop(phys_avail[pa_indx]);
1589
1590	/* Trim off space for the message buffer. */
1591	phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
1592
1593	avail_end = phys_avail[pa_indx];
1594
1595	/* now running on new page tables, configured,and u/iom is accessible */
1596
1597	/* Map the message buffer. */
1598	for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
1599		pmap_enter(kernel_pmap, (vm_offset_t)msgbufp + off,
1600			   avail_end + off, VM_PROT_ALL, TRUE);
1601
1602	msgbufinit(msgbufp, MSGBUF_SIZE);
1603
1604	/* make a call gate to reenter kernel with */
1605	gdp = &ldt[LSYS5CALLS_SEL].gd;
1606
1607	x = (int) &IDTVEC(syscall);
1608	gdp->gd_looffset = x++;
1609	gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
1610	gdp->gd_stkcpy = 1;
1611	gdp->gd_type = SDT_SYS386CGT;
1612	gdp->gd_dpl = SEL_UPL;
1613	gdp->gd_p = 1;
1614	gdp->gd_hioffset = ((int) &IDTVEC(syscall)) >>16;
1615
1616	/* XXX does this work? */
1617	ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
1618	ldt[LSOL26CALLS_SEL] = ldt[LSYS5CALLS_SEL];
1619
1620	/* transfer to user mode */
1621
1622	_ucodesel = LSEL(LUCODE_SEL, SEL_UPL);
1623	_udatasel = LSEL(LUDATA_SEL, SEL_UPL);
1624
1625	/* setup proc 0's pcb */
1626	proc0.p_addr->u_pcb.pcb_flags = 0;
1627	proc0.p_addr->u_pcb.pcb_cr3 = (int)IdlePTD;
1628#ifdef SMP
1629	proc0.p_addr->u_pcb.pcb_mpnest = 1;
1630#endif
1631#ifdef VM86
1632	proc0.p_addr->u_pcb.pcb_ext = 0;
1633#endif
1634
1635	/* Sigh, relocate physical addresses left from bootstrap */
1636	if (bootinfo.bi_modulep) {
1637		preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
1638		preload_bootstrap_relocate(KERNBASE);
1639	}
1640	if (bootinfo.bi_envp)
1641		kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
1642}
1643
1644#if defined(I586_CPU) && !defined(NO_F00F_HACK)
1645static void f00f_hack(void *unused);
1646SYSINIT(f00f_hack, SI_SUB_INTRINSIC, SI_ORDER_FIRST, f00f_hack, NULL);
1647
1648static void
1649f00f_hack(void *unused) {
1650#ifndef SMP
1651	struct region_descriptor r_idt;
1652#endif
1653	vm_offset_t tmp;
1654
1655	if (!has_f00f_bug)
1656		return;
1657
1658	printf("Intel Pentium detected, installing workaround for F00F bug\n");
1659
1660	r_idt.rd_limit = sizeof(idt) - 1;
1661
1662	tmp = kmem_alloc(kernel_map, PAGE_SIZE * 2);
1663	if (tmp == 0)
1664		panic("kmem_alloc returned 0");
1665	if (((unsigned int)tmp & (PAGE_SIZE-1)) != 0)
1666		panic("kmem_alloc returned non-page-aligned memory");
1667	/* Put the first seven entries in the lower page */
1668	t_idt = (struct gate_descriptor*)(tmp + PAGE_SIZE - (7*8));
1669	bcopy(idt, t_idt, sizeof(idt));
1670	r_idt.rd_base = (int)t_idt;
1671	lidt(&r_idt);
1672	if (vm_map_protect(kernel_map, tmp, tmp + PAGE_SIZE,
1673			   VM_PROT_READ, FALSE) != KERN_SUCCESS)
1674		panic("vm_map_protect failed");
1675	return;
1676}
1677#endif /* defined(I586_CPU) && !NO_F00F_HACK */
1678
1679int
1680ptrace_set_pc(p, addr)
1681	struct proc *p;
1682	unsigned long addr;
1683{
1684	p->p_md.md_regs->tf_eip = addr;
1685	return (0);
1686}
1687
1688int
1689ptrace_single_step(p)
1690	struct proc *p;
1691{
1692	p->p_md.md_regs->tf_eflags |= PSL_T;
1693	return (0);
1694}
1695
1696int ptrace_read_u_check(p, addr, len)
1697	struct proc *p;
1698	vm_offset_t addr;
1699	size_t len;
1700{
1701	vm_offset_t gap;
1702
1703	if ((vm_offset_t) (addr + len) < addr)
1704		return EPERM;
1705	if ((vm_offset_t) (addr + len) <= sizeof(struct user))
1706		return 0;
1707
1708	gap = (char *) p->p_md.md_regs - (char *) p->p_addr;
1709
1710	if ((vm_offset_t) addr < gap)
1711		return EPERM;
1712	if ((vm_offset_t) (addr + len) <=
1713	    (vm_offset_t) (gap + sizeof(struct trapframe)))
1714		return 0;
1715	return EPERM;
1716}
1717
1718int ptrace_write_u(p, off, data)
1719	struct proc *p;
1720	vm_offset_t off;
1721	long data;
1722{
1723	struct trapframe frame_copy;
1724	vm_offset_t min;
1725	struct trapframe *tp;
1726
1727	/*
1728	 * Privileged kernel state is scattered all over the user area.
1729	 * Only allow write access to parts of regs and to fpregs.
1730	 */
1731	min = (char *)p->p_md.md_regs - (char *)p->p_addr;
1732	if (off >= min && off <= min + sizeof(struct trapframe) - sizeof(int)) {
1733		tp = p->p_md.md_regs;
1734		frame_copy = *tp;
1735		*(int *)((char *)&frame_copy + (off - min)) = data;
1736		if (!EFLAGS_SECURE(frame_copy.tf_eflags, tp->tf_eflags) ||
1737		    !CS_SECURE(frame_copy.tf_cs))
1738			return (EINVAL);
1739		*(int*)((char *)p->p_addr + off) = data;
1740		return (0);
1741	}
1742	min = offsetof(struct user, u_pcb) + offsetof(struct pcb, pcb_savefpu);
1743	if (off >= min && off <= min + sizeof(struct save87) - sizeof(int)) {
1744		*(int*)((char *)p->p_addr + off) = data;
1745		return (0);
1746	}
1747	return (EFAULT);
1748}
1749
1750int
1751fill_regs(p, regs)
1752	struct proc *p;
1753	struct reg *regs;
1754{
1755	struct pcb *pcb;
1756	struct trapframe *tp;
1757
1758	tp = p->p_md.md_regs;
1759	regs->r_es = tp->tf_es;
1760	regs->r_ds = tp->tf_ds;
1761	regs->r_edi = tp->tf_edi;
1762	regs->r_esi = tp->tf_esi;
1763	regs->r_ebp = tp->tf_ebp;
1764	regs->r_ebx = tp->tf_ebx;
1765	regs->r_edx = tp->tf_edx;
1766	regs->r_ecx = tp->tf_ecx;
1767	regs->r_eax = tp->tf_eax;
1768	regs->r_eip = tp->tf_eip;
1769	regs->r_cs = tp->tf_cs;
1770	regs->r_eflags = tp->tf_eflags;
1771	regs->r_esp = tp->tf_esp;
1772	regs->r_ss = tp->tf_ss;
1773	pcb = &p->p_addr->u_pcb;
1774	regs->r_fs = pcb->pcb_fs;
1775	regs->r_gs = pcb->pcb_gs;
1776	return (0);
1777}
1778
1779int
1780set_regs(p, regs)
1781	struct proc *p;
1782	struct reg *regs;
1783{
1784	struct pcb *pcb;
1785	struct trapframe *tp;
1786
1787	tp = p->p_md.md_regs;
1788	if (!EFLAGS_SECURE(regs->r_eflags, tp->tf_eflags) ||
1789	    !CS_SECURE(regs->r_cs))
1790		return (EINVAL);
1791	tp->tf_es = regs->r_es;
1792	tp->tf_ds = regs->r_ds;
1793	tp->tf_edi = regs->r_edi;
1794	tp->tf_esi = regs->r_esi;
1795	tp->tf_ebp = regs->r_ebp;
1796	tp->tf_ebx = regs->r_ebx;
1797	tp->tf_edx = regs->r_edx;
1798	tp->tf_ecx = regs->r_ecx;
1799	tp->tf_eax = regs->r_eax;
1800	tp->tf_eip = regs->r_eip;
1801	tp->tf_cs = regs->r_cs;
1802	tp->tf_eflags = regs->r_eflags;
1803	tp->tf_esp = regs->r_esp;
1804	tp->tf_ss = regs->r_ss;
1805	pcb = &p->p_addr->u_pcb;
1806	pcb->pcb_fs = regs->r_fs;
1807	pcb->pcb_gs = regs->r_gs;
1808	return (0);
1809}
1810
1811int
1812fill_fpregs(p, fpregs)
1813	struct proc *p;
1814	struct fpreg *fpregs;
1815{
1816	bcopy(&p->p_addr->u_pcb.pcb_savefpu, fpregs, sizeof *fpregs);
1817	return (0);
1818}
1819
1820int
1821set_fpregs(p, fpregs)
1822	struct proc *p;
1823	struct fpreg *fpregs;
1824{
1825	bcopy(fpregs, &p->p_addr->u_pcb.pcb_savefpu, sizeof *fpregs);
1826	return (0);
1827}
1828
1829#ifndef DDB
1830void
1831Debugger(const char *msg)
1832{
1833	printf("Debugger(\"%s\") called.\n", msg);
1834}
1835#endif /* no DDB */
1836
1837#include <sys/disklabel.h>
1838
1839/*
1840 * Determine the size of the transfer, and make sure it is
1841 * within the boundaries of the partition. Adjust transfer
1842 * if needed, and signal errors or early completion.
1843 */
1844int
1845bounds_check_with_label(struct buf *bp, struct disklabel *lp, int wlabel)
1846{
1847        struct partition *p = lp->d_partitions + dkpart(bp->b_dev);
1848        int labelsect = lp->d_partitions[0].p_offset;
1849        int maxsz = p->p_size,
1850                sz = (bp->b_bcount + DEV_BSIZE - 1) >> DEV_BSHIFT;
1851
1852        /* overwriting disk label ? */
1853        /* XXX should also protect bootstrap in first 8K */
1854        if (bp->b_blkno + p->p_offset <= LABELSECTOR + labelsect &&
1855#if LABELSECTOR != 0
1856            bp->b_blkno + p->p_offset + sz > LABELSECTOR + labelsect &&
1857#endif
1858            (bp->b_flags & B_READ) == 0 && wlabel == 0) {
1859                bp->b_error = EROFS;
1860                goto bad;
1861        }
1862
1863#if     defined(DOSBBSECTOR) && defined(notyet)
1864        /* overwriting master boot record? */
1865        if (bp->b_blkno + p->p_offset <= DOSBBSECTOR &&
1866            (bp->b_flags & B_READ) == 0 && wlabel == 0) {
1867                bp->b_error = EROFS;
1868                goto bad;
1869        }
1870#endif
1871
1872        /* beyond partition? */
1873        if (bp->b_blkno < 0 || bp->b_blkno + sz > maxsz) {
1874                /* if exactly at end of disk, return an EOF */
1875                if (bp->b_blkno == maxsz) {
1876                        bp->b_resid = bp->b_bcount;
1877                        return(0);
1878                }
1879                /* or truncate if part of it fits */
1880                sz = maxsz - bp->b_blkno;
1881                if (sz <= 0) {
1882                        bp->b_error = EINVAL;
1883                        goto bad;
1884                }
1885                bp->b_bcount = sz << DEV_BSHIFT;
1886        }
1887
1888        bp->b_pblkno = bp->b_blkno + p->p_offset;
1889        return(1);
1890
1891bad:
1892        bp->b_flags |= B_ERROR;
1893        return(-1);
1894}
1895
1896#ifdef DDB
1897
1898/*
1899 * Provide inb() and outb() as functions.  They are normally only
1900 * available as macros calling inlined functions, thus cannot be
1901 * called inside DDB.
1902 *
1903 * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
1904 */
1905
1906#undef inb
1907#undef outb
1908
1909/* silence compiler warnings */
1910u_char inb(u_int);
1911void outb(u_int, u_char);
1912
1913u_char
1914inb(u_int port)
1915{
1916	u_char	data;
1917	/*
1918	 * We use %%dx and not %1 here because i/o is done at %dx and not at
1919	 * %edx, while gcc generates inferior code (movw instead of movl)
1920	 * if we tell it to load (u_short) port.
1921	 */
1922	__asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
1923	return (data);
1924}
1925
1926void
1927outb(u_int port, u_char data)
1928{
1929	u_char	al;
1930	/*
1931	 * Use an unnecessary assignment to help gcc's register allocator.
1932	 * This make a large difference for gcc-1.40 and a tiny difference
1933	 * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
1934	 * best results.  gcc-2.6.0 can't handle this.
1935	 */
1936	al = data;
1937	__asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
1938}
1939
1940#endif /* DDB */
1941